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/
22 #include "v8-version.h"
25 // We reserve the V8_* prefix for macros defined in V8 public API and
26 // assume there are no name conflicts with the embedder's code.
30 // Setup for Windows DLL export/import. When building the V8 DLL the
31 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
32 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
33 // static library or building a program which uses the V8 static library neither
34 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
35 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
36 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
37 build configuration to ensure that at most one of these is set
40 #ifdef BUILDING_V8_SHARED
41 # define V8_EXPORT __declspec(dllexport)
43 # define V8_EXPORT __declspec(dllimport)
46 #endif // BUILDING_V8_SHARED
50 // Setup for Linux shared library export.
51 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
52 # ifdef BUILDING_V8_SHARED
53 # define V8_EXPORT __attribute__ ((visibility("default")))
64 * The v8 JavaScript engine.
68 class AccessorSignature;
78 class FunctionTemplate;
80 class ImplementationUtilities;
88 class ObjectOperationDescriptor;
93 class RawOperationDescriptor;
106 template <class T> class Handle;
107 template <class T> class Local;
108 template <class T> class Eternal;
109 template<class T> class NonCopyablePersistentTraits;
110 template<class T> class PersistentBase;
112 class M = NonCopyablePersistentTraits<T> > class Persistent;
113 template<class T> class UniquePersistent;
114 template<class K, class V, class T> class PersistentValueMap;
115 template <class K, class V, class T>
116 class PersistentValueMapBase;
117 template <class K, class V, class T>
118 class PhantomPersistentValueMap;
119 template<class V, class T> class PersistentValueVector;
120 template<class T, class P> class WeakCallbackObject;
121 class FunctionTemplate;
122 class ObjectTemplate;
124 template<typename T> class FunctionCallbackInfo;
125 template<typename T> class PropertyCallbackInfo;
129 class CallHandlerHelper;
130 class EscapableHandleScope;
131 template<typename T> class ReturnValue;
139 struct StreamedSource;
140 template<typename T> class CustomArguments;
141 class PropertyCallbackArguments;
142 class FunctionCallbackArguments;
145 template <typename T>
148 V8_INLINE v8::Isolate* GetIsolate() const { return isolate_; }
150 explicit CallbackData(v8::Isolate* isolate, T* parameter)
151 : isolate_(isolate), parameter_(parameter) {}
152 V8_INLINE T* GetParameter() const { return parameter_; }
155 v8::Isolate* isolate_;
162 * General purpose unique identifier.
166 explicit UniqueId(intptr_t data)
169 bool operator==(const UniqueId& other) const {
170 return data_ == other.data_;
173 bool operator!=(const UniqueId& other) const {
174 return data_ != other.data_;
177 bool operator<(const UniqueId& other) const {
178 return data_ < other.data_;
187 #define TYPE_CHECK(T, S) \
189 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
194 * An object reference managed by the v8 garbage collector.
196 * All objects returned from v8 have to be tracked by the garbage
197 * collector so that it knows that the objects are still alive. Also,
198 * because the garbage collector may move objects, it is unsafe to
199 * point directly to an object. Instead, all objects are stored in
200 * handles which are known by the garbage collector and updated
201 * whenever an object moves. Handles should always be passed by value
202 * (except in cases like out-parameters) and they should never be
203 * allocated on the heap.
205 * There are two types of handles: local and persistent handles.
206 * Local handles are light-weight and transient and typically used in
207 * local operations. They are managed by HandleScopes. Persistent
208 * handles can be used when storing objects across several independent
209 * operations and have to be explicitly deallocated when they're no
212 * It is safe to extract the object stored in the handle by
213 * dereferencing the handle (for instance, to extract the Object* from
214 * a Handle<Object>); the value will still be governed by a handle
215 * behind the scenes and the same rules apply to these values as to
218 template <class T> class Handle {
221 * Creates an empty handle.
223 V8_INLINE Handle() : val_(0) {}
226 * Creates a handle for the contents of the specified handle. This
227 * constructor allows you to pass handles as arguments by value and
228 * to assign between handles. However, if you try to assign between
229 * incompatible handles, for instance from a Handle<String> to a
230 * Handle<Number> it will cause a compile-time error. Assigning
231 * between compatible handles, for instance assigning a
232 * Handle<String> to a variable declared as Handle<Value>, is legal
233 * because String is a subclass of Value.
235 template <class S> V8_INLINE Handle(Handle<S> that)
236 : val_(reinterpret_cast<T*>(*that)) {
238 * This check fails when trying to convert between incompatible
239 * handles. For example, converting from a Handle<String> to a
246 * Returns true if the handle is empty.
248 V8_INLINE bool IsEmpty() const { return val_ == 0; }
251 * Sets the handle to be empty. IsEmpty() will then return true.
253 V8_INLINE void Clear() { val_ = 0; }
255 V8_INLINE T* operator->() const { return val_; }
257 V8_INLINE T* operator*() const { return val_; }
260 * Checks whether two handles are the same.
261 * Returns true if both are empty, or if the objects
262 * to which they refer are identical.
263 * The handles' references are not checked.
265 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
266 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
267 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
268 if (a == 0) return b == 0;
269 if (b == 0) return false;
273 template <class S> V8_INLINE bool operator==(
274 const PersistentBase<S>& that) const {
275 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
276 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
277 if (a == 0) return b == 0;
278 if (b == 0) return false;
283 * Checks whether two handles are different.
284 * Returns true if only one of the handles is empty, or if
285 * the objects to which they refer are different.
286 * The handles' references are not checked.
288 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
289 return !operator==(that);
292 template <class S> V8_INLINE bool operator!=(
293 const Persistent<S>& that) const {
294 return !operator==(that);
297 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
298 #ifdef V8_ENABLE_CHECKS
299 // If we're going to perform the type check then we have to check
300 // that the handle isn't empty before doing the checked cast.
301 if (that.IsEmpty()) return Handle<T>();
303 return Handle<T>(T::Cast(*that));
306 template <class S> V8_INLINE Handle<S> As() {
307 return Handle<S>::Cast(*this);
310 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
311 return New(isolate, that.val_);
313 V8_INLINE static Handle<T> New(Isolate* isolate,
314 const PersistentBase<T>& that) {
315 return New(isolate, that.val_);
320 template<class F, class M> friend class Persistent;
321 template<class F> friend class PersistentBase;
322 template<class F> friend class Handle;
323 template<class F> friend class Local;
324 template<class F> friend class FunctionCallbackInfo;
325 template<class F> friend class PropertyCallbackInfo;
326 template<class F> friend class internal::CustomArguments;
327 friend Handle<Primitive> Undefined(Isolate* isolate);
328 friend Handle<Primitive> Null(Isolate* isolate);
329 friend Handle<Boolean> True(Isolate* isolate);
330 friend Handle<Boolean> False(Isolate* isolate);
331 friend class Context;
332 friend class HandleScope;
334 friend class Private;
337 * Creates a new handle for the specified value.
339 V8_INLINE explicit Handle(T* val) : val_(val) {}
341 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
348 * A light-weight stack-allocated object handle. All operations
349 * that return objects from within v8 return them in local handles. They
350 * are created within HandleScopes, and all local handles allocated within a
351 * handle scope are destroyed when the handle scope is destroyed. Hence it
352 * is not necessary to explicitly deallocate local handles.
354 template <class T> class Local : public Handle<T> {
357 template <class S> V8_INLINE Local(Local<S> that)
358 : Handle<T>(reinterpret_cast<T*>(*that)) {
360 * This check fails when trying to convert between incompatible
361 * handles. For example, converting from a Handle<String> to a
368 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
369 #ifdef V8_ENABLE_CHECKS
370 // If we're going to perform the type check then we have to check
371 // that the handle isn't empty before doing the checked cast.
372 if (that.IsEmpty()) return Local<T>();
374 return Local<T>(T::Cast(*that));
376 template <class S> V8_INLINE Local(Handle<S> that)
377 : Handle<T>(reinterpret_cast<T*>(*that)) {
381 template <class S> V8_INLINE Local<S> As() {
382 return Local<S>::Cast(*this);
386 * Create a local handle for the content of another handle.
387 * The referee is kept alive by the local handle even when
388 * the original handle is destroyed/disposed.
390 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
391 V8_INLINE static Local<T> New(Isolate* isolate,
392 const PersistentBase<T>& that);
396 template<class F> friend class Eternal;
397 template<class F> friend class PersistentBase;
398 template<class F, class M> friend class Persistent;
399 template<class F> friend class Handle;
400 template<class F> friend class Local;
401 template<class F> friend class FunctionCallbackInfo;
402 template<class F> friend class PropertyCallbackInfo;
405 friend class Context;
406 template<class F> friend class internal::CustomArguments;
407 friend class HandleScope;
408 friend class EscapableHandleScope;
409 template <class F1, class F2, class F3>
410 friend class PersistentValueMapBase;
411 template<class F1, class F2> friend class PersistentValueVector;
413 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
414 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
418 // Eternal handles are set-once handles that live for the life of the isolate.
419 template <class T> class Eternal {
421 V8_INLINE Eternal() : index_(kInitialValue) { }
423 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
424 Set(isolate, handle);
426 // Can only be safely called if already set.
427 V8_INLINE Local<T> Get(Isolate* isolate);
428 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
429 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
432 static const int kInitialValue = -1;
437 template <typename T>
438 class PhantomCallbackData : public internal::CallbackData<T> {
440 typedef void (*Callback)(const PhantomCallbackData<T>& data);
442 V8_INLINE void* GetInternalField1() const { return internal_field1_; }
443 V8_INLINE void* GetInternalField2() const { return internal_field2_; }
445 PhantomCallbackData(Isolate* isolate, T* parameter, void* internal_field1,
446 void* internal_field2)
447 : internal::CallbackData<T>(isolate, parameter),
448 internal_field1_(internal_field1),
449 internal_field2_(internal_field2) {}
452 void* internal_field1_;
453 void* internal_field2_;
457 template <class T, class P>
458 class WeakCallbackData : public internal::CallbackData<P> {
460 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
462 V8_INLINE Local<T> GetValue() const { return handle_; }
465 friend class internal::GlobalHandles;
466 WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
467 : internal::CallbackData<P>(isolate, parameter), handle_(handle) {}
472 static const int kNoInternalFieldIndex = -1;
476 * An object reference that is independent of any handle scope. Where
477 * a Local handle only lives as long as the HandleScope in which it was
478 * allocated, a PersistentBase handle remains valid until it is explicitly
481 * A persistent handle contains a reference to a storage cell within
482 * the v8 engine which holds an object value and which is updated by
483 * the garbage collector whenever the object is moved. A new storage
484 * cell can be created using the constructor or PersistentBase::Reset and
485 * existing handles can be disposed using PersistentBase::Reset.
488 template <class T> class PersistentBase {
491 * If non-empty, destroy the underlying storage cell
492 * IsEmpty() will return true after this call.
494 V8_INLINE void Reset();
496 * If non-empty, destroy the underlying storage cell
497 * and create a new one with the contents of other if other is non empty
500 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
503 * If non-empty, destroy the underlying storage cell
504 * and create a new one with the contents of other if other is non empty
507 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
509 V8_INLINE bool IsEmpty() const { return val_ == NULL; }
510 V8_INLINE void Empty() { val_ = 0; }
513 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
514 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
515 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
516 if (a == NULL) return b == NULL;
517 if (b == NULL) return false;
521 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
522 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
523 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
524 if (a == NULL) return b == NULL;
525 if (b == NULL) return false;
530 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
531 return !operator==(that);
534 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
535 return !operator==(that);
539 * Install a finalization callback on this object.
540 * NOTE: There is no guarantee as to *when* or even *if* the callback is
541 * invoked. The invocation is performed solely on a best effort basis.
542 * As always, GC-based finalization should *not* be relied upon for any
543 * critical form of resource management!
546 V8_INLINE void SetWeak(
548 typename WeakCallbackData<T, P>::Callback callback);
550 template<typename S, typename P>
551 V8_INLINE void SetWeak(
553 typename WeakCallbackData<S, P>::Callback callback);
555 // Phantom persistents work like weak persistents, except that the pointer to
556 // the object being collected is not available in the finalization callback.
557 // This enables the garbage collector to collect the object and any objects
558 // it references transitively in one GC cycle. At the moment you can either
559 // specify a parameter for the callback or the location of two internal
560 // fields in the dying object.
561 template <typename P>
562 V8_INLINE void SetPhantom(P* parameter,
563 typename PhantomCallbackData<P>::Callback callback,
564 int internal_field_index1 = kNoInternalFieldIndex,
565 int internal_field_index2 = kNoInternalFieldIndex);
568 V8_INLINE P* ClearWeak();
570 // TODO(dcarney): remove this.
571 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
574 * Marks the reference to this object independent. Garbage collector is free
575 * to ignore any object groups containing this object. Weak callback for an
576 * independent handle should not assume that it will be preceded by a global
577 * GC prologue callback or followed by a global GC epilogue callback.
579 V8_INLINE void MarkIndependent();
582 * Marks the reference to this object partially dependent. Partially dependent
583 * handles only depend on other partially dependent handles and these
584 * dependencies are provided through object groups. It provides a way to build
585 * smaller object groups for young objects that represent only a subset of all
586 * external dependencies. This mark is automatically cleared after each
587 * garbage collection.
589 V8_INLINE void MarkPartiallyDependent();
591 V8_INLINE bool IsIndependent() const;
593 /** Checks if the handle holds the only reference to an object. */
594 V8_INLINE bool IsNearDeath() const;
596 /** Returns true if the handle's reference is weak. */
597 V8_INLINE bool IsWeak() const;
600 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
601 * description in v8-profiler.h for details.
603 V8_INLINE void SetWrapperClassId(uint16_t class_id);
606 * Returns the class ID previously assigned to this handle or 0 if no class ID
607 * was previously assigned.
609 V8_INLINE uint16_t WrapperClassId() const;
612 friend class Isolate;
614 template<class F> friend class Handle;
615 template<class F> friend class Local;
616 template<class F1, class F2> friend class Persistent;
617 template<class F> friend class UniquePersistent;
618 template<class F> friend class PersistentBase;
619 template<class F> friend class ReturnValue;
620 template <class F1, class F2, class F3>
621 friend class PersistentValueMapBase;
622 template<class F1, class F2> friend class PersistentValueVector;
625 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
626 PersistentBase(PersistentBase& other); // NOLINT
627 void operator=(PersistentBase&);
628 V8_INLINE static T* New(Isolate* isolate, T* that);
635 * Default traits for Persistent. This class does not allow
636 * use of the copy constructor or assignment operator.
637 * At present kResetInDestructor is not set, but that will change in a future
641 class NonCopyablePersistentTraits {
643 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
644 static const bool kResetInDestructor = false;
645 template<class S, class M>
646 V8_INLINE static void Copy(const Persistent<S, M>& source,
647 NonCopyablePersistent* dest) {
648 Uncompilable<Object>();
650 // TODO(dcarney): come up with a good compile error here.
651 template<class O> V8_INLINE static void Uncompilable() {
652 TYPE_CHECK(O, Primitive);
658 * Helper class traits to allow copying and assignment of Persistent.
659 * This will clone the contents of storage cell, but not any of the flags, etc.
662 struct CopyablePersistentTraits {
663 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
664 static const bool kResetInDestructor = true;
665 template<class S, class M>
666 static V8_INLINE void Copy(const Persistent<S, M>& source,
667 CopyablePersistent* dest) {
668 // do nothing, just allow copy
674 * A PersistentBase which allows copy and assignment.
676 * Copy, assignment and destructor bevavior is controlled by the traits
679 * Note: Persistent class hierarchy is subject to future changes.
681 template <class T, class M> class Persistent : public PersistentBase<T> {
684 * A Persistent with no storage cell.
686 V8_INLINE Persistent() : PersistentBase<T>(0) { }
688 * Construct a Persistent from a Handle.
689 * When the Handle is non-empty, a new storage cell is created
690 * pointing to the same object, and no flags are set.
692 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
693 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
697 * Construct a Persistent from a Persistent.
698 * When the Persistent is non-empty, a new storage cell is created
699 * pointing to the same object, and no flags are set.
701 template <class S, class M2>
702 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
703 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
707 * The copy constructors and assignment operator create a Persistent
708 * exactly as the Persistent constructor, but the Copy function from the
709 * traits class is called, allowing the setting of flags based on the
712 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
715 template <class S, class M2>
716 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
719 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
723 template <class S, class M2>
724 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
729 * The destructor will dispose the Persistent based on the
730 * kResetInDestructor flags in the traits class. Since not calling dispose
731 * can result in a memory leak, it is recommended to always set this flag.
733 V8_INLINE ~Persistent() {
734 if (M::kResetInDestructor) this->Reset();
737 // TODO(dcarney): this is pretty useless, fix or remove
739 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
740 #ifdef V8_ENABLE_CHECKS
741 // If we're going to perform the type check then we have to check
742 // that the handle isn't empty before doing the checked cast.
743 if (!that.IsEmpty()) T::Cast(*that);
745 return reinterpret_cast<Persistent<T>&>(that);
748 // TODO(dcarney): this is pretty useless, fix or remove
749 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
750 return Persistent<S>::Cast(*this);
754 friend class Isolate;
756 template<class F> friend class Handle;
757 template<class F> friend class Local;
758 template<class F1, class F2> friend class Persistent;
759 template<class F> friend class ReturnValue;
761 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
762 V8_INLINE T* operator*() const { return this->val_; }
763 template<class S, class M2>
764 V8_INLINE void Copy(const Persistent<S, M2>& that);
769 * A PersistentBase which has move semantics.
771 * Note: Persistent class hierarchy is subject to future changes.
774 class UniquePersistent : public PersistentBase<T> {
776 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
777 UniquePersistent* object;
782 * A UniquePersistent with no storage cell.
784 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
786 * Construct a UniquePersistent from a Handle.
787 * When the Handle is non-empty, a new storage cell is created
788 * pointing to the same object, and no flags are set.
791 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
792 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
796 * Construct a UniquePersistent from a PersistentBase.
797 * When the Persistent is non-empty, a new storage cell is created
798 * pointing to the same object, and no flags are set.
801 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
802 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
808 V8_INLINE UniquePersistent(RValue rvalue)
809 : PersistentBase<T>(rvalue.object->val_) {
810 rvalue.object->val_ = 0;
812 V8_INLINE ~UniquePersistent() { this->Reset(); }
814 * Move via assignment.
817 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
820 this->val_ = rhs.val_;
825 * Cast operator for moves.
827 V8_INLINE operator RValue() { return RValue(this); }
829 * Pass allows returning uniques from functions, etc.
831 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
834 UniquePersistent(UniquePersistent&);
835 void operator=(UniquePersistent&);
840 * A stack-allocated class that governs a number of local handles.
841 * After a handle scope has been created, all local handles will be
842 * allocated within that handle scope until either the handle scope is
843 * deleted or another handle scope is created. If there is already a
844 * handle scope and a new one is created, all allocations will take
845 * place in the new handle scope until it is deleted. After that,
846 * new handles will again be allocated in the original handle scope.
848 * After the handle scope of a local handle has been deleted the
849 * garbage collector will no longer track the object stored in the
850 * handle and may deallocate it. The behavior of accessing a handle
851 * for which the handle scope has been deleted is undefined.
853 class V8_EXPORT HandleScope {
855 HandleScope(Isolate* isolate);
860 * Counts the number of allocated handles.
862 static int NumberOfHandles(Isolate* isolate);
864 V8_INLINE Isolate* GetIsolate() const {
865 return reinterpret_cast<Isolate*>(isolate_);
869 V8_INLINE HandleScope() {}
871 void Initialize(Isolate* isolate);
873 static internal::Object** CreateHandle(internal::Isolate* isolate,
874 internal::Object* value);
877 // Uses heap_object to obtain the current Isolate.
878 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
879 internal::Object* value);
881 // Make it hard to create heap-allocated or illegal handle scopes by
882 // disallowing certain operations.
883 HandleScope(const HandleScope&);
884 void operator=(const HandleScope&);
885 void* operator new(size_t size);
886 void operator delete(void*, size_t);
888 internal::Isolate* isolate_;
889 internal::Object** prev_next_;
890 internal::Object** prev_limit_;
892 // Local::New uses CreateHandle with an Isolate* parameter.
893 template<class F> friend class Local;
895 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
896 // a HeapObject* in their shortcuts.
898 friend class Context;
903 * A HandleScope which first allocates a handle in the current scope
904 * which will be later filled with the escape value.
906 class V8_EXPORT EscapableHandleScope : public HandleScope {
908 EscapableHandleScope(Isolate* isolate);
909 V8_INLINE ~EscapableHandleScope() {}
912 * Pushes the value into the previous scope and returns a handle to it.
913 * Cannot be called twice.
916 V8_INLINE Local<T> Escape(Local<T> value) {
917 internal::Object** slot =
918 Escape(reinterpret_cast<internal::Object**>(*value));
919 return Local<T>(reinterpret_cast<T*>(slot));
923 internal::Object** Escape(internal::Object** escape_value);
925 // Make it hard to create heap-allocated or illegal handle scopes by
926 // disallowing certain operations.
927 EscapableHandleScope(const EscapableHandleScope&);
928 void operator=(const EscapableHandleScope&);
929 void* operator new(size_t size);
930 void operator delete(void*, size_t);
932 internal::Object** escape_slot_;
935 class V8_EXPORT SealHandleScope {
937 SealHandleScope(Isolate* isolate);
941 // Make it hard to create heap-allocated or illegal handle scopes by
942 // disallowing certain operations.
943 SealHandleScope(const SealHandleScope&);
944 void operator=(const SealHandleScope&);
945 void* operator new(size_t size);
946 void operator delete(void*, size_t);
948 internal::Isolate* isolate_;
950 internal::Object** prev_limit_;
955 * A simple Maybe type, representing an object which may or may not have a
960 Maybe() : has_value(false) {}
961 explicit Maybe(T t) : has_value(true), value(t) {}
962 Maybe(bool has, T t) : has_value(has), value(t) {}
969 // Convenience wrapper.
971 inline Maybe<T> maybe(T t) {
976 // --- Special objects ---
980 * The superclass of values and API object templates.
982 class V8_EXPORT Data {
989 * The origin, within a file, of a script.
993 V8_INLINE ScriptOrigin(
994 Handle<Value> resource_name,
995 Handle<Integer> resource_line_offset = Handle<Integer>(),
996 Handle<Integer> resource_column_offset = Handle<Integer>(),
997 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
998 Handle<Integer> script_id = Handle<Integer>(),
999 Handle<Boolean> resource_is_embedder_debug_script = Handle<Boolean>())
1000 : resource_name_(resource_name),
1001 resource_line_offset_(resource_line_offset),
1002 resource_column_offset_(resource_column_offset),
1003 resource_is_embedder_debug_script_(resource_is_embedder_debug_script),
1004 resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
1005 script_id_(script_id) {}
1006 V8_INLINE Handle<Value> ResourceName() const;
1007 V8_INLINE Handle<Integer> ResourceLineOffset() const;
1008 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
1010 * Returns true for embedder's debugger scripts
1012 V8_INLINE Handle<Boolean> ResourceIsEmbedderDebugScript() const;
1013 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
1014 V8_INLINE Handle<Integer> ScriptID() const;
1017 Handle<Value> resource_name_;
1018 Handle<Integer> resource_line_offset_;
1019 Handle<Integer> resource_column_offset_;
1020 Handle<Boolean> resource_is_embedder_debug_script_;
1021 Handle<Boolean> resource_is_shared_cross_origin_;
1022 Handle<Integer> script_id_;
1027 * A compiled JavaScript script, not yet tied to a Context.
1029 class V8_EXPORT UnboundScript {
1032 * Binds the script to the currently entered context.
1034 Local<Script> BindToCurrentContext();
1037 Handle<Value> GetScriptName();
1040 * Data read from magic sourceURL comments.
1042 Handle<Value> GetSourceURL();
1044 * Data read from magic sourceMappingURL comments.
1046 Handle<Value> GetSourceMappingURL();
1049 * Returns zero based line number of the code_pos location in the script.
1050 * -1 will be returned if no information available.
1052 int GetLineNumber(int code_pos);
1054 static const int kNoScriptId = 0;
1059 * A compiled JavaScript script, tied to a Context which was active when the
1060 * script was compiled.
1062 class V8_EXPORT Script {
1065 * A shorthand for ScriptCompiler::Compile().
1067 static Local<Script> Compile(Handle<String> source,
1068 ScriptOrigin* origin = NULL);
1070 // To be decprecated, use the Compile above.
1071 static Local<Script> Compile(Handle<String> source,
1072 Handle<String> file_name);
1075 * Runs the script returning the resulting value. It will be run in the
1076 * context in which it was created (ScriptCompiler::CompileBound or
1077 * UnboundScript::BindToCurrentContext()).
1082 * Returns the corresponding context-unbound script.
1084 Local<UnboundScript> GetUnboundScript();
1086 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1088 return GetUnboundScript()->GetId();
1094 * For compiling scripts.
1096 class V8_EXPORT ScriptCompiler {
1099 * Compilation data that the embedder can cache and pass back to speed up
1100 * future compilations. The data is produced if the CompilerOptions passed to
1101 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1102 * = true. The data to cache can then can be retrieved from
1105 struct V8_EXPORT CachedData {
1115 buffer_policy(BufferNotOwned) {}
1117 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1118 // data and guarantees that it stays alive until the CachedData object is
1119 // destroyed. If the policy is BufferOwned, the given data will be deleted
1120 // (with delete[]) when the CachedData object is destroyed.
1121 CachedData(const uint8_t* data, int length,
1122 BufferPolicy buffer_policy = BufferNotOwned);
1124 // TODO(marja): Async compilation; add constructors which take a callback
1125 // which will be called when V8 no longer needs the data.
1126 const uint8_t* data;
1129 BufferPolicy buffer_policy;
1132 // Prevent copying. Not implemented.
1133 CachedData(const CachedData&);
1134 CachedData& operator=(const CachedData&);
1138 * Source code which can be then compiled to a UnboundScript or Script.
1142 // Source takes ownership of CachedData.
1143 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1144 CachedData* cached_data = NULL);
1145 V8_INLINE Source(Local<String> source_string,
1146 CachedData* cached_data = NULL);
1147 V8_INLINE ~Source();
1149 // Ownership of the CachedData or its buffers is *not* transferred to the
1150 // caller. The CachedData object is alive as long as the Source object is
1152 V8_INLINE const CachedData* GetCachedData() const;
1155 friend class ScriptCompiler;
1156 // Prevent copying. Not implemented.
1157 Source(const Source&);
1158 Source& operator=(const Source&);
1160 Local<String> source_string;
1162 // Origin information
1163 Handle<Value> resource_name;
1164 Handle<Integer> resource_line_offset;
1165 Handle<Integer> resource_column_offset;
1166 Handle<Boolean> resource_is_embedder_debug_script;
1167 Handle<Boolean> resource_is_shared_cross_origin;
1169 // Cached data from previous compilation (if a kConsume*Cache flag is
1170 // set), or hold newly generated cache data (kProduce*Cache flags) are
1171 // set when calling a compile method.
1172 CachedData* cached_data;
1176 * For streaming incomplete script data to V8. The embedder should implement a
1177 * subclass of this class.
1179 class ExternalSourceStream {
1181 virtual ~ExternalSourceStream() {}
1184 * V8 calls this to request the next chunk of data from the embedder. This
1185 * function will be called on a background thread, so it's OK to block and
1186 * wait for the data, if the embedder doesn't have data yet. Returns the
1187 * length of the data returned. When the data ends, GetMoreData should
1188 * return 0. Caller takes ownership of the data.
1190 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1191 * two data chunks, but doesn't handle multi-byte characters split between
1192 * more than two data chunks. The embedder can avoid this problem by always
1193 * returning at least 2 bytes of data.
1195 * If the embedder wants to cancel the streaming, they should make the next
1196 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1197 * probably, parsing will fail). The streaming task will return as soon as
1198 * V8 has parsed the data it received so far.
1200 virtual size_t GetMoreData(const uint8_t** src) = 0;
1205 * Source code which can be streamed into V8 in pieces. It will be parsed
1206 * while streaming. It can be compiled after the streaming is complete.
1207 * StreamedSource must be kept alive while the streaming task is ran (see
1208 * ScriptStreamingTask below).
1210 class V8_EXPORT StreamedSource {
1212 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1214 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1217 // Ownership of the CachedData or its buffers is *not* transferred to the
1218 // caller. The CachedData object is alive as long as the StreamedSource
1220 const CachedData* GetCachedData() const;
1222 internal::StreamedSource* impl() const { return impl_; }
1225 // Prevent copying. Not implemented.
1226 StreamedSource(const StreamedSource&);
1227 StreamedSource& operator=(const StreamedSource&);
1229 internal::StreamedSource* impl_;
1233 * A streaming task which the embedder must run on a background thread to
1234 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1236 class ScriptStreamingTask {
1238 virtual ~ScriptStreamingTask() {}
1239 virtual void Run() = 0;
1242 enum CompileOptions {
1243 kNoCompileOptions = 0,
1244 kProduceParserCache,
1245 kConsumeParserCache,
1249 // Support the previous API for a transition period.
1254 * Compiles the specified script (context-independent).
1255 * Cached data as part of the source object can be optionally produced to be
1256 * consumed later to speed up compilation of identical source scripts.
1258 * Note that when producing cached data, the source must point to NULL for
1259 * cached data. When consuming cached data, the cached data must have been
1260 * produced by the same version of V8.
1262 * \param source Script source code.
1263 * \return Compiled script object (context independent; for running it must be
1264 * bound to a context).
1266 static Local<UnboundScript> CompileUnbound(
1267 Isolate* isolate, Source* source,
1268 CompileOptions options = kNoCompileOptions);
1271 * Compiles the specified script (bound to current context).
1273 * \param source Script source code.
1274 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1275 * using pre_data speeds compilation if it's done multiple times.
1276 * Owned by caller, no references are kept when this function returns.
1277 * \return Compiled script object, bound to the context that was active
1278 * when this function was called. When run it will always use this
1281 static Local<Script> Compile(
1282 Isolate* isolate, Source* source,
1283 CompileOptions options = kNoCompileOptions);
1286 * Returns a task which streams script data into V8, or NULL if the script
1287 * cannot be streamed. The user is responsible for running the task on a
1288 * background thread and deleting it. When ran, the task starts parsing the
1289 * script, and it will request data from the StreamedSource as needed. When
1290 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1291 * can be compiled (see Compile below).
1293 * This API allows to start the streaming with as little data as possible, and
1294 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1296 static ScriptStreamingTask* StartStreamingScript(
1297 Isolate* isolate, StreamedSource* source,
1298 CompileOptions options = kNoCompileOptions);
1301 * Compiles a streamed script (bound to current context).
1303 * This can only be called after the streaming has finished
1304 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1305 * during streaming, so the embedder needs to pass the full source here.
1307 static Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1308 Handle<String> full_source_string,
1309 const ScriptOrigin& origin);
1312 * Return a version tag for CachedData for the current V8 version & flags.
1314 * This value is meant only for determining whether a previously generated
1315 * CachedData instance is still valid; the tag has no other meaing.
1317 * Background: The data carried by CachedData may depend on the exact
1318 * V8 version number or currently compiler flags. This means when
1319 * persisting CachedData, the embedder must take care to not pass in
1320 * data from another V8 version, or the same version with different
1323 * The easiest way to do so is to clear the embedder's cache on any
1326 * Alternatively, this tag can be stored alongside the cached data and
1327 * compared when it is being used.
1329 static uint32_t CachedDataVersionTag();
1332 * Compile an ES6 module.
1334 * This is an experimental feature.
1336 * TODO(adamk): Script is likely the wrong return value for this;
1337 * should return some new Module type.
1339 static Local<Script> CompileModule(
1340 Isolate* isolate, Source* source,
1341 CompileOptions options = kNoCompileOptions);
1344 * Compile a function for a given context. This is equivalent to running
1347 * return function(args) { ... }
1350 * It is possible to specify multiple context extensions (obj in the above
1353 static Local<Function> CompileFunctionInContext(
1354 Isolate* isolate, Source* source, Local<Context> context,
1355 size_t arguments_count, Local<String> arguments[],
1356 size_t context_extension_count, Local<Object> context_extensions[]);
1359 static Local<UnboundScript> CompileUnboundInternal(Isolate* isolate,
1361 CompileOptions options,
1369 class V8_EXPORT Message {
1371 Local<String> Get() const;
1372 Local<String> GetSourceLine() const;
1375 * Returns the origin for the script from where the function causing the
1378 ScriptOrigin GetScriptOrigin() const;
1381 * Returns the resource name for the script from where the function causing
1382 * the error originates.
1384 Handle<Value> GetScriptResourceName() const;
1387 * Exception stack trace. By default stack traces are not captured for
1388 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1389 * to change this option.
1391 Handle<StackTrace> GetStackTrace() const;
1394 * Returns the number, 1-based, of the line where the error occurred.
1396 int GetLineNumber() const;
1399 * Returns the index within the script of the first character where
1400 * the error occurred.
1402 int GetStartPosition() const;
1405 * Returns the index within the script of the last character where
1406 * the error occurred.
1408 int GetEndPosition() const;
1411 * Returns the index within the line of the first character where
1412 * the error occurred.
1414 int GetStartColumn() const;
1417 * Returns the index within the line of the last character where
1418 * the error occurred.
1420 int GetEndColumn() const;
1423 * Passes on the value set by the embedder when it fed the script from which
1424 * this Message was generated to V8.
1426 bool IsSharedCrossOrigin() const;
1428 // TODO(1245381): Print to a string instead of on a FILE.
1429 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1431 static const int kNoLineNumberInfo = 0;
1432 static const int kNoColumnInfo = 0;
1433 static const int kNoScriptIdInfo = 0;
1438 * Representation of a JavaScript stack trace. The information collected is a
1439 * snapshot of the execution stack and the information remains valid after
1440 * execution continues.
1442 class V8_EXPORT StackTrace {
1445 * Flags that determine what information is placed captured for each
1446 * StackFrame when grabbing the current stack trace.
1448 enum StackTraceOptions {
1450 kColumnOffset = 1 << 1 | kLineNumber,
1451 kScriptName = 1 << 2,
1452 kFunctionName = 1 << 3,
1454 kIsConstructor = 1 << 5,
1455 kScriptNameOrSourceURL = 1 << 6,
1457 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1458 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1459 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1463 * Returns a StackFrame at a particular index.
1465 Local<StackFrame> GetFrame(uint32_t index) const;
1468 * Returns the number of StackFrames.
1470 int GetFrameCount() const;
1473 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1475 Local<Array> AsArray();
1478 * Grab a snapshot of the current JavaScript execution stack.
1480 * \param frame_limit The maximum number of stack frames we want to capture.
1481 * \param options Enumerates the set of things we will capture for each
1484 static Local<StackTrace> CurrentStackTrace(
1487 StackTraceOptions options = kOverview);
1492 * A single JavaScript stack frame.
1494 class V8_EXPORT StackFrame {
1497 * Returns the number, 1-based, of the line for the associate function call.
1498 * This method will return Message::kNoLineNumberInfo if it is unable to
1499 * retrieve the line number, or if kLineNumber was not passed as an option
1500 * when capturing the StackTrace.
1502 int GetLineNumber() const;
1505 * Returns the 1-based column offset on the line for the associated function
1507 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1508 * the column number, or if kColumnOffset was not passed as an option when
1509 * capturing the StackTrace.
1511 int GetColumn() const;
1514 * Returns the id of the script for the function for this StackFrame.
1515 * This method will return Message::kNoScriptIdInfo if it is unable to
1516 * retrieve the script id, or if kScriptId was not passed as an option when
1517 * capturing the StackTrace.
1519 int GetScriptId() const;
1522 * Returns the name of the resource that contains the script for the
1523 * function for this StackFrame.
1525 Local<String> GetScriptName() const;
1528 * Returns the name of the resource that contains the script for the
1529 * function for this StackFrame or sourceURL value if the script name
1530 * is undefined and its source ends with //# sourceURL=... string or
1531 * deprecated //@ sourceURL=... string.
1533 Local<String> GetScriptNameOrSourceURL() const;
1536 * Returns the name of the function associated with this stack frame.
1538 Local<String> GetFunctionName() const;
1541 * Returns whether or not the associated function is compiled via a call to
1544 bool IsEval() const;
1547 * Returns whether or not the associated function is called as a
1548 * constructor via "new".
1550 bool IsConstructor() const;
1554 // A StateTag represents a possible state of the VM.
1555 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1558 // A RegisterState represents the current state of registers used
1559 // by the sampling profiler API.
1560 struct RegisterState {
1561 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1562 void* pc; // Instruction pointer.
1563 void* sp; // Stack pointer.
1564 void* fp; // Frame pointer.
1568 // The output structure filled up by GetStackSample API function.
1570 size_t frames_count;
1578 class V8_EXPORT JSON {
1581 * Tries to parse the string |json_string| and returns it as value if
1584 * \param json_string The string to parse.
1585 * \return The corresponding value if successfully parsed.
1587 static Local<Value> Parse(Local<String> json_string);
1592 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1593 * but can be created without entering a v8::Context and hence shouldn't
1594 * escape to JavaScript.
1596 class V8_EXPORT NativeWeakMap : public Data {
1598 static Local<NativeWeakMap> New(Isolate* isolate);
1599 void Set(Handle<Value> key, Handle<Value> value);
1600 Local<Value> Get(Handle<Value> key);
1601 bool Has(Handle<Value> key);
1602 bool Delete(Handle<Value> key);
1610 * The superclass of all JavaScript values and objects.
1612 class V8_EXPORT Value : public Data {
1615 * Returns true if this value is the undefined value. See ECMA-262
1618 V8_INLINE bool IsUndefined() const;
1621 * Returns true if this value is the null value. See ECMA-262
1624 V8_INLINE bool IsNull() const;
1627 * Returns true if this value is true.
1629 bool IsTrue() const;
1632 * Returns true if this value is false.
1634 bool IsFalse() const;
1637 * Returns true if this value is a symbol or a string.
1638 * This is an experimental feature.
1640 bool IsName() const;
1643 * Returns true if this value is an instance of the String type.
1646 V8_INLINE bool IsString() const;
1649 * Returns true if this value is a symbol.
1650 * This is an experimental feature.
1652 bool IsSymbol() const;
1655 * Returns true if this value is a function.
1657 bool IsFunction() const;
1660 * Returns true if this value is an array.
1662 bool IsArray() const;
1665 * Returns true if this value is an object.
1667 bool IsObject() const;
1670 * Returns true if this value is boolean.
1672 bool IsBoolean() const;
1675 * Returns true if this value is a number.
1677 bool IsNumber() const;
1680 * Returns true if this value is external.
1682 bool IsExternal() const;
1685 * Returns true if this value is a 32-bit signed integer.
1687 bool IsInt32() const;
1690 * Returns true if this value is a 32-bit unsigned integer.
1692 bool IsUint32() const;
1695 * Returns true if this value is a Date.
1697 bool IsDate() const;
1700 * Returns true if this value is an Arguments object.
1702 bool IsArgumentsObject() const;
1705 * Returns true if this value is a Boolean object.
1707 bool IsBooleanObject() const;
1710 * Returns true if this value is a Number object.
1712 bool IsNumberObject() const;
1715 * Returns true if this value is a String object.
1717 bool IsStringObject() const;
1720 * Returns true if this value is a Symbol object.
1721 * This is an experimental feature.
1723 bool IsSymbolObject() const;
1726 * Returns true if this value is a NativeError.
1728 bool IsNativeError() const;
1731 * Returns true if this value is a RegExp.
1733 bool IsRegExp() const;
1736 * Returns true if this value is a Generator function.
1737 * This is an experimental feature.
1739 bool IsGeneratorFunction() const;
1742 * Returns true if this value is a Generator object (iterator).
1743 * This is an experimental feature.
1745 bool IsGeneratorObject() const;
1748 * Returns true if this value is a Promise.
1749 * This is an experimental feature.
1751 bool IsPromise() const;
1754 * Returns true if this value is a Map.
1755 * This is an experimental feature.
1760 * Returns true if this value is a Set.
1761 * This is an experimental feature.
1766 * Returns true if this value is a Map Iterator.
1767 * This is an experimental feature.
1769 bool IsMapIterator() const;
1772 * Returns true if this value is a Set Iterator.
1773 * This is an experimental feature.
1775 bool IsSetIterator() const;
1778 * Returns true if this value is a WeakMap.
1779 * This is an experimental feature.
1781 bool IsWeakMap() const;
1784 * Returns true if this value is a WeakSet.
1785 * This is an experimental feature.
1787 bool IsWeakSet() const;
1790 * Returns true if this value is an ArrayBuffer.
1791 * This is an experimental feature.
1793 bool IsArrayBuffer() const;
1796 * Returns true if this value is an ArrayBufferView.
1797 * This is an experimental feature.
1799 bool IsArrayBufferView() const;
1802 * Returns true if this value is one of TypedArrays.
1803 * This is an experimental feature.
1805 bool IsTypedArray() const;
1808 * Returns true if this value is an Uint8Array.
1809 * This is an experimental feature.
1811 bool IsUint8Array() const;
1814 * Returns true if this value is an Uint8ClampedArray.
1815 * This is an experimental feature.
1817 bool IsUint8ClampedArray() const;
1820 * Returns true if this value is an Int8Array.
1821 * This is an experimental feature.
1823 bool IsInt8Array() const;
1826 * Returns true if this value is an Uint16Array.
1827 * This is an experimental feature.
1829 bool IsUint16Array() const;
1832 * Returns true if this value is an Int16Array.
1833 * This is an experimental feature.
1835 bool IsInt16Array() const;
1838 * Returns true if this value is an Uint32Array.
1839 * This is an experimental feature.
1841 bool IsUint32Array() const;
1844 * Returns true if this value is an Int32Array.
1845 * This is an experimental feature.
1847 bool IsInt32Array() const;
1850 * Returns true if this value is a Float32Array.
1851 * This is an experimental feature.
1853 bool IsFloat32Array() const;
1856 * Returns true if this value is a Float64Array.
1857 * This is an experimental feature.
1859 bool IsFloat64Array() const;
1862 * Returns true if this value is a DataView.
1863 * This is an experimental feature.
1865 bool IsDataView() const;
1867 Local<Boolean> ToBoolean(Isolate* isolate) const;
1868 Local<Number> ToNumber(Isolate* isolate) const;
1869 Local<String> ToString(Isolate* isolate) const;
1870 Local<String> ToDetailString(Isolate* isolate) const;
1871 Local<Object> ToObject(Isolate* isolate) const;
1872 Local<Integer> ToInteger(Isolate* isolate) const;
1873 Local<Uint32> ToUint32(Isolate* isolate) const;
1874 Local<Int32> ToInt32(Isolate* isolate) const;
1876 // TODO(dcarney): deprecate all these.
1877 inline Local<Boolean> ToBoolean() const;
1878 inline Local<Number> ToNumber() const;
1879 inline Local<String> ToString() const;
1880 inline Local<String> ToDetailString() const;
1881 inline Local<Object> ToObject() const;
1882 inline Local<Integer> ToInteger() const;
1883 inline Local<Uint32> ToUint32() const;
1884 inline Local<Int32> ToInt32() const;
1887 * Attempts to convert a string to an array index.
1888 * Returns an empty handle if the conversion fails.
1890 Local<Uint32> ToArrayIndex() const;
1892 bool BooleanValue() const;
1893 double NumberValue() const;
1894 int64_t IntegerValue() const;
1895 uint32_t Uint32Value() const;
1896 int32_t Int32Value() const;
1899 bool Equals(Handle<Value> that) const;
1900 bool StrictEquals(Handle<Value> that) const;
1901 bool SameValue(Handle<Value> that) const;
1903 template <class T> V8_INLINE static Value* Cast(T* value);
1906 V8_INLINE bool QuickIsUndefined() const;
1907 V8_INLINE bool QuickIsNull() const;
1908 V8_INLINE bool QuickIsString() const;
1909 bool FullIsUndefined() const;
1910 bool FullIsNull() const;
1911 bool FullIsString() const;
1916 * The superclass of primitive values. See ECMA-262 4.3.2.
1918 class V8_EXPORT Primitive : public Value { };
1922 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1925 class V8_EXPORT Boolean : public Primitive {
1928 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1933 * A superclass for symbols and strings.
1935 class V8_EXPORT Name : public Primitive {
1938 * Returns the identity hash for this object. The current implementation
1939 * uses an inline property on the object to store the identity hash.
1941 * The return value will never be 0. Also, it is not guaranteed to be
1944 int GetIdentityHash();
1946 V8_INLINE static Name* Cast(v8::Value* obj);
1948 static void CheckCast(v8::Value* obj);
1953 * A JavaScript string value (ECMA-262, 4.3.17).
1955 class V8_EXPORT String : public Name {
1958 UNKNOWN_ENCODING = 0x1,
1959 TWO_BYTE_ENCODING = 0x0,
1960 ONE_BYTE_ENCODING = 0x4
1963 * Returns the number of characters in this string.
1968 * Returns the number of bytes in the UTF-8 encoded
1969 * representation of this string.
1971 int Utf8Length() const;
1974 * Returns whether this string is known to contain only one byte data.
1975 * Does not read the string.
1976 * False negatives are possible.
1978 bool IsOneByte() const;
1981 * Returns whether this string contain only one byte data.
1982 * Will read the entire string in some cases.
1984 bool ContainsOnlyOneByte() const;
1987 * Write the contents of the string to an external buffer.
1988 * If no arguments are given, expects the buffer to be large
1989 * enough to hold the entire string and NULL terminator. Copies
1990 * the contents of the string and the NULL terminator into the
1993 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1994 * before the end of the buffer.
1996 * Copies up to length characters into the output buffer.
1997 * Only null-terminates if there is enough space in the buffer.
1999 * \param buffer The buffer into which the string will be copied.
2000 * \param start The starting position within the string at which
2002 * \param length The number of characters to copy from the string. For
2003 * WriteUtf8 the number of bytes in the buffer.
2004 * \param nchars_ref The number of characters written, can be NULL.
2005 * \param options Various options that might affect performance of this or
2006 * subsequent operations.
2007 * \return The number of characters copied to the buffer excluding the null
2008 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2009 * including the null terminator (if written).
2013 HINT_MANY_WRITES_EXPECTED = 1,
2014 NO_NULL_TERMINATION = 2,
2015 PRESERVE_ONE_BYTE_NULL = 4,
2016 // Used by WriteUtf8 to replace orphan surrogate code units with the
2017 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2019 REPLACE_INVALID_UTF8 = 8
2022 // 16-bit character codes.
2023 int Write(uint16_t* buffer,
2026 int options = NO_OPTIONS) const;
2027 // One byte characters.
2028 int WriteOneByte(uint8_t* buffer,
2031 int options = NO_OPTIONS) const;
2032 // UTF-8 encoded characters.
2033 int WriteUtf8(char* buffer,
2035 int* nchars_ref = NULL,
2036 int options = NO_OPTIONS) const;
2039 * A zero length string.
2041 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2044 * Returns true if the string is external
2046 bool IsExternal() const;
2049 * Returns true if the string is both external and one-byte.
2051 bool IsExternalOneByte() const;
2053 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2055 virtual ~ExternalStringResourceBase() {}
2058 ExternalStringResourceBase() {}
2061 * Internally V8 will call this Dispose method when the external string
2062 * resource is no longer needed. The default implementation will use the
2063 * delete operator. This method can be overridden in subclasses to
2064 * control how allocated external string resources are disposed.
2066 virtual void Dispose() { delete this; }
2069 // Disallow copying and assigning.
2070 ExternalStringResourceBase(const ExternalStringResourceBase&);
2071 void operator=(const ExternalStringResourceBase&);
2073 friend class v8::internal::Heap;
2077 * An ExternalStringResource is a wrapper around a two-byte string
2078 * buffer that resides outside V8's heap. Implement an
2079 * ExternalStringResource to manage the life cycle of the underlying
2080 * buffer. Note that the string data must be immutable.
2082 class V8_EXPORT ExternalStringResource
2083 : public ExternalStringResourceBase {
2086 * Override the destructor to manage the life cycle of the underlying
2089 virtual ~ExternalStringResource() {}
2092 * The string data from the underlying buffer.
2094 virtual const uint16_t* data() const = 0;
2097 * The length of the string. That is, the number of two-byte characters.
2099 virtual size_t length() const = 0;
2102 ExternalStringResource() {}
2106 * An ExternalOneByteStringResource is a wrapper around an one-byte
2107 * string buffer that resides outside V8's heap. Implement an
2108 * ExternalOneByteStringResource to manage the life cycle of the
2109 * underlying buffer. Note that the string data must be immutable
2110 * and that the data must be Latin-1 and not UTF-8, which would require
2111 * special treatment internally in the engine and do not allow efficient
2112 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2115 class V8_EXPORT ExternalOneByteStringResource
2116 : public ExternalStringResourceBase {
2119 * Override the destructor to manage the life cycle of the underlying
2122 virtual ~ExternalOneByteStringResource() {}
2123 /** The string data from the underlying buffer.*/
2124 virtual const char* data() const = 0;
2125 /** The number of Latin-1 characters in the string.*/
2126 virtual size_t length() const = 0;
2128 ExternalOneByteStringResource() {}
2132 * If the string is an external string, return the ExternalStringResourceBase
2133 * regardless of the encoding, otherwise return NULL. The encoding of the
2134 * string is returned in encoding_out.
2136 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2137 Encoding* encoding_out) const;
2140 * Get the ExternalStringResource for an external string. Returns
2141 * NULL if IsExternal() doesn't return true.
2143 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2146 * Get the ExternalOneByteStringResource for an external one-byte string.
2147 * Returns NULL if IsExternalOneByte() doesn't return true.
2149 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2151 V8_INLINE static String* Cast(v8::Value* obj);
2153 enum NewStringType { kNormalString, kInternalizedString };
2155 /** Allocates a new string from UTF-8 data.*/
2156 static Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2157 NewStringType type = kNormalString,
2160 /** Allocates a new string from Latin-1 data.*/
2161 static Local<String> NewFromOneByte(
2163 const uint8_t* data,
2164 NewStringType type = kNormalString,
2167 /** Allocates a new string from UTF-16 data.*/
2168 static Local<String> NewFromTwoByte(
2170 const uint16_t* data,
2171 NewStringType type = kNormalString,
2175 * Creates a new string by concatenating the left and the right strings
2176 * passed in as parameters.
2178 static Local<String> Concat(Handle<String> left, Handle<String> right);
2181 * Creates a new external string using the data defined in the given
2182 * resource. When the external string is no longer live on V8's heap the
2183 * resource will be disposed by calling its Dispose method. The caller of
2184 * this function should not otherwise delete or modify the resource. Neither
2185 * should the underlying buffer be deallocated or modified except through the
2186 * destructor of the external string resource.
2188 static Local<String> NewExternal(Isolate* isolate,
2189 ExternalStringResource* resource);
2192 * Associate an external string resource with this string by transforming it
2193 * in place so that existing references to this string in the JavaScript heap
2194 * will use the external string resource. The external string resource's
2195 * character contents need to be equivalent to this string.
2196 * Returns true if the string has been changed to be an external string.
2197 * The string is not modified if the operation fails. See NewExternal for
2198 * information on the lifetime of the resource.
2200 bool MakeExternal(ExternalStringResource* resource);
2203 * Creates a new external string using the one-byte data defined in the given
2204 * resource. When the external string is no longer live on V8's heap the
2205 * resource will be disposed by calling its Dispose method. The caller of
2206 * this function should not otherwise delete or modify the resource. Neither
2207 * should the underlying buffer be deallocated or modified except through the
2208 * destructor of the external string resource.
2210 static Local<String> NewExternal(Isolate* isolate,
2211 ExternalOneByteStringResource* resource);
2214 * Associate an external string resource with this string by transforming it
2215 * in place so that existing references to this string in the JavaScript heap
2216 * will use the external string resource. The external string resource's
2217 * character contents need to be equivalent to this string.
2218 * Returns true if the string has been changed to be an external string.
2219 * The string is not modified if the operation fails. See NewExternal for
2220 * information on the lifetime of the resource.
2222 bool MakeExternal(ExternalOneByteStringResource* resource);
2225 * Returns true if this string can be made external.
2227 bool CanMakeExternal();
2230 * Converts an object to a UTF-8-encoded character array. Useful if
2231 * you want to print the object. If conversion to a string fails
2232 * (e.g. due to an exception in the toString() method of the object)
2233 * then the length() method returns 0 and the * operator returns
2236 class V8_EXPORT Utf8Value {
2238 explicit Utf8Value(Handle<v8::Value> obj);
2240 char* operator*() { return str_; }
2241 const char* operator*() const { return str_; }
2242 int length() const { return length_; }
2247 // Disallow copying and assigning.
2248 Utf8Value(const Utf8Value&);
2249 void operator=(const Utf8Value&);
2253 * Converts an object to a two-byte string.
2254 * If conversion to a string fails (eg. due to an exception in the toString()
2255 * method of the object) then the length() method returns 0 and the * operator
2258 class V8_EXPORT Value {
2260 explicit Value(Handle<v8::Value> obj);
2262 uint16_t* operator*() { return str_; }
2263 const uint16_t* operator*() const { return str_; }
2264 int length() const { return length_; }
2269 // Disallow copying and assigning.
2270 Value(const Value&);
2271 void operator=(const Value&);
2275 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2276 Encoding encoding) const;
2277 void VerifyExternalStringResource(ExternalStringResource* val) const;
2278 static void CheckCast(v8::Value* obj);
2283 * A JavaScript symbol (ECMA-262 edition 6)
2285 * This is an experimental feature. Use at your own risk.
2287 class V8_EXPORT Symbol : public Name {
2289 // Returns the print name string of the symbol, or undefined if none.
2290 Local<Value> Name() const;
2292 // Create a symbol. If name is not empty, it will be used as the description.
2293 static Local<Symbol> New(
2294 Isolate *isolate, Local<String> name = Local<String>());
2296 // Access global symbol registry.
2297 // Note that symbols created this way are never collected, so
2298 // they should only be used for statically fixed properties.
2299 // Also, there is only one global name space for the names used as keys.
2300 // To minimize the potential for clashes, use qualified names as keys.
2301 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2303 // Retrieve a global symbol. Similar to |For|, but using a separate
2304 // registry that is not accessible by (and cannot clash with) JavaScript code.
2305 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2307 // Well-known symbols
2308 static Local<Symbol> GetIterator(Isolate* isolate);
2309 static Local<Symbol> GetUnscopables(Isolate* isolate);
2310 static Local<Symbol> GetToStringTag(Isolate* isolate);
2312 V8_INLINE static Symbol* Cast(v8::Value* obj);
2316 static void CheckCast(v8::Value* obj);
2323 * This is an experimental feature. Use at your own risk.
2325 class V8_EXPORT Private : public Data {
2327 // Returns the print name string of the private symbol, or undefined if none.
2328 Local<Value> Name() const;
2330 // Create a private symbol. If name is not empty, it will be the description.
2331 static Local<Private> New(
2332 Isolate *isolate, Local<String> name = Local<String>());
2334 // Retrieve a global private symbol. If a symbol with this name has not
2335 // been retrieved in the same isolate before, it is created.
2336 // Note that private symbols created this way are never collected, so
2337 // they should only be used for statically fixed properties.
2338 // Also, there is only one global name space for the names used as keys.
2339 // To minimize the potential for clashes, use qualified names as keys,
2340 // e.g., "Class#property".
2341 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2349 * A JavaScript number value (ECMA-262, 4.3.20)
2351 class V8_EXPORT Number : public Primitive {
2353 double Value() const;
2354 static Local<Number> New(Isolate* isolate, double value);
2355 V8_INLINE static Number* Cast(v8::Value* obj);
2358 static void CheckCast(v8::Value* obj);
2363 * A JavaScript value representing a signed integer.
2365 class V8_EXPORT Integer : public Number {
2367 static Local<Integer> New(Isolate* isolate, int32_t value);
2368 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2369 int64_t Value() const;
2370 V8_INLINE static Integer* Cast(v8::Value* obj);
2373 static void CheckCast(v8::Value* obj);
2378 * A JavaScript value representing a 32-bit signed integer.
2380 class V8_EXPORT Int32 : public Integer {
2382 int32_t Value() const;
2389 * A JavaScript value representing a 32-bit unsigned integer.
2391 class V8_EXPORT Uint32 : public Integer {
2393 uint32_t Value() const;
2399 enum PropertyAttribute {
2406 enum ExternalArrayType {
2407 kExternalInt8Array = 1,
2408 kExternalUint8Array,
2409 kExternalInt16Array,
2410 kExternalUint16Array,
2411 kExternalInt32Array,
2412 kExternalUint32Array,
2413 kExternalFloat32Array,
2414 kExternalFloat64Array,
2415 kExternalUint8ClampedArray,
2417 // Legacy constant names
2418 kExternalByteArray = kExternalInt8Array,
2419 kExternalUnsignedByteArray = kExternalUint8Array,
2420 kExternalShortArray = kExternalInt16Array,
2421 kExternalUnsignedShortArray = kExternalUint16Array,
2422 kExternalIntArray = kExternalInt32Array,
2423 kExternalUnsignedIntArray = kExternalUint32Array,
2424 kExternalFloatArray = kExternalFloat32Array,
2425 kExternalDoubleArray = kExternalFloat64Array,
2426 kExternalPixelArray = kExternalUint8ClampedArray
2430 * Accessor[Getter|Setter] are used as callback functions when
2431 * setting|getting a particular property. See Object and ObjectTemplate's
2432 * method SetAccessor.
2434 typedef void (*AccessorGetterCallback)(
2435 Local<String> property,
2436 const PropertyCallbackInfo<Value>& info);
2437 typedef void (*AccessorNameGetterCallback)(
2438 Local<Name> property,
2439 const PropertyCallbackInfo<Value>& info);
2442 typedef void (*AccessorSetterCallback)(
2443 Local<String> property,
2445 const PropertyCallbackInfo<void>& info);
2446 typedef void (*AccessorNameSetterCallback)(
2447 Local<Name> property,
2449 const PropertyCallbackInfo<void>& info);
2453 * Access control specifications.
2455 * Some accessors should be accessible across contexts. These
2456 * accessors have an explicit access control parameter which specifies
2457 * the kind of cross-context access that should be allowed.
2459 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2461 enum AccessControl {
2464 ALL_CAN_WRITE = 1 << 1,
2465 PROHIBITS_OVERWRITING = 1 << 2
2470 * A JavaScript object (ECMA-262, 4.3.3)
2472 class V8_EXPORT Object : public Value {
2474 bool Set(Handle<Value> key, Handle<Value> value);
2476 bool Set(uint32_t index, Handle<Value> value);
2478 // Sets an own property on this object bypassing interceptors and
2479 // overriding accessors or read-only properties.
2481 // Note that if the object has an interceptor the property will be set
2482 // locally, but since the interceptor takes precedence the local property
2483 // will only be returned if the interceptor doesn't return a value.
2485 // Note also that this only works for named properties.
2486 bool ForceSet(Handle<Value> key,
2487 Handle<Value> value,
2488 PropertyAttribute attribs = None);
2490 Local<Value> Get(Handle<Value> key);
2492 Local<Value> Get(uint32_t index);
2495 * Gets the property attributes of a property which can be None or
2496 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2497 * None when the property doesn't exist.
2499 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2502 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2504 Local<Value> GetOwnPropertyDescriptor(Local<String> key);
2506 bool Has(Handle<Value> key);
2508 bool Delete(Handle<Value> key);
2510 bool Has(uint32_t index);
2512 bool Delete(uint32_t index);
2514 bool SetAccessor(Handle<String> name,
2515 AccessorGetterCallback getter,
2516 AccessorSetterCallback setter = 0,
2517 Handle<Value> data = Handle<Value>(),
2518 AccessControl settings = DEFAULT,
2519 PropertyAttribute attribute = None);
2520 bool SetAccessor(Handle<Name> name,
2521 AccessorNameGetterCallback getter,
2522 AccessorNameSetterCallback setter = 0,
2523 Handle<Value> data = Handle<Value>(),
2524 AccessControl settings = DEFAULT,
2525 PropertyAttribute attribute = None);
2527 void SetAccessorProperty(Local<Name> name,
2528 Local<Function> getter,
2529 Handle<Function> setter = Handle<Function>(),
2530 PropertyAttribute attribute = None,
2531 AccessControl settings = DEFAULT);
2534 * Functionality for private properties.
2535 * This is an experimental feature, use at your own risk.
2536 * Note: Private properties are inherited. Do not rely on this, since it may
2539 bool HasPrivate(Handle<Private> key);
2540 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2541 bool DeletePrivate(Handle<Private> key);
2542 Local<Value> GetPrivate(Handle<Private> key);
2545 * Returns an array containing the names of the enumerable properties
2546 * of this object, including properties from prototype objects. The
2547 * array returned by this method contains the same values as would
2548 * be enumerated by a for-in statement over this object.
2550 Local<Array> GetPropertyNames();
2553 * This function has the same functionality as GetPropertyNames but
2554 * the returned array doesn't contain the names of properties from
2555 * prototype objects.
2557 Local<Array> GetOwnPropertyNames();
2560 * Get the prototype object. This does not skip objects marked to
2561 * be skipped by __proto__ and it does not consult the security
2564 Local<Value> GetPrototype();
2567 * Set the prototype object. This does not skip objects marked to
2568 * be skipped by __proto__ and it does not consult the security
2571 bool SetPrototype(Handle<Value> prototype);
2574 * Finds an instance of the given function template in the prototype
2577 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2580 * Call builtin Object.prototype.toString on this object.
2581 * This is different from Value::ToString() that may call
2582 * user-defined toString function. This one does not.
2584 Local<String> ObjectProtoToString();
2587 * Returns the name of the function invoked as a constructor for this object.
2589 Local<String> GetConstructorName();
2591 /** Gets the number of internal fields for this Object. */
2592 int InternalFieldCount();
2594 /** Same as above, but works for Persistents */
2595 V8_INLINE static int InternalFieldCount(
2596 const PersistentBase<Object>& object) {
2597 return object.val_->InternalFieldCount();
2600 /** Gets the value from an internal field. */
2601 V8_INLINE Local<Value> GetInternalField(int index);
2603 /** Sets the value in an internal field. */
2604 void SetInternalField(int index, Handle<Value> value);
2607 * Gets a 2-byte-aligned native pointer from an internal field. This field
2608 * must have been set by SetAlignedPointerInInternalField, everything else
2609 * leads to undefined behavior.
2611 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2613 /** Same as above, but works for Persistents */
2614 V8_INLINE static void* GetAlignedPointerFromInternalField(
2615 const PersistentBase<Object>& object, int index) {
2616 return object.val_->GetAlignedPointerFromInternalField(index);
2620 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2621 * a field, GetAlignedPointerFromInternalField must be used, everything else
2622 * leads to undefined behavior.
2624 void SetAlignedPointerInInternalField(int index, void* value);
2626 // Testers for local properties.
2627 bool HasOwnProperty(Handle<String> key);
2628 bool HasRealNamedProperty(Handle<String> key);
2629 bool HasRealIndexedProperty(uint32_t index);
2630 bool HasRealNamedCallbackProperty(Handle<String> key);
2633 * If result.IsEmpty() no real property was located in the prototype chain.
2634 * This means interceptors in the prototype chain are not called.
2636 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2639 * If result.IsEmpty() no real property was located on the object or
2640 * in the prototype chain.
2641 * This means interceptors in the prototype chain are not called.
2643 Local<Value> GetRealNamedProperty(Handle<String> key);
2645 /** Tests for a named lookup interceptor.*/
2646 bool HasNamedLookupInterceptor();
2648 /** Tests for an index lookup interceptor.*/
2649 bool HasIndexedLookupInterceptor();
2652 * Turns on access check on the object if the object is an instance of
2653 * a template that has access check callbacks. If an object has no
2654 * access check info, the object cannot be accessed by anyone.
2656 void TurnOnAccessCheck();
2659 * Returns the identity hash for this object. The current implementation
2660 * uses a hidden property on the object to store the identity hash.
2662 * The return value will never be 0. Also, it is not guaranteed to be
2665 int GetIdentityHash();
2668 * Access hidden properties on JavaScript objects. These properties are
2669 * hidden from the executing JavaScript and only accessible through the V8
2670 * C++ API. Hidden properties introduced by V8 internally (for example the
2671 * identity hash) are prefixed with "v8::".
2673 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2674 Local<Value> GetHiddenValue(Handle<String> key);
2675 bool DeleteHiddenValue(Handle<String> key);
2678 * Clone this object with a fast but shallow copy. Values will point
2679 * to the same values as the original object.
2681 Local<Object> Clone();
2684 * Returns the context in which the object was created.
2686 Local<Context> CreationContext();
2689 * Set the backing store of the indexed properties to be managed by the
2690 * embedding layer. Access to the indexed properties will follow the rules
2691 * spelled out in CanvasPixelArray.
2692 * Note: The embedding program still owns the data and needs to ensure that
2693 * the backing store is preserved while V8 has a reference.
2695 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2696 bool HasIndexedPropertiesInPixelData();
2697 uint8_t* GetIndexedPropertiesPixelData();
2698 int GetIndexedPropertiesPixelDataLength();
2701 * Set the backing store of the indexed properties to be managed by the
2702 * embedding layer. Access to the indexed properties will follow the rules
2703 * spelled out for the CanvasArray subtypes in the WebGL specification.
2704 * Note: The embedding program still owns the data and needs to ensure that
2705 * the backing store is preserved while V8 has a reference.
2707 void SetIndexedPropertiesToExternalArrayData(void* data,
2708 ExternalArrayType array_type,
2709 int number_of_elements);
2710 bool HasIndexedPropertiesInExternalArrayData();
2711 void* GetIndexedPropertiesExternalArrayData();
2712 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2713 int GetIndexedPropertiesExternalArrayDataLength();
2716 * Checks whether a callback is set by the
2717 * ObjectTemplate::SetCallAsFunctionHandler method.
2718 * When an Object is callable this method returns true.
2723 * Call an Object as a function if a callback is set by the
2724 * ObjectTemplate::SetCallAsFunctionHandler method.
2726 Local<Value> CallAsFunction(Handle<Value> recv,
2728 Handle<Value> argv[]);
2731 * Call an Object as a constructor if a callback is set by the
2732 * ObjectTemplate::SetCallAsFunctionHandler method.
2733 * Note: This method behaves like the Function::NewInstance method.
2735 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2738 * Return the isolate to which the Object belongs to.
2740 Isolate* GetIsolate();
2742 static Local<Object> New(Isolate* isolate);
2744 V8_INLINE static Object* Cast(Value* obj);
2748 static void CheckCast(Value* obj);
2749 Local<Value> SlowGetInternalField(int index);
2750 void* SlowGetAlignedPointerFromInternalField(int index);
2755 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2757 class V8_EXPORT Array : public Object {
2759 uint32_t Length() const;
2762 * Clones an element at index |index|. Returns an empty
2763 * handle if cloning fails (for any reason).
2765 Local<Object> CloneElementAt(uint32_t index);
2768 * Creates a JavaScript array with the given length. If the length
2769 * is negative the returned array will have length 0.
2771 static Local<Array> New(Isolate* isolate, int length = 0);
2773 V8_INLINE static Array* Cast(Value* obj);
2776 static void CheckCast(Value* obj);
2780 template<typename T>
2783 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2784 : value_(that.value_) {
2788 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2789 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2790 // Fast primitive setters
2791 V8_INLINE void Set(bool value);
2792 V8_INLINE void Set(double i);
2793 V8_INLINE void Set(int32_t i);
2794 V8_INLINE void Set(uint32_t i);
2795 // Fast JS primitive setters
2796 V8_INLINE void SetNull();
2797 V8_INLINE void SetUndefined();
2798 V8_INLINE void SetEmptyString();
2799 // Convenience getter for Isolate
2800 V8_INLINE Isolate* GetIsolate();
2802 // Pointer setter: Uncompilable to prevent inadvertent misuse.
2803 template <typename S>
2804 V8_INLINE void Set(S* whatever);
2807 template<class F> friend class ReturnValue;
2808 template<class F> friend class FunctionCallbackInfo;
2809 template<class F> friend class PropertyCallbackInfo;
2810 template <class F, class G, class H>
2811 friend class PersistentValueMapBase;
2812 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2813 V8_INLINE internal::Object* GetDefaultValue();
2814 V8_INLINE explicit ReturnValue(internal::Object** slot);
2815 internal::Object** value_;
2820 * The argument information given to function call callbacks. This
2821 * class provides access to information about the context of the call,
2822 * including the receiver, the number and values of arguments, and
2823 * the holder of the function.
2825 template<typename T>
2826 class FunctionCallbackInfo {
2828 V8_INLINE int Length() const;
2829 V8_INLINE Local<Value> operator[](int i) const;
2830 V8_INLINE Local<Function> Callee() const;
2831 V8_INLINE Local<Object> This() const;
2832 V8_INLINE Local<Object> Holder() const;
2833 V8_INLINE bool IsConstructCall() const;
2834 V8_INLINE Local<Value> Data() const;
2835 V8_INLINE Isolate* GetIsolate() const;
2836 V8_INLINE ReturnValue<T> GetReturnValue() const;
2837 // This shouldn't be public, but the arm compiler needs it.
2838 static const int kArgsLength = 7;
2841 friend class internal::FunctionCallbackArguments;
2842 friend class internal::CustomArguments<FunctionCallbackInfo>;
2843 static const int kHolderIndex = 0;
2844 static const int kIsolateIndex = 1;
2845 static const int kReturnValueDefaultValueIndex = 2;
2846 static const int kReturnValueIndex = 3;
2847 static const int kDataIndex = 4;
2848 static const int kCalleeIndex = 5;
2849 static const int kContextSaveIndex = 6;
2851 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2852 internal::Object** values,
2854 bool is_construct_call);
2855 internal::Object** implicit_args_;
2856 internal::Object** values_;
2858 int is_construct_call_;
2863 * The information passed to a property callback about the context
2864 * of the property access.
2866 template<typename T>
2867 class PropertyCallbackInfo {
2869 V8_INLINE Isolate* GetIsolate() const;
2870 V8_INLINE Local<Value> Data() const;
2871 V8_INLINE Local<Object> This() const;
2872 V8_INLINE Local<Object> Holder() const;
2873 V8_INLINE ReturnValue<T> GetReturnValue() const;
2874 // This shouldn't be public, but the arm compiler needs it.
2875 static const int kArgsLength = 6;
2878 friend class MacroAssembler;
2879 friend class internal::PropertyCallbackArguments;
2880 friend class internal::CustomArguments<PropertyCallbackInfo>;
2881 static const int kHolderIndex = 0;
2882 static const int kIsolateIndex = 1;
2883 static const int kReturnValueDefaultValueIndex = 2;
2884 static const int kReturnValueIndex = 3;
2885 static const int kDataIndex = 4;
2886 static const int kThisIndex = 5;
2888 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2889 internal::Object** args_;
2893 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2897 * A JavaScript function object (ECMA-262, 15.3).
2899 class V8_EXPORT Function : public Object {
2902 * Create a function in the current execution context
2903 * for a given FunctionCallback.
2905 static Local<Function> New(Isolate* isolate,
2906 FunctionCallback callback,
2907 Local<Value> data = Local<Value>(),
2910 Local<Object> NewInstance() const;
2911 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2912 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2913 void SetName(Handle<String> name);
2914 Handle<Value> GetName() const;
2917 * Name inferred from variable or property assignment of this function.
2918 * Used to facilitate debugging and profiling of JavaScript code written
2919 * in an OO style, where many functions are anonymous but are assigned
2920 * to object properties.
2922 Handle<Value> GetInferredName() const;
2925 * User-defined name assigned to the "displayName" property of this function.
2926 * Used to facilitate debugging and profiling of JavaScript code.
2928 Handle<Value> GetDisplayName() const;
2931 * Returns zero based line number of function body and
2932 * kLineOffsetNotFound if no information available.
2934 int GetScriptLineNumber() const;
2936 * Returns zero based column number of function body and
2937 * kLineOffsetNotFound if no information available.
2939 int GetScriptColumnNumber() const;
2942 * Tells whether this function is builtin.
2944 bool IsBuiltin() const;
2949 int ScriptId() const;
2952 * Returns the original function if this function is bound, else returns
2955 Local<Value> GetBoundFunction() const;
2957 ScriptOrigin GetScriptOrigin() const;
2958 V8_INLINE static Function* Cast(Value* obj);
2959 static const int kLineOffsetNotFound;
2963 static void CheckCast(Value* obj);
2968 * An instance of the built-in Promise constructor (ES6 draft).
2969 * This API is experimental. Only works with --harmony flag.
2971 class V8_EXPORT Promise : public Object {
2973 class V8_EXPORT Resolver : public Object {
2976 * Create a new resolver, along with an associated promise in pending state.
2978 static Local<Resolver> New(Isolate* isolate);
2981 * Extract the associated promise.
2983 Local<Promise> GetPromise();
2986 * Resolve/reject the associated promise with a given value.
2987 * Ignored if the promise is no longer pending.
2989 void Resolve(Handle<Value> value);
2990 void Reject(Handle<Value> value);
2992 V8_INLINE static Resolver* Cast(Value* obj);
2996 static void CheckCast(Value* obj);
3000 * Register a resolution/rejection handler with a promise.
3001 * The handler is given the respective resolution/rejection value as
3002 * an argument. If the promise is already resolved/rejected, the handler is
3003 * invoked at the end of turn.
3005 Local<Promise> Chain(Handle<Function> handler);
3006 Local<Promise> Catch(Handle<Function> handler);
3007 Local<Promise> Then(Handle<Function> handler);
3010 * Returns true if the promise has at least one derived promise, and
3011 * therefore resolve/reject handlers (including default handler).
3015 V8_INLINE static Promise* Cast(Value* obj);
3019 static void CheckCast(Value* obj);
3023 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3024 // The number of required internal fields can be defined by embedder.
3025 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3029 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3030 * This API is experimental and may change significantly.
3032 class V8_EXPORT ArrayBuffer : public Object {
3035 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3036 * The allocator is a global V8 setting. It should be set with
3037 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
3039 * This API is experimental and may change significantly.
3041 class V8_EXPORT Allocator { // NOLINT
3043 virtual ~Allocator() {}
3046 * Allocate |length| bytes. Return NULL if allocation is not successful.
3047 * Memory should be initialized to zeroes.
3049 virtual void* Allocate(size_t length) = 0;
3052 * Allocate |length| bytes. Return NULL if allocation is not successful.
3053 * Memory does not have to be initialized.
3055 virtual void* AllocateUninitialized(size_t length) = 0;
3057 * Free the memory block of size |length|, pointed to by |data|.
3058 * That memory is guaranteed to be previously allocated by |Allocate|.
3060 virtual void Free(void* data, size_t length) = 0;
3064 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3065 * returns an instance of this class, populated, with a pointer to data
3068 * The Data pointer of ArrayBuffer::Contents is always allocated with
3069 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
3071 * This API is experimental and may change significantly.
3073 class V8_EXPORT Contents { // NOLINT
3075 Contents() : data_(NULL), byte_length_(0) {}
3077 void* Data() const { return data_; }
3078 size_t ByteLength() const { return byte_length_; }
3082 size_t byte_length_;
3084 friend class ArrayBuffer;
3089 * Data length in bytes.
3091 size_t ByteLength() const;
3094 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3095 * Allocated memory will be owned by a created ArrayBuffer and
3096 * will be deallocated when it is garbage-collected,
3097 * unless the object is externalized.
3099 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3102 * Create a new ArrayBuffer over an existing memory block.
3103 * The created array buffer is immediately in externalized state.
3104 * The memory block will not be reclaimed when a created ArrayBuffer
3105 * is garbage-collected.
3107 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
3108 size_t byte_length);
3111 * Returns true if ArrayBuffer is extrenalized, that is, does not
3112 * own its memory block.
3114 bool IsExternal() const;
3117 * Returns true if this ArrayBuffer may be neutered.
3119 bool IsNeuterable() const;
3122 * Neuters this ArrayBuffer and all its views (typed arrays).
3123 * Neutering sets the byte length of the buffer and all typed arrays to zero,
3124 * preventing JavaScript from ever accessing underlying backing store.
3125 * ArrayBuffer should have been externalized and must be neuterable.
3130 * Make this ArrayBuffer external. The pointer to underlying memory block
3131 * and byte length are returned as |Contents| structure. After ArrayBuffer
3132 * had been etxrenalized, it does no longer owns the memory block. The caller
3133 * should take steps to free memory when it is no longer needed.
3135 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3136 * that has been set with V8::SetArrayBufferAllocator.
3138 Contents Externalize();
3140 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3142 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3146 static void CheckCast(Value* obj);
3150 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3151 // The number of required internal fields can be defined by embedder.
3152 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3157 * A base class for an instance of one of "views" over ArrayBuffer,
3158 * including TypedArrays and DataView (ES6 draft 15.13).
3160 * This API is experimental and may change significantly.
3162 class V8_EXPORT ArrayBufferView : public Object {
3165 * Returns underlying ArrayBuffer.
3167 Local<ArrayBuffer> Buffer();
3169 * Byte offset in |Buffer|.
3171 size_t ByteOffset();
3173 * Size of a view in bytes.
3175 size_t ByteLength();
3177 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3179 static const int kInternalFieldCount =
3180 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3184 static void CheckCast(Value* obj);
3189 * A base class for an instance of TypedArray series of constructors
3190 * (ES6 draft 15.13.6).
3191 * This API is experimental and may change significantly.
3193 class V8_EXPORT TypedArray : public ArrayBufferView {
3196 * Number of elements in this typed array
3197 * (e.g. for Int16Array, |ByteLength|/2).
3201 V8_INLINE static TypedArray* Cast(Value* obj);
3205 static void CheckCast(Value* obj);
3210 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3211 * This API is experimental and may change significantly.
3213 class V8_EXPORT Uint8Array : public TypedArray {
3215 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
3216 size_t byte_offset, size_t length);
3217 V8_INLINE static Uint8Array* Cast(Value* obj);
3221 static void CheckCast(Value* obj);
3226 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3227 * This API is experimental and may change significantly.
3229 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3231 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
3232 size_t byte_offset, size_t length);
3233 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3236 Uint8ClampedArray();
3237 static void CheckCast(Value* obj);
3241 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3242 * This API is experimental and may change significantly.
3244 class V8_EXPORT Int8Array : public TypedArray {
3246 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
3247 size_t byte_offset, size_t length);
3248 V8_INLINE static Int8Array* Cast(Value* obj);
3252 static void CheckCast(Value* obj);
3257 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3258 * This API is experimental and may change significantly.
3260 class V8_EXPORT Uint16Array : public TypedArray {
3262 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
3263 size_t byte_offset, size_t length);
3264 V8_INLINE static Uint16Array* Cast(Value* obj);
3268 static void CheckCast(Value* obj);
3273 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3274 * This API is experimental and may change significantly.
3276 class V8_EXPORT Int16Array : public TypedArray {
3278 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
3279 size_t byte_offset, size_t length);
3280 V8_INLINE static Int16Array* Cast(Value* obj);
3284 static void CheckCast(Value* obj);
3289 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3290 * This API is experimental and may change significantly.
3292 class V8_EXPORT Uint32Array : public TypedArray {
3294 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
3295 size_t byte_offset, size_t length);
3296 V8_INLINE static Uint32Array* Cast(Value* obj);
3300 static void CheckCast(Value* obj);
3305 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3306 * This API is experimental and may change significantly.
3308 class V8_EXPORT Int32Array : public TypedArray {
3310 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
3311 size_t byte_offset, size_t length);
3312 V8_INLINE static Int32Array* Cast(Value* obj);
3316 static void CheckCast(Value* obj);
3321 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3322 * This API is experimental and may change significantly.
3324 class V8_EXPORT Float32Array : public TypedArray {
3326 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
3327 size_t byte_offset, size_t length);
3328 V8_INLINE static Float32Array* Cast(Value* obj);
3332 static void CheckCast(Value* obj);
3337 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3338 * This API is experimental and may change significantly.
3340 class V8_EXPORT Float64Array : public TypedArray {
3342 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3343 size_t byte_offset, size_t length);
3344 V8_INLINE static Float64Array* Cast(Value* obj);
3348 static void CheckCast(Value* obj);
3353 * An instance of DataView constructor (ES6 draft 15.13.7).
3354 * This API is experimental and may change significantly.
3356 class V8_EXPORT DataView : public ArrayBufferView {
3358 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3359 size_t byte_offset, size_t length);
3360 V8_INLINE static DataView* Cast(Value* obj);
3364 static void CheckCast(Value* obj);
3369 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3371 class V8_EXPORT Date : public Object {
3373 static Local<Value> New(Isolate* isolate, double time);
3376 * A specialization of Value::NumberValue that is more efficient
3377 * because we know the structure of this object.
3379 double ValueOf() const;
3381 V8_INLINE static Date* Cast(v8::Value* obj);
3384 * Notification that the embedder has changed the time zone,
3385 * daylight savings time, or other date / time configuration
3386 * parameters. V8 keeps a cache of various values used for
3387 * date / time computation. This notification will reset
3388 * those cached values for the current context so that date /
3389 * time configuration changes would be reflected in the Date
3392 * This API should not be called more than needed as it will
3393 * negatively impact the performance of date operations.
3395 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3398 static void CheckCast(v8::Value* obj);
3403 * A Number object (ECMA-262, 4.3.21).
3405 class V8_EXPORT NumberObject : public Object {
3407 static Local<Value> New(Isolate* isolate, double value);
3409 double ValueOf() const;
3411 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3414 static void CheckCast(v8::Value* obj);
3419 * A Boolean object (ECMA-262, 4.3.15).
3421 class V8_EXPORT BooleanObject : public Object {
3423 static Local<Value> New(bool value);
3425 bool ValueOf() const;
3427 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3430 static void CheckCast(v8::Value* obj);
3435 * A String object (ECMA-262, 4.3.18).
3437 class V8_EXPORT StringObject : public Object {
3439 static Local<Value> New(Handle<String> value);
3441 Local<String> ValueOf() const;
3443 V8_INLINE static StringObject* Cast(v8::Value* obj);
3446 static void CheckCast(v8::Value* obj);
3451 * A Symbol object (ECMA-262 edition 6).
3453 * This is an experimental feature. Use at your own risk.
3455 class V8_EXPORT SymbolObject : public Object {
3457 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3459 Local<Symbol> ValueOf() const;
3461 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3464 static void CheckCast(v8::Value* obj);
3469 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3471 class V8_EXPORT RegExp : public Object {
3474 * Regular expression flag bits. They can be or'ed to enable a set
3485 * Creates a regular expression from the given pattern string and
3486 * the flags bit field. May throw a JavaScript exception as
3487 * described in ECMA-262, 15.10.4.1.
3490 * RegExp::New(v8::String::New("foo"),
3491 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3492 * is equivalent to evaluating "/foo/gm".
3494 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3497 * Returns the value of the source property: a string representing
3498 * the regular expression.
3500 Local<String> GetSource() const;
3503 * Returns the flags bit field.
3505 Flags GetFlags() const;
3507 V8_INLINE static RegExp* Cast(v8::Value* obj);
3510 static void CheckCast(v8::Value* obj);
3515 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3516 * to associate C++ data structures with JavaScript objects.
3518 class V8_EXPORT External : public Value {
3520 static Local<External> New(Isolate* isolate, void* value);
3521 V8_INLINE static External* Cast(Value* obj);
3522 void* Value() const;
3524 static void CheckCast(v8::Value* obj);
3528 // --- Templates ---
3532 * The superclass of object and function templates.
3534 class V8_EXPORT Template : public Data {
3536 /** Adds a property to each instance created by this template.*/
3537 void Set(Handle<Name> name, Handle<Data> value,
3538 PropertyAttribute attributes = None);
3539 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3541 void SetAccessorProperty(
3543 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3544 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3545 PropertyAttribute attribute = None,
3546 AccessControl settings = DEFAULT);
3549 * Whenever the property with the given name is accessed on objects
3550 * created from this Template the getter and setter callbacks
3551 * are called instead of getting and setting the property directly
3552 * on the JavaScript object.
3554 * \param name The name of the property for which an accessor is added.
3555 * \param getter The callback to invoke when getting the property.
3556 * \param setter The callback to invoke when setting the property.
3557 * \param data A piece of data that will be passed to the getter and setter
3558 * callbacks whenever they are invoked.
3559 * \param settings Access control settings for the accessor. This is a bit
3560 * field consisting of one of more of
3561 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3562 * The default is to not allow cross-context access.
3563 * ALL_CAN_READ means that all cross-context reads are allowed.
3564 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3565 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3566 * cross-context access.
3567 * \param attribute The attributes of the property for which an accessor
3569 * \param signature The signature describes valid receivers for the accessor
3570 * and is used to perform implicit instance checks against them. If the
3571 * receiver is incompatible (i.e. is not an instance of the constructor as
3572 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3573 * thrown and no callback is invoked.
3575 void SetNativeDataProperty(Local<String> name,
3576 AccessorGetterCallback getter,
3577 AccessorSetterCallback setter = 0,
3578 // TODO(dcarney): gcc can't handle Local below
3579 Handle<Value> data = Handle<Value>(),
3580 PropertyAttribute attribute = None,
3581 Local<AccessorSignature> signature =
3582 Local<AccessorSignature>(),
3583 AccessControl settings = DEFAULT);
3584 void SetNativeDataProperty(Local<Name> name,
3585 AccessorNameGetterCallback getter,
3586 AccessorNameSetterCallback setter = 0,
3587 // TODO(dcarney): gcc can't handle Local below
3588 Handle<Value> data = Handle<Value>(),
3589 PropertyAttribute attribute = None,
3590 Local<AccessorSignature> signature =
3591 Local<AccessorSignature>(),
3592 AccessControl settings = DEFAULT);
3597 friend class ObjectTemplate;
3598 friend class FunctionTemplate;
3603 * NamedProperty[Getter|Setter] are used as interceptors on object.
3604 * See ObjectTemplate::SetNamedPropertyHandler.
3606 typedef void (*NamedPropertyGetterCallback)(
3607 Local<String> property,
3608 const PropertyCallbackInfo<Value>& info);
3612 * Returns the value if the setter intercepts the request.
3613 * Otherwise, returns an empty handle.
3615 typedef void (*NamedPropertySetterCallback)(
3616 Local<String> property,
3618 const PropertyCallbackInfo<Value>& info);
3622 * Returns a non-empty handle if the interceptor intercepts the request.
3623 * The result is an integer encoding property attributes (like v8::None,
3624 * v8::DontEnum, etc.)
3626 typedef void (*NamedPropertyQueryCallback)(
3627 Local<String> property,
3628 const PropertyCallbackInfo<Integer>& info);
3632 * Returns a non-empty handle if the deleter intercepts the request.
3633 * The return value is true if the property could be deleted and false
3636 typedef void (*NamedPropertyDeleterCallback)(
3637 Local<String> property,
3638 const PropertyCallbackInfo<Boolean>& info);
3642 * Returns an array containing the names of the properties the named
3643 * property getter intercepts.
3645 typedef void (*NamedPropertyEnumeratorCallback)(
3646 const PropertyCallbackInfo<Array>& info);
3649 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
3650 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
3652 * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
3653 * See ObjectTemplate::SetNamedPropertyHandler.
3655 typedef void (*GenericNamedPropertyGetterCallback)(
3656 Local<Name> property, const PropertyCallbackInfo<Value>& info);
3660 * Returns the value if the setter intercepts the request.
3661 * Otherwise, returns an empty handle.
3663 typedef void (*GenericNamedPropertySetterCallback)(
3664 Local<Name> property, Local<Value> value,
3665 const PropertyCallbackInfo<Value>& info);
3669 * Returns a non-empty handle if the interceptor intercepts the request.
3670 * The result is an integer encoding property attributes (like v8::None,
3671 * v8::DontEnum, etc.)
3673 typedef void (*GenericNamedPropertyQueryCallback)(
3674 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
3678 * Returns a non-empty handle if the deleter intercepts the request.
3679 * The return value is true if the property could be deleted and false
3682 typedef void (*GenericNamedPropertyDeleterCallback)(
3683 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
3687 * Returns an array containing the names of the properties the named
3688 * property getter intercepts.
3690 typedef void (*GenericNamedPropertyEnumeratorCallback)(
3691 const PropertyCallbackInfo<Array>& info);
3695 * Returns the value of the property if the getter intercepts the
3696 * request. Otherwise, returns an empty handle.
3698 typedef void (*IndexedPropertyGetterCallback)(
3700 const PropertyCallbackInfo<Value>& info);
3704 * Returns the value if the setter intercepts the request.
3705 * Otherwise, returns an empty handle.
3707 typedef void (*IndexedPropertySetterCallback)(
3710 const PropertyCallbackInfo<Value>& info);
3714 * Returns a non-empty handle if the interceptor intercepts the request.
3715 * The result is an integer encoding property attributes.
3717 typedef void (*IndexedPropertyQueryCallback)(
3719 const PropertyCallbackInfo<Integer>& info);
3723 * Returns a non-empty handle if the deleter intercepts the request.
3724 * The return value is true if the property could be deleted and false
3727 typedef void (*IndexedPropertyDeleterCallback)(
3729 const PropertyCallbackInfo<Boolean>& info);
3733 * Returns an array containing the indices of the properties the
3734 * indexed property getter intercepts.
3736 typedef void (*IndexedPropertyEnumeratorCallback)(
3737 const PropertyCallbackInfo<Array>& info);
3741 * Access type specification.
3753 * Returns true if cross-context access should be allowed to the named
3754 * property with the given key on the host object.
3756 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3763 * Returns true if cross-context access should be allowed to the indexed
3764 * property with the given index on the host object.
3766 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3773 * A FunctionTemplate is used to create functions at runtime. There
3774 * can only be one function created from a FunctionTemplate in a
3775 * context. The lifetime of the created function is equal to the
3776 * lifetime of the context. So in case the embedder needs to create
3777 * temporary functions that can be collected using Scripts is
3780 * Any modification of a FunctionTemplate after first instantiation will trigger
3783 * A FunctionTemplate can have properties, these properties are added to the
3784 * function object when it is created.
3786 * A FunctionTemplate has a corresponding instance template which is
3787 * used to create object instances when the function is used as a
3788 * constructor. Properties added to the instance template are added to
3789 * each object instance.
3791 * A FunctionTemplate can have a prototype template. The prototype template
3792 * is used to create the prototype object of the function.
3794 * The following example shows how to use a FunctionTemplate:
3797 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3798 * t->Set("func_property", v8::Number::New(1));
3800 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3801 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3802 * proto_t->Set("proto_const", v8::Number::New(2));
3804 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3805 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3806 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3807 * instance_t->Set("instance_property", Number::New(3));
3809 * v8::Local<v8::Function> function = t->GetFunction();
3810 * v8::Local<v8::Object> instance = function->NewInstance();
3813 * Let's use "function" as the JS variable name of the function object
3814 * and "instance" for the instance object created above. The function
3815 * and the instance will have the following properties:
3818 * func_property in function == true;
3819 * function.func_property == 1;
3821 * function.prototype.proto_method() invokes 'InvokeCallback'
3822 * function.prototype.proto_const == 2;
3824 * instance instanceof function == true;
3825 * instance.instance_accessor calls 'InstanceAccessorCallback'
3826 * instance.instance_property == 3;
3829 * A FunctionTemplate can inherit from another one by calling the
3830 * FunctionTemplate::Inherit method. The following graph illustrates
3831 * the semantics of inheritance:
3834 * FunctionTemplate Parent -> Parent() . prototype -> { }
3836 * | Inherit(Parent) | .__proto__
3838 * FunctionTemplate Child -> Child() . prototype -> { }
3841 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3842 * object of the Child() function has __proto__ pointing to the
3843 * Parent() function's prototype object. An instance of the Child
3844 * function has all properties on Parent's instance templates.
3846 * Let Parent be the FunctionTemplate initialized in the previous
3847 * section and create a Child FunctionTemplate by:
3850 * Local<FunctionTemplate> parent = t;
3851 * Local<FunctionTemplate> child = FunctionTemplate::New();
3852 * child->Inherit(parent);
3854 * Local<Function> child_function = child->GetFunction();
3855 * Local<Object> child_instance = child_function->NewInstance();
3858 * The Child function and Child instance will have the following
3862 * child_func.prototype.__proto__ == function.prototype;
3863 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3864 * child_instance.instance_property == 3;
3867 class V8_EXPORT FunctionTemplate : public Template {
3869 /** Creates a function template.*/
3870 static Local<FunctionTemplate> New(
3872 FunctionCallback callback = 0,
3873 Handle<Value> data = Handle<Value>(),
3874 Handle<Signature> signature = Handle<Signature>(),
3877 /** Returns the unique function instance in the current execution context.*/
3878 Local<Function> GetFunction();
3881 * Set the call-handler callback for a FunctionTemplate. This
3882 * callback is called whenever the function created from this
3883 * FunctionTemplate is called.
3885 void SetCallHandler(FunctionCallback callback,
3886 Handle<Value> data = Handle<Value>());
3888 /** Set the predefined length property for the FunctionTemplate. */
3889 void SetLength(int length);
3891 /** Get the InstanceTemplate. */
3892 Local<ObjectTemplate> InstanceTemplate();
3894 /** Causes the function template to inherit from a parent function template.*/
3895 void Inherit(Handle<FunctionTemplate> parent);
3898 * A PrototypeTemplate is the template used to create the prototype object
3899 * of the function created by this template.
3901 Local<ObjectTemplate> PrototypeTemplate();
3904 * Set the class name of the FunctionTemplate. This is used for
3905 * printing objects created with the function created from the
3906 * FunctionTemplate as its constructor.
3908 void SetClassName(Handle<String> name);
3911 * Determines whether the __proto__ accessor ignores instances of
3912 * the function template. If instances of the function template are
3913 * ignored, __proto__ skips all instances and instead returns the
3914 * next object in the prototype chain.
3916 * Call with a value of true to make the __proto__ accessor ignore
3917 * instances of the function template. Call with a value of false
3918 * to make the __proto__ accessor not ignore instances of the
3919 * function template. By default, instances of a function template
3922 void SetHiddenPrototype(bool value);
3925 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3926 * of functions created from this FunctionTemplate to true.
3928 void ReadOnlyPrototype();
3931 * Removes the prototype property from functions created from this
3934 void RemovePrototype();
3937 * Returns true if the given object is an instance of this function
3940 bool HasInstance(Handle<Value> object);
3944 friend class Context;
3945 friend class ObjectTemplate;
3949 enum class PropertyHandlerFlags { kNone = 0, kAllCanRead = 1 };
3952 struct NamedPropertyHandlerConfiguration {
3953 NamedPropertyHandlerConfiguration(
3954 /** Note: getter is required **/
3955 GenericNamedPropertyGetterCallback getter = 0,
3956 GenericNamedPropertySetterCallback setter = 0,
3957 GenericNamedPropertyQueryCallback query = 0,
3958 GenericNamedPropertyDeleterCallback deleter = 0,
3959 GenericNamedPropertyEnumeratorCallback enumerator = 0,
3960 Handle<Value> data = Handle<Value>(),
3961 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
3966 enumerator(enumerator),
3970 GenericNamedPropertyGetterCallback getter;
3971 GenericNamedPropertySetterCallback setter;
3972 GenericNamedPropertyQueryCallback query;
3973 GenericNamedPropertyDeleterCallback deleter;
3974 GenericNamedPropertyEnumeratorCallback enumerator;
3976 PropertyHandlerFlags flags;
3980 struct IndexedPropertyHandlerConfiguration {
3981 IndexedPropertyHandlerConfiguration(
3982 /** Note: getter is required **/
3983 IndexedPropertyGetterCallback getter = 0,
3984 IndexedPropertySetterCallback setter = 0,
3985 IndexedPropertyQueryCallback query = 0,
3986 IndexedPropertyDeleterCallback deleter = 0,
3987 IndexedPropertyEnumeratorCallback enumerator = 0,
3988 Handle<Value> data = Handle<Value>(),
3989 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
3994 enumerator(enumerator),
3998 IndexedPropertyGetterCallback getter;
3999 IndexedPropertySetterCallback setter;
4000 IndexedPropertyQueryCallback query;
4001 IndexedPropertyDeleterCallback deleter;
4002 IndexedPropertyEnumeratorCallback enumerator;
4004 PropertyHandlerFlags flags;
4009 * An ObjectTemplate is used to create objects at runtime.
4011 * Properties added to an ObjectTemplate are added to each object
4012 * created from the ObjectTemplate.
4014 class V8_EXPORT ObjectTemplate : public Template {
4016 /** Creates an ObjectTemplate. */
4017 static Local<ObjectTemplate> New(Isolate* isolate);
4018 // Will be deprecated soon.
4019 static Local<ObjectTemplate> New();
4021 /** Creates a new instance of this template.*/
4022 Local<Object> NewInstance();
4025 * Sets an accessor on the object template.
4027 * Whenever the property with the given name is accessed on objects
4028 * created from this ObjectTemplate the getter and setter callbacks
4029 * are called instead of getting and setting the property directly
4030 * on the JavaScript object.
4032 * \param name The name of the property for which an accessor is added.
4033 * \param getter The callback to invoke when getting the property.
4034 * \param setter The callback to invoke when setting the property.
4035 * \param data A piece of data that will be passed to the getter and setter
4036 * callbacks whenever they are invoked.
4037 * \param settings Access control settings for the accessor. This is a bit
4038 * field consisting of one of more of
4039 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4040 * The default is to not allow cross-context access.
4041 * ALL_CAN_READ means that all cross-context reads are allowed.
4042 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4043 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4044 * cross-context access.
4045 * \param attribute The attributes of the property for which an accessor
4047 * \param signature The signature describes valid receivers for the accessor
4048 * and is used to perform implicit instance checks against them. If the
4049 * receiver is incompatible (i.e. is not an instance of the constructor as
4050 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4051 * thrown and no callback is invoked.
4053 void SetAccessor(Handle<String> name,
4054 AccessorGetterCallback getter,
4055 AccessorSetterCallback setter = 0,
4056 Handle<Value> data = Handle<Value>(),
4057 AccessControl settings = DEFAULT,
4058 PropertyAttribute attribute = None,
4059 Handle<AccessorSignature> signature =
4060 Handle<AccessorSignature>());
4061 void SetAccessor(Handle<Name> name,
4062 AccessorNameGetterCallback getter,
4063 AccessorNameSetterCallback setter = 0,
4064 Handle<Value> data = Handle<Value>(),
4065 AccessControl settings = DEFAULT,
4066 PropertyAttribute attribute = None,
4067 Handle<AccessorSignature> signature =
4068 Handle<AccessorSignature>());
4071 * Sets a named property handler on the object template.
4073 * Whenever a property whose name is a string is accessed on objects created
4074 * from this object template, the provided callback is invoked instead of
4075 * accessing the property directly on the JavaScript object.
4077 * Note that new code should use the second version that can intercept
4078 * symbol-named properties as well as string-named properties.
4080 * \param getter The callback to invoke when getting a property.
4081 * \param setter The callback to invoke when setting a property.
4082 * \param query The callback to invoke to check if a property is present,
4083 * and if present, get its attributes.
4084 * \param deleter The callback to invoke when deleting a property.
4085 * \param enumerator The callback to invoke to enumerate all the named
4086 * properties of an object.
4087 * \param data A piece of data that will be passed to the callbacks
4088 * whenever they are invoked.
4090 // TODO(dcarney): deprecate
4091 void SetNamedPropertyHandler(
4092 NamedPropertyGetterCallback getter,
4093 NamedPropertySetterCallback setter = 0,
4094 NamedPropertyQueryCallback query = 0,
4095 NamedPropertyDeleterCallback deleter = 0,
4096 NamedPropertyEnumeratorCallback enumerator = 0,
4097 Handle<Value> data = Handle<Value>());
4098 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4101 * Sets an indexed property handler on the object template.
4103 * Whenever an indexed property is accessed on objects created from
4104 * this object template, the provided callback is invoked instead of
4105 * accessing the property directly on the JavaScript object.
4107 * \param getter The callback to invoke when getting a property.
4108 * \param setter The callback to invoke when setting a property.
4109 * \param query The callback to invoke to check if an object has a property.
4110 * \param deleter The callback to invoke when deleting a property.
4111 * \param enumerator The callback to invoke to enumerate all the indexed
4112 * properties of an object.
4113 * \param data A piece of data that will be passed to the callbacks
4114 * whenever they are invoked.
4116 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4117 // TODO(dcarney): deprecate
4118 void SetIndexedPropertyHandler(
4119 IndexedPropertyGetterCallback getter,
4120 IndexedPropertySetterCallback setter = 0,
4121 IndexedPropertyQueryCallback query = 0,
4122 IndexedPropertyDeleterCallback deleter = 0,
4123 IndexedPropertyEnumeratorCallback enumerator = 0,
4124 Handle<Value> data = Handle<Value>()) {
4125 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4126 deleter, enumerator, data));
4129 * Sets the callback to be used when calling instances created from
4130 * this template as a function. If no callback is set, instances
4131 * behave like normal JavaScript objects that cannot be called as a
4134 void SetCallAsFunctionHandler(FunctionCallback callback,
4135 Handle<Value> data = Handle<Value>());
4138 * Mark object instances of the template as undetectable.
4140 * In many ways, undetectable objects behave as though they are not
4141 * there. They behave like 'undefined' in conditionals and when
4142 * printed. However, properties can be accessed and called as on
4145 void MarkAsUndetectable();
4148 * Sets access check callbacks on the object template.
4150 * When accessing properties on instances of this object template,
4151 * the access check callback will be called to determine whether or
4152 * not to allow cross-context access to the properties.
4153 * The last parameter specifies whether access checks are turned
4154 * on by default on instances. If access checks are off by default,
4155 * they can be turned on on individual instances by calling
4156 * Object::TurnOnAccessCheck().
4158 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4159 IndexedSecurityCallback indexed_handler,
4160 Handle<Value> data = Handle<Value>(),
4161 bool turned_on_by_default = true);
4164 * Gets the number of internal fields for objects generated from
4167 int InternalFieldCount();
4170 * Sets the number of internal fields for objects generated from
4173 void SetInternalFieldCount(int value);
4177 static Local<ObjectTemplate> New(internal::Isolate* isolate,
4178 Handle<FunctionTemplate> constructor);
4179 friend class FunctionTemplate;
4184 * A Signature specifies which receiver is valid for a function.
4186 class V8_EXPORT Signature : public Data {
4188 static Local<Signature> New(
4190 Handle<FunctionTemplate> receiver = Handle<FunctionTemplate>());
4198 * An AccessorSignature specifies which receivers are valid parameters
4199 * to an accessor callback.
4201 class V8_EXPORT AccessorSignature : public Data {
4203 static Local<AccessorSignature> New(Isolate* isolate,
4204 Handle<FunctionTemplate> receiver =
4205 Handle<FunctionTemplate>());
4208 AccessorSignature();
4213 * A utility for determining the type of objects based on the template
4214 * they were constructed from.
4216 class V8_EXPORT TypeSwitch : public Data {
4218 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
4219 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
4220 int match(Handle<Value> value);
4226 // --- Extensions ---
4228 class V8_EXPORT ExternalOneByteStringResourceImpl
4229 : public String::ExternalOneByteStringResource {
4231 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4232 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4233 : data_(data), length_(length) {}
4234 const char* data() const { return data_; }
4235 size_t length() const { return length_; }
4245 class V8_EXPORT Extension { // NOLINT
4247 // Note that the strings passed into this constructor must live as long
4248 // as the Extension itself.
4249 Extension(const char* name,
4250 const char* source = 0,
4252 const char** deps = 0,
4253 int source_length = -1);
4254 virtual ~Extension() { }
4255 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
4256 v8::Isolate* isolate, v8::Handle<v8::String> name) {
4257 return v8::Handle<v8::FunctionTemplate>();
4260 const char* name() const { return name_; }
4261 size_t source_length() const { return source_length_; }
4262 const String::ExternalOneByteStringResource* source() const {
4264 int dependency_count() { return dep_count_; }
4265 const char** dependencies() { return deps_; }
4266 void set_auto_enable(bool value) { auto_enable_ = value; }
4267 bool auto_enable() { return auto_enable_; }
4271 size_t source_length_; // expected to initialize before source_
4272 ExternalOneByteStringResourceImpl source_;
4277 // Disallow copying and assigning.
4278 Extension(const Extension&);
4279 void operator=(const Extension&);
4283 void V8_EXPORT RegisterExtension(Extension* extension);
4288 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
4289 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
4290 V8_INLINE Handle<Boolean> True(Isolate* isolate);
4291 V8_INLINE Handle<Boolean> False(Isolate* isolate);
4295 * A set of constraints that specifies the limits of the runtime's memory use.
4296 * You must set the heap size before initializing the VM - the size cannot be
4297 * adjusted after the VM is initialized.
4299 * If you are using threads then you should hold the V8::Locker lock while
4300 * setting the stack limit and you must set a non-default stack limit separately
4303 class V8_EXPORT ResourceConstraints {
4305 ResourceConstraints();
4308 * Configures the constraints with reasonable default values based on the
4309 * capabilities of the current device the VM is running on.
4311 * \param physical_memory The total amount of physical memory on the current
4313 * \param virtual_memory_limit The amount of virtual memory on the current
4314 * device, in bytes, or zero, if there is no limit.
4315 * \param number_of_processors The number of CPUs available on the current
4318 void ConfigureDefaults(uint64_t physical_memory,
4319 uint64_t virtual_memory_limit,
4320 uint32_t number_of_processors);
4322 int max_semi_space_size() const { return max_semi_space_size_; }
4323 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4324 int max_old_space_size() const { return max_old_space_size_; }
4325 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4326 int max_executable_size() const { return max_executable_size_; }
4327 void set_max_executable_size(int value) { max_executable_size_ = value; }
4328 uint32_t* stack_limit() const { return stack_limit_; }
4329 // Sets an address beyond which the VM's stack may not grow.
4330 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4331 int max_available_threads() const { return max_available_threads_; }
4332 // Set the number of threads available to V8, assuming at least 1.
4333 void set_max_available_threads(int value) {
4334 max_available_threads_ = value;
4336 size_t code_range_size() const { return code_range_size_; }
4337 void set_code_range_size(size_t value) {
4338 code_range_size_ = value;
4342 int max_semi_space_size_;
4343 int max_old_space_size_;
4344 int max_executable_size_;
4345 uint32_t* stack_limit_;
4346 int max_available_threads_;
4347 size_t code_range_size_;
4351 // --- Exceptions ---
4354 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4357 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
4361 typedef void (*LogEventCallback)(const char* name, int event);
4364 * Create new error objects by calling the corresponding error object
4365 * constructor with the message.
4367 class V8_EXPORT Exception {
4369 static Local<Value> RangeError(Handle<String> message);
4370 static Local<Value> ReferenceError(Handle<String> message);
4371 static Local<Value> SyntaxError(Handle<String> message);
4372 static Local<Value> TypeError(Handle<String> message);
4373 static Local<Value> Error(Handle<String> message);
4376 * Creates an error message for the given exception.
4377 * Will try to reconstruct the original stack trace from the exception value,
4378 * or capture the current stack trace if not available.
4380 static Local<Message> CreateMessage(Handle<Value> exception);
4383 * Returns the original stack trace that was captured at the creation time
4384 * of a given exception, or an empty handle if not available.
4386 static Local<StackTrace> GetStackTrace(Handle<Value> exception);
4390 // --- Counters Callbacks ---
4392 typedef int* (*CounterLookupCallback)(const char* name);
4394 typedef void* (*CreateHistogramCallback)(const char* name,
4399 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4401 // --- Memory Allocation Callback ---
4403 kObjectSpaceNewSpace = 1 << 0,
4404 kObjectSpaceOldPointerSpace = 1 << 1,
4405 kObjectSpaceOldDataSpace = 1 << 2,
4406 kObjectSpaceCodeSpace = 1 << 3,
4407 kObjectSpaceMapSpace = 1 << 4,
4408 kObjectSpaceCellSpace = 1 << 5,
4409 kObjectSpacePropertyCellSpace = 1 << 6,
4410 kObjectSpaceLoSpace = 1 << 7,
4411 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4412 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace |
4413 kObjectSpaceMapSpace | kObjectSpaceLoSpace
4416 enum AllocationAction {
4417 kAllocationActionAllocate = 1 << 0,
4418 kAllocationActionFree = 1 << 1,
4419 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4422 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4423 AllocationAction action,
4426 // --- Leave Script Callback ---
4427 typedef void (*CallCompletedCallback)();
4429 // --- Promise Reject Callback ---
4430 enum PromiseRejectEvent {
4431 kPromiseRejectWithNoHandler = 0,
4432 kPromiseHandlerAddedAfterReject = 1
4435 class PromiseRejectMessage {
4437 PromiseRejectMessage(Handle<Promise> promise, PromiseRejectEvent event,
4438 Handle<Value> value, Handle<StackTrace> stack_trace)
4439 : promise_(promise),
4442 stack_trace_(stack_trace) {}
4444 V8_INLINE Handle<Promise> GetPromise() const { return promise_; }
4445 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4446 V8_INLINE Handle<Value> GetValue() const { return value_; }
4448 // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4449 V8_INLINE Handle<StackTrace> GetStackTrace() const { return stack_trace_; }
4452 Handle<Promise> promise_;
4453 PromiseRejectEvent event_;
4454 Handle<Value> value_;
4455 Handle<StackTrace> stack_trace_;
4458 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4460 // --- Microtask Callback ---
4461 typedef void (*MicrotaskCallback)(void* data);
4463 // --- Failed Access Check Callback ---
4464 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4468 // --- AllowCodeGenerationFromStrings callbacks ---
4471 * Callback to check if code generation from strings is allowed. See
4472 * Context::AllowCodeGenerationFromStrings.
4474 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4476 // --- Garbage Collection Callbacks ---
4479 * Applications can register callback functions which will be called
4480 * before and after a garbage collection. Allocations are not
4481 * allowed in the callback functions, you therefore cannot manipulate
4482 * objects (set or delete properties for example) since it is possible
4483 * such operations will result in the allocation of objects.
4486 kGCTypeScavenge = 1 << 0,
4487 kGCTypeMarkSweepCompact = 1 << 1,
4488 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4491 enum GCCallbackFlags {
4492 kNoGCCallbackFlags = 0,
4493 kGCCallbackFlagCompacted = 1 << 0,
4494 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4495 kGCCallbackFlagForced = 1 << 2
4498 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4499 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4501 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4505 * Collection of V8 heap information.
4507 * Instances of this class can be passed to v8::V8::HeapStatistics to
4508 * get heap statistics from V8.
4510 class V8_EXPORT HeapStatistics {
4513 size_t total_heap_size() { return total_heap_size_; }
4514 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4515 size_t total_physical_size() { return total_physical_size_; }
4516 size_t used_heap_size() { return used_heap_size_; }
4517 size_t heap_size_limit() { return heap_size_limit_; }
4520 size_t total_heap_size_;
4521 size_t total_heap_size_executable_;
4522 size_t total_physical_size_;
4523 size_t used_heap_size_;
4524 size_t heap_size_limit_;
4527 friend class Isolate;
4531 class RetainedObjectInfo;
4535 * FunctionEntryHook is the type of the profile entry hook called at entry to
4536 * any generated function when function-level profiling is enabled.
4538 * \param function the address of the function that's being entered.
4539 * \param return_addr_location points to a location on stack where the machine
4540 * return address resides. This can be used to identify the caller of
4541 * \p function, and/or modified to divert execution when \p function exits.
4543 * \note the entry hook must not cause garbage collection.
4545 typedef void (*FunctionEntryHook)(uintptr_t function,
4546 uintptr_t return_addr_location);
4549 * A JIT code event is issued each time code is added, moved or removed.
4551 * \note removal events are not currently issued.
4553 struct JitCodeEvent {
4558 CODE_ADD_LINE_POS_INFO,
4559 CODE_START_LINE_INFO_RECORDING,
4560 CODE_END_LINE_INFO_RECORDING
4562 // Definition of the code position type. The "POSITION" type means the place
4563 // in the source code which are of interest when making stack traces to
4564 // pin-point the source location of a stack frame as close as possible.
4565 // The "STATEMENT_POSITION" means the place at the beginning of each
4566 // statement, and is used to indicate possible break locations.
4567 enum PositionType { POSITION, STATEMENT_POSITION };
4571 // Start of the instructions.
4573 // Size of the instructions.
4575 // Script info for CODE_ADDED event.
4576 Handle<UnboundScript> script;
4577 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4578 // code line information which is returned from the
4579 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4580 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4584 // Name of the object associated with the code, note that the string is not
4587 // Number of chars in str.
4591 struct line_info_t {
4596 // The position type.
4597 PositionType position_type;
4601 // Only valid for CODE_ADDED.
4604 // Only valid for CODE_ADD_LINE_POS_INFO
4605 struct line_info_t line_info;
4607 // New location of instructions. Only valid for CODE_MOVED.
4608 void* new_code_start;
4613 * Option flags passed to the SetJitCodeEventHandler function.
4615 enum JitCodeEventOptions {
4616 kJitCodeEventDefault = 0,
4617 // Generate callbacks for already existent code.
4618 kJitCodeEventEnumExisting = 1
4623 * Callback function passed to SetJitCodeEventHandler.
4625 * \param event code add, move or removal event.
4627 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4631 * Interface for iterating through all external resources in the heap.
4633 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4635 virtual ~ExternalResourceVisitor() {}
4636 virtual void VisitExternalString(Handle<String> string) {}
4641 * Interface for iterating through all the persistent handles in the heap.
4643 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4645 virtual ~PersistentHandleVisitor() {}
4646 virtual void VisitPersistentHandle(Persistent<Value>* value,
4647 uint16_t class_id) {}
4652 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
4653 * completely separate states. Objects from one isolate must not be used in
4654 * other isolates. The embedder can create multiple isolates and use them in
4655 * parallel in multiple threads. An isolate can be entered by at most one
4656 * thread at any given time. The Locker/Unlocker API must be used to
4659 class V8_EXPORT Isolate {
4662 * Initial configuration parameters for a new Isolate.
4664 struct CreateParams {
4667 code_event_handler(NULL),
4668 enable_serializer(false) {}
4671 * The optional entry_hook allows the host application to provide the
4672 * address of a function that's invoked on entry to every V8-generated
4673 * function. Note that entry_hook is invoked at the very start of each
4674 * generated function. Furthermore, if an entry_hook is given, V8 will
4675 * always run without a context snapshot.
4677 FunctionEntryHook entry_hook;
4680 * Allows the host application to provide the address of a function that is
4681 * notified each time code is added, moved or removed.
4683 JitCodeEventHandler code_event_handler;
4686 * ResourceConstraints to use for the new Isolate.
4688 ResourceConstraints constraints;
4691 * This flag currently renders the Isolate unusable.
4693 bool enable_serializer;
4698 * Stack-allocated class which sets the isolate for all operations
4699 * executed within a local scope.
4701 class V8_EXPORT Scope {
4703 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4707 ~Scope() { isolate_->Exit(); }
4710 Isolate* const isolate_;
4712 // Prevent copying of Scope objects.
4713 Scope(const Scope&);
4714 Scope& operator=(const Scope&);
4719 * Assert that no Javascript code is invoked.
4721 class V8_EXPORT DisallowJavascriptExecutionScope {
4723 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4725 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4726 ~DisallowJavascriptExecutionScope();
4732 // Prevent copying of Scope objects.
4733 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4734 DisallowJavascriptExecutionScope& operator=(
4735 const DisallowJavascriptExecutionScope&);
4740 * Introduce exception to DisallowJavascriptExecutionScope.
4742 class V8_EXPORT AllowJavascriptExecutionScope {
4744 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4745 ~AllowJavascriptExecutionScope();
4748 void* internal_throws_;
4749 void* internal_assert_;
4751 // Prevent copying of Scope objects.
4752 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4753 AllowJavascriptExecutionScope& operator=(
4754 const AllowJavascriptExecutionScope&);
4758 * Do not run microtasks while this scope is active, even if microtasks are
4759 * automatically executed otherwise.
4761 class V8_EXPORT SuppressMicrotaskExecutionScope {
4763 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4764 ~SuppressMicrotaskExecutionScope();
4767 internal::Isolate* isolate_;
4769 // Prevent copying of Scope objects.
4770 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4771 SuppressMicrotaskExecutionScope& operator=(
4772 const SuppressMicrotaskExecutionScope&);
4776 * Types of garbage collections that can be requested via
4777 * RequestGarbageCollectionForTesting.
4779 enum GarbageCollectionType {
4780 kFullGarbageCollection,
4781 kMinorGarbageCollection
4785 * Features reported via the SetUseCounterCallback callback. Do not chang
4786 * assigned numbers of existing items; add new features to the end of this
4789 enum UseCounterFeature {
4792 kUseCounterFeatureCount // This enum value must be last.
4795 typedef void (*UseCounterCallback)(Isolate* isolate,
4796 UseCounterFeature feature);
4800 * Creates a new isolate. Does not change the currently entered
4803 * When an isolate is no longer used its resources should be freed
4804 * by calling Dispose(). Using the delete operator is not allowed.
4806 * V8::Initialize() must have run prior to this.
4808 static Isolate* New(const CreateParams& params = CreateParams());
4811 * Returns the entered isolate for the current thread or NULL in
4812 * case there is no current isolate.
4814 * This method must not be invoked before V8::Initialize() was invoked.
4816 static Isolate* GetCurrent();
4819 * Methods below this point require holding a lock (using Locker) in
4820 * a multi-threaded environment.
4824 * Sets this isolate as the entered one for the current thread.
4825 * Saves the previously entered one (if any), so that it can be
4826 * restored when exiting. Re-entering an isolate is allowed.
4831 * Exits this isolate by restoring the previously entered one in the
4832 * current thread. The isolate may still stay the same, if it was
4833 * entered more than once.
4835 * Requires: this == Isolate::GetCurrent().
4840 * Disposes the isolate. The isolate must not be entered by any
4841 * thread to be disposable.
4846 * Associate embedder-specific data with the isolate. |slot| has to be
4847 * between 0 and GetNumberOfDataSlots() - 1.
4849 V8_INLINE void SetData(uint32_t slot, void* data);
4852 * Retrieve embedder-specific data from the isolate.
4853 * Returns NULL if SetData has never been called for the given |slot|.
4855 V8_INLINE void* GetData(uint32_t slot);
4858 * Returns the maximum number of available embedder data slots. Valid slots
4859 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4861 V8_INLINE static uint32_t GetNumberOfDataSlots();
4864 * Get statistics about the heap memory usage.
4866 void GetHeapStatistics(HeapStatistics* heap_statistics);
4869 * Get a call stack sample from the isolate.
4870 * \param state Execution state.
4871 * \param frames Caller allocated buffer to store stack frames.
4872 * \param frames_limit Maximum number of frames to capture. The buffer must
4873 * be large enough to hold the number of frames.
4874 * \param sample_info The sample info is filled up by the function
4875 * provides number of actual captured stack frames and
4876 * the current VM state.
4877 * \note GetStackSample should only be called when the JS thread is paused or
4878 * interrupted. Otherwise the behavior is undefined.
4880 void GetStackSample(const RegisterState& state, void** frames,
4881 size_t frames_limit, SampleInfo* sample_info);
4884 * Adjusts the amount of registered external memory. Used to give V8 an
4885 * indication of the amount of externally allocated memory that is kept alive
4886 * by JavaScript objects. V8 uses this to decide when to perform global
4887 * garbage collections. Registering externally allocated memory will trigger
4888 * global garbage collections more often than it would otherwise in an attempt
4889 * to garbage collect the JavaScript objects that keep the externally
4890 * allocated memory alive.
4892 * \param change_in_bytes the change in externally allocated memory that is
4893 * kept alive by JavaScript objects.
4894 * \returns the adjusted value.
4897 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4900 * Returns heap profiler for this isolate. Will return NULL until the isolate
4903 HeapProfiler* GetHeapProfiler();
4906 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4907 * is initialized. It is the embedder's responsibility to stop all CPU
4908 * profiling activities if it has started any.
4910 CpuProfiler* GetCpuProfiler();
4912 /** Returns true if this isolate has a current context. */
4915 /** Returns the context that is on the top of the stack. */
4916 Local<Context> GetCurrentContext();
4919 * Returns the context of the calling JavaScript code. That is the
4920 * context of the top-most JavaScript frame. If there are no
4921 * JavaScript frames an empty handle is returned.
4923 Local<Context> GetCallingContext();
4925 /** Returns the last entered context. */
4926 Local<Context> GetEnteredContext();
4929 * Schedules an exception to be thrown when returning to JavaScript. When an
4930 * exception has been scheduled it is illegal to invoke any JavaScript
4931 * operation; the caller must return immediately and only after the exception
4932 * has been handled does it become legal to invoke JavaScript operations.
4934 Local<Value> ThrowException(Local<Value> exception);
4937 * Allows the host application to group objects together. If one
4938 * object in the group is alive, all objects in the group are alive.
4939 * After each garbage collection, object groups are removed. It is
4940 * intended to be used in the before-garbage-collection callback
4941 * function, for instance to simulate DOM tree connections among JS
4942 * wrapper objects. Object groups for all dependent handles need to
4943 * be provided for kGCTypeMarkSweepCompact collections, for all other
4944 * garbage collection types it is sufficient to provide object groups
4945 * for partially dependent handles only.
4947 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4951 * Allows the host application to declare implicit references from an object
4952 * group to an object. If the objects of the object group are alive, the child
4953 * object is alive too. After each garbage collection, all implicit references
4954 * are removed. It is intended to be used in the before-garbage-collection
4955 * callback function.
4957 template<typename T> void SetReferenceFromGroup(UniqueId id,
4958 const Persistent<T>& child);
4961 * Allows the host application to declare implicit references from an object
4962 * to another object. If the parent object is alive, the child object is alive
4963 * too. After each garbage collection, all implicit references are removed. It
4964 * is intended to be used in the before-garbage-collection callback function.
4966 template<typename T, typename S>
4967 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4969 typedef void (*GCPrologueCallback)(Isolate* isolate,
4971 GCCallbackFlags flags);
4972 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4974 GCCallbackFlags flags);
4977 * Enables the host application to receive a notification before a
4978 * garbage collection. Allocations are allowed in the callback function,
4979 * but the callback is not re-entrant: if the allocation inside it will
4980 * trigger the garbage collection, the callback won't be called again.
4981 * It is possible to specify the GCType filter for your callback. But it is
4982 * not possible to register the same callback function two times with
4983 * different GCType filters.
4985 void AddGCPrologueCallback(
4986 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4989 * This function removes callback which was installed by
4990 * AddGCPrologueCallback function.
4992 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4995 * Enables the host application to receive a notification after a
4996 * garbage collection. Allocations are allowed in the callback function,
4997 * but the callback is not re-entrant: if the allocation inside it will
4998 * trigger the garbage collection, the callback won't be called again.
4999 * It is possible to specify the GCType filter for your callback. But it is
5000 * not possible to register the same callback function two times with
5001 * different GCType filters.
5003 void AddGCEpilogueCallback(
5004 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5007 * This function removes callback which was installed by
5008 * AddGCEpilogueCallback function.
5010 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5014 * Forcefully terminate the current thread of JavaScript execution
5015 * in the given isolate.
5017 * This method can be used by any thread even if that thread has not
5018 * acquired the V8 lock with a Locker object.
5020 void TerminateExecution();
5023 * Is V8 terminating JavaScript execution.
5025 * Returns true if JavaScript execution is currently terminating
5026 * because of a call to TerminateExecution. In that case there are
5027 * still JavaScript frames on the stack and the termination
5028 * exception is still active.
5030 bool IsExecutionTerminating();
5033 * Resume execution capability in the given isolate, whose execution
5034 * was previously forcefully terminated using TerminateExecution().
5036 * When execution is forcefully terminated using TerminateExecution(),
5037 * the isolate can not resume execution until all JavaScript frames
5038 * have propagated the uncatchable exception which is generated. This
5039 * method allows the program embedding the engine to handle the
5040 * termination event and resume execution capability, even if
5041 * JavaScript frames remain on the stack.
5043 * This method can be used by any thread even if that thread has not
5044 * acquired the V8 lock with a Locker object.
5046 void CancelTerminateExecution();
5049 * Request V8 to interrupt long running JavaScript code and invoke
5050 * the given |callback| passing the given |data| to it. After |callback|
5051 * returns control will be returned to the JavaScript code.
5052 * There may be a number of interrupt requests in flight.
5053 * Can be called from another thread without acquiring a |Locker|.
5054 * Registered |callback| must not reenter interrupted Isolate.
5056 void RequestInterrupt(InterruptCallback callback, void* data);
5059 * Clear interrupt request created by |RequestInterrupt|.
5060 * Can be called from another thread without acquiring a |Locker|.
5062 V8_DEPRECATED("There's no way to clear interrupts in flight.",
5063 void ClearInterrupt());
5066 * Request garbage collection in this Isolate. It is only valid to call this
5067 * function if --expose_gc was specified.
5069 * This should only be used for testing purposes and not to enforce a garbage
5070 * collection schedule. It has strong negative impact on the garbage
5071 * collection performance. Use IdleNotification() or LowMemoryNotification()
5072 * instead to influence the garbage collection schedule.
5074 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5077 * Set the callback to invoke for logging event.
5079 void SetEventLogger(LogEventCallback that);
5082 * Adds a callback to notify the host application when a script finished
5083 * running. If a script re-enters the runtime during executing, the
5084 * CallCompletedCallback is only invoked when the outer-most script
5085 * execution ends. Executing scripts inside the callback do not trigger
5086 * further callbacks.
5088 void AddCallCompletedCallback(CallCompletedCallback callback);
5091 * Removes callback that was installed by AddCallCompletedCallback.
5093 void RemoveCallCompletedCallback(CallCompletedCallback callback);
5097 * Set callback to notify about promise reject with no handler, or
5098 * revocation of such a previous notification once the handler is added.
5100 void SetPromiseRejectCallback(PromiseRejectCallback callback);
5103 * Experimental: Runs the Microtask Work Queue until empty
5104 * Any exceptions thrown by microtask callbacks are swallowed.
5106 void RunMicrotasks();
5109 * Experimental: Enqueues the callback to the Microtask Work Queue
5111 void EnqueueMicrotask(Handle<Function> microtask);
5114 * Experimental: Enqueues the callback to the Microtask Work Queue
5116 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5119 * Experimental: Controls whether the Microtask Work Queue is automatically
5120 * run when the script call depth decrements to zero.
5122 void SetAutorunMicrotasks(bool autorun);
5125 * Experimental: Returns whether the Microtask Work Queue is automatically
5126 * run when the script call depth decrements to zero.
5128 bool WillAutorunMicrotasks() const;
5131 * Sets a callback for counting the number of times a feature of V8 is used.
5133 void SetUseCounterCallback(UseCounterCallback callback);
5136 * Enables the host application to provide a mechanism for recording
5137 * statistics counters.
5139 void SetCounterFunction(CounterLookupCallback);
5142 * Enables the host application to provide a mechanism for recording
5143 * histograms. The CreateHistogram function returns a
5144 * histogram which will later be passed to the AddHistogramSample
5147 void SetCreateHistogramFunction(CreateHistogramCallback);
5148 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5151 * Optional notification that the embedder is idle.
5152 * V8 uses the notification to perform garbage collection.
5153 * This call can be used repeatedly if the embedder remains idle.
5154 * Returns true if the embedder should stop calling IdleNotification
5155 * until real work has been done. This indicates that V8 has done
5156 * as much cleanup as it will be able to do.
5158 * The idle_time_in_ms argument specifies the time V8 has to perform
5159 * garbage collection. There is no guarantee that the actual work will be
5160 * done within the time limit.
5161 * The deadline_in_seconds argument specifies the deadline V8 has to finish
5162 * garbage collection work. deadline_in_seconds is compared with
5163 * MonotonicallyIncreasingTime() and should be based on the same timebase as
5164 * that function. There is no guarantee that the actual work will be done
5165 * within the time limit.
5167 bool IdleNotification(int idle_time_in_ms);
5168 bool IdleNotificationDeadline(double deadline_in_seconds);
5171 * Optional notification that the system is running low on memory.
5172 * V8 uses these notifications to attempt to free memory.
5174 void LowMemoryNotification();
5177 * Optional notification that a context has been disposed. V8 uses
5178 * these notifications to guide the GC heuristic. Returns the number
5179 * of context disposals - including this one - since the last time
5180 * V8 had a chance to clean up.
5182 * The optional parameter |dependant_context| specifies whether the disposed
5183 * context was depending on state from other contexts or not.
5185 int ContextDisposedNotification(bool dependant_context = true);
5188 * Allows the host application to provide the address of a function that is
5189 * notified each time code is added, moved or removed.
5191 * \param options options for the JIT code event handler.
5192 * \param event_handler the JIT code event handler, which will be invoked
5193 * each time code is added, moved or removed.
5194 * \note \p event_handler won't get notified of existent code.
5195 * \note since code removal notifications are not currently issued, the
5196 * \p event_handler may get notifications of code that overlaps earlier
5197 * code notifications. This happens when code areas are reused, and the
5198 * earlier overlapping code areas should therefore be discarded.
5199 * \note the events passed to \p event_handler and the strings they point to
5200 * are not guaranteed to live past each call. The \p event_handler must
5201 * copy strings and other parameters it needs to keep around.
5202 * \note the set of events declared in JitCodeEvent::EventType is expected to
5203 * grow over time, and the JitCodeEvent structure is expected to accrue
5204 * new members. The \p event_handler function must ignore event codes
5205 * it does not recognize to maintain future compatibility.
5206 * \note Use Isolate::CreateParams to get events for code executed during
5209 void SetJitCodeEventHandler(JitCodeEventOptions options,
5210 JitCodeEventHandler event_handler);
5213 * Modifies the stack limit for this Isolate.
5215 * \param stack_limit An address beyond which the Vm's stack may not grow.
5217 * \note If you are using threads then you should hold the V8::Locker lock
5218 * while setting the stack limit and you must set a non-default stack
5219 * limit separately for each thread.
5221 void SetStackLimit(uintptr_t stack_limit);
5224 * Returns a memory range that can potentially contain jitted code.
5226 * On Win64, embedders are advised to install function table callbacks for
5227 * these ranges, as default SEH won't be able to unwind through jitted code.
5229 * The first page of the code range is reserved for the embedder and is
5230 * committed, writable, and executable.
5232 * Might be empty on other platforms.
5234 * https://code.google.com/p/v8/issues/detail?id=3598
5236 void GetCodeRange(void** start, size_t* length_in_bytes);
5238 /** Set the callback to invoke in case of fatal errors. */
5239 void SetFatalErrorHandler(FatalErrorCallback that);
5242 * Set the callback to invoke to check if code generation from
5243 * strings should be allowed.
5245 void SetAllowCodeGenerationFromStringsCallback(
5246 AllowCodeGenerationFromStringsCallback callback);
5249 * Check if V8 is dead and therefore unusable. This is the case after
5250 * fatal errors such as out-of-memory situations.
5255 * Adds a message listener.
5257 * The same message listener can be added more than once and in that
5258 * case it will be called more than once for each message.
5260 * If data is specified, it will be passed to the callback when it is called.
5261 * Otherwise, the exception object will be passed to the callback instead.
5263 bool AddMessageListener(MessageCallback that,
5264 Handle<Value> data = Handle<Value>());
5267 * Remove all message listeners from the specified callback function.
5269 void RemoveMessageListeners(MessageCallback that);
5271 /** Callback function for reporting failed access checks.*/
5272 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5275 * Tells V8 to capture current stack trace when uncaught exception occurs
5276 * and report it to the message listeners. The option is off by default.
5278 void SetCaptureStackTraceForUncaughtExceptions(
5279 bool capture, int frame_limit = 10,
5280 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5283 * Enables the host application to provide a mechanism to be notified
5284 * and perform custom logging when V8 Allocates Executable Memory.
5286 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5287 ObjectSpace space, AllocationAction action);
5290 * Removes callback that was installed by AddMemoryAllocationCallback.
5292 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5295 * Iterates through all external resources referenced from current isolate
5296 * heap. GC is not invoked prior to iterating, therefore there is no
5297 * guarantee that visited objects are still alive.
5299 void VisitExternalResources(ExternalResourceVisitor* visitor);
5302 * Iterates through all the persistent handles in the current isolate's heap
5303 * that have class_ids.
5305 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5308 * Iterates through all the persistent handles in the current isolate's heap
5309 * that have class_ids and are candidates to be marked as partially dependent
5310 * handles. This will visit handles to young objects created since the last
5311 * garbage collection but is free to visit an arbitrary superset of these
5314 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5317 template <class K, class V, class Traits>
5318 friend class PersistentValueMapBase;
5321 Isolate(const Isolate&);
5323 Isolate& operator=(const Isolate&);
5324 void* operator new(size_t size);
5325 void operator delete(void*, size_t);
5327 void SetObjectGroupId(internal::Object** object, UniqueId id);
5328 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5329 void SetReference(internal::Object** parent, internal::Object** child);
5330 void CollectAllGarbage(const char* gc_reason);
5333 class V8_EXPORT StartupData {
5341 * EntropySource is used as a callback function when v8 needs a source
5344 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5348 * ReturnAddressLocationResolver is used as a callback function when v8 is
5349 * resolving the location of a return address on the stack. Profilers that
5350 * change the return address on the stack can use this to resolve the stack
5351 * location to whereever the profiler stashed the original return address.
5353 * \param return_addr_location points to a location on stack where a machine
5354 * return address resides.
5355 * \returns either return_addr_location, or else a pointer to the profiler's
5356 * copy of the original return address.
5358 * \note the resolver function must not cause garbage collection.
5360 typedef uintptr_t (*ReturnAddressLocationResolver)(
5361 uintptr_t return_addr_location);
5365 * Container class for static utility functions.
5367 class V8_EXPORT V8 {
5369 /** Set the callback to invoke in case of fatal errors. */
5370 // TODO(dcarney): deprecate this.
5371 V8_INLINE static void SetFatalErrorHandler(FatalErrorCallback that);
5374 * Set the callback to invoke to check if code generation from
5375 * strings should be allowed.
5377 // TODO(dcarney): deprecate this.
5378 V8_INLINE static void SetAllowCodeGenerationFromStringsCallback(
5379 AllowCodeGenerationFromStringsCallback that);
5382 * Set allocator to use for ArrayBuffer memory.
5383 * The allocator should be set only once. The allocator should be set
5384 * before any code tha uses ArrayBuffers is executed.
5385 * This allocator is used in all isolates.
5387 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
5390 * Check if V8 is dead and therefore unusable. This is the case after
5391 * fatal errors such as out-of-memory situations.
5393 // TODO(dcarney): deprecate this.
5394 V8_INLINE static bool IsDead();
5397 * Hand startup data to V8, in case the embedder has chosen to build
5398 * V8 with external startup data.
5401 * - By default the startup data is linked into the V8 library, in which
5402 * case this function is not meaningful.
5403 * - If this needs to be called, it needs to be called before V8
5404 * tries to make use of its built-ins.
5405 * - To avoid unnecessary copies of data, V8 will point directly into the
5406 * given data blob, so pretty please keep it around until V8 exit.
5407 * - Compression of the startup blob might be useful, but needs to
5408 * handled entirely on the embedders' side.
5409 * - The call will abort if the data is invalid.
5411 static void SetNativesDataBlob(StartupData* startup_blob);
5412 static void SetSnapshotDataBlob(StartupData* startup_blob);
5415 * Create a new isolate and context for the purpose of capturing a snapshot
5416 * Returns { NULL, 0 } on failure.
5417 * The caller owns the data array in the return value.
5419 static StartupData CreateSnapshotDataBlob(char* custom_source = NULL);
5422 * Adds a message listener.
5424 * The same message listener can be added more than once and in that
5425 * case it will be called more than once for each message.
5427 * If data is specified, it will be passed to the callback when it is called.
5428 * Otherwise, the exception object will be passed to the callback instead.
5430 // TODO(dcarney): deprecate this.
5431 V8_INLINE static bool AddMessageListener(
5432 MessageCallback that, Handle<Value> data = Handle<Value>());
5435 * Remove all message listeners from the specified callback function.
5437 // TODO(dcarney): deprecate this.
5438 V8_INLINE static void RemoveMessageListeners(MessageCallback that);
5441 * Tells V8 to capture current stack trace when uncaught exception occurs
5442 * and report it to the message listeners. The option is off by default.
5444 // TODO(dcarney): deprecate this.
5445 V8_INLINE static void SetCaptureStackTraceForUncaughtExceptions(
5446 bool capture, int frame_limit = 10,
5447 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5450 * Sets V8 flags from a string.
5452 static void SetFlagsFromString(const char* str, int length);
5455 * Sets V8 flags from the command line.
5457 static void SetFlagsFromCommandLine(int* argc,
5461 /** Get the version string. */
5462 static const char* GetVersion();
5464 /** Callback function for reporting failed access checks.*/
5465 // TODO(dcarney): deprecate this.
5466 V8_INLINE static void SetFailedAccessCheckCallbackFunction(
5467 FailedAccessCheckCallback);
5470 * Enables the host application to receive a notification before a
5471 * garbage collection. Allocations are not allowed in the
5472 * callback function, you therefore cannot manipulate objects (set
5473 * or delete properties for example) since it is possible such
5474 * operations will result in the allocation of objects. It is possible
5475 * to specify the GCType filter for your callback. But it is not possible to
5476 * register the same callback function two times with different
5479 // TODO(dcarney): deprecate this.
5480 static void AddGCPrologueCallback(
5481 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5484 * This function removes callback which was installed by
5485 * AddGCPrologueCallback function.
5487 // TODO(dcarney): deprecate this.
5488 V8_INLINE static void RemoveGCPrologueCallback(GCPrologueCallback callback);
5491 * Enables the host application to receive a notification after a
5492 * garbage collection. Allocations are not allowed in the
5493 * callback function, you therefore cannot manipulate objects (set
5494 * or delete properties for example) since it is possible such
5495 * operations will result in the allocation of objects. It is possible
5496 * to specify the GCType filter for your callback. But it is not possible to
5497 * register the same callback function two times with different
5500 // TODO(dcarney): deprecate this.
5501 static void AddGCEpilogueCallback(
5502 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5505 * This function removes callback which was installed by
5506 * AddGCEpilogueCallback function.
5508 // TODO(dcarney): deprecate this.
5509 V8_INLINE static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5512 * Enables the host application to provide a mechanism to be notified
5513 * and perform custom logging when V8 Allocates Executable Memory.
5515 // TODO(dcarney): deprecate this.
5516 V8_INLINE static void AddMemoryAllocationCallback(
5517 MemoryAllocationCallback callback, ObjectSpace space,
5518 AllocationAction action);
5521 * Removes callback that was installed by AddMemoryAllocationCallback.
5523 // TODO(dcarney): deprecate this.
5524 V8_INLINE static void RemoveMemoryAllocationCallback(
5525 MemoryAllocationCallback callback);
5528 * Initializes V8. This function needs to be called before the first Isolate
5529 * is created. It always returns true.
5531 static bool Initialize();
5534 * Allows the host application to provide a callback which can be used
5535 * as a source of entropy for random number generators.
5537 static void SetEntropySource(EntropySource source);
5540 * Allows the host application to provide a callback that allows v8 to
5541 * cooperate with a profiler that rewrites return addresses on stack.
5543 static void SetReturnAddressLocationResolver(
5544 ReturnAddressLocationResolver return_address_resolver);
5547 * Forcefully terminate the current thread of JavaScript execution
5548 * in the given isolate.
5550 * This method can be used by any thread even if that thread has not
5551 * acquired the V8 lock with a Locker object.
5553 * \param isolate The isolate in which to terminate the current JS execution.
5555 // TODO(dcarney): deprecate this.
5556 V8_INLINE static void TerminateExecution(Isolate* isolate);
5559 * Is V8 terminating JavaScript execution.
5561 * Returns true if JavaScript execution is currently terminating
5562 * because of a call to TerminateExecution. In that case there are
5563 * still JavaScript frames on the stack and the termination
5564 * exception is still active.
5566 * \param isolate The isolate in which to check.
5568 // TODO(dcarney): deprecate this.
5569 V8_INLINE static bool IsExecutionTerminating(Isolate* isolate = NULL);
5572 * Resume execution capability in the given isolate, whose execution
5573 * was previously forcefully terminated using TerminateExecution().
5575 * When execution is forcefully terminated using TerminateExecution(),
5576 * the isolate can not resume execution until all JavaScript frames
5577 * have propagated the uncatchable exception which is generated. This
5578 * method allows the program embedding the engine to handle the
5579 * termination event and resume execution capability, even if
5580 * JavaScript frames remain on the stack.
5582 * This method can be used by any thread even if that thread has not
5583 * acquired the V8 lock with a Locker object.
5585 * \param isolate The isolate in which to resume execution capability.
5587 // TODO(dcarney): deprecate this.
5588 V8_INLINE static void CancelTerminateExecution(Isolate* isolate);
5591 * Releases any resources used by v8 and stops any utility threads
5592 * that may be running. Note that disposing v8 is permanent, it
5593 * cannot be reinitialized.
5595 * It should generally not be necessary to dispose v8 before exiting
5596 * a process, this should happen automatically. It is only necessary
5597 * to use if the process needs the resources taken up by v8.
5599 static bool Dispose();
5602 * Iterates through all external resources referenced from current isolate
5603 * heap. GC is not invoked prior to iterating, therefore there is no
5604 * guarantee that visited objects are still alive.
5606 // TODO(dcarney): deprecate this.
5607 V8_INLINE static void VisitExternalResources(
5608 ExternalResourceVisitor* visitor);
5611 * Iterates through all the persistent handles in the current isolate's heap
5612 * that have class_ids.
5614 // TODO(dcarney): deprecate this.
5615 V8_INLINE static void VisitHandlesWithClassIds(
5616 PersistentHandleVisitor* visitor);
5619 * Iterates through all the persistent handles in isolate's heap that have
5622 // TODO(dcarney): deprecate this.
5623 V8_INLINE static void VisitHandlesWithClassIds(
5624 Isolate* isolate, PersistentHandleVisitor* visitor);
5627 * Iterates through all the persistent handles in the current isolate's heap
5628 * that have class_ids and are candidates to be marked as partially dependent
5629 * handles. This will visit handles to young objects created since the last
5630 * garbage collection but is free to visit an arbitrary superset of these
5633 // TODO(dcarney): deprecate this.
5634 V8_INLINE static void VisitHandlesForPartialDependence(
5635 Isolate* isolate, PersistentHandleVisitor* visitor);
5638 * Initialize the ICU library bundled with V8. The embedder should only
5639 * invoke this method when using the bundled ICU. Returns true on success.
5641 * If V8 was compiled with the ICU data in an external file, the location
5642 * of the data file has to be provided.
5644 static bool InitializeICU(const char* icu_data_file = NULL);
5647 * Sets the v8::Platform to use. This should be invoked before V8 is
5650 static void InitializePlatform(Platform* platform);
5653 * Clears all references to the v8::Platform. This should be invoked after
5656 static void ShutdownPlatform();
5661 enum WeakHandleType { PhantomHandle, NonphantomHandle };
5663 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5664 internal::Object** handle);
5665 static internal::Object** CopyPersistent(internal::Object** handle);
5666 static void DisposeGlobal(internal::Object** global_handle);
5667 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5668 static void MakeWeak(internal::Object** global_handle, void* data,
5669 WeakCallback weak_callback);
5670 static void MakePhantom(internal::Object** global_handle, void* data,
5671 // Must be 0 or kNoInternalFieldIndex.
5672 int internal_field_index1,
5673 // Must be 1 or kNoInternalFieldIndex.
5674 int internal_field_index2,
5675 PhantomCallbackData<void>::Callback weak_callback);
5676 static void* ClearWeak(internal::Object** global_handle);
5677 static void Eternalize(Isolate* isolate,
5680 static Local<Value> GetEternal(Isolate* isolate, int index);
5682 template <class T> friend class Handle;
5683 template <class T> friend class Local;
5684 template <class T> friend class Eternal;
5685 template <class T> friend class PersistentBase;
5686 template <class T, class M> friend class Persistent;
5687 friend class Context;
5692 * An external exception handler.
5694 class V8_EXPORT TryCatch {
5697 * Creates a new try/catch block and registers it with v8. Note that
5698 * all TryCatch blocks should be stack allocated because the memory
5699 * location itself is compared against JavaScript try/catch blocks.
5701 // TODO(dcarney): deprecate.
5705 * Creates a new try/catch block and registers it with v8. Note that
5706 * all TryCatch blocks should be stack allocated because the memory
5707 * location itself is compared against JavaScript try/catch blocks.
5709 TryCatch(Isolate* isolate);
5712 * Unregisters and deletes this try/catch block.
5717 * Returns true if an exception has been caught by this try/catch block.
5719 bool HasCaught() const;
5722 * For certain types of exceptions, it makes no sense to continue execution.
5724 * If CanContinue returns false, the correct action is to perform any C++
5725 * cleanup needed and then return. If CanContinue returns false and
5726 * HasTerminated returns true, it is possible to call
5727 * CancelTerminateExecution in order to continue calling into the engine.
5729 bool CanContinue() const;
5732 * Returns true if an exception has been caught due to script execution
5735 * There is no JavaScript representation of an execution termination
5736 * exception. Such exceptions are thrown when the TerminateExecution
5737 * methods are called to terminate a long-running script.
5739 * If such an exception has been thrown, HasTerminated will return true,
5740 * indicating that it is possible to call CancelTerminateExecution in order
5741 * to continue calling into the engine.
5743 bool HasTerminated() const;
5746 * Throws the exception caught by this TryCatch in a way that avoids
5747 * it being caught again by this same TryCatch. As with ThrowException
5748 * it is illegal to execute any JavaScript operations after calling
5749 * ReThrow; the caller must return immediately to where the exception
5752 Handle<Value> ReThrow();
5755 * Returns the exception caught by this try/catch block. If no exception has
5756 * been caught an empty handle is returned.
5758 * The returned handle is valid until this TryCatch block has been destroyed.
5760 Local<Value> Exception() const;
5763 * Returns the .stack property of the thrown object. If no .stack
5764 * property is present an empty handle is returned.
5766 Local<Value> StackTrace() const;
5769 * Returns the message associated with this exception. If there is
5770 * no message associated an empty handle is returned.
5772 * The returned handle is valid until this TryCatch block has been
5775 Local<v8::Message> Message() const;
5778 * Clears any exceptions that may have been caught by this try/catch block.
5779 * After this method has been called, HasCaught() will return false. Cancels
5780 * the scheduled exception if it is caught and ReThrow() is not called before.
5782 * It is not necessary to clear a try/catch block before using it again; if
5783 * another exception is thrown the previously caught exception will just be
5784 * overwritten. However, it is often a good idea since it makes it easier
5785 * to determine which operation threw a given exception.
5790 * Set verbosity of the external exception handler.
5792 * By default, exceptions that are caught by an external exception
5793 * handler are not reported. Call SetVerbose with true on an
5794 * external exception handler to have exceptions caught by the
5795 * handler reported as if they were not caught.
5797 void SetVerbose(bool value);
5800 * Set whether or not this TryCatch should capture a Message object
5801 * which holds source information about where the exception
5802 * occurred. True by default.
5804 void SetCaptureMessage(bool value);
5807 * There are cases when the raw address of C++ TryCatch object cannot be
5808 * used for comparisons with addresses into the JS stack. The cases are:
5809 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5810 * 2) Address sanitizer allocates local C++ object in the heap when
5811 * UseAfterReturn mode is enabled.
5812 * This method returns address that can be used for comparisons with
5813 * addresses into the JS stack. When neither simulator nor ASAN's
5814 * UseAfterReturn is enabled, then the address returned will be the address
5815 * of the C++ try catch handler itself.
5817 static void* JSStackComparableAddress(v8::TryCatch* handler) {
5818 if (handler == NULL) return NULL;
5819 return handler->js_stack_comparable_address_;
5823 void ResetInternal();
5825 // Make it hard to create heap-allocated TryCatch blocks.
5826 TryCatch(const TryCatch&);
5827 void operator=(const TryCatch&);
5828 void* operator new(size_t size);
5829 void operator delete(void*, size_t);
5831 v8::internal::Isolate* isolate_;
5832 v8::TryCatch* next_;
5835 void* message_script_;
5836 void* js_stack_comparable_address_;
5837 int message_start_pos_;
5838 int message_end_pos_;
5839 bool is_verbose_ : 1;
5840 bool can_continue_ : 1;
5841 bool capture_message_ : 1;
5843 bool has_terminated_ : 1;
5845 friend class v8::internal::Isolate;
5853 * A container for extension names.
5855 class V8_EXPORT ExtensionConfiguration {
5857 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
5858 ExtensionConfiguration(int name_count, const char* names[])
5859 : name_count_(name_count), names_(names) { }
5861 const char** begin() const { return &names_[0]; }
5862 const char** end() const { return &names_[name_count_]; }
5865 const int name_count_;
5866 const char** names_;
5871 * A sandboxed execution context with its own set of built-in objects
5874 class V8_EXPORT Context {
5877 * Returns the global proxy object.
5879 * Global proxy object is a thin wrapper whose prototype points to actual
5880 * context's global object with the properties like Object, etc. This is done
5881 * that way for security reasons (for more details see
5882 * https://wiki.mozilla.org/Gecko:SplitWindow).
5884 * Please note that changes to global proxy object prototype most probably
5885 * would break VM---v8 expects only global object as a prototype of global
5888 Local<Object> Global();
5891 * Detaches the global object from its context before
5892 * the global object can be reused to create a new context.
5894 void DetachGlobal();
5897 * Creates a new context and returns a handle to the newly allocated
5900 * \param isolate The isolate in which to create the context.
5902 * \param extensions An optional extension configuration containing
5903 * the extensions to be installed in the newly created context.
5905 * \param global_template An optional object template from which the
5906 * global object for the newly created context will be created.
5908 * \param global_object An optional global object to be reused for
5909 * the newly created context. This global object must have been
5910 * created by a previous call to Context::New with the same global
5911 * template. The state of the global object will be completely reset
5912 * and only object identify will remain.
5914 static Local<Context> New(
5916 ExtensionConfiguration* extensions = NULL,
5917 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5918 Handle<Value> global_object = Handle<Value>());
5921 * Sets the security token for the context. To access an object in
5922 * another context, the security tokens must match.
5924 void SetSecurityToken(Handle<Value> token);
5926 /** Restores the security token to the default value. */
5927 void UseDefaultSecurityToken();
5929 /** Returns the security token of this context.*/
5930 Handle<Value> GetSecurityToken();
5933 * Enter this context. After entering a context, all code compiled
5934 * and run is compiled and run in this context. If another context
5935 * is already entered, this old context is saved so it can be
5936 * restored when the new context is exited.
5941 * Exit this context. Exiting the current context restores the
5942 * context that was in place when entering the current context.
5946 /** Returns an isolate associated with a current context. */
5947 v8::Isolate* GetIsolate();
5950 * Gets the embedder data with the given index, which must have been set by a
5951 * previous call to SetEmbedderData with the same index. Note that index 0
5952 * currently has a special meaning for Chrome's debugger.
5954 V8_INLINE Local<Value> GetEmbedderData(int index);
5957 * Sets the embedder data with the given index, growing the data as
5958 * needed. Note that index 0 currently has a special meaning for Chrome's
5961 void SetEmbedderData(int index, Handle<Value> value);
5964 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5965 * index, which must have bees set by a previous call to
5966 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5967 * currently has a special meaning for Chrome's debugger.
5969 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5972 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5973 * index, growing the data as needed. Note that index 0 currently has a
5974 * special meaning for Chrome's debugger.
5976 void SetAlignedPointerInEmbedderData(int index, void* value);
5979 * Control whether code generation from strings is allowed. Calling
5980 * this method with false will disable 'eval' and the 'Function'
5981 * constructor for code running in this context. If 'eval' or the
5982 * 'Function' constructor are used an exception will be thrown.
5984 * If code generation from strings is not allowed the
5985 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5986 * set before blocking the call to 'eval' or the 'Function'
5987 * constructor. If that callback returns true, the call will be
5988 * allowed, otherwise an exception will be thrown. If no callback is
5989 * set an exception will be thrown.
5991 void AllowCodeGenerationFromStrings(bool allow);
5994 * Returns true if code generation from strings is allowed for the context.
5995 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5997 bool IsCodeGenerationFromStringsAllowed();
6000 * Sets the error description for the exception that is thrown when
6001 * code generation from strings is not allowed and 'eval' or the 'Function'
6002 * constructor are called.
6004 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
6007 * Stack-allocated class which sets the execution context for all
6008 * operations executed within a local scope.
6012 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
6015 V8_INLINE ~Scope() { context_->Exit(); }
6018 Handle<Context> context_;
6023 friend class Script;
6024 friend class Object;
6025 friend class Function;
6027 Local<Value> SlowGetEmbedderData(int index);
6028 void* SlowGetAlignedPointerFromEmbedderData(int index);
6033 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6034 * to use any given V8 isolate, see the comments in the Isolate class. The
6035 * definition of 'using a V8 isolate' includes accessing handles or holding onto
6036 * object pointers obtained from V8 handles while in the particular V8 isolate.
6037 * It is up to the user of V8 to ensure, perhaps with locking, that this
6038 * constraint is not violated. In addition to any other synchronization
6039 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6040 * used to signal thead switches to V8.
6042 * v8::Locker is a scoped lock object. While it's active, i.e. between its
6043 * construction and destruction, the current thread is allowed to use the locked
6044 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6045 * any time. In other words, the scope of a v8::Locker is a critical section.
6051 * v8::Locker locker(isolate);
6052 * v8::Isolate::Scope isolate_scope(isolate);
6054 * // Code using V8 and isolate goes here.
6056 * } // Destructor called here
6059 * If you wish to stop using V8 in a thread A you can do this either by
6060 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6066 * v8::Unlocker unlocker(isolate);
6068 * // Code not using V8 goes here while V8 can run in another thread.
6070 * } // Destructor called here.
6074 * The Unlocker object is intended for use in a long-running callback from V8,
6075 * where you want to release the V8 lock for other threads to use.
6077 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6078 * given thread. This can be useful if you have code that can be called either
6079 * from code that holds the lock or from code that does not. The Unlocker is
6080 * not recursive so you can not have several Unlockers on the stack at once, and
6081 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6083 * An unlocker will unlock several lockers if it has to and reinstate the
6084 * correct depth of locking on its destruction, e.g.:
6089 * v8::Locker locker(isolate);
6090 * Isolate::Scope isolate_scope(isolate);
6093 * v8::Locker another_locker(isolate);
6094 * // V8 still locked (2 levels).
6097 * v8::Unlocker unlocker(isolate);
6101 * // V8 locked again (2 levels).
6103 * // V8 still locked (1 level).
6105 * // V8 Now no longer locked.
6108 class V8_EXPORT Unlocker {
6111 * Initialize Unlocker for a given Isolate.
6113 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6117 void Initialize(Isolate* isolate);
6119 internal::Isolate* isolate_;
6123 class V8_EXPORT Locker {
6126 * Initialize Locker for a given Isolate.
6128 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6133 * Returns whether or not the locker for a given isolate, is locked by the
6136 static bool IsLocked(Isolate* isolate);
6139 * Returns whether v8::Locker is being used by this V8 instance.
6141 static bool IsActive();
6144 void Initialize(Isolate* isolate);
6148 internal::Isolate* isolate_;
6150 // Disallow copying and assigning.
6151 Locker(const Locker&);
6152 void operator=(const Locker&);
6156 // --- Implementation ---
6159 namespace internal {
6161 const int kApiPointerSize = sizeof(void*); // NOLINT
6162 const int kApiIntSize = sizeof(int); // NOLINT
6163 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6165 // Tag information for HeapObject.
6166 const int kHeapObjectTag = 1;
6167 const int kHeapObjectTagSize = 2;
6168 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6170 // Tag information for Smi.
6171 const int kSmiTag = 0;
6172 const int kSmiTagSize = 1;
6173 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6175 template <size_t ptr_size> struct SmiTagging;
6177 template<int kSmiShiftSize>
6178 V8_INLINE internal::Object* IntToSmi(int value) {
6179 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6180 uintptr_t tagged_value =
6181 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6182 return reinterpret_cast<internal::Object*>(tagged_value);
6185 // Smi constants for 32-bit systems.
6186 template <> struct SmiTagging<4> {
6187 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6188 static int SmiShiftSize() { return kSmiShiftSize; }
6189 static int SmiValueSize() { return kSmiValueSize; }
6190 V8_INLINE static int SmiToInt(const internal::Object* value) {
6191 int shift_bits = kSmiTagSize + kSmiShiftSize;
6192 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6193 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6195 V8_INLINE static internal::Object* IntToSmi(int value) {
6196 return internal::IntToSmi<kSmiShiftSize>(value);
6198 V8_INLINE static bool IsValidSmi(intptr_t value) {
6199 // To be representable as an tagged small integer, the two
6200 // most-significant bits of 'value' must be either 00 or 11 due to
6201 // sign-extension. To check this we add 01 to the two
6202 // most-significant bits, and check if the most-significant bit is 0
6204 // CAUTION: The original code below:
6205 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6206 // may lead to incorrect results according to the C language spec, and
6207 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6208 // compiler may produce undefined results in case of signed integer
6209 // overflow. The computation must be done w/ unsigned ints.
6210 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6214 // Smi constants for 64-bit systems.
6215 template <> struct SmiTagging<8> {
6216 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6217 static int SmiShiftSize() { return kSmiShiftSize; }
6218 static int SmiValueSize() { return kSmiValueSize; }
6219 V8_INLINE static int SmiToInt(const internal::Object* value) {
6220 int shift_bits = kSmiTagSize + kSmiShiftSize;
6221 // Shift down and throw away top 32 bits.
6222 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6224 V8_INLINE static internal::Object* IntToSmi(int value) {
6225 return internal::IntToSmi<kSmiShiftSize>(value);
6227 V8_INLINE static bool IsValidSmi(intptr_t value) {
6228 // To be representable as a long smi, the value must be a 32-bit integer.
6229 return (value == static_cast<int32_t>(value));
6233 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6234 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6235 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6236 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6237 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6240 * This class exports constants and functionality from within v8 that
6241 * is necessary to implement inline functions in the v8 api. Don't
6242 * depend on functions and constants defined here.
6246 // These values match non-compiler-dependent values defined within
6247 // the implementation of v8.
6248 static const int kHeapObjectMapOffset = 0;
6249 static const int kMapInstanceTypeAndBitFieldOffset =
6250 1 * kApiPointerSize + kApiIntSize;
6251 static const int kStringResourceOffset = 3 * kApiPointerSize;
6253 static const int kOddballKindOffset = 3 * kApiPointerSize;
6254 static const int kForeignAddressOffset = kApiPointerSize;
6255 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6256 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6257 static const int kContextHeaderSize = 2 * kApiPointerSize;
6258 static const int kContextEmbedderDataIndex = 74;
6259 static const int kFullStringRepresentationMask = 0x07;
6260 static const int kStringEncodingMask = 0x4;
6261 static const int kExternalTwoByteRepresentationTag = 0x02;
6262 static const int kExternalOneByteRepresentationTag = 0x06;
6264 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6265 static const int kAmountOfExternalAllocatedMemoryOffset =
6266 4 * kApiPointerSize;
6267 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6268 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6269 static const int kIsolateRootsOffset =
6270 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6272 static const int kUndefinedValueRootIndex = 5;
6273 static const int kNullValueRootIndex = 7;
6274 static const int kTrueValueRootIndex = 8;
6275 static const int kFalseValueRootIndex = 9;
6276 static const int kEmptyStringRootIndex = 155;
6278 // The external allocation limit should be below 256 MB on all architectures
6279 // to avoid that resource-constrained embedders run low on memory.
6280 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6282 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6283 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6284 static const int kNodeStateMask = 0x7;
6285 static const int kNodeStateIsWeakValue = 2;
6286 static const int kNodeStateIsPendingValue = 3;
6287 static const int kNodeStateIsNearDeathValue = 4;
6288 static const int kNodeIsIndependentShift = 3;
6289 static const int kNodeIsPartiallyDependentShift = 4;
6291 static const int kJSObjectType = 0xbd;
6292 static const int kFirstNonstringType = 0x80;
6293 static const int kOddballType = 0x83;
6294 static const int kForeignType = 0x88;
6296 static const int kUndefinedOddballKind = 5;
6297 static const int kNullOddballKind = 3;
6299 static const uint32_t kNumIsolateDataSlots = 4;
6301 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
6302 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
6303 #ifdef V8_ENABLE_CHECKS
6304 CheckInitializedImpl(isolate);
6308 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
6309 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
6313 V8_INLINE static int SmiValue(const internal::Object* value) {
6314 return PlatformSmiTagging::SmiToInt(value);
6317 V8_INLINE static internal::Object* IntToSmi(int value) {
6318 return PlatformSmiTagging::IntToSmi(value);
6321 V8_INLINE static bool IsValidSmi(intptr_t value) {
6322 return PlatformSmiTagging::IsValidSmi(value);
6325 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
6326 typedef internal::Object O;
6327 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
6328 // Map::InstanceType is defined so that it will always be loaded into
6329 // the LS 8 bits of one 16-bit word, regardless of endianess.
6330 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
6333 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
6334 typedef internal::Object O;
6335 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
6338 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
6339 int representation = (instance_type & kFullStringRepresentationMask);
6340 return representation == kExternalTwoByteRepresentationTag;
6343 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
6344 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6345 return *addr & static_cast<uint8_t>(1U << shift);
6348 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
6349 bool value, int shift) {
6350 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6351 uint8_t mask = static_cast<uint8_t>(1U << shift);
6352 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
6355 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
6356 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6357 return *addr & kNodeStateMask;
6360 V8_INLINE static void UpdateNodeState(internal::Object** obj,
6362 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6363 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
6366 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
6369 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
6370 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
6371 *reinterpret_cast<void**>(addr) = data;
6374 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
6376 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
6377 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
6378 return *reinterpret_cast<void* const*>(addr);
6381 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
6383 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
6384 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
6387 template <typename T>
6388 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
6389 const uint8_t* addr =
6390 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
6391 return *reinterpret_cast<const T*>(addr);
6394 template <typename T>
6395 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
6396 typedef internal::Object O;
6397 typedef internal::Internals I;
6398 O* ctx = *reinterpret_cast<O* const*>(context);
6399 int embedder_data_offset = I::kContextHeaderSize +
6400 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
6401 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
6403 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
6404 return I::ReadField<T>(embedder_data, value_offset);
6408 } // namespace internal
6412 Local<T>::Local() : Handle<T>() { }
6416 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
6417 return New(isolate, that.val_);
6421 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
6422 return New(isolate, that.val_);
6426 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
6427 if (that == NULL) return Handle<T>();
6429 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
6430 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
6431 reinterpret_cast<internal::Isolate*>(isolate), *p)));
6436 Local<T> Local<T>::New(Isolate* isolate, T* that) {
6437 if (that == NULL) return Local<T>();
6439 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
6440 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
6441 reinterpret_cast<internal::Isolate*>(isolate), *p)));
6447 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
6449 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
6454 Local<T> Eternal<T>::Get(Isolate* isolate) {
6455 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
6460 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
6461 if (that == NULL) return NULL;
6462 internal::Object** p = reinterpret_cast<internal::Object**>(that);
6463 return reinterpret_cast<T*>(
6464 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
6469 template <class T, class M>
6470 template <class S, class M2>
6471 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
6474 if (that.IsEmpty()) return;
6475 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
6476 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
6477 M::Copy(that, this);
6482 bool PersistentBase<T>::IsIndependent() const {
6483 typedef internal::Internals I;
6484 if (this->IsEmpty()) return false;
6485 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6486 I::kNodeIsIndependentShift);
6491 bool PersistentBase<T>::IsNearDeath() const {
6492 typedef internal::Internals I;
6493 if (this->IsEmpty()) return false;
6494 uint8_t node_state =
6495 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
6496 return node_state == I::kNodeStateIsNearDeathValue ||
6497 node_state == I::kNodeStateIsPendingValue;
6502 bool PersistentBase<T>::IsWeak() const {
6503 typedef internal::Internals I;
6504 if (this->IsEmpty()) return false;
6505 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
6506 I::kNodeStateIsWeakValue;
6511 void PersistentBase<T>::Reset() {
6512 if (this->IsEmpty()) return;
6513 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
6520 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
6523 if (other.IsEmpty()) return;
6524 this->val_ = New(isolate, other.val_);
6530 void PersistentBase<T>::Reset(Isolate* isolate,
6531 const PersistentBase<S>& other) {
6534 if (other.IsEmpty()) return;
6535 this->val_ = New(isolate, other.val_);
6540 template <typename S, typename P>
6541 void PersistentBase<T>::SetWeak(
6543 typename WeakCallbackData<S, P>::Callback callback) {
6545 typedef typename WeakCallbackData<Value, void>::Callback Callback;
6546 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
6547 reinterpret_cast<Callback>(callback));
6552 template <typename P>
6553 void PersistentBase<T>::SetWeak(
6555 typename WeakCallbackData<T, P>::Callback callback) {
6556 SetWeak<T, P>(parameter, callback);
6561 template <typename P>
6562 void PersistentBase<T>::SetPhantom(
6563 P* parameter, typename PhantomCallbackData<P>::Callback callback,
6564 int internal_field_index1, int internal_field_index2) {
6565 typedef typename PhantomCallbackData<void>::Callback Callback;
6566 V8::MakePhantom(reinterpret_cast<internal::Object**>(this->val_), parameter,
6567 internal_field_index1, internal_field_index2,
6568 reinterpret_cast<Callback>(callback));
6573 template <typename P>
6574 P* PersistentBase<T>::ClearWeak() {
6575 return reinterpret_cast<P*>(
6576 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
6581 void PersistentBase<T>::MarkIndependent() {
6582 typedef internal::Internals I;
6583 if (this->IsEmpty()) return;
6584 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6586 I::kNodeIsIndependentShift);
6591 void PersistentBase<T>::MarkPartiallyDependent() {
6592 typedef internal::Internals I;
6593 if (this->IsEmpty()) return;
6594 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6596 I::kNodeIsPartiallyDependentShift);
6601 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
6602 typedef internal::Internals I;
6603 if (this->IsEmpty()) return;
6604 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6605 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6606 *reinterpret_cast<uint16_t*>(addr) = class_id;
6611 uint16_t PersistentBase<T>::WrapperClassId() const {
6612 typedef internal::Internals I;
6613 if (this->IsEmpty()) return 0;
6614 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6615 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6616 return *reinterpret_cast<uint16_t*>(addr);
6620 template<typename T>
6621 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
6623 template<typename T>
6624 template<typename S>
6625 void ReturnValue<T>::Set(const Persistent<S>& handle) {
6627 if (V8_UNLIKELY(handle.IsEmpty())) {
6628 *value_ = GetDefaultValue();
6630 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6634 template<typename T>
6635 template<typename S>
6636 void ReturnValue<T>::Set(const Handle<S> handle) {
6638 if (V8_UNLIKELY(handle.IsEmpty())) {
6639 *value_ = GetDefaultValue();
6641 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6645 template<typename T>
6646 void ReturnValue<T>::Set(double i) {
6647 TYPE_CHECK(T, Number);
6648 Set(Number::New(GetIsolate(), i));
6651 template<typename T>
6652 void ReturnValue<T>::Set(int32_t i) {
6653 TYPE_CHECK(T, Integer);
6654 typedef internal::Internals I;
6655 if (V8_LIKELY(I::IsValidSmi(i))) {
6656 *value_ = I::IntToSmi(i);
6659 Set(Integer::New(GetIsolate(), i));
6662 template<typename T>
6663 void ReturnValue<T>::Set(uint32_t i) {
6664 TYPE_CHECK(T, Integer);
6665 // Can't simply use INT32_MAX here for whatever reason.
6666 bool fits_into_int32_t = (i & (1U << 31)) == 0;
6667 if (V8_LIKELY(fits_into_int32_t)) {
6668 Set(static_cast<int32_t>(i));
6671 Set(Integer::NewFromUnsigned(GetIsolate(), i));
6674 template<typename T>
6675 void ReturnValue<T>::Set(bool value) {
6676 TYPE_CHECK(T, Boolean);
6677 typedef internal::Internals I;
6680 root_index = I::kTrueValueRootIndex;
6682 root_index = I::kFalseValueRootIndex;
6684 *value_ = *I::GetRoot(GetIsolate(), root_index);
6687 template<typename T>
6688 void ReturnValue<T>::SetNull() {
6689 TYPE_CHECK(T, Primitive);
6690 typedef internal::Internals I;
6691 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6694 template<typename T>
6695 void ReturnValue<T>::SetUndefined() {
6696 TYPE_CHECK(T, Primitive);
6697 typedef internal::Internals I;
6698 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6701 template<typename T>
6702 void ReturnValue<T>::SetEmptyString() {
6703 TYPE_CHECK(T, String);
6704 typedef internal::Internals I;
6705 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6708 template<typename T>
6709 Isolate* ReturnValue<T>::GetIsolate() {
6710 // Isolate is always the pointer below the default value on the stack.
6711 return *reinterpret_cast<Isolate**>(&value_[-2]);
6714 template<typename T>
6715 template<typename S>
6716 void ReturnValue<T>::Set(S* whatever) {
6717 // Uncompilable to prevent inadvertent misuse.
6718 TYPE_CHECK(S*, Primitive);
6721 template<typename T>
6722 internal::Object* ReturnValue<T>::GetDefaultValue() {
6723 // Default value is always the pointer below value_ on the stack.
6728 template<typename T>
6729 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6730 internal::Object** values,
6732 bool is_construct_call)
6733 : implicit_args_(implicit_args),
6736 is_construct_call_(is_construct_call) { }
6739 template<typename T>
6740 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6741 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6742 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6746 template<typename T>
6747 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6748 return Local<Function>(reinterpret_cast<Function*>(
6749 &implicit_args_[kCalleeIndex]));
6753 template<typename T>
6754 Local<Object> FunctionCallbackInfo<T>::This() const {
6755 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6759 template<typename T>
6760 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6761 return Local<Object>(reinterpret_cast<Object*>(
6762 &implicit_args_[kHolderIndex]));
6766 template<typename T>
6767 Local<Value> FunctionCallbackInfo<T>::Data() const {
6768 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6772 template<typename T>
6773 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6774 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6778 template<typename T>
6779 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6780 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6784 template<typename T>
6785 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6786 return is_construct_call_ & 0x1;
6790 template<typename T>
6791 int FunctionCallbackInfo<T>::Length() const {
6796 Handle<Value> ScriptOrigin::ResourceName() const {
6797 return resource_name_;
6801 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6802 return resource_line_offset_;
6806 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6807 return resource_column_offset_;
6811 Handle<Boolean> ScriptOrigin::ResourceIsEmbedderDebugScript() const {
6812 return resource_is_embedder_debug_script_;
6816 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6817 return resource_is_shared_cross_origin_;
6821 Handle<Integer> ScriptOrigin::ScriptID() const {
6826 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6828 : source_string(string),
6829 resource_name(origin.ResourceName()),
6830 resource_line_offset(origin.ResourceLineOffset()),
6831 resource_column_offset(origin.ResourceColumnOffset()),
6832 resource_is_embedder_debug_script(origin.ResourceIsEmbedderDebugScript()),
6833 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6834 cached_data(data) {}
6837 ScriptCompiler::Source::Source(Local<String> string,
6839 : source_string(string), cached_data(data) {}
6842 ScriptCompiler::Source::~Source() {
6847 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6853 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6854 return value ? True(isolate) : False(isolate);
6858 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6859 Set(v8::String::NewFromUtf8(isolate, name), value);
6863 Local<Value> Object::GetInternalField(int index) {
6864 #ifndef V8_ENABLE_CHECKS
6865 typedef internal::Object O;
6866 typedef internal::HeapObject HO;
6867 typedef internal::Internals I;
6868 O* obj = *reinterpret_cast<O**>(this);
6869 // Fast path: If the object is a plain JSObject, which is the common case, we
6870 // know where to find the internal fields and can return the value directly.
6871 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6872 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6873 O* value = I::ReadField<O*>(obj, offset);
6874 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6875 return Local<Value>(reinterpret_cast<Value*>(result));
6878 return SlowGetInternalField(index);
6882 void* Object::GetAlignedPointerFromInternalField(int index) {
6883 #ifndef V8_ENABLE_CHECKS
6884 typedef internal::Object O;
6885 typedef internal::Internals I;
6886 O* obj = *reinterpret_cast<O**>(this);
6887 // Fast path: If the object is a plain JSObject, which is the common case, we
6888 // know where to find the internal fields and can return the value directly.
6889 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6890 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6891 return I::ReadField<void*>(obj, offset);
6894 return SlowGetAlignedPointerFromInternalField(index);
6898 String* String::Cast(v8::Value* value) {
6899 #ifdef V8_ENABLE_CHECKS
6902 return static_cast<String*>(value);
6906 Local<String> String::Empty(Isolate* isolate) {
6907 typedef internal::Object* S;
6908 typedef internal::Internals I;
6909 I::CheckInitialized(isolate);
6910 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6911 return Local<String>(reinterpret_cast<String*>(slot));
6915 String::ExternalStringResource* String::GetExternalStringResource() const {
6916 typedef internal::Object O;
6917 typedef internal::Internals I;
6918 O* obj = *reinterpret_cast<O* const*>(this);
6919 String::ExternalStringResource* result;
6920 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6921 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6922 result = reinterpret_cast<String::ExternalStringResource*>(value);
6926 #ifdef V8_ENABLE_CHECKS
6927 VerifyExternalStringResource(result);
6933 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6934 String::Encoding* encoding_out) const {
6935 typedef internal::Object O;
6936 typedef internal::Internals I;
6937 O* obj = *reinterpret_cast<O* const*>(this);
6938 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6939 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6940 ExternalStringResourceBase* resource = NULL;
6941 if (type == I::kExternalOneByteRepresentationTag ||
6942 type == I::kExternalTwoByteRepresentationTag) {
6943 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6944 resource = static_cast<ExternalStringResourceBase*>(value);
6946 #ifdef V8_ENABLE_CHECKS
6947 VerifyExternalStringResourceBase(resource, *encoding_out);
6953 bool Value::IsUndefined() const {
6954 #ifdef V8_ENABLE_CHECKS
6955 return FullIsUndefined();
6957 return QuickIsUndefined();
6961 bool Value::QuickIsUndefined() const {
6962 typedef internal::Object O;
6963 typedef internal::Internals I;
6964 O* obj = *reinterpret_cast<O* const*>(this);
6965 if (!I::HasHeapObjectTag(obj)) return false;
6966 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6967 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6971 bool Value::IsNull() const {
6972 #ifdef V8_ENABLE_CHECKS
6973 return FullIsNull();
6975 return QuickIsNull();
6979 bool Value::QuickIsNull() const {
6980 typedef internal::Object O;
6981 typedef internal::Internals I;
6982 O* obj = *reinterpret_cast<O* const*>(this);
6983 if (!I::HasHeapObjectTag(obj)) return false;
6984 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6985 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6989 bool Value::IsString() const {
6990 #ifdef V8_ENABLE_CHECKS
6991 return FullIsString();
6993 return QuickIsString();
6997 bool Value::QuickIsString() const {
6998 typedef internal::Object O;
6999 typedef internal::Internals I;
7000 O* obj = *reinterpret_cast<O* const*>(this);
7001 if (!I::HasHeapObjectTag(obj)) return false;
7002 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7006 template <class T> Value* Value::Cast(T* value) {
7007 return static_cast<Value*>(value);
7011 Local<Boolean> Value::ToBoolean() const {
7012 return ToBoolean(Isolate::GetCurrent());
7016 Local<Number> Value::ToNumber() const {
7017 return ToNumber(Isolate::GetCurrent());
7021 Local<String> Value::ToString() const {
7022 return ToString(Isolate::GetCurrent());
7026 Local<String> Value::ToDetailString() const {
7027 return ToDetailString(Isolate::GetCurrent());
7031 Local<Object> Value::ToObject() const {
7032 return ToObject(Isolate::GetCurrent());
7036 Local<Integer> Value::ToInteger() const {
7037 return ToInteger(Isolate::GetCurrent());
7041 Local<Uint32> Value::ToUint32() const {
7042 return ToUint32(Isolate::GetCurrent());
7046 Local<Int32> Value::ToInt32() const { return ToInt32(Isolate::GetCurrent()); }
7049 Name* Name::Cast(v8::Value* value) {
7050 #ifdef V8_ENABLE_CHECKS
7053 return static_cast<Name*>(value);
7057 Symbol* Symbol::Cast(v8::Value* value) {
7058 #ifdef V8_ENABLE_CHECKS
7061 return static_cast<Symbol*>(value);
7065 Number* Number::Cast(v8::Value* value) {
7066 #ifdef V8_ENABLE_CHECKS
7069 return static_cast<Number*>(value);
7073 Integer* Integer::Cast(v8::Value* value) {
7074 #ifdef V8_ENABLE_CHECKS
7077 return static_cast<Integer*>(value);
7081 Date* Date::Cast(v8::Value* value) {
7082 #ifdef V8_ENABLE_CHECKS
7085 return static_cast<Date*>(value);
7089 StringObject* StringObject::Cast(v8::Value* value) {
7090 #ifdef V8_ENABLE_CHECKS
7093 return static_cast<StringObject*>(value);
7097 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7098 #ifdef V8_ENABLE_CHECKS
7101 return static_cast<SymbolObject*>(value);
7105 NumberObject* NumberObject::Cast(v8::Value* value) {
7106 #ifdef V8_ENABLE_CHECKS
7109 return static_cast<NumberObject*>(value);
7113 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7114 #ifdef V8_ENABLE_CHECKS
7117 return static_cast<BooleanObject*>(value);
7121 RegExp* RegExp::Cast(v8::Value* value) {
7122 #ifdef V8_ENABLE_CHECKS
7125 return static_cast<RegExp*>(value);
7129 Object* Object::Cast(v8::Value* value) {
7130 #ifdef V8_ENABLE_CHECKS
7133 return static_cast<Object*>(value);
7137 Array* Array::Cast(v8::Value* value) {
7138 #ifdef V8_ENABLE_CHECKS
7141 return static_cast<Array*>(value);
7145 Promise* Promise::Cast(v8::Value* value) {
7146 #ifdef V8_ENABLE_CHECKS
7149 return static_cast<Promise*>(value);
7153 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7154 #ifdef V8_ENABLE_CHECKS
7157 return static_cast<Promise::Resolver*>(value);
7161 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7162 #ifdef V8_ENABLE_CHECKS
7165 return static_cast<ArrayBuffer*>(value);
7169 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7170 #ifdef V8_ENABLE_CHECKS
7173 return static_cast<ArrayBufferView*>(value);
7177 TypedArray* TypedArray::Cast(v8::Value* value) {
7178 #ifdef V8_ENABLE_CHECKS
7181 return static_cast<TypedArray*>(value);
7185 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7186 #ifdef V8_ENABLE_CHECKS
7189 return static_cast<Uint8Array*>(value);
7193 Int8Array* Int8Array::Cast(v8::Value* value) {
7194 #ifdef V8_ENABLE_CHECKS
7197 return static_cast<Int8Array*>(value);
7201 Uint16Array* Uint16Array::Cast(v8::Value* value) {
7202 #ifdef V8_ENABLE_CHECKS
7205 return static_cast<Uint16Array*>(value);
7209 Int16Array* Int16Array::Cast(v8::Value* value) {
7210 #ifdef V8_ENABLE_CHECKS
7213 return static_cast<Int16Array*>(value);
7217 Uint32Array* Uint32Array::Cast(v8::Value* value) {
7218 #ifdef V8_ENABLE_CHECKS
7221 return static_cast<Uint32Array*>(value);
7225 Int32Array* Int32Array::Cast(v8::Value* value) {
7226 #ifdef V8_ENABLE_CHECKS
7229 return static_cast<Int32Array*>(value);
7233 Float32Array* Float32Array::Cast(v8::Value* value) {
7234 #ifdef V8_ENABLE_CHECKS
7237 return static_cast<Float32Array*>(value);
7241 Float64Array* Float64Array::Cast(v8::Value* value) {
7242 #ifdef V8_ENABLE_CHECKS
7245 return static_cast<Float64Array*>(value);
7249 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
7250 #ifdef V8_ENABLE_CHECKS
7253 return static_cast<Uint8ClampedArray*>(value);
7257 DataView* DataView::Cast(v8::Value* value) {
7258 #ifdef V8_ENABLE_CHECKS
7261 return static_cast<DataView*>(value);
7265 Function* Function::Cast(v8::Value* value) {
7266 #ifdef V8_ENABLE_CHECKS
7269 return static_cast<Function*>(value);
7273 External* External::Cast(v8::Value* value) {
7274 #ifdef V8_ENABLE_CHECKS
7277 return static_cast<External*>(value);
7281 template<typename T>
7282 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
7283 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
7287 template<typename T>
7288 Local<Value> PropertyCallbackInfo<T>::Data() const {
7289 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
7293 template<typename T>
7294 Local<Object> PropertyCallbackInfo<T>::This() const {
7295 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
7299 template<typename T>
7300 Local<Object> PropertyCallbackInfo<T>::Holder() const {
7301 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
7305 template<typename T>
7306 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
7307 return ReturnValue<T>(&args_[kReturnValueIndex]);
7311 Handle<Primitive> Undefined(Isolate* isolate) {
7312 typedef internal::Object* S;
7313 typedef internal::Internals I;
7314 I::CheckInitialized(isolate);
7315 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
7316 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
7320 Handle<Primitive> Null(Isolate* isolate) {
7321 typedef internal::Object* S;
7322 typedef internal::Internals I;
7323 I::CheckInitialized(isolate);
7324 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
7325 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
7329 Handle<Boolean> True(Isolate* isolate) {
7330 typedef internal::Object* S;
7331 typedef internal::Internals I;
7332 I::CheckInitialized(isolate);
7333 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
7334 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
7338 Handle<Boolean> False(Isolate* isolate) {
7339 typedef internal::Object* S;
7340 typedef internal::Internals I;
7341 I::CheckInitialized(isolate);
7342 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
7343 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
7347 void Isolate::SetData(uint32_t slot, void* data) {
7348 typedef internal::Internals I;
7349 I::SetEmbedderData(this, slot, data);
7353 void* Isolate::GetData(uint32_t slot) {
7354 typedef internal::Internals I;
7355 return I::GetEmbedderData(this, slot);
7359 uint32_t Isolate::GetNumberOfDataSlots() {
7360 typedef internal::Internals I;
7361 return I::kNumIsolateDataSlots;
7365 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
7366 int64_t change_in_bytes) {
7367 typedef internal::Internals I;
7368 int64_t* amount_of_external_allocated_memory =
7369 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
7370 I::kAmountOfExternalAllocatedMemoryOffset);
7371 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
7372 reinterpret_cast<int64_t*>(
7373 reinterpret_cast<uint8_t*>(this) +
7374 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
7375 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
7376 if (change_in_bytes > 0 &&
7377 amount - *amount_of_external_allocated_memory_at_last_global_gc >
7378 I::kExternalAllocationLimit) {
7379 CollectAllGarbage("external memory allocation limit reached.");
7381 *amount_of_external_allocated_memory = amount;
7382 return *amount_of_external_allocated_memory;
7386 template<typename T>
7387 void Isolate::SetObjectGroupId(const Persistent<T>& object,
7389 TYPE_CHECK(Value, T);
7390 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
7394 template<typename T>
7395 void Isolate::SetReferenceFromGroup(UniqueId id,
7396 const Persistent<T>& object) {
7397 TYPE_CHECK(Value, T);
7398 SetReferenceFromGroup(id,
7399 reinterpret_cast<v8::internal::Object**>(object.val_));
7403 template<typename T, typename S>
7404 void Isolate::SetReference(const Persistent<T>& parent,
7405 const Persistent<S>& child) {
7406 TYPE_CHECK(Object, T);
7407 TYPE_CHECK(Value, S);
7408 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
7409 reinterpret_cast<v8::internal::Object**>(child.val_));
7413 Local<Value> Context::GetEmbedderData(int index) {
7414 #ifndef V8_ENABLE_CHECKS
7415 typedef internal::Object O;
7416 typedef internal::HeapObject HO;
7417 typedef internal::Internals I;
7418 HO* context = *reinterpret_cast<HO**>(this);
7420 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
7421 return Local<Value>(reinterpret_cast<Value*>(result));
7423 return SlowGetEmbedderData(index);
7428 void* Context::GetAlignedPointerFromEmbedderData(int index) {
7429 #ifndef V8_ENABLE_CHECKS
7430 typedef internal::Internals I;
7431 return I::ReadEmbedderData<void*>(this, index);
7433 return SlowGetAlignedPointerFromEmbedderData(index);
7438 void V8::SetAllowCodeGenerationFromStringsCallback(
7439 AllowCodeGenerationFromStringsCallback callback) {
7440 Isolate* isolate = Isolate::GetCurrent();
7441 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
7446 Isolate* isolate = Isolate::GetCurrent();
7447 return isolate->IsDead();
7451 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
7452 Isolate* isolate = Isolate::GetCurrent();
7453 return isolate->AddMessageListener(that, data);
7457 void V8::RemoveMessageListeners(MessageCallback that) {
7458 Isolate* isolate = Isolate::GetCurrent();
7459 isolate->RemoveMessageListeners(that);
7463 void V8::SetFailedAccessCheckCallbackFunction(
7464 FailedAccessCheckCallback callback) {
7465 Isolate* isolate = Isolate::GetCurrent();
7466 isolate->SetFailedAccessCheckCallbackFunction(callback);
7470 void V8::SetCaptureStackTraceForUncaughtExceptions(
7471 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7472 Isolate* isolate = Isolate::GetCurrent();
7473 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7478 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
7479 Isolate* isolate = Isolate::GetCurrent();
7480 isolate->SetFatalErrorHandler(callback);
7484 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
7485 Isolate* isolate = Isolate::GetCurrent();
7486 isolate->RemoveGCPrologueCallback(
7487 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
7491 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7492 Isolate* isolate = Isolate::GetCurrent();
7493 isolate->RemoveGCEpilogueCallback(
7494 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
7498 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7500 AllocationAction action) {
7501 Isolate* isolate = Isolate::GetCurrent();
7502 isolate->AddMemoryAllocationCallback(callback, space, action);
7506 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
7507 Isolate* isolate = Isolate::GetCurrent();
7508 isolate->RemoveMemoryAllocationCallback(callback);
7512 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
7515 bool V8::IsExecutionTerminating(Isolate* isolate) {
7516 if (isolate == NULL) {
7517 isolate = Isolate::GetCurrent();
7519 return isolate->IsExecutionTerminating();
7523 void V8::CancelTerminateExecution(Isolate* isolate) {
7524 isolate->CancelTerminateExecution();
7528 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
7529 Isolate* isolate = Isolate::GetCurrent();
7530 isolate->VisitExternalResources(visitor);
7534 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7535 Isolate* isolate = Isolate::GetCurrent();
7536 isolate->VisitHandlesWithClassIds(visitor);
7540 void V8::VisitHandlesWithClassIds(Isolate* isolate,
7541 PersistentHandleVisitor* visitor) {
7542 isolate->VisitHandlesWithClassIds(visitor);
7546 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
7547 PersistentHandleVisitor* visitor) {
7548 isolate->VisitHandlesForPartialDependence(visitor);
7553 * A simple shell that takes a list of expressions on the
7554 * command-line and executes them.
7559 * \example process.cc