1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /** \mainpage V8 API Reference Guide
7 * V8 is Google's open source JavaScript engine.
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
12 * For other documentation see http://code.google.com/apis/v8/
20 // We reserve the V8_* prefix for macros defined in V8 public API and
21 // assume there are no name conflicts with the embedder's code.
25 // Setup for Windows DLL export/import. When building the V8 DLL the
26 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
27 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
28 // static library or building a program which uses the V8 static library neither
29 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
30 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
31 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
32 build configuration to ensure that at most one of these is set
35 #ifdef BUILDING_V8_SHARED
36 # define V8_EXPORT __declspec(dllexport)
38 # define V8_EXPORT __declspec(dllimport)
41 #endif // BUILDING_V8_SHARED
45 // Setup for Linux shared library export.
46 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
47 # ifdef BUILDING_V8_SHARED
48 # define V8_EXPORT __attribute__ ((visibility("default")))
59 * The v8 JavaScript engine.
63 class AccessorSignature;
71 class DeclaredAccessorDescriptor;
74 class FunctionTemplate;
76 class ImplementationUtilities;
84 class ObjectOperationDescriptor;
88 class RawOperationDescriptor;
101 template <class T> class Handle;
102 template <class T> class Local;
103 template <class T> class Eternal;
104 template<class T> class NonCopyablePersistentTraits;
105 template<class T> class PersistentBase;
107 class M = NonCopyablePersistentTraits<T> > class Persistent;
108 template<class T> class UniquePersistent;
109 template<class K, class V, class T> class PersistentValueMap;
110 template<class V, class T> class PersistentValueVector;
111 template<class T, class P> class WeakCallbackObject;
112 class FunctionTemplate;
113 class ObjectTemplate;
115 template<typename T> class FunctionCallbackInfo;
116 template<typename T> class PropertyCallbackInfo;
120 class DeclaredAccessorDescriptor;
121 class ObjectOperationDescriptor;
122 class RawOperationDescriptor;
123 class CallHandlerHelper;
124 class EscapableHandleScope;
125 template<typename T> class ReturnValue;
133 struct StreamedSource;
134 template<typename T> class CustomArguments;
135 class PropertyCallbackArguments;
136 class FunctionCallbackArguments;
142 * General purpose unique identifier.
146 explicit UniqueId(intptr_t data)
149 bool operator==(const UniqueId& other) const {
150 return data_ == other.data_;
153 bool operator!=(const UniqueId& other) const {
154 return data_ != other.data_;
157 bool operator<(const UniqueId& other) const {
158 return data_ < other.data_;
167 #define TYPE_CHECK(T, S) \
169 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
174 * An object reference managed by the v8 garbage collector.
176 * All objects returned from v8 have to be tracked by the garbage
177 * collector so that it knows that the objects are still alive. Also,
178 * because the garbage collector may move objects, it is unsafe to
179 * point directly to an object. Instead, all objects are stored in
180 * handles which are known by the garbage collector and updated
181 * whenever an object moves. Handles should always be passed by value
182 * (except in cases like out-parameters) and they should never be
183 * allocated on the heap.
185 * There are two types of handles: local and persistent handles.
186 * Local handles are light-weight and transient and typically used in
187 * local operations. They are managed by HandleScopes. Persistent
188 * handles can be used when storing objects across several independent
189 * operations and have to be explicitly deallocated when they're no
192 * It is safe to extract the object stored in the handle by
193 * dereferencing the handle (for instance, to extract the Object* from
194 * a Handle<Object>); the value will still be governed by a handle
195 * behind the scenes and the same rules apply to these values as to
198 template <class T> class Handle {
201 * Creates an empty handle.
203 V8_INLINE Handle() : val_(0) {}
206 * Creates a handle for the contents of the specified handle. This
207 * constructor allows you to pass handles as arguments by value and
208 * to assign between handles. However, if you try to assign between
209 * incompatible handles, for instance from a Handle<String> to a
210 * Handle<Number> it will cause a compile-time error. Assigning
211 * between compatible handles, for instance assigning a
212 * Handle<String> to a variable declared as Handle<Value>, is legal
213 * because String is a subclass of Value.
215 template <class S> V8_INLINE Handle(Handle<S> that)
216 : val_(reinterpret_cast<T*>(*that)) {
218 * This check fails when trying to convert between incompatible
219 * handles. For example, converting from a Handle<String> to a
226 * Returns true if the handle is empty.
228 V8_INLINE bool IsEmpty() const { return val_ == 0; }
231 * Sets the handle to be empty. IsEmpty() will then return true.
233 V8_INLINE void Clear() { val_ = 0; }
235 V8_INLINE T* operator->() const { return val_; }
237 V8_INLINE T* operator*() const { return val_; }
240 * Checks whether two handles are the same.
241 * Returns true if both are empty, or if the objects
242 * to which they refer are identical.
243 * The handles' references are not checked.
245 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
246 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
247 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
248 if (a == 0) return b == 0;
249 if (b == 0) return false;
253 template <class S> V8_INLINE bool operator==(
254 const PersistentBase<S>& that) const {
255 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
256 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
257 if (a == 0) return b == 0;
258 if (b == 0) return false;
263 * Checks whether two handles are different.
264 * Returns true if only one of the handles is empty, or if
265 * the objects to which they refer are different.
266 * The handles' references are not checked.
268 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
269 return !operator==(that);
272 template <class S> V8_INLINE bool operator!=(
273 const Persistent<S>& that) const {
274 return !operator==(that);
277 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
278 #ifdef V8_ENABLE_CHECKS
279 // If we're going to perform the type check then we have to check
280 // that the handle isn't empty before doing the checked cast.
281 if (that.IsEmpty()) return Handle<T>();
283 return Handle<T>(T::Cast(*that));
286 template <class S> V8_INLINE Handle<S> As() {
287 return Handle<S>::Cast(*this);
290 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
291 return New(isolate, that.val_);
293 V8_INLINE static Handle<T> New(Isolate* isolate,
294 const PersistentBase<T>& that) {
295 return New(isolate, that.val_);
300 template<class F, class M> friend class Persistent;
301 template<class F> friend class PersistentBase;
302 template<class F> friend class Handle;
303 template<class F> friend class Local;
304 template<class F> friend class FunctionCallbackInfo;
305 template<class F> friend class PropertyCallbackInfo;
306 template<class F> friend class internal::CustomArguments;
307 friend Handle<Primitive> Undefined(Isolate* isolate);
308 friend Handle<Primitive> Null(Isolate* isolate);
309 friend Handle<Boolean> True(Isolate* isolate);
310 friend Handle<Boolean> False(Isolate* isolate);
311 friend class Context;
312 friend class HandleScope;
314 friend class Private;
317 * Creates a new handle for the specified value.
319 V8_INLINE explicit Handle(T* val) : val_(val) {}
321 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
328 * A light-weight stack-allocated object handle. All operations
329 * that return objects from within v8 return them in local handles. They
330 * are created within HandleScopes, and all local handles allocated within a
331 * handle scope are destroyed when the handle scope is destroyed. Hence it
332 * is not necessary to explicitly deallocate local handles.
334 template <class T> class Local : public Handle<T> {
337 template <class S> V8_INLINE Local(Local<S> that)
338 : Handle<T>(reinterpret_cast<T*>(*that)) {
340 * This check fails when trying to convert between incompatible
341 * handles. For example, converting from a Handle<String> to a
348 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
349 #ifdef V8_ENABLE_CHECKS
350 // If we're going to perform the type check then we have to check
351 // that the handle isn't empty before doing the checked cast.
352 if (that.IsEmpty()) return Local<T>();
354 return Local<T>(T::Cast(*that));
356 template <class S> V8_INLINE Local(Handle<S> that)
357 : Handle<T>(reinterpret_cast<T*>(*that)) {
361 template <class S> V8_INLINE Local<S> As() {
362 return Local<S>::Cast(*this);
366 * Create a local handle for the content of another handle.
367 * The referee is kept alive by the local handle even when
368 * the original handle is destroyed/disposed.
370 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
371 V8_INLINE static Local<T> New(Isolate* isolate,
372 const PersistentBase<T>& that);
376 template<class F> friend class Eternal;
377 template<class F> friend class PersistentBase;
378 template<class F, class M> friend class Persistent;
379 template<class F> friend class Handle;
380 template<class F> friend class Local;
381 template<class F> friend class FunctionCallbackInfo;
382 template<class F> friend class PropertyCallbackInfo;
385 friend class Context;
386 template<class F> friend class internal::CustomArguments;
387 friend class HandleScope;
388 friend class EscapableHandleScope;
389 template<class F1, class F2, class F3> friend class PersistentValueMap;
390 template<class F1, class F2> friend class PersistentValueVector;
392 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
393 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
397 // Eternal handles are set-once handles that live for the life of the isolate.
398 template <class T> class Eternal {
400 V8_INLINE Eternal() : index_(kInitialValue) { }
402 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
403 Set(isolate, handle);
405 // Can only be safely called if already set.
406 V8_INLINE Local<T> Get(Isolate* isolate);
407 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
408 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
411 static const int kInitialValue = -1;
416 template<class T, class P>
417 class WeakCallbackData {
419 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
421 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
422 V8_INLINE Local<T> GetValue() const { return handle_; }
423 V8_INLINE P* GetParameter() const { return parameter_; }
426 friend class internal::GlobalHandles;
427 WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
428 : isolate_(isolate), handle_(handle), parameter_(parameter) { }
436 * An object reference that is independent of any handle scope. Where
437 * a Local handle only lives as long as the HandleScope in which it was
438 * allocated, a PersistentBase handle remains valid until it is explicitly
441 * A persistent handle contains a reference to a storage cell within
442 * the v8 engine which holds an object value and which is updated by
443 * the garbage collector whenever the object is moved. A new storage
444 * cell can be created using the constructor or PersistentBase::Reset and
445 * existing handles can be disposed using PersistentBase::Reset.
448 template <class T> class PersistentBase {
451 * If non-empty, destroy the underlying storage cell
452 * IsEmpty() will return true after this call.
454 V8_INLINE void Reset();
456 * If non-empty, destroy the underlying storage cell
457 * and create a new one with the contents of other if other is non empty
460 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
463 * If non-empty, destroy the underlying storage cell
464 * and create a new one with the contents of other if other is non empty
467 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
469 V8_INLINE bool IsEmpty() const { return val_ == 0; }
472 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
473 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
474 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
475 if (a == 0) return b == 0;
476 if (b == 0) return false;
480 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
481 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
482 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
483 if (a == 0) return b == 0;
484 if (b == 0) return false;
489 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
490 return !operator==(that);
493 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
494 return !operator==(that);
498 * Install a finalization callback on this object.
499 * NOTE: There is no guarantee as to *when* or even *if* the callback is
500 * invoked. The invocation is performed solely on a best effort basis.
501 * As always, GC-based finalization should *not* be relied upon for any
502 * critical form of resource management!
505 V8_INLINE void SetWeak(
507 typename WeakCallbackData<T, P>::Callback callback);
509 template<typename S, typename P>
510 V8_INLINE void SetWeak(
512 typename WeakCallbackData<S, P>::Callback callback);
515 V8_INLINE P* ClearWeak();
517 // TODO(dcarney): remove this.
518 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
521 * Marks the reference to this object independent. Garbage collector is free
522 * to ignore any object groups containing this object. Weak callback for an
523 * independent handle should not assume that it will be preceded by a global
524 * GC prologue callback or followed by a global GC epilogue callback.
526 V8_INLINE void MarkIndependent();
529 * Marks the reference to this object partially dependent. Partially dependent
530 * handles only depend on other partially dependent handles and these
531 * dependencies are provided through object groups. It provides a way to build
532 * smaller object groups for young objects that represent only a subset of all
533 * external dependencies. This mark is automatically cleared after each
534 * garbage collection.
536 V8_INLINE void MarkPartiallyDependent();
538 V8_INLINE bool IsIndependent() const;
540 /** Checks if the handle holds the only reference to an object. */
541 V8_INLINE bool IsNearDeath() const;
543 /** Returns true if the handle's reference is weak. */
544 V8_INLINE bool IsWeak() const;
547 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
548 * description in v8-profiler.h for details.
550 V8_INLINE void SetWrapperClassId(uint16_t class_id);
553 * Returns the class ID previously assigned to this handle or 0 if no class ID
554 * was previously assigned.
556 V8_INLINE uint16_t WrapperClassId() const;
559 friend class Isolate;
561 template<class F> friend class Handle;
562 template<class F> friend class Local;
563 template<class F1, class F2> friend class Persistent;
564 template<class F> friend class UniquePersistent;
565 template<class F> friend class PersistentBase;
566 template<class F> friend class ReturnValue;
567 template<class F1, class F2, class F3> friend class PersistentValueMap;
568 template<class F1, class F2> friend class PersistentValueVector;
571 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
572 PersistentBase(PersistentBase& other); // NOLINT
573 void operator=(PersistentBase&);
574 V8_INLINE static T* New(Isolate* isolate, T* that);
581 * Default traits for Persistent. This class does not allow
582 * use of the copy constructor or assignment operator.
583 * At present kResetInDestructor is not set, but that will change in a future
587 class NonCopyablePersistentTraits {
589 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
590 static const bool kResetInDestructor = false;
591 template<class S, class M>
592 V8_INLINE static void Copy(const Persistent<S, M>& source,
593 NonCopyablePersistent* dest) {
594 Uncompilable<Object>();
596 // TODO(dcarney): come up with a good compile error here.
597 template<class O> V8_INLINE static void Uncompilable() {
598 TYPE_CHECK(O, Primitive);
604 * Helper class traits to allow copying and assignment of Persistent.
605 * This will clone the contents of storage cell, but not any of the flags, etc.
608 struct CopyablePersistentTraits {
609 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
610 static const bool kResetInDestructor = true;
611 template<class S, class M>
612 static V8_INLINE void Copy(const Persistent<S, M>& source,
613 CopyablePersistent* dest) {
614 // do nothing, just allow copy
620 * A PersistentBase which allows copy and assignment.
622 * Copy, assignment and destructor bevavior is controlled by the traits
625 * Note: Persistent class hierarchy is subject to future changes.
627 template <class T, class M> class Persistent : public PersistentBase<T> {
630 * A Persistent with no storage cell.
632 V8_INLINE Persistent() : PersistentBase<T>(0) { }
634 * Construct a Persistent from a Handle.
635 * When the Handle is non-empty, a new storage cell is created
636 * pointing to the same object, and no flags are set.
638 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
639 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
643 * Construct a Persistent from a Persistent.
644 * When the Persistent is non-empty, a new storage cell is created
645 * pointing to the same object, and no flags are set.
647 template <class S, class M2>
648 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
649 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
653 * The copy constructors and assignment operator create a Persistent
654 * exactly as the Persistent constructor, but the Copy function from the
655 * traits class is called, allowing the setting of flags based on the
658 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
661 template <class S, class M2>
662 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
665 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
669 template <class S, class M2>
670 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
675 * The destructor will dispose the Persistent based on the
676 * kResetInDestructor flags in the traits class. Since not calling dispose
677 * can result in a memory leak, it is recommended to always set this flag.
679 V8_INLINE ~Persistent() {
680 if (M::kResetInDestructor) this->Reset();
683 // TODO(dcarney): this is pretty useless, fix or remove
685 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
686 #ifdef V8_ENABLE_CHECKS
687 // If we're going to perform the type check then we have to check
688 // that the handle isn't empty before doing the checked cast.
689 if (!that.IsEmpty()) T::Cast(*that);
691 return reinterpret_cast<Persistent<T>&>(that);
694 // TODO(dcarney): this is pretty useless, fix or remove
695 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
696 return Persistent<S>::Cast(*this);
699 // This will be removed.
700 V8_INLINE T* ClearAndLeak();
703 friend class Isolate;
705 template<class F> friend class Handle;
706 template<class F> friend class Local;
707 template<class F1, class F2> friend class Persistent;
708 template<class F> friend class ReturnValue;
710 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
711 V8_INLINE T* operator*() const { return this->val_; }
712 template<class S, class M2>
713 V8_INLINE void Copy(const Persistent<S, M2>& that);
718 * A PersistentBase which has move semantics.
720 * Note: Persistent class hierarchy is subject to future changes.
723 class UniquePersistent : public PersistentBase<T> {
725 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
726 UniquePersistent* object;
731 * A UniquePersistent with no storage cell.
733 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
735 * Construct a UniquePersistent from a Handle.
736 * When the Handle is non-empty, a new storage cell is created
737 * pointing to the same object, and no flags are set.
740 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
741 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
745 * Construct a UniquePersistent from a PersistentBase.
746 * When the Persistent is non-empty, a new storage cell is created
747 * pointing to the same object, and no flags are set.
750 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
751 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
757 V8_INLINE UniquePersistent(RValue rvalue)
758 : PersistentBase<T>(rvalue.object->val_) {
759 rvalue.object->val_ = 0;
761 V8_INLINE ~UniquePersistent() { this->Reset(); }
763 * Move via assignment.
766 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
769 this->val_ = rhs.val_;
774 * Cast operator for moves.
776 V8_INLINE operator RValue() { return RValue(this); }
778 * Pass allows returning uniques from functions, etc.
780 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
783 UniquePersistent(UniquePersistent&);
784 void operator=(UniquePersistent&);
789 * A stack-allocated class that governs a number of local handles.
790 * After a handle scope has been created, all local handles will be
791 * allocated within that handle scope until either the handle scope is
792 * deleted or another handle scope is created. If there is already a
793 * handle scope and a new one is created, all allocations will take
794 * place in the new handle scope until it is deleted. After that,
795 * new handles will again be allocated in the original handle scope.
797 * After the handle scope of a local handle has been deleted the
798 * garbage collector will no longer track the object stored in the
799 * handle and may deallocate it. The behavior of accessing a handle
800 * for which the handle scope has been deleted is undefined.
802 class V8_EXPORT HandleScope {
804 HandleScope(Isolate* isolate);
809 * Counts the number of allocated handles.
811 static int NumberOfHandles(Isolate* isolate);
813 V8_INLINE Isolate* GetIsolate() const {
814 return reinterpret_cast<Isolate*>(isolate_);
818 V8_INLINE HandleScope() {}
820 void Initialize(Isolate* isolate);
822 static internal::Object** CreateHandle(internal::Isolate* isolate,
823 internal::Object* value);
826 // Uses heap_object to obtain the current Isolate.
827 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
828 internal::Object* value);
830 // Make it hard to create heap-allocated or illegal handle scopes by
831 // disallowing certain operations.
832 HandleScope(const HandleScope&);
833 void operator=(const HandleScope&);
834 void* operator new(size_t size);
835 void operator delete(void*, size_t);
837 internal::Isolate* isolate_;
838 internal::Object** prev_next_;
839 internal::Object** prev_limit_;
841 // Local::New uses CreateHandle with an Isolate* parameter.
842 template<class F> friend class Local;
844 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
845 // a HeapObject* in their shortcuts.
847 friend class Context;
852 * A HandleScope which first allocates a handle in the current scope
853 * which will be later filled with the escape value.
855 class V8_EXPORT EscapableHandleScope : public HandleScope {
857 EscapableHandleScope(Isolate* isolate);
858 V8_INLINE ~EscapableHandleScope() {}
861 * Pushes the value into the previous scope and returns a handle to it.
862 * Cannot be called twice.
865 V8_INLINE Local<T> Escape(Local<T> value) {
866 internal::Object** slot =
867 Escape(reinterpret_cast<internal::Object**>(*value));
868 return Local<T>(reinterpret_cast<T*>(slot));
872 internal::Object** Escape(internal::Object** escape_value);
874 // Make it hard to create heap-allocated or illegal handle scopes by
875 // disallowing certain operations.
876 EscapableHandleScope(const EscapableHandleScope&);
877 void operator=(const EscapableHandleScope&);
878 void* operator new(size_t size);
879 void operator delete(void*, size_t);
881 internal::Object** escape_slot_;
886 * A simple Maybe type, representing an object which may or may not have a
891 Maybe() : has_value(false) {}
892 explicit Maybe(T t) : has_value(true), value(t) {}
893 Maybe(bool has, T t) : has_value(has), value(t) {}
900 // Convenience wrapper.
902 inline Maybe<T> maybe(T t) {
907 // --- Special objects ---
911 * The superclass of values and API object templates.
913 class V8_EXPORT Data {
920 * The origin, within a file, of a script.
924 V8_INLINE ScriptOrigin(
925 Handle<Value> resource_name,
926 Handle<Integer> resource_line_offset = Handle<Integer>(),
927 Handle<Integer> resource_column_offset = Handle<Integer>(),
928 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
929 Handle<Integer> script_id = Handle<Integer>())
930 : resource_name_(resource_name),
931 resource_line_offset_(resource_line_offset),
932 resource_column_offset_(resource_column_offset),
933 resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
934 script_id_(script_id) { }
935 V8_INLINE Handle<Value> ResourceName() const;
936 V8_INLINE Handle<Integer> ResourceLineOffset() const;
937 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
938 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
939 V8_INLINE Handle<Integer> ScriptID() const;
941 Handle<Value> resource_name_;
942 Handle<Integer> resource_line_offset_;
943 Handle<Integer> resource_column_offset_;
944 Handle<Boolean> resource_is_shared_cross_origin_;
945 Handle<Integer> script_id_;
950 * A compiled JavaScript script, not yet tied to a Context.
952 class V8_EXPORT UnboundScript {
955 * Binds the script to the currently entered context.
957 Local<Script> BindToCurrentContext();
960 Handle<Value> GetScriptName();
963 * Data read from magic sourceURL comments.
965 Handle<Value> GetSourceURL();
967 * Data read from magic sourceMappingURL comments.
969 Handle<Value> GetSourceMappingURL();
972 * Returns zero based line number of the code_pos location in the script.
973 * -1 will be returned if no information available.
975 int GetLineNumber(int code_pos);
977 static const int kNoScriptId = 0;
982 * A compiled JavaScript script, tied to a Context which was active when the
983 * script was compiled.
985 class V8_EXPORT Script {
988 * A shorthand for ScriptCompiler::Compile().
990 static Local<Script> Compile(Handle<String> source,
991 ScriptOrigin* origin = NULL);
993 // To be decprecated, use the Compile above.
994 static Local<Script> Compile(Handle<String> source,
995 Handle<String> file_name);
998 * Runs the script returning the resulting value. It will be run in the
999 * context in which it was created (ScriptCompiler::CompileBound or
1000 * UnboundScript::BindToGlobalContext()).
1005 * Returns the corresponding context-unbound script.
1007 Local<UnboundScript> GetUnboundScript();
1009 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1011 return GetUnboundScript()->GetId();
1017 * For compiling scripts.
1019 class V8_EXPORT ScriptCompiler {
1022 * Compilation data that the embedder can cache and pass back to speed up
1023 * future compilations. The data is produced if the CompilerOptions passed to
1024 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1025 * = true. The data to cache can then can be retrieved from
1028 struct V8_EXPORT CachedData {
1034 CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1036 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1037 // data and guarantees that it stays alive until the CachedData object is
1038 // destroyed. If the policy is BufferOwned, the given data will be deleted
1039 // (with delete[]) when the CachedData object is destroyed.
1040 CachedData(const uint8_t* data, int length,
1041 BufferPolicy buffer_policy = BufferNotOwned);
1043 // TODO(marja): Async compilation; add constructors which take a callback
1044 // which will be called when V8 no longer needs the data.
1045 const uint8_t* data;
1047 BufferPolicy buffer_policy;
1050 // Prevent copying. Not implemented.
1051 CachedData(const CachedData&);
1052 CachedData& operator=(const CachedData&);
1056 * Source code which can be then compiled to a UnboundScript or Script.
1060 // Source takes ownership of CachedData.
1061 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1062 CachedData* cached_data = NULL);
1063 V8_INLINE Source(Local<String> source_string,
1064 CachedData* cached_data = NULL);
1065 V8_INLINE ~Source();
1067 // Ownership of the CachedData or its buffers is *not* transferred to the
1068 // caller. The CachedData object is alive as long as the Source object is
1070 V8_INLINE const CachedData* GetCachedData() const;
1073 friend class ScriptCompiler;
1074 // Prevent copying. Not implemented.
1075 Source(const Source&);
1076 Source& operator=(const Source&);
1078 Local<String> source_string;
1080 // Origin information
1081 Handle<Value> resource_name;
1082 Handle<Integer> resource_line_offset;
1083 Handle<Integer> resource_column_offset;
1084 Handle<Boolean> resource_is_shared_cross_origin;
1086 // Cached data from previous compilation (if a kConsume*Cache flag is
1087 // set), or hold newly generated cache data (kProduce*Cache flags) are
1088 // set when calling a compile method.
1089 CachedData* cached_data;
1093 * For streaming incomplete script data to V8. The embedder should implement a
1094 * subclass of this class.
1096 class ExternalSourceStream {
1098 virtual ~ExternalSourceStream() {}
1101 * V8 calls this to request the next chunk of data from the embedder. This
1102 * function will be called on a background thread, so it's OK to block and
1103 * wait for the data, if the embedder doesn't have data yet. Returns the
1104 * length of the data returned. When the data ends, GetMoreData should
1105 * return 0. Caller takes ownership of the data.
1107 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1108 * two data chunks, but doesn't handle multi-byte characters split between
1109 * more than two data chunks. The embedder can avoid this problem by always
1110 * returning at least 2 bytes of data.
1112 * If the embedder wants to cancel the streaming, they should make the next
1113 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1114 * probably, parsing will fail). The streaming task will return as soon as
1115 * V8 has parsed the data it received so far.
1117 virtual size_t GetMoreData(const uint8_t** src) = 0;
1122 * Source code which can be streamed into V8 in pieces. It will be parsed
1123 * while streaming. It can be compiled after the streaming is complete.
1124 * StreamedSource must be kept alive while the streaming task is ran (see
1125 * ScriptStreamingTask below).
1127 class V8_EXPORT StreamedSource {
1129 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1131 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1134 // Ownership of the CachedData or its buffers is *not* transferred to the
1135 // caller. The CachedData object is alive as long as the StreamedSource
1137 const CachedData* GetCachedData() const;
1139 internal::StreamedSource* impl() const { return impl_; }
1142 // Prevent copying. Not implemented.
1143 StreamedSource(const StreamedSource&);
1144 StreamedSource& operator=(const StreamedSource&);
1146 internal::StreamedSource* impl_;
1150 * A streaming task which the embedder must run on a background thread to
1151 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1153 class ScriptStreamingTask {
1155 virtual ~ScriptStreamingTask() {}
1156 virtual void Run() = 0;
1159 enum CompileOptions {
1160 kNoCompileOptions = 0,
1161 kProduceParserCache,
1162 kConsumeParserCache,
1166 // Support the previous API for a transition period.
1171 * Compiles the specified script (context-independent).
1172 * Cached data as part of the source object can be optionally produced to be
1173 * consumed later to speed up compilation of identical source scripts.
1175 * Note that when producing cached data, the source must point to NULL for
1176 * cached data. When consuming cached data, the cached data must have been
1177 * produced by the same version of V8.
1179 * \param source Script source code.
1180 * \return Compiled script object (context independent; for running it must be
1181 * bound to a context).
1183 static Local<UnboundScript> CompileUnbound(
1184 Isolate* isolate, Source* source,
1185 CompileOptions options = kNoCompileOptions);
1188 * Compiles the specified script (bound to current context).
1190 * \param source Script source code.
1191 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1192 * using pre_data speeds compilation if it's done multiple times.
1193 * Owned by caller, no references are kept when this function returns.
1194 * \return Compiled script object, bound to the context that was active
1195 * when this function was called. When run it will always use this
1198 static Local<Script> Compile(
1199 Isolate* isolate, Source* source,
1200 CompileOptions options = kNoCompileOptions);
1203 * Returns a task which streams script data into V8, or NULL if the script
1204 * cannot be streamed. The user is responsible for running the task on a
1205 * background thread and deleting it. When ran, the task starts parsing the
1206 * script, and it will request data from the StreamedSource as needed. When
1207 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1208 * can be compiled (see Compile below).
1210 * This API allows to start the streaming with as little data as possible, and
1211 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1213 static ScriptStreamingTask* StartStreamingScript(
1214 Isolate* isolate, StreamedSource* source,
1215 CompileOptions options = kNoCompileOptions);
1218 * Compiles a streamed script (bound to current context).
1220 * This can only be called after the streaming has finished
1221 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1222 * during streaming, so the embedder needs to pass the full source here.
1224 static Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1225 Handle<String> full_source_string,
1226 const ScriptOrigin& origin);
1233 class V8_EXPORT Message {
1235 Local<String> Get() const;
1236 Local<String> GetSourceLine() const;
1239 * Returns the origin for the script from where the function causing the
1242 ScriptOrigin GetScriptOrigin() const;
1245 * Returns the resource name for the script from where the function causing
1246 * the error originates.
1248 Handle<Value> GetScriptResourceName() const;
1251 * Exception stack trace. By default stack traces are not captured for
1252 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1253 * to change this option.
1255 Handle<StackTrace> GetStackTrace() const;
1258 * Returns the number, 1-based, of the line where the error occurred.
1260 int GetLineNumber() const;
1263 * Returns the index within the script of the first character where
1264 * the error occurred.
1266 int GetStartPosition() const;
1269 * Returns the index within the script of the last character where
1270 * the error occurred.
1272 int GetEndPosition() const;
1275 * Returns the index within the line of the first character where
1276 * the error occurred.
1278 int GetStartColumn() const;
1281 * Returns the index within the line of the last character where
1282 * the error occurred.
1284 int GetEndColumn() const;
1287 * Passes on the value set by the embedder when it fed the script from which
1288 * this Message was generated to V8.
1290 bool IsSharedCrossOrigin() const;
1292 // TODO(1245381): Print to a string instead of on a FILE.
1293 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1295 static const int kNoLineNumberInfo = 0;
1296 static const int kNoColumnInfo = 0;
1297 static const int kNoScriptIdInfo = 0;
1302 * Representation of a JavaScript stack trace. The information collected is a
1303 * snapshot of the execution stack and the information remains valid after
1304 * execution continues.
1306 class V8_EXPORT StackTrace {
1309 * Flags that determine what information is placed captured for each
1310 * StackFrame when grabbing the current stack trace.
1312 enum StackTraceOptions {
1314 kColumnOffset = 1 << 1 | kLineNumber,
1315 kScriptName = 1 << 2,
1316 kFunctionName = 1 << 3,
1318 kIsConstructor = 1 << 5,
1319 kScriptNameOrSourceURL = 1 << 6,
1321 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1322 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1323 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1327 * Returns a StackFrame at a particular index.
1329 Local<StackFrame> GetFrame(uint32_t index) const;
1332 * Returns the number of StackFrames.
1334 int GetFrameCount() const;
1337 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1339 Local<Array> AsArray();
1342 * Grab a snapshot of the current JavaScript execution stack.
1344 * \param frame_limit The maximum number of stack frames we want to capture.
1345 * \param options Enumerates the set of things we will capture for each
1348 static Local<StackTrace> CurrentStackTrace(
1351 StackTraceOptions options = kOverview);
1356 * A single JavaScript stack frame.
1358 class V8_EXPORT StackFrame {
1361 * Returns the number, 1-based, of the line for the associate function call.
1362 * This method will return Message::kNoLineNumberInfo if it is unable to
1363 * retrieve the line number, or if kLineNumber was not passed as an option
1364 * when capturing the StackTrace.
1366 int GetLineNumber() const;
1369 * Returns the 1-based column offset on the line for the associated function
1371 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1372 * the column number, or if kColumnOffset was not passed as an option when
1373 * capturing the StackTrace.
1375 int GetColumn() const;
1378 * Returns the id of the script for the function for this StackFrame.
1379 * This method will return Message::kNoScriptIdInfo if it is unable to
1380 * retrieve the script id, or if kScriptId was not passed as an option when
1381 * capturing the StackTrace.
1383 int GetScriptId() const;
1386 * Returns the name of the resource that contains the script for the
1387 * function for this StackFrame.
1389 Local<String> GetScriptName() const;
1392 * Returns the name of the resource that contains the script for the
1393 * function for this StackFrame or sourceURL value if the script name
1394 * is undefined and its source ends with //# sourceURL=... string or
1395 * deprecated //@ sourceURL=... string.
1397 Local<String> GetScriptNameOrSourceURL() const;
1400 * Returns the name of the function associated with this stack frame.
1402 Local<String> GetFunctionName() const;
1405 * Returns whether or not the associated function is compiled via a call to
1408 bool IsEval() const;
1411 * Returns whether or not the associated function is called as a
1412 * constructor via "new".
1414 bool IsConstructor() const;
1421 class V8_EXPORT JSON {
1424 * Tries to parse the string |json_string| and returns it as value if
1427 * \param json_string The string to parse.
1428 * \return The corresponding value if successfully parsed.
1430 static Local<Value> Parse(Local<String> json_string);
1438 * The superclass of all JavaScript values and objects.
1440 class V8_EXPORT Value : public Data {
1443 * Returns true if this value is the undefined value. See ECMA-262
1446 V8_INLINE bool IsUndefined() const;
1449 * Returns true if this value is the null value. See ECMA-262
1452 V8_INLINE bool IsNull() const;
1455 * Returns true if this value is true.
1457 bool IsTrue() const;
1460 * Returns true if this value is false.
1462 bool IsFalse() const;
1465 * Returns true if this value is a symbol or a string.
1466 * This is an experimental feature.
1468 bool IsName() const;
1471 * Returns true if this value is an instance of the String type.
1474 V8_INLINE bool IsString() const;
1477 * Returns true if this value is a symbol.
1478 * This is an experimental feature.
1480 bool IsSymbol() const;
1483 * Returns true if this value is a function.
1485 bool IsFunction() const;
1488 * Returns true if this value is an array.
1490 bool IsArray() const;
1493 * Returns true if this value is an object.
1495 bool IsObject() const;
1498 * Returns true if this value is boolean.
1500 bool IsBoolean() const;
1503 * Returns true if this value is a number.
1505 bool IsNumber() const;
1508 * Returns true if this value is external.
1510 bool IsExternal() const;
1513 * Returns true if this value is a 32-bit signed integer.
1515 bool IsInt32() const;
1518 * Returns true if this value is a 32-bit unsigned integer.
1520 bool IsUint32() const;
1523 * Returns true if this value is a Date.
1525 bool IsDate() const;
1528 * Returns true if this value is an Arguments object.
1530 bool IsArgumentsObject() const;
1533 * Returns true if this value is a Boolean object.
1535 bool IsBooleanObject() const;
1538 * Returns true if this value is a Number object.
1540 bool IsNumberObject() const;
1543 * Returns true if this value is a String object.
1545 bool IsStringObject() const;
1548 * Returns true if this value is a Symbol object.
1549 * This is an experimental feature.
1551 bool IsSymbolObject() const;
1554 * Returns true if this value is a NativeError.
1556 bool IsNativeError() const;
1559 * Returns true if this value is a RegExp.
1561 bool IsRegExp() const;
1564 * Returns true if this value is a Promise.
1565 * This is an experimental feature.
1567 bool IsPromise() const;
1570 * Returns true if this value is a Map.
1571 * This is an experimental feature.
1576 * Returns true if this value is a Set.
1577 * This is an experimental feature.
1582 * Returns true if this value is a WeakMap.
1583 * This is an experimental feature.
1585 bool IsWeakMap() const;
1588 * Returns true if this value is a WeakSet.
1589 * This is an experimental feature.
1591 bool IsWeakSet() const;
1594 * Returns true if this value is an ArrayBuffer.
1595 * This is an experimental feature.
1597 bool IsArrayBuffer() const;
1600 * Returns true if this value is an ArrayBufferView.
1601 * This is an experimental feature.
1603 bool IsArrayBufferView() const;
1606 * Returns true if this value is one of TypedArrays.
1607 * This is an experimental feature.
1609 bool IsTypedArray() const;
1612 * Returns true if this value is an Uint8Array.
1613 * This is an experimental feature.
1615 bool IsUint8Array() const;
1618 * Returns true if this value is an Uint8ClampedArray.
1619 * This is an experimental feature.
1621 bool IsUint8ClampedArray() const;
1624 * Returns true if this value is an Int8Array.
1625 * This is an experimental feature.
1627 bool IsInt8Array() const;
1630 * Returns true if this value is an Uint16Array.
1631 * This is an experimental feature.
1633 bool IsUint16Array() const;
1636 * Returns true if this value is an Int16Array.
1637 * This is an experimental feature.
1639 bool IsInt16Array() const;
1642 * Returns true if this value is an Uint32Array.
1643 * This is an experimental feature.
1645 bool IsUint32Array() const;
1648 * Returns true if this value is an Int32Array.
1649 * This is an experimental feature.
1651 bool IsInt32Array() const;
1654 * Returns true if this value is a Float32Array.
1655 * This is an experimental feature.
1657 bool IsFloat32Array() const;
1660 * Returns true if this value is a Float64Array.
1661 * This is an experimental feature.
1663 bool IsFloat64Array() const;
1666 * Returns true if this value is a DataView.
1667 * This is an experimental feature.
1669 bool IsDataView() const;
1671 Local<Boolean> ToBoolean() const;
1672 Local<Number> ToNumber() const;
1673 Local<String> ToString() const;
1674 Local<String> ToDetailString() const;
1675 Local<Object> ToObject() const;
1676 Local<Integer> ToInteger() const;
1677 Local<Uint32> ToUint32() const;
1678 Local<Int32> ToInt32() const;
1681 * Attempts to convert a string to an array index.
1682 * Returns an empty handle if the conversion fails.
1684 Local<Uint32> ToArrayIndex() const;
1686 bool BooleanValue() const;
1687 double NumberValue() const;
1688 int64_t IntegerValue() const;
1689 uint32_t Uint32Value() const;
1690 int32_t Int32Value() const;
1693 bool Equals(Handle<Value> that) const;
1694 bool StrictEquals(Handle<Value> that) const;
1695 bool SameValue(Handle<Value> that) const;
1697 template <class T> V8_INLINE static Value* Cast(T* value);
1700 V8_INLINE bool QuickIsUndefined() const;
1701 V8_INLINE bool QuickIsNull() const;
1702 V8_INLINE bool QuickIsString() const;
1703 bool FullIsUndefined() const;
1704 bool FullIsNull() const;
1705 bool FullIsString() const;
1710 * The superclass of primitive values. See ECMA-262 4.3.2.
1712 class V8_EXPORT Primitive : public Value { };
1716 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1719 class V8_EXPORT Boolean : public Primitive {
1722 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1727 * A superclass for symbols and strings.
1729 class V8_EXPORT Name : public Primitive {
1731 V8_INLINE static Name* Cast(v8::Value* obj);
1733 static void CheckCast(v8::Value* obj);
1738 * A JavaScript string value (ECMA-262, 4.3.17).
1740 class V8_EXPORT String : public Name {
1743 UNKNOWN_ENCODING = 0x1,
1744 TWO_BYTE_ENCODING = 0x0,
1745 ASCII_ENCODING = 0x4, // TODO(yangguo): deprecate this.
1746 ONE_BYTE_ENCODING = 0x4
1749 * Returns the number of characters in this string.
1754 * Returns the number of bytes in the UTF-8 encoded
1755 * representation of this string.
1757 int Utf8Length() const;
1760 * Returns whether this string is known to contain only one byte data.
1761 * Does not read the string.
1762 * False negatives are possible.
1764 bool IsOneByte() const;
1767 * Returns whether this string contain only one byte data.
1768 * Will read the entire string in some cases.
1770 bool ContainsOnlyOneByte() const;
1773 * Write the contents of the string to an external buffer.
1774 * If no arguments are given, expects the buffer to be large
1775 * enough to hold the entire string and NULL terminator. Copies
1776 * the contents of the string and the NULL terminator into the
1779 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1780 * before the end of the buffer.
1782 * Copies up to length characters into the output buffer.
1783 * Only null-terminates if there is enough space in the buffer.
1785 * \param buffer The buffer into which the string will be copied.
1786 * \param start The starting position within the string at which
1788 * \param length The number of characters to copy from the string. For
1789 * WriteUtf8 the number of bytes in the buffer.
1790 * \param nchars_ref The number of characters written, can be NULL.
1791 * \param options Various options that might affect performance of this or
1792 * subsequent operations.
1793 * \return The number of characters copied to the buffer excluding the null
1794 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1795 * including the null terminator (if written).
1799 HINT_MANY_WRITES_EXPECTED = 1,
1800 NO_NULL_TERMINATION = 2,
1801 PRESERVE_ASCII_NULL = 4, // TODO(yangguo): deprecate this.
1802 PRESERVE_ONE_BYTE_NULL = 4,
1803 // Used by WriteUtf8 to replace orphan surrogate code units with the
1804 // unicode replacement character. Needs to be set to guarantee valid UTF-8
1806 REPLACE_INVALID_UTF8 = 8
1809 // 16-bit character codes.
1810 int Write(uint16_t* buffer,
1813 int options = NO_OPTIONS) const;
1814 // One byte characters.
1815 int WriteOneByte(uint8_t* buffer,
1818 int options = NO_OPTIONS) const;
1819 // UTF-8 encoded characters.
1820 int WriteUtf8(char* buffer,
1822 int* nchars_ref = NULL,
1823 int options = NO_OPTIONS) const;
1826 * A zero length string.
1828 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1831 * Returns true if the string is external
1833 bool IsExternal() const;
1836 * Returns true if the string is both external and one-byte.
1838 bool IsExternalOneByte() const;
1840 // TODO(yangguo): deprecate this.
1841 bool IsExternalAscii() const { return IsExternalOneByte(); }
1843 class V8_EXPORT ExternalStringResourceBase { // NOLINT
1845 virtual ~ExternalStringResourceBase() {}
1848 ExternalStringResourceBase() {}
1851 * Internally V8 will call this Dispose method when the external string
1852 * resource is no longer needed. The default implementation will use the
1853 * delete operator. This method can be overridden in subclasses to
1854 * control how allocated external string resources are disposed.
1856 virtual void Dispose() { delete this; }
1859 // Disallow copying and assigning.
1860 ExternalStringResourceBase(const ExternalStringResourceBase&);
1861 void operator=(const ExternalStringResourceBase&);
1863 friend class v8::internal::Heap;
1867 * An ExternalStringResource is a wrapper around a two-byte string
1868 * buffer that resides outside V8's heap. Implement an
1869 * ExternalStringResource to manage the life cycle of the underlying
1870 * buffer. Note that the string data must be immutable.
1872 class V8_EXPORT ExternalStringResource
1873 : public ExternalStringResourceBase {
1876 * Override the destructor to manage the life cycle of the underlying
1879 virtual ~ExternalStringResource() {}
1882 * The string data from the underlying buffer.
1884 virtual const uint16_t* data() const = 0;
1887 * The length of the string. That is, the number of two-byte characters.
1889 virtual size_t length() const = 0;
1892 ExternalStringResource() {}
1896 * An ExternalOneByteStringResource is a wrapper around an one-byte
1897 * string buffer that resides outside V8's heap. Implement an
1898 * ExternalOneByteStringResource to manage the life cycle of the
1899 * underlying buffer. Note that the string data must be immutable
1900 * and that the data must be Latin-1 and not UTF-8, which would require
1901 * special treatment internally in the engine and do not allow efficient
1902 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
1905 class V8_EXPORT ExternalOneByteStringResource
1906 : public ExternalStringResourceBase {
1909 * Override the destructor to manage the life cycle of the underlying
1912 virtual ~ExternalOneByteStringResource() {}
1913 /** The string data from the underlying buffer.*/
1914 virtual const char* data() const = 0;
1915 /** The number of Latin-1 characters in the string.*/
1916 virtual size_t length() const = 0;
1918 ExternalOneByteStringResource() {}
1921 typedef ExternalOneByteStringResource ExternalAsciiStringResource;
1924 * If the string is an external string, return the ExternalStringResourceBase
1925 * regardless of the encoding, otherwise return NULL. The encoding of the
1926 * string is returned in encoding_out.
1928 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1929 Encoding* encoding_out) const;
1932 * Get the ExternalStringResource for an external string. Returns
1933 * NULL if IsExternal() doesn't return true.
1935 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1938 * Get the ExternalOneByteStringResource for an external one-byte string.
1939 * Returns NULL if IsExternalOneByte() doesn't return true.
1941 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
1943 // TODO(yangguo): deprecate this.
1944 const ExternalAsciiStringResource* GetExternalAsciiStringResource() const {
1945 return GetExternalOneByteStringResource();
1948 V8_INLINE static String* Cast(v8::Value* obj);
1950 enum NewStringType {
1951 kNormalString, kInternalizedString, kUndetectableString
1954 /** Allocates a new string from UTF-8 data.*/
1955 static Local<String> NewFromUtf8(Isolate* isolate,
1957 NewStringType type = kNormalString,
1960 /** Allocates a new string from Latin-1 data.*/
1961 static Local<String> NewFromOneByte(
1963 const uint8_t* data,
1964 NewStringType type = kNormalString,
1967 /** Allocates a new string from UTF-16 data.*/
1968 static Local<String> NewFromTwoByte(
1970 const uint16_t* data,
1971 NewStringType type = kNormalString,
1975 * Creates a new string by concatenating the left and the right strings
1976 * passed in as parameters.
1978 static Local<String> Concat(Handle<String> left, Handle<String> right);
1981 * Creates a new external string using the data defined in the given
1982 * resource. When the external string is no longer live on V8's heap the
1983 * resource will be disposed by calling its Dispose method. The caller of
1984 * this function should not otherwise delete or modify the resource. Neither
1985 * should the underlying buffer be deallocated or modified except through the
1986 * destructor of the external string resource.
1988 static Local<String> NewExternal(Isolate* isolate,
1989 ExternalStringResource* resource);
1992 * Associate an external string resource with this string by transforming it
1993 * in place so that existing references to this string in the JavaScript heap
1994 * will use the external string resource. The external string resource's
1995 * character contents need to be equivalent to this string.
1996 * Returns true if the string has been changed to be an external string.
1997 * The string is not modified if the operation fails. See NewExternal for
1998 * information on the lifetime of the resource.
2000 bool MakeExternal(ExternalStringResource* resource);
2003 * Creates a new external string using the one-byte data defined in the given
2004 * resource. When the external string is no longer live on V8's heap the
2005 * resource will be disposed by calling its Dispose method. The caller of
2006 * this function should not otherwise delete or modify the resource. Neither
2007 * should the underlying buffer be deallocated or modified except through the
2008 * destructor of the external string resource.
2010 static Local<String> NewExternal(Isolate* isolate,
2011 ExternalOneByteStringResource* resource);
2014 * Associate an external string resource with this string by transforming it
2015 * in place so that existing references to this string in the JavaScript heap
2016 * will use the external string resource. The external string resource's
2017 * character contents need to be equivalent to this string.
2018 * Returns true if the string has been changed to be an external string.
2019 * The string is not modified if the operation fails. See NewExternal for
2020 * information on the lifetime of the resource.
2022 bool MakeExternal(ExternalOneByteStringResource* resource);
2025 * Returns true if this string can be made external.
2027 bool CanMakeExternal();
2030 * Converts an object to a UTF-8-encoded character array. Useful if
2031 * you want to print the object. If conversion to a string fails
2032 * (e.g. due to an exception in the toString() method of the object)
2033 * then the length() method returns 0 and the * operator returns
2036 class V8_EXPORT Utf8Value {
2038 explicit Utf8Value(Handle<v8::Value> obj);
2040 char* operator*() { return str_; }
2041 const char* operator*() const { return str_; }
2042 int length() const { return length_; }
2047 // Disallow copying and assigning.
2048 Utf8Value(const Utf8Value&);
2049 void operator=(const Utf8Value&);
2053 * Converts an object to a two-byte string.
2054 * If conversion to a string fails (eg. due to an exception in the toString()
2055 * method of the object) then the length() method returns 0 and the * operator
2058 class V8_EXPORT Value {
2060 explicit Value(Handle<v8::Value> obj);
2062 uint16_t* operator*() { return str_; }
2063 const uint16_t* operator*() const { return str_; }
2064 int length() const { return length_; }
2069 // Disallow copying and assigning.
2070 Value(const Value&);
2071 void operator=(const Value&);
2075 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2076 Encoding encoding) const;
2077 void VerifyExternalStringResource(ExternalStringResource* val) const;
2078 static void CheckCast(v8::Value* obj);
2083 * A JavaScript symbol (ECMA-262 edition 6)
2085 * This is an experimental feature. Use at your own risk.
2087 class V8_EXPORT Symbol : public Name {
2089 // Returns the print name string of the symbol, or undefined if none.
2090 Local<Value> Name() const;
2092 // Create a symbol. If name is not empty, it will be used as the description.
2093 static Local<Symbol> New(
2094 Isolate *isolate, Local<String> name = Local<String>());
2096 // Access global symbol registry.
2097 // Note that symbols created this way are never collected, so
2098 // they should only be used for statically fixed properties.
2099 // Also, there is only one global name space for the names used as keys.
2100 // To minimize the potential for clashes, use qualified names as keys.
2101 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2103 // Retrieve a global symbol. Similar to |For|, but using a separate
2104 // registry that is not accessible by (and cannot clash with) JavaScript code.
2105 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2107 // Well-known symbols
2108 static Local<Symbol> GetIterator(Isolate* isolate);
2109 static Local<Symbol> GetUnscopables(Isolate* isolate);
2111 V8_INLINE static Symbol* Cast(v8::Value* obj);
2115 static void CheckCast(v8::Value* obj);
2122 * This is an experimental feature. Use at your own risk.
2124 class V8_EXPORT Private : public Data {
2126 // Returns the print name string of the private symbol, or undefined if none.
2127 Local<Value> Name() const;
2129 // Create a private symbol. If name is not empty, it will be the description.
2130 static Local<Private> New(
2131 Isolate *isolate, Local<String> name = Local<String>());
2133 // Retrieve a global private symbol. If a symbol with this name has not
2134 // been retrieved in the same isolate before, it is created.
2135 // Note that private symbols created this way are never collected, so
2136 // they should only be used for statically fixed properties.
2137 // Also, there is only one global name space for the names used as keys.
2138 // To minimize the potential for clashes, use qualified names as keys,
2139 // e.g., "Class#property".
2140 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2148 * A JavaScript number value (ECMA-262, 4.3.20)
2150 class V8_EXPORT Number : public Primitive {
2152 double Value() const;
2153 static Local<Number> New(Isolate* isolate, double value);
2154 V8_INLINE static Number* Cast(v8::Value* obj);
2157 static void CheckCast(v8::Value* obj);
2162 * A JavaScript value representing a signed integer.
2164 class V8_EXPORT Integer : public Number {
2166 static Local<Integer> New(Isolate* isolate, int32_t value);
2167 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2168 int64_t Value() const;
2169 V8_INLINE static Integer* Cast(v8::Value* obj);
2172 static void CheckCast(v8::Value* obj);
2177 * A JavaScript value representing a 32-bit signed integer.
2179 class V8_EXPORT Int32 : public Integer {
2181 int32_t Value() const;
2188 * A JavaScript value representing a 32-bit unsigned integer.
2190 class V8_EXPORT Uint32 : public Integer {
2192 uint32_t Value() const;
2198 enum PropertyAttribute {
2205 enum ExternalArrayType {
2206 kExternalInt8Array = 1,
2207 kExternalUint8Array,
2208 kExternalInt16Array,
2209 kExternalUint16Array,
2210 kExternalInt32Array,
2211 kExternalUint32Array,
2212 kExternalFloat32Array,
2213 kExternalFloat64Array,
2214 kExternalUint8ClampedArray,
2216 // Legacy constant names
2217 kExternalByteArray = kExternalInt8Array,
2218 kExternalUnsignedByteArray = kExternalUint8Array,
2219 kExternalShortArray = kExternalInt16Array,
2220 kExternalUnsignedShortArray = kExternalUint16Array,
2221 kExternalIntArray = kExternalInt32Array,
2222 kExternalUnsignedIntArray = kExternalUint32Array,
2223 kExternalFloatArray = kExternalFloat32Array,
2224 kExternalDoubleArray = kExternalFloat64Array,
2225 kExternalPixelArray = kExternalUint8ClampedArray
2229 * Accessor[Getter|Setter] are used as callback functions when
2230 * setting|getting a particular property. See Object and ObjectTemplate's
2231 * method SetAccessor.
2233 typedef void (*AccessorGetterCallback)(
2234 Local<String> property,
2235 const PropertyCallbackInfo<Value>& info);
2236 typedef void (*AccessorNameGetterCallback)(
2237 Local<Name> property,
2238 const PropertyCallbackInfo<Value>& info);
2241 typedef void (*AccessorSetterCallback)(
2242 Local<String> property,
2244 const PropertyCallbackInfo<void>& info);
2245 typedef void (*AccessorNameSetterCallback)(
2246 Local<Name> property,
2248 const PropertyCallbackInfo<void>& info);
2252 * Access control specifications.
2254 * Some accessors should be accessible across contexts. These
2255 * accessors have an explicit access control parameter which specifies
2256 * the kind of cross-context access that should be allowed.
2258 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2260 enum AccessControl {
2263 ALL_CAN_WRITE = 1 << 1,
2264 PROHIBITS_OVERWRITING = 1 << 2
2269 * A JavaScript object (ECMA-262, 4.3.3)
2271 class V8_EXPORT Object : public Value {
2273 bool Set(Handle<Value> key, Handle<Value> value);
2275 bool Set(uint32_t index, Handle<Value> value);
2277 // Sets an own property on this object bypassing interceptors and
2278 // overriding accessors or read-only properties.
2280 // Note that if the object has an interceptor the property will be set
2281 // locally, but since the interceptor takes precedence the local property
2282 // will only be returned if the interceptor doesn't return a value.
2284 // Note also that this only works for named properties.
2285 bool ForceSet(Handle<Value> key,
2286 Handle<Value> value,
2287 PropertyAttribute attribs = None);
2289 Local<Value> Get(Handle<Value> key);
2291 Local<Value> Get(uint32_t index);
2294 * Gets the property attributes of a property which can be None or
2295 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2296 * None when the property doesn't exist.
2298 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2301 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2303 Local<Value> GetOwnPropertyDescriptor(Local<String> key);
2305 bool Has(Handle<Value> key);
2307 bool Delete(Handle<Value> key);
2309 // Delete a property on this object bypassing interceptors and
2310 // ignoring dont-delete attributes.
2311 bool ForceDelete(Handle<Value> key);
2313 bool Has(uint32_t index);
2315 bool Delete(uint32_t index);
2317 bool SetAccessor(Handle<String> name,
2318 AccessorGetterCallback getter,
2319 AccessorSetterCallback setter = 0,
2320 Handle<Value> data = Handle<Value>(),
2321 AccessControl settings = DEFAULT,
2322 PropertyAttribute attribute = None);
2323 bool SetAccessor(Handle<Name> name,
2324 AccessorNameGetterCallback getter,
2325 AccessorNameSetterCallback setter = 0,
2326 Handle<Value> data = Handle<Value>(),
2327 AccessControl settings = DEFAULT,
2328 PropertyAttribute attribute = None);
2330 // This function is not yet stable and should not be used at this time.
2331 bool SetDeclaredAccessor(Local<Name> name,
2332 Local<DeclaredAccessorDescriptor> descriptor,
2333 PropertyAttribute attribute = None,
2334 AccessControl settings = DEFAULT);
2336 void SetAccessorProperty(Local<Name> name,
2337 Local<Function> getter,
2338 Handle<Function> setter = Handle<Function>(),
2339 PropertyAttribute attribute = None,
2340 AccessControl settings = DEFAULT);
2343 * Functionality for private properties.
2344 * This is an experimental feature, use at your own risk.
2345 * Note: Private properties are inherited. Do not rely on this, since it may
2348 bool HasPrivate(Handle<Private> key);
2349 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2350 bool DeletePrivate(Handle<Private> key);
2351 Local<Value> GetPrivate(Handle<Private> key);
2354 * Returns an array containing the names of the enumerable properties
2355 * of this object, including properties from prototype objects. The
2356 * array returned by this method contains the same values as would
2357 * be enumerated by a for-in statement over this object.
2359 Local<Array> GetPropertyNames();
2362 * This function has the same functionality as GetPropertyNames but
2363 * the returned array doesn't contain the names of properties from
2364 * prototype objects.
2366 Local<Array> GetOwnPropertyNames();
2369 * Get the prototype object. This does not skip objects marked to
2370 * be skipped by __proto__ and it does not consult the security
2373 Local<Value> GetPrototype();
2376 * Set the prototype object. This does not skip objects marked to
2377 * be skipped by __proto__ and it does not consult the security
2380 bool SetPrototype(Handle<Value> prototype);
2383 * Finds an instance of the given function template in the prototype
2386 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2389 * Call builtin Object.prototype.toString on this object.
2390 * This is different from Value::ToString() that may call
2391 * user-defined toString function. This one does not.
2393 Local<String> ObjectProtoToString();
2396 * Returns the name of the function invoked as a constructor for this object.
2398 Local<String> GetConstructorName();
2400 /** Gets the number of internal fields for this Object. */
2401 int InternalFieldCount();
2403 /** Same as above, but works for Persistents */
2404 V8_INLINE static int InternalFieldCount(
2405 const PersistentBase<Object>& object) {
2406 return object.val_->InternalFieldCount();
2409 /** Gets the value from an internal field. */
2410 V8_INLINE Local<Value> GetInternalField(int index);
2412 /** Sets the value in an internal field. */
2413 void SetInternalField(int index, Handle<Value> value);
2416 * Gets a 2-byte-aligned native pointer from an internal field. This field
2417 * must have been set by SetAlignedPointerInInternalField, everything else
2418 * leads to undefined behavior.
2420 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2422 /** Same as above, but works for Persistents */
2423 V8_INLINE static void* GetAlignedPointerFromInternalField(
2424 const PersistentBase<Object>& object, int index) {
2425 return object.val_->GetAlignedPointerFromInternalField(index);
2429 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2430 * a field, GetAlignedPointerFromInternalField must be used, everything else
2431 * leads to undefined behavior.
2433 void SetAlignedPointerInInternalField(int index, void* value);
2435 // Testers for local properties.
2436 bool HasOwnProperty(Handle<String> key);
2437 bool HasRealNamedProperty(Handle<String> key);
2438 bool HasRealIndexedProperty(uint32_t index);
2439 bool HasRealNamedCallbackProperty(Handle<String> key);
2442 * If result.IsEmpty() no real property was located in the prototype chain.
2443 * This means interceptors in the prototype chain are not called.
2445 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2448 * If result.IsEmpty() no real property was located on the object or
2449 * in the prototype chain.
2450 * This means interceptors in the prototype chain are not called.
2452 Local<Value> GetRealNamedProperty(Handle<String> key);
2454 /** Tests for a named lookup interceptor.*/
2455 bool HasNamedLookupInterceptor();
2457 /** Tests for an index lookup interceptor.*/
2458 bool HasIndexedLookupInterceptor();
2461 * Turns on access check on the object if the object is an instance of
2462 * a template that has access check callbacks. If an object has no
2463 * access check info, the object cannot be accessed by anyone.
2465 void TurnOnAccessCheck();
2468 * Returns the identity hash for this object. The current implementation
2469 * uses a hidden property on the object to store the identity hash.
2471 * The return value will never be 0. Also, it is not guaranteed to be
2474 int GetIdentityHash();
2477 * Access hidden properties on JavaScript objects. These properties are
2478 * hidden from the executing JavaScript and only accessible through the V8
2479 * C++ API. Hidden properties introduced by V8 internally (for example the
2480 * identity hash) are prefixed with "v8::".
2482 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2483 Local<Value> GetHiddenValue(Handle<String> key);
2484 bool DeleteHiddenValue(Handle<String> key);
2487 * Returns true if this is an instance of an api function (one
2488 * created from a function created from a function template) and has
2489 * been modified since it was created. Note that this method is
2490 * conservative and may return true for objects that haven't actually
2496 * Clone this object with a fast but shallow copy. Values will point
2497 * to the same values as the original object.
2499 Local<Object> Clone();
2502 * Returns the context in which the object was created.
2504 Local<Context> CreationContext();
2507 * Set the backing store of the indexed properties to be managed by the
2508 * embedding layer. Access to the indexed properties will follow the rules
2509 * spelled out in CanvasPixelArray.
2510 * Note: The embedding program still owns the data and needs to ensure that
2511 * the backing store is preserved while V8 has a reference.
2513 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2514 bool HasIndexedPropertiesInPixelData();
2515 uint8_t* GetIndexedPropertiesPixelData();
2516 int GetIndexedPropertiesPixelDataLength();
2519 * Set the backing store of the indexed properties to be managed by the
2520 * embedding layer. Access to the indexed properties will follow the rules
2521 * spelled out for the CanvasArray subtypes in the WebGL specification.
2522 * Note: The embedding program still owns the data and needs to ensure that
2523 * the backing store is preserved while V8 has a reference.
2525 void SetIndexedPropertiesToExternalArrayData(void* data,
2526 ExternalArrayType array_type,
2527 int number_of_elements);
2528 bool HasIndexedPropertiesInExternalArrayData();
2529 void* GetIndexedPropertiesExternalArrayData();
2530 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2531 int GetIndexedPropertiesExternalArrayDataLength();
2534 * Checks whether a callback is set by the
2535 * ObjectTemplate::SetCallAsFunctionHandler method.
2536 * When an Object is callable this method returns true.
2541 * Call an Object as a function if a callback is set by the
2542 * ObjectTemplate::SetCallAsFunctionHandler method.
2544 Local<Value> CallAsFunction(Handle<Value> recv,
2546 Handle<Value> argv[]);
2549 * Call an Object as a constructor if a callback is set by the
2550 * ObjectTemplate::SetCallAsFunctionHandler method.
2551 * Note: This method behaves like the Function::NewInstance method.
2553 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2555 static Local<Object> New(Isolate* isolate);
2557 V8_INLINE static Object* Cast(Value* obj);
2561 static void CheckCast(Value* obj);
2562 Local<Value> SlowGetInternalField(int index);
2563 void* SlowGetAlignedPointerFromInternalField(int index);
2568 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2570 class V8_EXPORT Array : public Object {
2572 uint32_t Length() const;
2575 * Clones an element at index |index|. Returns an empty
2576 * handle if cloning fails (for any reason).
2578 Local<Object> CloneElementAt(uint32_t index);
2581 * Creates a JavaScript array with the given length. If the length
2582 * is negative the returned array will have length 0.
2584 static Local<Array> New(Isolate* isolate, int length = 0);
2586 V8_INLINE static Array* Cast(Value* obj);
2589 static void CheckCast(Value* obj);
2593 template<typename T>
2596 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2597 : value_(that.value_) {
2601 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2602 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2603 // Fast primitive setters
2604 V8_INLINE void Set(bool value);
2605 V8_INLINE void Set(double i);
2606 V8_INLINE void Set(int32_t i);
2607 V8_INLINE void Set(uint32_t i);
2608 // Fast JS primitive setters
2609 V8_INLINE void SetNull();
2610 V8_INLINE void SetUndefined();
2611 V8_INLINE void SetEmptyString();
2612 // Convenience getter for Isolate
2613 V8_INLINE Isolate* GetIsolate();
2615 // Pointer setter: Uncompilable to prevent inadvertent misuse.
2616 template <typename S>
2617 V8_INLINE void Set(S* whatever);
2620 template<class F> friend class ReturnValue;
2621 template<class F> friend class FunctionCallbackInfo;
2622 template<class F> friend class PropertyCallbackInfo;
2623 template<class F, class G, class H> friend class PersistentValueMap;
2624 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2625 V8_INLINE internal::Object* GetDefaultValue();
2626 V8_INLINE explicit ReturnValue(internal::Object** slot);
2627 internal::Object** value_;
2632 * The argument information given to function call callbacks. This
2633 * class provides access to information about the context of the call,
2634 * including the receiver, the number and values of arguments, and
2635 * the holder of the function.
2637 template<typename T>
2638 class FunctionCallbackInfo {
2640 V8_INLINE int Length() const;
2641 V8_INLINE Local<Value> operator[](int i) const;
2642 V8_INLINE Local<Function> Callee() const;
2643 V8_INLINE Local<Object> This() const;
2644 V8_INLINE Local<Object> Holder() const;
2645 V8_INLINE bool IsConstructCall() const;
2646 V8_INLINE Local<Value> Data() const;
2647 V8_INLINE Isolate* GetIsolate() const;
2648 V8_INLINE ReturnValue<T> GetReturnValue() const;
2649 // This shouldn't be public, but the arm compiler needs it.
2650 static const int kArgsLength = 7;
2653 friend class internal::FunctionCallbackArguments;
2654 friend class internal::CustomArguments<FunctionCallbackInfo>;
2655 static const int kHolderIndex = 0;
2656 static const int kIsolateIndex = 1;
2657 static const int kReturnValueDefaultValueIndex = 2;
2658 static const int kReturnValueIndex = 3;
2659 static const int kDataIndex = 4;
2660 static const int kCalleeIndex = 5;
2661 static const int kContextSaveIndex = 6;
2663 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2664 internal::Object** values,
2666 bool is_construct_call);
2667 internal::Object** implicit_args_;
2668 internal::Object** values_;
2670 bool is_construct_call_;
2675 * The information passed to a property callback about the context
2676 * of the property access.
2678 template<typename T>
2679 class PropertyCallbackInfo {
2681 V8_INLINE Isolate* GetIsolate() const;
2682 V8_INLINE Local<Value> Data() const;
2683 V8_INLINE Local<Object> This() const;
2684 V8_INLINE Local<Object> Holder() const;
2685 V8_INLINE ReturnValue<T> GetReturnValue() const;
2686 // This shouldn't be public, but the arm compiler needs it.
2687 static const int kArgsLength = 6;
2690 friend class MacroAssembler;
2691 friend class internal::PropertyCallbackArguments;
2692 friend class internal::CustomArguments<PropertyCallbackInfo>;
2693 static const int kHolderIndex = 0;
2694 static const int kIsolateIndex = 1;
2695 static const int kReturnValueDefaultValueIndex = 2;
2696 static const int kReturnValueIndex = 3;
2697 static const int kDataIndex = 4;
2698 static const int kThisIndex = 5;
2700 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2701 internal::Object** args_;
2705 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2709 * A JavaScript function object (ECMA-262, 15.3).
2711 class V8_EXPORT Function : public Object {
2714 * Create a function in the current execution context
2715 * for a given FunctionCallback.
2717 static Local<Function> New(Isolate* isolate,
2718 FunctionCallback callback,
2719 Local<Value> data = Local<Value>(),
2722 Local<Object> NewInstance() const;
2723 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2724 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2725 void SetName(Handle<String> name);
2726 Handle<Value> GetName() const;
2729 * Name inferred from variable or property assignment of this function.
2730 * Used to facilitate debugging and profiling of JavaScript code written
2731 * in an OO style, where many functions are anonymous but are assigned
2732 * to object properties.
2734 Handle<Value> GetInferredName() const;
2737 * User-defined name assigned to the "displayName" property of this function.
2738 * Used to facilitate debugging and profiling of JavaScript code.
2740 Handle<Value> GetDisplayName() const;
2743 * Returns zero based line number of function body and
2744 * kLineOffsetNotFound if no information available.
2746 int GetScriptLineNumber() const;
2748 * Returns zero based column number of function body and
2749 * kLineOffsetNotFound if no information available.
2751 int GetScriptColumnNumber() const;
2754 * Tells whether this function is builtin.
2756 bool IsBuiltin() const;
2761 int ScriptId() const;
2764 * Returns the original function if this function is bound, else returns
2767 Local<Value> GetBoundFunction() const;
2769 ScriptOrigin GetScriptOrigin() const;
2770 V8_INLINE static Function* Cast(Value* obj);
2771 static const int kLineOffsetNotFound;
2775 static void CheckCast(Value* obj);
2780 * An instance of the built-in Promise constructor (ES6 draft).
2781 * This API is experimental. Only works with --harmony flag.
2783 class V8_EXPORT Promise : public Object {
2785 class V8_EXPORT Resolver : public Object {
2788 * Create a new resolver, along with an associated promise in pending state.
2790 static Local<Resolver> New(Isolate* isolate);
2793 * Extract the associated promise.
2795 Local<Promise> GetPromise();
2798 * Resolve/reject the associated promise with a given value.
2799 * Ignored if the promise is no longer pending.
2801 void Resolve(Handle<Value> value);
2802 void Reject(Handle<Value> value);
2804 V8_INLINE static Resolver* Cast(Value* obj);
2808 static void CheckCast(Value* obj);
2812 * Register a resolution/rejection handler with a promise.
2813 * The handler is given the respective resolution/rejection value as
2814 * an argument. If the promise is already resolved/rejected, the handler is
2815 * invoked at the end of turn.
2817 Local<Promise> Chain(Handle<Function> handler);
2818 Local<Promise> Catch(Handle<Function> handler);
2819 Local<Promise> Then(Handle<Function> handler);
2821 V8_INLINE static Promise* Cast(Value* obj);
2825 static void CheckCast(Value* obj);
2829 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2830 // The number of required internal fields can be defined by embedder.
2831 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2835 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2836 * This API is experimental and may change significantly.
2838 class V8_EXPORT ArrayBuffer : public Object {
2841 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2842 * The allocator is a global V8 setting. It should be set with
2843 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2845 * This API is experimental and may change significantly.
2847 class V8_EXPORT Allocator { // NOLINT
2849 virtual ~Allocator() {}
2852 * Allocate |length| bytes. Return NULL if allocation is not successful.
2853 * Memory should be initialized to zeroes.
2855 virtual void* Allocate(size_t length) = 0;
2858 * Allocate |length| bytes. Return NULL if allocation is not successful.
2859 * Memory does not have to be initialized.
2861 virtual void* AllocateUninitialized(size_t length) = 0;
2863 * Free the memory block of size |length|, pointed to by |data|.
2864 * That memory is guaranteed to be previously allocated by |Allocate|.
2866 virtual void Free(void* data, size_t length) = 0;
2870 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2871 * returns an instance of this class, populated, with a pointer to data
2874 * The Data pointer of ArrayBuffer::Contents is always allocated with
2875 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2877 * This API is experimental and may change significantly.
2879 class V8_EXPORT Contents { // NOLINT
2881 Contents() : data_(NULL), byte_length_(0) {}
2883 void* Data() const { return data_; }
2884 size_t ByteLength() const { return byte_length_; }
2888 size_t byte_length_;
2890 friend class ArrayBuffer;
2895 * Data length in bytes.
2897 size_t ByteLength() const;
2900 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2901 * Allocated memory will be owned by a created ArrayBuffer and
2902 * will be deallocated when it is garbage-collected,
2903 * unless the object is externalized.
2905 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2908 * Create a new ArrayBuffer over an existing memory block.
2909 * The created array buffer is immediately in externalized state.
2910 * The memory block will not be reclaimed when a created ArrayBuffer
2911 * is garbage-collected.
2913 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2914 size_t byte_length);
2917 * Returns true if ArrayBuffer is extrenalized, that is, does not
2918 * own its memory block.
2920 bool IsExternal() const;
2923 * Neuters this ArrayBuffer and all its views (typed arrays).
2924 * Neutering sets the byte length of the buffer and all typed arrays to zero,
2925 * preventing JavaScript from ever accessing underlying backing store.
2926 * ArrayBuffer should have been externalized.
2931 * Make this ArrayBuffer external. The pointer to underlying memory block
2932 * and byte length are returned as |Contents| structure. After ArrayBuffer
2933 * had been etxrenalized, it does no longer owns the memory block. The caller
2934 * should take steps to free memory when it is no longer needed.
2936 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2937 * that has been set with V8::SetArrayBufferAllocator.
2939 Contents Externalize();
2941 V8_INLINE static ArrayBuffer* Cast(Value* obj);
2943 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2947 static void CheckCast(Value* obj);
2951 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2952 // The number of required internal fields can be defined by embedder.
2953 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2958 * A base class for an instance of one of "views" over ArrayBuffer,
2959 * including TypedArrays and DataView (ES6 draft 15.13).
2961 * This API is experimental and may change significantly.
2963 class V8_EXPORT ArrayBufferView : public Object {
2966 * Returns underlying ArrayBuffer.
2968 Local<ArrayBuffer> Buffer();
2970 * Byte offset in |Buffer|.
2972 size_t ByteOffset();
2974 * Size of a view in bytes.
2976 size_t ByteLength();
2978 V8_INLINE static ArrayBufferView* Cast(Value* obj);
2980 static const int kInternalFieldCount =
2981 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2985 static void CheckCast(Value* obj);
2990 * A base class for an instance of TypedArray series of constructors
2991 * (ES6 draft 15.13.6).
2992 * This API is experimental and may change significantly.
2994 class V8_EXPORT TypedArray : public ArrayBufferView {
2997 * Number of elements in this typed array
2998 * (e.g. for Int16Array, |ByteLength|/2).
3002 V8_INLINE static TypedArray* Cast(Value* obj);
3006 static void CheckCast(Value* obj);
3011 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3012 * This API is experimental and may change significantly.
3014 class V8_EXPORT Uint8Array : public TypedArray {
3016 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
3017 size_t byte_offset, size_t length);
3018 V8_INLINE static Uint8Array* Cast(Value* obj);
3022 static void CheckCast(Value* obj);
3027 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3028 * This API is experimental and may change significantly.
3030 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3032 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
3033 size_t byte_offset, size_t length);
3034 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3037 Uint8ClampedArray();
3038 static void CheckCast(Value* obj);
3042 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3043 * This API is experimental and may change significantly.
3045 class V8_EXPORT Int8Array : public TypedArray {
3047 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
3048 size_t byte_offset, size_t length);
3049 V8_INLINE static Int8Array* Cast(Value* obj);
3053 static void CheckCast(Value* obj);
3058 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3059 * This API is experimental and may change significantly.
3061 class V8_EXPORT Uint16Array : public TypedArray {
3063 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
3064 size_t byte_offset, size_t length);
3065 V8_INLINE static Uint16Array* Cast(Value* obj);
3069 static void CheckCast(Value* obj);
3074 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3075 * This API is experimental and may change significantly.
3077 class V8_EXPORT Int16Array : public TypedArray {
3079 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
3080 size_t byte_offset, size_t length);
3081 V8_INLINE static Int16Array* Cast(Value* obj);
3085 static void CheckCast(Value* obj);
3090 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3091 * This API is experimental and may change significantly.
3093 class V8_EXPORT Uint32Array : public TypedArray {
3095 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
3096 size_t byte_offset, size_t length);
3097 V8_INLINE static Uint32Array* Cast(Value* obj);
3101 static void CheckCast(Value* obj);
3106 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3107 * This API is experimental and may change significantly.
3109 class V8_EXPORT Int32Array : public TypedArray {
3111 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
3112 size_t byte_offset, size_t length);
3113 V8_INLINE static Int32Array* Cast(Value* obj);
3117 static void CheckCast(Value* obj);
3122 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3123 * This API is experimental and may change significantly.
3125 class V8_EXPORT Float32Array : public TypedArray {
3127 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
3128 size_t byte_offset, size_t length);
3129 V8_INLINE static Float32Array* Cast(Value* obj);
3133 static void CheckCast(Value* obj);
3138 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3139 * This API is experimental and may change significantly.
3141 class V8_EXPORT Float64Array : public TypedArray {
3143 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3144 size_t byte_offset, size_t length);
3145 V8_INLINE static Float64Array* Cast(Value* obj);
3149 static void CheckCast(Value* obj);
3154 * An instance of DataView constructor (ES6 draft 15.13.7).
3155 * This API is experimental and may change significantly.
3157 class V8_EXPORT DataView : public ArrayBufferView {
3159 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3160 size_t byte_offset, size_t length);
3161 V8_INLINE static DataView* Cast(Value* obj);
3165 static void CheckCast(Value* obj);
3170 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3172 class V8_EXPORT Date : public Object {
3174 static Local<Value> New(Isolate* isolate, double time);
3177 * A specialization of Value::NumberValue that is more efficient
3178 * because we know the structure of this object.
3180 double ValueOf() const;
3182 V8_INLINE static Date* Cast(v8::Value* obj);
3185 * Notification that the embedder has changed the time zone,
3186 * daylight savings time, or other date / time configuration
3187 * parameters. V8 keeps a cache of various values used for
3188 * date / time computation. This notification will reset
3189 * those cached values for the current context so that date /
3190 * time configuration changes would be reflected in the Date
3193 * This API should not be called more than needed as it will
3194 * negatively impact the performance of date operations.
3196 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3199 static void CheckCast(v8::Value* obj);
3204 * A Number object (ECMA-262, 4.3.21).
3206 class V8_EXPORT NumberObject : public Object {
3208 static Local<Value> New(Isolate* isolate, double value);
3210 double ValueOf() const;
3212 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3215 static void CheckCast(v8::Value* obj);
3220 * A Boolean object (ECMA-262, 4.3.15).
3222 class V8_EXPORT BooleanObject : public Object {
3224 static Local<Value> New(bool value);
3226 bool ValueOf() const;
3228 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3231 static void CheckCast(v8::Value* obj);
3236 * A String object (ECMA-262, 4.3.18).
3238 class V8_EXPORT StringObject : public Object {
3240 static Local<Value> New(Handle<String> value);
3242 Local<String> ValueOf() const;
3244 V8_INLINE static StringObject* Cast(v8::Value* obj);
3247 static void CheckCast(v8::Value* obj);
3252 * A Symbol object (ECMA-262 edition 6).
3254 * This is an experimental feature. Use at your own risk.
3256 class V8_EXPORT SymbolObject : public Object {
3258 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3260 Local<Symbol> ValueOf() const;
3262 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3265 static void CheckCast(v8::Value* obj);
3270 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3272 class V8_EXPORT RegExp : public Object {
3275 * Regular expression flag bits. They can be or'ed to enable a set
3286 * Creates a regular expression from the given pattern string and
3287 * the flags bit field. May throw a JavaScript exception as
3288 * described in ECMA-262, 15.10.4.1.
3291 * RegExp::New(v8::String::New("foo"),
3292 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3293 * is equivalent to evaluating "/foo/gm".
3295 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3298 * Returns the value of the source property: a string representing
3299 * the regular expression.
3301 Local<String> GetSource() const;
3304 * Returns the flags bit field.
3306 Flags GetFlags() const;
3308 V8_INLINE static RegExp* Cast(v8::Value* obj);
3311 static void CheckCast(v8::Value* obj);
3316 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3317 * to associate C++ data structures with JavaScript objects.
3319 class V8_EXPORT External : public Value {
3321 static Local<External> New(Isolate* isolate, void* value);
3322 V8_INLINE static External* Cast(Value* obj);
3323 void* Value() const;
3325 static void CheckCast(v8::Value* obj);
3329 // --- Templates ---
3333 * The superclass of object and function templates.
3335 class V8_EXPORT Template : public Data {
3337 /** Adds a property to each instance created by this template.*/
3338 void Set(Handle<Name> name, Handle<Data> value,
3339 PropertyAttribute attributes = None);
3340 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3342 void SetAccessorProperty(
3344 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3345 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3346 PropertyAttribute attribute = None,
3347 AccessControl settings = DEFAULT);
3350 * Whenever the property with the given name is accessed on objects
3351 * created from this Template the getter and setter callbacks
3352 * are called instead of getting and setting the property directly
3353 * on the JavaScript object.
3355 * \param name The name of the property for which an accessor is added.
3356 * \param getter The callback to invoke when getting the property.
3357 * \param setter The callback to invoke when setting the property.
3358 * \param data A piece of data that will be passed to the getter and setter
3359 * callbacks whenever they are invoked.
3360 * \param settings Access control settings for the accessor. This is a bit
3361 * field consisting of one of more of
3362 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3363 * The default is to not allow cross-context access.
3364 * ALL_CAN_READ means that all cross-context reads are allowed.
3365 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3366 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3367 * cross-context access.
3368 * \param attribute The attributes of the property for which an accessor
3370 * \param signature The signature describes valid receivers for the accessor
3371 * and is used to perform implicit instance checks against them. If the
3372 * receiver is incompatible (i.e. is not an instance of the constructor as
3373 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3374 * thrown and no callback is invoked.
3376 void SetNativeDataProperty(Local<String> name,
3377 AccessorGetterCallback getter,
3378 AccessorSetterCallback setter = 0,
3379 // TODO(dcarney): gcc can't handle Local below
3380 Handle<Value> data = Handle<Value>(),
3381 PropertyAttribute attribute = None,
3382 Local<AccessorSignature> signature =
3383 Local<AccessorSignature>(),
3384 AccessControl settings = DEFAULT);
3385 void SetNativeDataProperty(Local<Name> name,
3386 AccessorNameGetterCallback getter,
3387 AccessorNameSetterCallback setter = 0,
3388 // TODO(dcarney): gcc can't handle Local below
3389 Handle<Value> data = Handle<Value>(),
3390 PropertyAttribute attribute = None,
3391 Local<AccessorSignature> signature =
3392 Local<AccessorSignature>(),
3393 AccessControl settings = DEFAULT);
3395 // This function is not yet stable and should not be used at this time.
3396 bool SetDeclaredAccessor(Local<Name> name,
3397 Local<DeclaredAccessorDescriptor> descriptor,
3398 PropertyAttribute attribute = None,
3399 Local<AccessorSignature> signature =
3400 Local<AccessorSignature>(),
3401 AccessControl settings = DEFAULT);
3406 friend class ObjectTemplate;
3407 friend class FunctionTemplate;
3412 * NamedProperty[Getter|Setter] are used as interceptors on object.
3413 * See ObjectTemplate::SetNamedPropertyHandler.
3415 typedef void (*NamedPropertyGetterCallback)(
3416 Local<String> property,
3417 const PropertyCallbackInfo<Value>& info);
3421 * Returns the value if the setter intercepts the request.
3422 * Otherwise, returns an empty handle.
3424 typedef void (*NamedPropertySetterCallback)(
3425 Local<String> property,
3427 const PropertyCallbackInfo<Value>& info);
3431 * Returns a non-empty handle if the interceptor intercepts the request.
3432 * The result is an integer encoding property attributes (like v8::None,
3433 * v8::DontEnum, etc.)
3435 typedef void (*NamedPropertyQueryCallback)(
3436 Local<String> property,
3437 const PropertyCallbackInfo<Integer>& info);
3441 * Returns a non-empty handle if the deleter intercepts the request.
3442 * The return value is true if the property could be deleted and false
3445 typedef void (*NamedPropertyDeleterCallback)(
3446 Local<String> property,
3447 const PropertyCallbackInfo<Boolean>& info);
3451 * Returns an array containing the names of the properties the named
3452 * property getter intercepts.
3454 typedef void (*NamedPropertyEnumeratorCallback)(
3455 const PropertyCallbackInfo<Array>& info);
3459 * Returns the value of the property if the getter intercepts the
3460 * request. Otherwise, returns an empty handle.
3462 typedef void (*IndexedPropertyGetterCallback)(
3464 const PropertyCallbackInfo<Value>& info);
3468 * Returns the value if the setter intercepts the request.
3469 * Otherwise, returns an empty handle.
3471 typedef void (*IndexedPropertySetterCallback)(
3474 const PropertyCallbackInfo<Value>& info);
3478 * Returns a non-empty handle if the interceptor intercepts the request.
3479 * The result is an integer encoding property attributes.
3481 typedef void (*IndexedPropertyQueryCallback)(
3483 const PropertyCallbackInfo<Integer>& info);
3487 * Returns a non-empty handle if the deleter intercepts the request.
3488 * The return value is true if the property could be deleted and false
3491 typedef void (*IndexedPropertyDeleterCallback)(
3493 const PropertyCallbackInfo<Boolean>& info);
3497 * Returns an array containing the indices of the properties the
3498 * indexed property getter intercepts.
3500 typedef void (*IndexedPropertyEnumeratorCallback)(
3501 const PropertyCallbackInfo<Array>& info);
3505 * Access type specification.
3517 * Returns true if cross-context access should be allowed to the named
3518 * property with the given key on the host object.
3520 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3527 * Returns true if cross-context access should be allowed to the indexed
3528 * property with the given index on the host object.
3530 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3537 * A FunctionTemplate is used to create functions at runtime. There
3538 * can only be one function created from a FunctionTemplate in a
3539 * context. The lifetime of the created function is equal to the
3540 * lifetime of the context. So in case the embedder needs to create
3541 * temporary functions that can be collected using Scripts is
3544 * A FunctionTemplate can have properties, these properties are added to the
3545 * function object when it is created.
3547 * A FunctionTemplate has a corresponding instance template which is
3548 * used to create object instances when the function is used as a
3549 * constructor. Properties added to the instance template are added to
3550 * each object instance.
3552 * A FunctionTemplate can have a prototype template. The prototype template
3553 * is used to create the prototype object of the function.
3555 * The following example shows how to use a FunctionTemplate:
3558 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3559 * t->Set("func_property", v8::Number::New(1));
3561 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3562 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3563 * proto_t->Set("proto_const", v8::Number::New(2));
3565 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3566 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3567 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3568 * instance_t->Set("instance_property", Number::New(3));
3570 * v8::Local<v8::Function> function = t->GetFunction();
3571 * v8::Local<v8::Object> instance = function->NewInstance();
3574 * Let's use "function" as the JS variable name of the function object
3575 * and "instance" for the instance object created above. The function
3576 * and the instance will have the following properties:
3579 * func_property in function == true;
3580 * function.func_property == 1;
3582 * function.prototype.proto_method() invokes 'InvokeCallback'
3583 * function.prototype.proto_const == 2;
3585 * instance instanceof function == true;
3586 * instance.instance_accessor calls 'InstanceAccessorCallback'
3587 * instance.instance_property == 3;
3590 * A FunctionTemplate can inherit from another one by calling the
3591 * FunctionTemplate::Inherit method. The following graph illustrates
3592 * the semantics of inheritance:
3595 * FunctionTemplate Parent -> Parent() . prototype -> { }
3597 * | Inherit(Parent) | .__proto__
3599 * FunctionTemplate Child -> Child() . prototype -> { }
3602 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3603 * object of the Child() function has __proto__ pointing to the
3604 * Parent() function's prototype object. An instance of the Child
3605 * function has all properties on Parent's instance templates.
3607 * Let Parent be the FunctionTemplate initialized in the previous
3608 * section and create a Child FunctionTemplate by:
3611 * Local<FunctionTemplate> parent = t;
3612 * Local<FunctionTemplate> child = FunctionTemplate::New();
3613 * child->Inherit(parent);
3615 * Local<Function> child_function = child->GetFunction();
3616 * Local<Object> child_instance = child_function->NewInstance();
3619 * The Child function and Child instance will have the following
3623 * child_func.prototype.__proto__ == function.prototype;
3624 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3625 * child_instance.instance_property == 3;
3628 class V8_EXPORT FunctionTemplate : public Template {
3630 /** Creates a function template.*/
3631 static Local<FunctionTemplate> New(
3633 FunctionCallback callback = 0,
3634 Handle<Value> data = Handle<Value>(),
3635 Handle<Signature> signature = Handle<Signature>(),
3638 /** Returns the unique function instance in the current execution context.*/
3639 Local<Function> GetFunction();
3642 * Set the call-handler callback for a FunctionTemplate. This
3643 * callback is called whenever the function created from this
3644 * FunctionTemplate is called.
3646 void SetCallHandler(FunctionCallback callback,
3647 Handle<Value> data = Handle<Value>());
3649 /** Set the predefined length property for the FunctionTemplate. */
3650 void SetLength(int length);
3652 /** Get the InstanceTemplate. */
3653 Local<ObjectTemplate> InstanceTemplate();
3655 /** Causes the function template to inherit from a parent function template.*/
3656 void Inherit(Handle<FunctionTemplate> parent);
3659 * A PrototypeTemplate is the template used to create the prototype object
3660 * of the function created by this template.
3662 Local<ObjectTemplate> PrototypeTemplate();
3665 * Set the class name of the FunctionTemplate. This is used for
3666 * printing objects created with the function created from the
3667 * FunctionTemplate as its constructor.
3669 void SetClassName(Handle<String> name);
3672 * Determines whether the __proto__ accessor ignores instances of
3673 * the function template. If instances of the function template are
3674 * ignored, __proto__ skips all instances and instead returns the
3675 * next object in the prototype chain.
3677 * Call with a value of true to make the __proto__ accessor ignore
3678 * instances of the function template. Call with a value of false
3679 * to make the __proto__ accessor not ignore instances of the
3680 * function template. By default, instances of a function template
3683 void SetHiddenPrototype(bool value);
3686 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3687 * of functions created from this FunctionTemplate to true.
3689 void ReadOnlyPrototype();
3692 * Removes the prototype property from functions created from this
3695 void RemovePrototype();
3698 * Returns true if the given object is an instance of this function
3701 bool HasInstance(Handle<Value> object);
3705 friend class Context;
3706 friend class ObjectTemplate;
3711 * An ObjectTemplate is used to create objects at runtime.
3713 * Properties added to an ObjectTemplate are added to each object
3714 * created from the ObjectTemplate.
3716 class V8_EXPORT ObjectTemplate : public Template {
3718 /** Creates an ObjectTemplate. */
3719 static Local<ObjectTemplate> New(Isolate* isolate);
3720 // Will be deprecated soon.
3721 static Local<ObjectTemplate> New();
3723 /** Creates a new instance of this template.*/
3724 Local<Object> NewInstance();
3727 * Sets an accessor on the object template.
3729 * Whenever the property with the given name is accessed on objects
3730 * created from this ObjectTemplate the getter and setter callbacks
3731 * are called instead of getting and setting the property directly
3732 * on the JavaScript object.
3734 * \param name The name of the property for which an accessor is added.
3735 * \param getter The callback to invoke when getting the property.
3736 * \param setter The callback to invoke when setting the property.
3737 * \param data A piece of data that will be passed to the getter and setter
3738 * callbacks whenever they are invoked.
3739 * \param settings Access control settings for the accessor. This is a bit
3740 * field consisting of one of more of
3741 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3742 * The default is to not allow cross-context access.
3743 * ALL_CAN_READ means that all cross-context reads are allowed.
3744 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3745 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3746 * cross-context access.
3747 * \param attribute The attributes of the property for which an accessor
3749 * \param signature The signature describes valid receivers for the accessor
3750 * and is used to perform implicit instance checks against them. If the
3751 * receiver is incompatible (i.e. is not an instance of the constructor as
3752 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3753 * thrown and no callback is invoked.
3755 void SetAccessor(Handle<String> name,
3756 AccessorGetterCallback getter,
3757 AccessorSetterCallback setter = 0,
3758 Handle<Value> data = Handle<Value>(),
3759 AccessControl settings = DEFAULT,
3760 PropertyAttribute attribute = None,
3761 Handle<AccessorSignature> signature =
3762 Handle<AccessorSignature>());
3763 void SetAccessor(Handle<Name> name,
3764 AccessorNameGetterCallback getter,
3765 AccessorNameSetterCallback setter = 0,
3766 Handle<Value> data = Handle<Value>(),
3767 AccessControl settings = DEFAULT,
3768 PropertyAttribute attribute = None,
3769 Handle<AccessorSignature> signature =
3770 Handle<AccessorSignature>());
3773 * Sets a named property handler on the object template.
3775 * Whenever a property whose name is a string is accessed on objects created
3776 * from this object template, the provided callback is invoked instead of
3777 * accessing the property directly on the JavaScript object.
3779 * \param getter The callback to invoke when getting a property.
3780 * \param setter The callback to invoke when setting a property.
3781 * \param query The callback to invoke to check if a property is present,
3782 * and if present, get its attributes.
3783 * \param deleter The callback to invoke when deleting a property.
3784 * \param enumerator The callback to invoke to enumerate all the named
3785 * properties of an object.
3786 * \param data A piece of data that will be passed to the callbacks
3787 * whenever they are invoked.
3789 void SetNamedPropertyHandler(
3790 NamedPropertyGetterCallback getter,
3791 NamedPropertySetterCallback setter = 0,
3792 NamedPropertyQueryCallback query = 0,
3793 NamedPropertyDeleterCallback deleter = 0,
3794 NamedPropertyEnumeratorCallback enumerator = 0,
3795 Handle<Value> data = Handle<Value>());
3798 * Sets an indexed property handler on the object template.
3800 * Whenever an indexed property is accessed on objects created from
3801 * this object template, the provided callback is invoked instead of
3802 * accessing the property directly on the JavaScript object.
3804 * \param getter The callback to invoke when getting a property.
3805 * \param setter The callback to invoke when setting a property.
3806 * \param query The callback to invoke to check if an object has a property.
3807 * \param deleter The callback to invoke when deleting a property.
3808 * \param enumerator The callback to invoke to enumerate all the indexed
3809 * properties of an object.
3810 * \param data A piece of data that will be passed to the callbacks
3811 * whenever they are invoked.
3813 void SetIndexedPropertyHandler(
3814 IndexedPropertyGetterCallback getter,
3815 IndexedPropertySetterCallback setter = 0,
3816 IndexedPropertyQueryCallback query = 0,
3817 IndexedPropertyDeleterCallback deleter = 0,
3818 IndexedPropertyEnumeratorCallback enumerator = 0,
3819 Handle<Value> data = Handle<Value>());
3822 * Sets the callback to be used when calling instances created from
3823 * this template as a function. If no callback is set, instances
3824 * behave like normal JavaScript objects that cannot be called as a
3827 void SetCallAsFunctionHandler(FunctionCallback callback,
3828 Handle<Value> data = Handle<Value>());
3831 * Mark object instances of the template as undetectable.
3833 * In many ways, undetectable objects behave as though they are not
3834 * there. They behave like 'undefined' in conditionals and when
3835 * printed. However, properties can be accessed and called as on
3838 void MarkAsUndetectable();
3841 * Sets access check callbacks on the object template.
3843 * When accessing properties on instances of this object template,
3844 * the access check callback will be called to determine whether or
3845 * not to allow cross-context access to the properties.
3846 * The last parameter specifies whether access checks are turned
3847 * on by default on instances. If access checks are off by default,
3848 * they can be turned on on individual instances by calling
3849 * Object::TurnOnAccessCheck().
3851 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3852 IndexedSecurityCallback indexed_handler,
3853 Handle<Value> data = Handle<Value>(),
3854 bool turned_on_by_default = true);
3857 * Gets the number of internal fields for objects generated from
3860 int InternalFieldCount();
3863 * Sets the number of internal fields for objects generated from
3866 void SetInternalFieldCount(int value);
3870 static Local<ObjectTemplate> New(internal::Isolate* isolate,
3871 Handle<FunctionTemplate> constructor);
3872 friend class FunctionTemplate;
3877 * A Signature specifies which receivers and arguments are valid
3878 * parameters to a function.
3880 class V8_EXPORT Signature : public Data {
3882 static Local<Signature> New(Isolate* isolate,
3883 Handle<FunctionTemplate> receiver =
3884 Handle<FunctionTemplate>(),
3886 Handle<FunctionTemplate> argv[] = 0);
3894 * An AccessorSignature specifies which receivers are valid parameters
3895 * to an accessor callback.
3897 class V8_EXPORT AccessorSignature : public Data {
3899 static Local<AccessorSignature> New(Isolate* isolate,
3900 Handle<FunctionTemplate> receiver =
3901 Handle<FunctionTemplate>());
3904 AccessorSignature();
3908 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3910 DeclaredAccessorDescriptor();
3914 class V8_EXPORT ObjectOperationDescriptor : public Data {
3916 // This function is not yet stable and should not be used at this time.
3917 static Local<RawOperationDescriptor> NewInternalFieldDereference(
3919 int internal_field);
3921 ObjectOperationDescriptor();
3925 enum DeclaredAccessorDescriptorDataType {
3926 kDescriptorBoolType,
3927 kDescriptorInt8Type, kDescriptorUint8Type,
3928 kDescriptorInt16Type, kDescriptorUint16Type,
3929 kDescriptorInt32Type, kDescriptorUint32Type,
3930 kDescriptorFloatType, kDescriptorDoubleType
3934 class V8_EXPORT RawOperationDescriptor : public Data {
3936 Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3937 Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3938 Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3939 int16_t byte_offset);
3940 Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3941 void* compare_value);
3942 Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3944 DeclaredAccessorDescriptorDataType data_type,
3945 uint8_t bool_offset = 0);
3946 Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3948 uint8_t compare_value);
3949 Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3952 uint16_t compare_value);
3953 Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3956 uint32_t compare_value);
3959 RawOperationDescriptor();
3964 * A utility for determining the type of objects based on the template
3965 * they were constructed from.
3967 class V8_EXPORT TypeSwitch : public Data {
3969 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3970 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3971 int match(Handle<Value> value);
3977 // --- Extensions ---
3979 class V8_EXPORT ExternalOneByteStringResourceImpl
3980 : public String::ExternalOneByteStringResource {
3982 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
3983 ExternalOneByteStringResourceImpl(const char* data, size_t length)
3984 : data_(data), length_(length) {}
3985 const char* data() const { return data_; }
3986 size_t length() const { return length_; }
3996 class V8_EXPORT Extension { // NOLINT
3998 // Note that the strings passed into this constructor must live as long
3999 // as the Extension itself.
4000 Extension(const char* name,
4001 const char* source = 0,
4003 const char** deps = 0,
4004 int source_length = -1);
4005 virtual ~Extension() { }
4006 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
4007 v8::Isolate* isolate, v8::Handle<v8::String> name) {
4008 return v8::Handle<v8::FunctionTemplate>();
4011 const char* name() const { return name_; }
4012 size_t source_length() const { return source_length_; }
4013 const String::ExternalOneByteStringResource* source() const {
4015 int dependency_count() { return dep_count_; }
4016 const char** dependencies() { return deps_; }
4017 void set_auto_enable(bool value) { auto_enable_ = value; }
4018 bool auto_enable() { return auto_enable_; }
4022 size_t source_length_; // expected to initialize before source_
4023 ExternalOneByteStringResourceImpl source_;
4028 // Disallow copying and assigning.
4029 Extension(const Extension&);
4030 void operator=(const Extension&);
4034 void V8_EXPORT RegisterExtension(Extension* extension);
4039 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
4040 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
4041 V8_INLINE Handle<Boolean> True(Isolate* isolate);
4042 V8_INLINE Handle<Boolean> False(Isolate* isolate);
4046 * A set of constraints that specifies the limits of the runtime's memory use.
4047 * You must set the heap size before initializing the VM - the size cannot be
4048 * adjusted after the VM is initialized.
4050 * If you are using threads then you should hold the V8::Locker lock while
4051 * setting the stack limit and you must set a non-default stack limit separately
4054 class V8_EXPORT ResourceConstraints {
4056 ResourceConstraints();
4059 * Configures the constraints with reasonable default values based on the
4060 * capabilities of the current device the VM is running on.
4062 * \param physical_memory The total amount of physical memory on the current
4064 * \param virtual_memory_limit The amount of virtual memory on the current
4065 * device, in bytes, or zero, if there is no limit.
4066 * \param number_of_processors The number of CPUs available on the current
4069 void ConfigureDefaults(uint64_t physical_memory,
4070 uint64_t virtual_memory_limit,
4071 uint32_t number_of_processors);
4073 int max_semi_space_size() const { return max_semi_space_size_; }
4074 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4075 int max_old_space_size() const { return max_old_space_size_; }
4076 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4077 int max_executable_size() const { return max_executable_size_; }
4078 void set_max_executable_size(int value) { max_executable_size_ = value; }
4079 uint32_t* stack_limit() const { return stack_limit_; }
4080 // Sets an address beyond which the VM's stack may not grow.
4081 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4082 int max_available_threads() const { return max_available_threads_; }
4083 // Set the number of threads available to V8, assuming at least 1.
4084 void set_max_available_threads(int value) {
4085 max_available_threads_ = value;
4087 size_t code_range_size() const { return code_range_size_; }
4088 void set_code_range_size(size_t value) {
4089 code_range_size_ = value;
4093 int max_semi_space_size_;
4094 int max_old_space_size_;
4095 int max_executable_size_;
4096 uint32_t* stack_limit_;
4097 int max_available_threads_;
4098 size_t code_range_size_;
4102 // --- Exceptions ---
4105 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4108 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
4112 typedef void (*LogEventCallback)(const char* name, int event);
4115 * Create new error objects by calling the corresponding error object
4116 * constructor with the message.
4118 class V8_EXPORT Exception {
4120 static Local<Value> RangeError(Handle<String> message);
4121 static Local<Value> ReferenceError(Handle<String> message);
4122 static Local<Value> SyntaxError(Handle<String> message);
4123 static Local<Value> TypeError(Handle<String> message);
4124 static Local<Value> Error(Handle<String> message);
4128 // --- Counters Callbacks ---
4130 typedef int* (*CounterLookupCallback)(const char* name);
4132 typedef void* (*CreateHistogramCallback)(const char* name,
4137 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4139 // --- Memory Allocation Callback ---
4141 kObjectSpaceNewSpace = 1 << 0,
4142 kObjectSpaceOldPointerSpace = 1 << 1,
4143 kObjectSpaceOldDataSpace = 1 << 2,
4144 kObjectSpaceCodeSpace = 1 << 3,
4145 kObjectSpaceMapSpace = 1 << 4,
4146 kObjectSpaceLoSpace = 1 << 5,
4148 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4149 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4153 enum AllocationAction {
4154 kAllocationActionAllocate = 1 << 0,
4155 kAllocationActionFree = 1 << 1,
4156 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4159 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4160 AllocationAction action,
4163 // --- Leave Script Callback ---
4164 typedef void (*CallCompletedCallback)();
4166 // --- Microtask Callback ---
4167 typedef void (*MicrotaskCallback)(void* data);
4169 // --- Failed Access Check Callback ---
4170 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4174 // --- AllowCodeGenerationFromStrings callbacks ---
4177 * Callback to check if code generation from strings is allowed. See
4178 * Context::AllowCodeGenerationFromStrings.
4180 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4182 // --- Garbage Collection Callbacks ---
4185 * Applications can register callback functions which will be called
4186 * before and after a garbage collection. Allocations are not
4187 * allowed in the callback functions, you therefore cannot manipulate
4188 * objects (set or delete properties for example) since it is possible
4189 * such operations will result in the allocation of objects.
4192 kGCTypeScavenge = 1 << 0,
4193 kGCTypeMarkSweepCompact = 1 << 1,
4194 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4197 enum GCCallbackFlags {
4198 kNoGCCallbackFlags = 0,
4199 kGCCallbackFlagCompacted = 1 << 0,
4200 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4201 kGCCallbackFlagForced = 1 << 2
4204 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4205 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4207 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4211 * Collection of V8 heap information.
4213 * Instances of this class can be passed to v8::V8::HeapStatistics to
4214 * get heap statistics from V8.
4216 class V8_EXPORT HeapStatistics {
4219 size_t total_heap_size() { return total_heap_size_; }
4220 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4221 size_t total_physical_size() { return total_physical_size_; }
4222 size_t used_heap_size() { return used_heap_size_; }
4223 size_t heap_size_limit() { return heap_size_limit_; }
4226 size_t total_heap_size_;
4227 size_t total_heap_size_executable_;
4228 size_t total_physical_size_;
4229 size_t used_heap_size_;
4230 size_t heap_size_limit_;
4233 friend class Isolate;
4237 class RetainedObjectInfo;
4241 * FunctionEntryHook is the type of the profile entry hook called at entry to
4242 * any generated function when function-level profiling is enabled.
4244 * \param function the address of the function that's being entered.
4245 * \param return_addr_location points to a location on stack where the machine
4246 * return address resides. This can be used to identify the caller of
4247 * \p function, and/or modified to divert execution when \p function exits.
4249 * \note the entry hook must not cause garbage collection.
4251 typedef void (*FunctionEntryHook)(uintptr_t function,
4252 uintptr_t return_addr_location);
4255 * A JIT code event is issued each time code is added, moved or removed.
4257 * \note removal events are not currently issued.
4259 struct JitCodeEvent {
4264 CODE_ADD_LINE_POS_INFO,
4265 CODE_START_LINE_INFO_RECORDING,
4266 CODE_END_LINE_INFO_RECORDING
4268 // Definition of the code position type. The "POSITION" type means the place
4269 // in the source code which are of interest when making stack traces to
4270 // pin-point the source location of a stack frame as close as possible.
4271 // The "STATEMENT_POSITION" means the place at the beginning of each
4272 // statement, and is used to indicate possible break locations.
4273 enum PositionType { POSITION, STATEMENT_POSITION };
4277 // Start of the instructions.
4279 // Size of the instructions.
4281 // Script info for CODE_ADDED event.
4282 Handle<UnboundScript> script;
4283 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4284 // code line information which is returned from the
4285 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4286 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4290 // Name of the object associated with the code, note that the string is not
4293 // Number of chars in str.
4297 struct line_info_t {
4302 // The position type.
4303 PositionType position_type;
4307 // Only valid for CODE_ADDED.
4310 // Only valid for CODE_ADD_LINE_POS_INFO
4311 struct line_info_t line_info;
4313 // New location of instructions. Only valid for CODE_MOVED.
4314 void* new_code_start;
4319 * Option flags passed to the SetJitCodeEventHandler function.
4321 enum JitCodeEventOptions {
4322 kJitCodeEventDefault = 0,
4323 // Generate callbacks for already existent code.
4324 kJitCodeEventEnumExisting = 1
4329 * Callback function passed to SetJitCodeEventHandler.
4331 * \param event code add, move or removal event.
4333 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4337 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
4338 * completely separate states. Objects from one isolate must not be used in
4339 * other isolates. The embedder can create multiple isolates and use them in
4340 * parallel in multiple threads. An isolate can be entered by at most one
4341 * thread at any given time. The Locker/Unlocker API must be used to
4344 class V8_EXPORT Isolate {
4347 * Initial configuration parameters for a new Isolate.
4349 struct CreateParams {
4352 code_event_handler(NULL),
4353 enable_serializer(false) {}
4356 * The optional entry_hook allows the host application to provide the
4357 * address of a function that's invoked on entry to every V8-generated
4358 * function. Note that entry_hook is invoked at the very start of each
4359 * generated function. Furthermore, if an entry_hook is given, V8 will
4360 * always run without a context snapshot.
4362 FunctionEntryHook entry_hook;
4365 * Allows the host application to provide the address of a function that is
4366 * notified each time code is added, moved or removed.
4368 JitCodeEventHandler code_event_handler;
4371 * ResourceConstraints to use for the new Isolate.
4373 ResourceConstraints constraints;
4376 * This flag currently renders the Isolate unusable.
4378 bool enable_serializer;
4383 * Stack-allocated class which sets the isolate for all operations
4384 * executed within a local scope.
4386 class V8_EXPORT Scope {
4388 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4392 ~Scope() { isolate_->Exit(); }
4395 Isolate* const isolate_;
4397 // Prevent copying of Scope objects.
4398 Scope(const Scope&);
4399 Scope& operator=(const Scope&);
4404 * Assert that no Javascript code is invoked.
4406 class V8_EXPORT DisallowJavascriptExecutionScope {
4408 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4410 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4411 ~DisallowJavascriptExecutionScope();
4417 // Prevent copying of Scope objects.
4418 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4419 DisallowJavascriptExecutionScope& operator=(
4420 const DisallowJavascriptExecutionScope&);
4425 * Introduce exception to DisallowJavascriptExecutionScope.
4427 class V8_EXPORT AllowJavascriptExecutionScope {
4429 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4430 ~AllowJavascriptExecutionScope();
4433 void* internal_throws_;
4434 void* internal_assert_;
4436 // Prevent copying of Scope objects.
4437 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4438 AllowJavascriptExecutionScope& operator=(
4439 const AllowJavascriptExecutionScope&);
4443 * Do not run microtasks while this scope is active, even if microtasks are
4444 * automatically executed otherwise.
4446 class V8_EXPORT SuppressMicrotaskExecutionScope {
4448 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4449 ~SuppressMicrotaskExecutionScope();
4452 internal::Isolate* isolate_;
4454 // Prevent copying of Scope objects.
4455 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4456 SuppressMicrotaskExecutionScope& operator=(
4457 const SuppressMicrotaskExecutionScope&);
4461 * Types of garbage collections that can be requested via
4462 * RequestGarbageCollectionForTesting.
4464 enum GarbageCollectionType {
4465 kFullGarbageCollection,
4466 kMinorGarbageCollection
4470 * Features reported via the SetUseCounterCallback callback. Do not chang
4471 * assigned numbers of existing items; add new features to the end of this
4474 enum UseCounterFeature {
4476 kUseCounterFeatureCount // This enum value must be last.
4479 typedef void (*UseCounterCallback)(Isolate* isolate,
4480 UseCounterFeature feature);
4484 * Creates a new isolate. Does not change the currently entered
4487 * When an isolate is no longer used its resources should be freed
4488 * by calling Dispose(). Using the delete operator is not allowed.
4490 * V8::Initialize() must have run prior to this.
4492 static Isolate* New(const CreateParams& params = CreateParams());
4495 * Returns the entered isolate for the current thread or NULL in
4496 * case there is no current isolate.
4498 static Isolate* GetCurrent();
4501 * Methods below this point require holding a lock (using Locker) in
4502 * a multi-threaded environment.
4506 * Sets this isolate as the entered one for the current thread.
4507 * Saves the previously entered one (if any), so that it can be
4508 * restored when exiting. Re-entering an isolate is allowed.
4513 * Exits this isolate by restoring the previously entered one in the
4514 * current thread. The isolate may still stay the same, if it was
4515 * entered more than once.
4517 * Requires: this == Isolate::GetCurrent().
4522 * Disposes the isolate. The isolate must not be entered by any
4523 * thread to be disposable.
4528 * Associate embedder-specific data with the isolate. |slot| has to be
4529 * between 0 and GetNumberOfDataSlots() - 1.
4531 V8_INLINE void SetData(uint32_t slot, void* data);
4534 * Retrieve embedder-specific data from the isolate.
4535 * Returns NULL if SetData has never been called for the given |slot|.
4537 V8_INLINE void* GetData(uint32_t slot);
4540 * Returns the maximum number of available embedder data slots. Valid slots
4541 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4543 V8_INLINE static uint32_t GetNumberOfDataSlots();
4546 * Get statistics about the heap memory usage.
4548 void GetHeapStatistics(HeapStatistics* heap_statistics);
4551 * Adjusts the amount of registered external memory. Used to give V8 an
4552 * indication of the amount of externally allocated memory that is kept alive
4553 * by JavaScript objects. V8 uses this to decide when to perform global
4554 * garbage collections. Registering externally allocated memory will trigger
4555 * global garbage collections more often than it would otherwise in an attempt
4556 * to garbage collect the JavaScript objects that keep the externally
4557 * allocated memory alive.
4559 * \param change_in_bytes the change in externally allocated memory that is
4560 * kept alive by JavaScript objects.
4561 * \returns the adjusted value.
4564 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4567 * Returns heap profiler for this isolate. Will return NULL until the isolate
4570 HeapProfiler* GetHeapProfiler();
4573 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4574 * is initialized. It is the embedder's responsibility to stop all CPU
4575 * profiling activities if it has started any.
4577 CpuProfiler* GetCpuProfiler();
4579 /** Returns true if this isolate has a current context. */
4582 /** Returns the context that is on the top of the stack. */
4583 Local<Context> GetCurrentContext();
4586 * Returns the context of the calling JavaScript code. That is the
4587 * context of the top-most JavaScript frame. If there are no
4588 * JavaScript frames an empty handle is returned.
4590 Local<Context> GetCallingContext();
4592 /** Returns the last entered context. */
4593 Local<Context> GetEnteredContext();
4596 * Schedules an exception to be thrown when returning to JavaScript. When an
4597 * exception has been scheduled it is illegal to invoke any JavaScript
4598 * operation; the caller must return immediately and only after the exception
4599 * has been handled does it become legal to invoke JavaScript operations.
4601 Local<Value> ThrowException(Local<Value> exception);
4604 * Allows the host application to group objects together. If one
4605 * object in the group is alive, all objects in the group are alive.
4606 * After each garbage collection, object groups are removed. It is
4607 * intended to be used in the before-garbage-collection callback
4608 * function, for instance to simulate DOM tree connections among JS
4609 * wrapper objects. Object groups for all dependent handles need to
4610 * be provided for kGCTypeMarkSweepCompact collections, for all other
4611 * garbage collection types it is sufficient to provide object groups
4612 * for partially dependent handles only.
4614 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4618 * Allows the host application to declare implicit references from an object
4619 * group to an object. If the objects of the object group are alive, the child
4620 * object is alive too. After each garbage collection, all implicit references
4621 * are removed. It is intended to be used in the before-garbage-collection
4622 * callback function.
4624 template<typename T> void SetReferenceFromGroup(UniqueId id,
4625 const Persistent<T>& child);
4628 * Allows the host application to declare implicit references from an object
4629 * to another object. If the parent object is alive, the child object is alive
4630 * too. After each garbage collection, all implicit references are removed. It
4631 * is intended to be used in the before-garbage-collection callback function.
4633 template<typename T, typename S>
4634 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4636 typedef void (*GCPrologueCallback)(Isolate* isolate,
4638 GCCallbackFlags flags);
4639 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4641 GCCallbackFlags flags);
4644 * Enables the host application to receive a notification before a
4645 * garbage collection. Allocations are allowed in the callback function,
4646 * but the callback is not re-entrant: if the allocation inside it will
4647 * trigger the garbage collection, the callback won't be called again.
4648 * It is possible to specify the GCType filter for your callback. But it is
4649 * not possible to register the same callback function two times with
4650 * different GCType filters.
4652 void AddGCPrologueCallback(
4653 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4656 * This function removes callback which was installed by
4657 * AddGCPrologueCallback function.
4659 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4662 * Enables the host application to receive a notification after a
4663 * garbage collection. Allocations are allowed in the callback function,
4664 * but the callback is not re-entrant: if the allocation inside it will
4665 * trigger the garbage collection, the callback won't be called again.
4666 * It is possible to specify the GCType filter for your callback. But it is
4667 * not possible to register the same callback function two times with
4668 * different GCType filters.
4670 void AddGCEpilogueCallback(
4671 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4674 * This function removes callback which was installed by
4675 * AddGCEpilogueCallback function.
4677 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4680 * Request V8 to interrupt long running JavaScript code and invoke
4681 * the given |callback| passing the given |data| to it. After |callback|
4682 * returns control will be returned to the JavaScript code.
4683 * At any given moment V8 can remember only a single callback for the very
4684 * last interrupt request.
4685 * Can be called from another thread without acquiring a |Locker|.
4686 * Registered |callback| must not reenter interrupted Isolate.
4688 void RequestInterrupt(InterruptCallback callback, void* data);
4691 * Clear interrupt request created by |RequestInterrupt|.
4692 * Can be called from another thread without acquiring a |Locker|.
4694 void ClearInterrupt();
4697 * Request garbage collection in this Isolate. It is only valid to call this
4698 * function if --expose_gc was specified.
4700 * This should only be used for testing purposes and not to enforce a garbage
4701 * collection schedule. It has strong negative impact on the garbage
4702 * collection performance. Use IdleNotification() or LowMemoryNotification()
4703 * instead to influence the garbage collection schedule.
4705 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4708 * Set the callback to invoke for logging event.
4710 void SetEventLogger(LogEventCallback that);
4713 * Adds a callback to notify the host application when a script finished
4714 * running. If a script re-enters the runtime during executing, the
4715 * CallCompletedCallback is only invoked when the outer-most script
4716 * execution ends. Executing scripts inside the callback do not trigger
4717 * further callbacks.
4719 void AddCallCompletedCallback(CallCompletedCallback callback);
4722 * Removes callback that was installed by AddCallCompletedCallback.
4724 void RemoveCallCompletedCallback(CallCompletedCallback callback);
4727 * Experimental: Runs the Microtask Work Queue until empty
4728 * Any exceptions thrown by microtask callbacks are swallowed.
4730 void RunMicrotasks();
4733 * Experimental: Enqueues the callback to the Microtask Work Queue
4735 void EnqueueMicrotask(Handle<Function> microtask);
4738 * Experimental: Enqueues the callback to the Microtask Work Queue
4740 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
4743 * Experimental: Controls whether the Microtask Work Queue is automatically
4744 * run when the script call depth decrements to zero.
4746 void SetAutorunMicrotasks(bool autorun);
4749 * Experimental: Returns whether the Microtask Work Queue is automatically
4750 * run when the script call depth decrements to zero.
4752 bool WillAutorunMicrotasks() const;
4755 * Sets a callback for counting the number of times a feature of V8 is used.
4757 void SetUseCounterCallback(UseCounterCallback callback);
4760 * Enables the host application to provide a mechanism for recording
4761 * statistics counters.
4763 void SetCounterFunction(CounterLookupCallback);
4766 * Enables the host application to provide a mechanism for recording
4767 * histograms. The CreateHistogram function returns a
4768 * histogram which will later be passed to the AddHistogramSample
4771 void SetCreateHistogramFunction(CreateHistogramCallback);
4772 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4775 * Optional notification that the embedder is idle.
4776 * V8 uses the notification to reduce memory footprint.
4777 * This call can be used repeatedly if the embedder remains idle.
4778 * Returns true if the embedder should stop calling IdleNotification
4779 * until real work has been done. This indicates that V8 has done
4780 * as much cleanup as it will be able to do.
4782 * The idle_time_in_ms argument specifies the time V8 has to do reduce
4783 * the memory footprint. There is no guarantee that the actual work will be
4784 * done within the time limit.
4786 bool IdleNotification(int idle_time_in_ms);
4789 * Optional notification that the system is running low on memory.
4790 * V8 uses these notifications to attempt to free memory.
4792 void LowMemoryNotification();
4795 * Optional notification that a context has been disposed. V8 uses
4796 * these notifications to guide the GC heuristic. Returns the number
4797 * of context disposals - including this one - since the last time
4798 * V8 had a chance to clean up.
4800 int ContextDisposedNotification();
4803 * Allows the host application to provide the address of a function that is
4804 * notified each time code is added, moved or removed.
4806 * \param options options for the JIT code event handler.
4807 * \param event_handler the JIT code event handler, which will be invoked
4808 * each time code is added, moved or removed.
4809 * \note \p event_handler won't get notified of existent code.
4810 * \note since code removal notifications are not currently issued, the
4811 * \p event_handler may get notifications of code that overlaps earlier
4812 * code notifications. This happens when code areas are reused, and the
4813 * earlier overlapping code areas should therefore be discarded.
4814 * \note the events passed to \p event_handler and the strings they point to
4815 * are not guaranteed to live past each call. The \p event_handler must
4816 * copy strings and other parameters it needs to keep around.
4817 * \note the set of events declared in JitCodeEvent::EventType is expected to
4818 * grow over time, and the JitCodeEvent structure is expected to accrue
4819 * new members. The \p event_handler function must ignore event codes
4820 * it does not recognize to maintain future compatibility.
4821 * \note Use Isolate::CreateParams to get events for code executed during
4824 void SetJitCodeEventHandler(JitCodeEventOptions options,
4825 JitCodeEventHandler event_handler);
4828 * Modifies the stack limit for this Isolate.
4830 * \param stack_limit An address beyond which the Vm's stack may not grow.
4832 * \note If you are using threads then you should hold the V8::Locker lock
4833 * while setting the stack limit and you must set a non-default stack
4834 * limit separately for each thread.
4836 void SetStackLimit(uintptr_t stack_limit);
4839 template<class K, class V, class Traits> friend class PersistentValueMap;
4842 Isolate(const Isolate&);
4844 Isolate& operator=(const Isolate&);
4845 void* operator new(size_t size);
4846 void operator delete(void*, size_t);
4848 void SetObjectGroupId(internal::Object** object, UniqueId id);
4849 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4850 void SetReference(internal::Object** parent, internal::Object** child);
4851 void CollectAllGarbage(const char* gc_reason);
4854 class V8_EXPORT StartupData {
4856 enum CompressionAlgorithm {
4862 int compressed_size;
4868 * A helper class for driving V8 startup data decompression. It is based on
4869 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
4870 * for an embedder to use this class, instead, API functions can be used
4873 * For an example of the class usage, see the "shell.cc" sample application.
4875 class V8_EXPORT StartupDataDecompressor { // NOLINT
4877 StartupDataDecompressor();
4878 virtual ~StartupDataDecompressor();
4882 virtual int DecompressData(char* raw_data,
4884 const char* compressed_data,
4885 int compressed_data_size) = 0;
4893 * EntropySource is used as a callback function when v8 needs a source
4896 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4900 * ReturnAddressLocationResolver is used as a callback function when v8 is
4901 * resolving the location of a return address on the stack. Profilers that
4902 * change the return address on the stack can use this to resolve the stack
4903 * location to whereever the profiler stashed the original return address.
4905 * \param return_addr_location points to a location on stack where a machine
4906 * return address resides.
4907 * \returns either return_addr_location, or else a pointer to the profiler's
4908 * copy of the original return address.
4910 * \note the resolver function must not cause garbage collection.
4912 typedef uintptr_t (*ReturnAddressLocationResolver)(
4913 uintptr_t return_addr_location);
4917 * Interface for iterating through all external resources in the heap.
4919 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4921 virtual ~ExternalResourceVisitor() {}
4922 virtual void VisitExternalString(Handle<String> string) {}
4927 * Interface for iterating through all the persistent handles in the heap.
4929 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4931 virtual ~PersistentHandleVisitor() {}
4932 virtual void VisitPersistentHandle(Persistent<Value>* value,
4933 uint16_t class_id) {}
4938 * Container class for static utility functions.
4940 class V8_EXPORT V8 {
4942 /** Set the callback to invoke in case of fatal errors. */
4943 static void SetFatalErrorHandler(FatalErrorCallback that);
4946 * Set the callback to invoke to check if code generation from
4947 * strings should be allowed.
4949 static void SetAllowCodeGenerationFromStringsCallback(
4950 AllowCodeGenerationFromStringsCallback that);
4953 * Set allocator to use for ArrayBuffer memory.
4954 * The allocator should be set only once. The allocator should be set
4955 * before any code tha uses ArrayBuffers is executed.
4956 * This allocator is used in all isolates.
4958 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4961 * Check if V8 is dead and therefore unusable. This is the case after
4962 * fatal errors such as out-of-memory situations.
4964 static bool IsDead();
4967 * The following 4 functions are to be used when V8 is built with
4968 * the 'compress_startup_data' flag enabled. In this case, the
4969 * embedder must decompress startup data prior to initializing V8.
4971 * This is how interaction with V8 should look like:
4972 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4973 * v8::StartupData* compressed_data =
4974 * new v8::StartupData[compressed_data_count];
4975 * v8::V8::GetCompressedStartupData(compressed_data);
4976 * ... decompress data (compressed_data can be updated in-place) ...
4977 * v8::V8::SetDecompressedStartupData(compressed_data);
4978 * ... now V8 can be initialized
4979 * ... make sure the decompressed data stays valid until V8 shutdown
4981 * A helper class StartupDataDecompressor is provided. It implements
4982 * the protocol of the interaction described above, and can be used in
4983 * most cases instead of calling these API functions directly.
4985 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4986 static int GetCompressedStartupDataCount();
4987 static void GetCompressedStartupData(StartupData* compressed_data);
4988 static void SetDecompressedStartupData(StartupData* decompressed_data);
4991 * Hand startup data to V8, in case the embedder has chosen to build
4992 * V8 with external startup data.
4995 * - By default the startup data is linked into the V8 library, in which
4996 * case this function is not meaningful.
4997 * - If this needs to be called, it needs to be called before V8
4998 * tries to make use of its built-ins.
4999 * - To avoid unnecessary copies of data, V8 will point directly into the
5000 * given data blob, so pretty please keep it around until V8 exit.
5001 * - Compression of the startup blob might be useful, but needs to
5002 * handled entirely on the embedders' side.
5003 * - The call will abort if the data is invalid.
5005 static void SetNativesDataBlob(StartupData* startup_blob);
5006 static void SetSnapshotDataBlob(StartupData* startup_blob);
5009 * Adds a message listener.
5011 * The same message listener can be added more than once and in that
5012 * case it will be called more than once for each message.
5014 * If data is specified, it will be passed to the callback when it is called.
5015 * Otherwise, the exception object will be passed to the callback instead.
5017 static bool AddMessageListener(MessageCallback that,
5018 Handle<Value> data = Handle<Value>());
5021 * Remove all message listeners from the specified callback function.
5023 static void RemoveMessageListeners(MessageCallback that);
5026 * Tells V8 to capture current stack trace when uncaught exception occurs
5027 * and report it to the message listeners. The option is off by default.
5029 static void SetCaptureStackTraceForUncaughtExceptions(
5031 int frame_limit = 10,
5032 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5035 * Sets V8 flags from a string.
5037 static void SetFlagsFromString(const char* str, int length);
5040 * Sets V8 flags from the command line.
5042 static void SetFlagsFromCommandLine(int* argc,
5046 /** Get the version string. */
5047 static const char* GetVersion();
5049 /** Callback function for reporting failed access checks.*/
5050 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5053 * Enables the host application to receive a notification before a
5054 * garbage collection. Allocations are not allowed in the
5055 * callback function, you therefore cannot manipulate objects (set
5056 * or delete properties for example) since it is possible such
5057 * operations will result in the allocation of objects. It is possible
5058 * to specify the GCType filter for your callback. But it is not possible to
5059 * register the same callback function two times with different
5062 static void AddGCPrologueCallback(
5063 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5066 * This function removes callback which was installed by
5067 * AddGCPrologueCallback function.
5069 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
5072 * Enables the host application to receive a notification after a
5073 * garbage collection. Allocations are not allowed in the
5074 * callback function, you therefore cannot manipulate objects (set
5075 * or delete properties for example) since it is possible such
5076 * operations will result in the allocation of objects. It is possible
5077 * to specify the GCType filter for your callback. But it is not possible to
5078 * register the same callback function two times with different
5081 static void AddGCEpilogueCallback(
5082 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5085 * This function removes callback which was installed by
5086 * AddGCEpilogueCallback function.
5088 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5091 * Enables the host application to provide a mechanism to be notified
5092 * and perform custom logging when V8 Allocates Executable Memory.
5094 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5096 AllocationAction action);
5099 * Removes callback that was installed by AddMemoryAllocationCallback.
5101 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5104 * Initializes V8. This function needs to be called before the first Isolate
5105 * is created. It always returns true.
5107 static bool Initialize();
5110 * Allows the host application to provide a callback which can be used
5111 * as a source of entropy for random number generators.
5113 static void SetEntropySource(EntropySource source);
5116 * Allows the host application to provide a callback that allows v8 to
5117 * cooperate with a profiler that rewrites return addresses on stack.
5119 static void SetReturnAddressLocationResolver(
5120 ReturnAddressLocationResolver return_address_resolver);
5123 * Forcefully terminate the current thread of JavaScript execution
5124 * in the given isolate.
5126 * This method can be used by any thread even if that thread has not
5127 * acquired the V8 lock with a Locker object.
5129 * \param isolate The isolate in which to terminate the current JS execution.
5131 static void TerminateExecution(Isolate* isolate);
5134 * Is V8 terminating JavaScript execution.
5136 * Returns true if JavaScript execution is currently terminating
5137 * because of a call to TerminateExecution. In that case there are
5138 * still JavaScript frames on the stack and the termination
5139 * exception is still active.
5141 * \param isolate The isolate in which to check.
5143 static bool IsExecutionTerminating(Isolate* isolate = NULL);
5146 * Resume execution capability in the given isolate, whose execution
5147 * was previously forcefully terminated using TerminateExecution().
5149 * When execution is forcefully terminated using TerminateExecution(),
5150 * the isolate can not resume execution until all JavaScript frames
5151 * have propagated the uncatchable exception which is generated. This
5152 * method allows the program embedding the engine to handle the
5153 * termination event and resume execution capability, even if
5154 * JavaScript frames remain on the stack.
5156 * This method can be used by any thread even if that thread has not
5157 * acquired the V8 lock with a Locker object.
5159 * \param isolate The isolate in which to resume execution capability.
5161 static void CancelTerminateExecution(Isolate* isolate);
5164 * Releases any resources used by v8 and stops any utility threads
5165 * that may be running. Note that disposing v8 is permanent, it
5166 * cannot be reinitialized.
5168 * It should generally not be necessary to dispose v8 before exiting
5169 * a process, this should happen automatically. It is only necessary
5170 * to use if the process needs the resources taken up by v8.
5172 static bool Dispose();
5175 * Iterates through all external resources referenced from current isolate
5176 * heap. GC is not invoked prior to iterating, therefore there is no
5177 * guarantee that visited objects are still alive.
5179 static void VisitExternalResources(ExternalResourceVisitor* visitor);
5182 * Iterates through all the persistent handles in the current isolate's heap
5183 * that have class_ids.
5185 static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5188 * Iterates through all the persistent handles in the current isolate's heap
5189 * that have class_ids and are candidates to be marked as partially dependent
5190 * handles. This will visit handles to young objects created since the last
5191 * garbage collection but is free to visit an arbitrary superset of these
5194 static void VisitHandlesForPartialDependence(
5195 Isolate* isolate, PersistentHandleVisitor* visitor);
5198 * Initialize the ICU library bundled with V8. The embedder should only
5199 * invoke this method when using the bundled ICU. Returns true on success.
5201 * If V8 was compiled with the ICU data in an external file, the location
5202 * of the data file has to be provided.
5204 static bool InitializeICU(const char* icu_data_file = NULL);
5207 * Sets the v8::Platform to use. This should be invoked before V8 is
5210 static void InitializePlatform(Platform* platform);
5213 * Clears all references to the v8::Platform. This should be invoked after
5216 static void ShutdownPlatform();
5221 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5222 internal::Object** handle);
5223 static internal::Object** CopyPersistent(internal::Object** handle);
5224 static void DisposeGlobal(internal::Object** global_handle);
5225 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5226 static void MakeWeak(internal::Object** global_handle,
5228 WeakCallback weak_callback);
5229 static void* ClearWeak(internal::Object** global_handle);
5230 static void Eternalize(Isolate* isolate,
5233 static Local<Value> GetEternal(Isolate* isolate, int index);
5235 template <class T> friend class Handle;
5236 template <class T> friend class Local;
5237 template <class T> friend class Eternal;
5238 template <class T> friend class PersistentBase;
5239 template <class T, class M> friend class Persistent;
5240 friend class Context;
5245 * An external exception handler.
5247 class V8_EXPORT TryCatch {
5250 * Creates a new try/catch block and registers it with v8. Note that
5251 * all TryCatch blocks should be stack allocated because the memory
5252 * location itself is compared against JavaScript try/catch blocks.
5257 * Unregisters and deletes this try/catch block.
5262 * Returns true if an exception has been caught by this try/catch block.
5264 bool HasCaught() const;
5267 * For certain types of exceptions, it makes no sense to continue execution.
5269 * If CanContinue returns false, the correct action is to perform any C++
5270 * cleanup needed and then return. If CanContinue returns false and
5271 * HasTerminated returns true, it is possible to call
5272 * CancelTerminateExecution in order to continue calling into the engine.
5274 bool CanContinue() const;
5277 * Returns true if an exception has been caught due to script execution
5280 * There is no JavaScript representation of an execution termination
5281 * exception. Such exceptions are thrown when the TerminateExecution
5282 * methods are called to terminate a long-running script.
5284 * If such an exception has been thrown, HasTerminated will return true,
5285 * indicating that it is possible to call CancelTerminateExecution in order
5286 * to continue calling into the engine.
5288 bool HasTerminated() const;
5291 * Throws the exception caught by this TryCatch in a way that avoids
5292 * it being caught again by this same TryCatch. As with ThrowException
5293 * it is illegal to execute any JavaScript operations after calling
5294 * ReThrow; the caller must return immediately to where the exception
5297 Handle<Value> ReThrow();
5300 * Returns the exception caught by this try/catch block. If no exception has
5301 * been caught an empty handle is returned.
5303 * The returned handle is valid until this TryCatch block has been destroyed.
5305 Local<Value> Exception() const;
5308 * Returns the .stack property of the thrown object. If no .stack
5309 * property is present an empty handle is returned.
5311 Local<Value> StackTrace() const;
5314 * Returns the message associated with this exception. If there is
5315 * no message associated an empty handle is returned.
5317 * The returned handle is valid until this TryCatch block has been
5320 Local<v8::Message> Message() const;
5323 * Clears any exceptions that may have been caught by this try/catch block.
5324 * After this method has been called, HasCaught() will return false. Cancels
5325 * the scheduled exception if it is caught and ReThrow() is not called before.
5327 * It is not necessary to clear a try/catch block before using it again; if
5328 * another exception is thrown the previously caught exception will just be
5329 * overwritten. However, it is often a good idea since it makes it easier
5330 * to determine which operation threw a given exception.
5335 * Set verbosity of the external exception handler.
5337 * By default, exceptions that are caught by an external exception
5338 * handler are not reported. Call SetVerbose with true on an
5339 * external exception handler to have exceptions caught by the
5340 * handler reported as if they were not caught.
5342 void SetVerbose(bool value);
5345 * Set whether or not this TryCatch should capture a Message object
5346 * which holds source information about where the exception
5347 * occurred. True by default.
5349 void SetCaptureMessage(bool value);
5352 * There are cases when the raw address of C++ TryCatch object cannot be
5353 * used for comparisons with addresses into the JS stack. The cases are:
5354 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5355 * 2) Address sanitizer allocates local C++ object in the heap when
5356 * UseAfterReturn mode is enabled.
5357 * This method returns address that can be used for comparisons with
5358 * addresses into the JS stack. When neither simulator nor ASAN's
5359 * UseAfterReturn is enabled, then the address returned will be the address
5360 * of the C++ try catch handler itself.
5362 static void* JSStackComparableAddress(v8::TryCatch* handler) {
5363 if (handler == NULL) return NULL;
5364 return handler->js_stack_comparable_address_;
5368 void ResetInternal();
5370 // Make it hard to create heap-allocated TryCatch blocks.
5371 TryCatch(const TryCatch&);
5372 void operator=(const TryCatch&);
5373 void* operator new(size_t size);
5374 void operator delete(void*, size_t);
5376 v8::internal::Isolate* isolate_;
5377 v8::TryCatch* next_;
5380 void* message_script_;
5381 void* js_stack_comparable_address_;
5382 int message_start_pos_;
5383 int message_end_pos_;
5384 bool is_verbose_ : 1;
5385 bool can_continue_ : 1;
5386 bool capture_message_ : 1;
5388 bool has_terminated_ : 1;
5390 friend class v8::internal::Isolate;
5398 * A container for extension names.
5400 class V8_EXPORT ExtensionConfiguration {
5402 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
5403 ExtensionConfiguration(int name_count, const char* names[])
5404 : name_count_(name_count), names_(names) { }
5406 const char** begin() const { return &names_[0]; }
5407 const char** end() const { return &names_[name_count_]; }
5410 const int name_count_;
5411 const char** names_;
5416 * A sandboxed execution context with its own set of built-in objects
5419 class V8_EXPORT Context {
5422 * Returns the global proxy object.
5424 * Global proxy object is a thin wrapper whose prototype points to actual
5425 * context's global object with the properties like Object, etc. This is done
5426 * that way for security reasons (for more details see
5427 * https://wiki.mozilla.org/Gecko:SplitWindow).
5429 * Please note that changes to global proxy object prototype most probably
5430 * would break VM---v8 expects only global object as a prototype of global
5433 Local<Object> Global();
5436 * Detaches the global object from its context before
5437 * the global object can be reused to create a new context.
5439 void DetachGlobal();
5442 * Creates a new context and returns a handle to the newly allocated
5445 * \param isolate The isolate in which to create the context.
5447 * \param extensions An optional extension configuration containing
5448 * the extensions to be installed in the newly created context.
5450 * \param global_template An optional object template from which the
5451 * global object for the newly created context will be created.
5453 * \param global_object An optional global object to be reused for
5454 * the newly created context. This global object must have been
5455 * created by a previous call to Context::New with the same global
5456 * template. The state of the global object will be completely reset
5457 * and only object identify will remain.
5459 static Local<Context> New(
5461 ExtensionConfiguration* extensions = NULL,
5462 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5463 Handle<Value> global_object = Handle<Value>());
5466 * Sets the security token for the context. To access an object in
5467 * another context, the security tokens must match.
5469 void SetSecurityToken(Handle<Value> token);
5471 /** Restores the security token to the default value. */
5472 void UseDefaultSecurityToken();
5474 /** Returns the security token of this context.*/
5475 Handle<Value> GetSecurityToken();
5478 * Enter this context. After entering a context, all code compiled
5479 * and run is compiled and run in this context. If another context
5480 * is already entered, this old context is saved so it can be
5481 * restored when the new context is exited.
5486 * Exit this context. Exiting the current context restores the
5487 * context that was in place when entering the current context.
5491 /** Returns an isolate associated with a current context. */
5492 v8::Isolate* GetIsolate();
5495 * Gets the embedder data with the given index, which must have been set by a
5496 * previous call to SetEmbedderData with the same index. Note that index 0
5497 * currently has a special meaning for Chrome's debugger.
5499 V8_INLINE Local<Value> GetEmbedderData(int index);
5502 * Sets the embedder data with the given index, growing the data as
5503 * needed. Note that index 0 currently has a special meaning for Chrome's
5506 void SetEmbedderData(int index, Handle<Value> value);
5509 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5510 * index, which must have bees set by a previous call to
5511 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5512 * currently has a special meaning for Chrome's debugger.
5514 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5517 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5518 * index, growing the data as needed. Note that index 0 currently has a
5519 * special meaning for Chrome's debugger.
5521 void SetAlignedPointerInEmbedderData(int index, void* value);
5524 * Control whether code generation from strings is allowed. Calling
5525 * this method with false will disable 'eval' and the 'Function'
5526 * constructor for code running in this context. If 'eval' or the
5527 * 'Function' constructor are used an exception will be thrown.
5529 * If code generation from strings is not allowed the
5530 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5531 * set before blocking the call to 'eval' or the 'Function'
5532 * constructor. If that callback returns true, the call will be
5533 * allowed, otherwise an exception will be thrown. If no callback is
5534 * set an exception will be thrown.
5536 void AllowCodeGenerationFromStrings(bool allow);
5539 * Returns true if code generation from strings is allowed for the context.
5540 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5542 bool IsCodeGenerationFromStringsAllowed();
5545 * Sets the error description for the exception that is thrown when
5546 * code generation from strings is not allowed and 'eval' or the 'Function'
5547 * constructor are called.
5549 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5552 * Stack-allocated class which sets the execution context for all
5553 * operations executed within a local scope.
5557 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5560 V8_INLINE ~Scope() { context_->Exit(); }
5563 Handle<Context> context_;
5568 friend class Script;
5569 friend class Object;
5570 friend class Function;
5572 Local<Value> SlowGetEmbedderData(int index);
5573 void* SlowGetAlignedPointerFromEmbedderData(int index);
5578 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5579 * to use any given V8 isolate, see the comments in the Isolate class. The
5580 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5581 * object pointers obtained from V8 handles while in the particular V8 isolate.
5582 * It is up to the user of V8 to ensure, perhaps with locking, that this
5583 * constraint is not violated. In addition to any other synchronization
5584 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5585 * used to signal thead switches to V8.
5587 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5588 * construction and destruction, the current thread is allowed to use the locked
5589 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5590 * any time. In other words, the scope of a v8::Locker is a critical section.
5596 * v8::Locker locker(isolate);
5597 * v8::Isolate::Scope isolate_scope(isolate);
5599 * // Code using V8 and isolate goes here.
5601 * } // Destructor called here
5604 * If you wish to stop using V8 in a thread A you can do this either by
5605 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5611 * v8::Unlocker unlocker(isolate);
5613 * // Code not using V8 goes here while V8 can run in another thread.
5615 * } // Destructor called here.
5619 * The Unlocker object is intended for use in a long-running callback from V8,
5620 * where you want to release the V8 lock for other threads to use.
5622 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5623 * given thread. This can be useful if you have code that can be called either
5624 * from code that holds the lock or from code that does not. The Unlocker is
5625 * not recursive so you can not have several Unlockers on the stack at once, and
5626 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5628 * An unlocker will unlock several lockers if it has to and reinstate the
5629 * correct depth of locking on its destruction, e.g.:
5634 * v8::Locker locker(isolate);
5635 * Isolate::Scope isolate_scope(isolate);
5638 * v8::Locker another_locker(isolate);
5639 * // V8 still locked (2 levels).
5642 * v8::Unlocker unlocker(isolate);
5646 * // V8 locked again (2 levels).
5648 * // V8 still locked (1 level).
5650 * // V8 Now no longer locked.
5653 class V8_EXPORT Unlocker {
5656 * Initialize Unlocker for a given Isolate.
5658 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5662 void Initialize(Isolate* isolate);
5664 internal::Isolate* isolate_;
5668 class V8_EXPORT Locker {
5671 * Initialize Locker for a given Isolate.
5673 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5678 * Returns whether or not the locker for a given isolate, is locked by the
5681 static bool IsLocked(Isolate* isolate);
5684 * Returns whether v8::Locker is being used by this V8 instance.
5686 static bool IsActive();
5689 void Initialize(Isolate* isolate);
5693 internal::Isolate* isolate_;
5695 static bool active_;
5697 // Disallow copying and assigning.
5698 Locker(const Locker&);
5699 void operator=(const Locker&);
5703 // --- Implementation ---
5706 namespace internal {
5708 const int kApiPointerSize = sizeof(void*); // NOLINT
5709 const int kApiIntSize = sizeof(int); // NOLINT
5710 const int kApiInt64Size = sizeof(int64_t); // NOLINT
5712 // Tag information for HeapObject.
5713 const int kHeapObjectTag = 1;
5714 const int kHeapObjectTagSize = 2;
5715 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5717 // Tag information for Smi.
5718 const int kSmiTag = 0;
5719 const int kSmiTagSize = 1;
5720 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5722 template <size_t ptr_size> struct SmiTagging;
5724 template<int kSmiShiftSize>
5725 V8_INLINE internal::Object* IntToSmi(int value) {
5726 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5727 uintptr_t tagged_value =
5728 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
5729 return reinterpret_cast<internal::Object*>(tagged_value);
5732 // Smi constants for 32-bit systems.
5733 template <> struct SmiTagging<4> {
5734 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
5735 static int SmiShiftSize() { return kSmiShiftSize; }
5736 static int SmiValueSize() { return kSmiValueSize; }
5737 V8_INLINE static int SmiToInt(const internal::Object* value) {
5738 int shift_bits = kSmiTagSize + kSmiShiftSize;
5739 // Throw away top 32 bits and shift down (requires >> to be sign extending).
5740 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5742 V8_INLINE static internal::Object* IntToSmi(int value) {
5743 return internal::IntToSmi<kSmiShiftSize>(value);
5745 V8_INLINE static bool IsValidSmi(intptr_t value) {
5746 // To be representable as an tagged small integer, the two
5747 // most-significant bits of 'value' must be either 00 or 11 due to
5748 // sign-extension. To check this we add 01 to the two
5749 // most-significant bits, and check if the most-significant bit is 0
5751 // CAUTION: The original code below:
5752 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5753 // may lead to incorrect results according to the C language spec, and
5754 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5755 // compiler may produce undefined results in case of signed integer
5756 // overflow. The computation must be done w/ unsigned ints.
5757 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5761 // Smi constants for 64-bit systems.
5762 template <> struct SmiTagging<8> {
5763 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
5764 static int SmiShiftSize() { return kSmiShiftSize; }
5765 static int SmiValueSize() { return kSmiValueSize; }
5766 V8_INLINE static int SmiToInt(const internal::Object* value) {
5767 int shift_bits = kSmiTagSize + kSmiShiftSize;
5768 // Shift down and throw away top 32 bits.
5769 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5771 V8_INLINE static internal::Object* IntToSmi(int value) {
5772 return internal::IntToSmi<kSmiShiftSize>(value);
5774 V8_INLINE static bool IsValidSmi(intptr_t value) {
5775 // To be representable as a long smi, the value must be a 32-bit integer.
5776 return (value == static_cast<int32_t>(value));
5780 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5781 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5782 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5783 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5784 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5787 * This class exports constants and functionality from within v8 that
5788 * is necessary to implement inline functions in the v8 api. Don't
5789 * depend on functions and constants defined here.
5793 // These values match non-compiler-dependent values defined within
5794 // the implementation of v8.
5795 static const int kHeapObjectMapOffset = 0;
5796 static const int kMapInstanceTypeAndBitFieldOffset =
5797 1 * kApiPointerSize + kApiIntSize;
5798 static const int kStringResourceOffset = 3 * kApiPointerSize;
5800 static const int kOddballKindOffset = 3 * kApiPointerSize;
5801 static const int kForeignAddressOffset = kApiPointerSize;
5802 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5803 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5804 static const int kContextHeaderSize = 2 * kApiPointerSize;
5805 static const int kContextEmbedderDataIndex = 95;
5806 static const int kFullStringRepresentationMask = 0x07;
5807 static const int kStringEncodingMask = 0x4;
5808 static const int kExternalTwoByteRepresentationTag = 0x02;
5809 static const int kExternalOneByteRepresentationTag = 0x06;
5811 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
5812 static const int kAmountOfExternalAllocatedMemoryOffset =
5813 4 * kApiPointerSize;
5814 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
5815 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
5816 static const int kIsolateRootsOffset =
5817 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
5819 static const int kUndefinedValueRootIndex = 5;
5820 static const int kNullValueRootIndex = 7;
5821 static const int kTrueValueRootIndex = 8;
5822 static const int kFalseValueRootIndex = 9;
5823 static const int kEmptyStringRootIndex = 164;
5825 // The external allocation limit should be below 256 MB on all architectures
5826 // to avoid that resource-constrained embedders run low on memory.
5827 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
5829 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5830 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5831 static const int kNodeStateMask = 0xf;
5832 static const int kNodeStateIsWeakValue = 2;
5833 static const int kNodeStateIsPendingValue = 3;
5834 static const int kNodeStateIsNearDeathValue = 4;
5835 static const int kNodeIsIndependentShift = 4;
5836 static const int kNodeIsPartiallyDependentShift = 5;
5838 static const int kJSObjectType = 0xbc;
5839 static const int kFirstNonstringType = 0x80;
5840 static const int kOddballType = 0x83;
5841 static const int kForeignType = 0x88;
5843 static const int kUndefinedOddballKind = 5;
5844 static const int kNullOddballKind = 3;
5846 static const uint32_t kNumIsolateDataSlots = 4;
5848 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5849 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5850 #ifdef V8_ENABLE_CHECKS
5851 CheckInitializedImpl(isolate);
5855 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
5856 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5860 V8_INLINE static int SmiValue(const internal::Object* value) {
5861 return PlatformSmiTagging::SmiToInt(value);
5864 V8_INLINE static internal::Object* IntToSmi(int value) {
5865 return PlatformSmiTagging::IntToSmi(value);
5868 V8_INLINE static bool IsValidSmi(intptr_t value) {
5869 return PlatformSmiTagging::IsValidSmi(value);
5872 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
5873 typedef internal::Object O;
5874 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5875 // Map::InstanceType is defined so that it will always be loaded into
5876 // the LS 8 bits of one 16-bit word, regardless of endianess.
5877 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
5880 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
5881 typedef internal::Object O;
5882 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5885 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5886 int representation = (instance_type & kFullStringRepresentationMask);
5887 return representation == kExternalTwoByteRepresentationTag;
5890 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5891 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5892 return *addr & static_cast<uint8_t>(1U << shift);
5895 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5896 bool value, int shift) {
5897 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5898 uint8_t mask = static_cast<uint8_t>(1U << shift);
5899 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5902 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5903 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5904 return *addr & kNodeStateMask;
5907 V8_INLINE static void UpdateNodeState(internal::Object** obj,
5909 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5910 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5913 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
5916 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
5917 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5918 *reinterpret_cast<void**>(addr) = data;
5921 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
5923 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
5924 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5925 return *reinterpret_cast<void* const*>(addr);
5928 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5930 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5931 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5934 template <typename T>
5935 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
5936 const uint8_t* addr =
5937 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
5938 return *reinterpret_cast<const T*>(addr);
5941 template <typename T>
5942 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
5943 typedef internal::Object O;
5944 typedef internal::Internals I;
5945 O* ctx = *reinterpret_cast<O* const*>(context);
5946 int embedder_data_offset = I::kContextHeaderSize +
5947 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5948 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5950 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5951 return I::ReadField<T>(embedder_data, value_offset);
5955 } // namespace internal
5959 Local<T>::Local() : Handle<T>() { }
5963 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5964 return New(isolate, that.val_);
5968 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
5969 return New(isolate, that.val_);
5973 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5974 if (that == NULL) return Handle<T>();
5976 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5977 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5978 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5983 Local<T> Local<T>::New(Isolate* isolate, T* that) {
5984 if (that == NULL) return Local<T>();
5986 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5987 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5988 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5994 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5996 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
6001 Local<T> Eternal<T>::Get(Isolate* isolate) {
6002 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
6007 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
6008 if (that == NULL) return NULL;
6009 internal::Object** p = reinterpret_cast<internal::Object**>(that);
6010 return reinterpret_cast<T*>(
6011 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
6016 template <class T, class M>
6017 template <class S, class M2>
6018 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
6021 if (that.IsEmpty()) return;
6022 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
6023 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
6024 M::Copy(that, this);
6029 bool PersistentBase<T>::IsIndependent() const {
6030 typedef internal::Internals I;
6031 if (this->IsEmpty()) return false;
6032 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6033 I::kNodeIsIndependentShift);
6038 bool PersistentBase<T>::IsNearDeath() const {
6039 typedef internal::Internals I;
6040 if (this->IsEmpty()) return false;
6041 uint8_t node_state =
6042 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
6043 return node_state == I::kNodeStateIsNearDeathValue ||
6044 node_state == I::kNodeStateIsPendingValue;
6049 bool PersistentBase<T>::IsWeak() const {
6050 typedef internal::Internals I;
6051 if (this->IsEmpty()) return false;
6052 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
6053 I::kNodeStateIsWeakValue;
6058 void PersistentBase<T>::Reset() {
6059 if (this->IsEmpty()) return;
6060 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
6067 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
6070 if (other.IsEmpty()) return;
6071 this->val_ = New(isolate, other.val_);
6077 void PersistentBase<T>::Reset(Isolate* isolate,
6078 const PersistentBase<S>& other) {
6081 if (other.IsEmpty()) return;
6082 this->val_ = New(isolate, other.val_);
6087 template <typename S, typename P>
6088 void PersistentBase<T>::SetWeak(
6090 typename WeakCallbackData<S, P>::Callback callback) {
6092 typedef typename WeakCallbackData<Value, void>::Callback Callback;
6093 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
6095 reinterpret_cast<Callback>(callback));
6100 template <typename P>
6101 void PersistentBase<T>::SetWeak(
6103 typename WeakCallbackData<T, P>::Callback callback) {
6104 SetWeak<T, P>(parameter, callback);
6109 template<typename P>
6110 P* PersistentBase<T>::ClearWeak() {
6111 return reinterpret_cast<P*>(
6112 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
6117 void PersistentBase<T>::MarkIndependent() {
6118 typedef internal::Internals I;
6119 if (this->IsEmpty()) return;
6120 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6122 I::kNodeIsIndependentShift);
6127 void PersistentBase<T>::MarkPartiallyDependent() {
6128 typedef internal::Internals I;
6129 if (this->IsEmpty()) return;
6130 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6132 I::kNodeIsPartiallyDependentShift);
6136 template <class T, class M>
6137 T* Persistent<T, M>::ClearAndLeak() {
6146 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
6147 typedef internal::Internals I;
6148 if (this->IsEmpty()) return;
6149 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6150 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6151 *reinterpret_cast<uint16_t*>(addr) = class_id;
6156 uint16_t PersistentBase<T>::WrapperClassId() const {
6157 typedef internal::Internals I;
6158 if (this->IsEmpty()) return 0;
6159 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6160 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6161 return *reinterpret_cast<uint16_t*>(addr);
6165 template<typename T>
6166 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
6168 template<typename T>
6169 template<typename S>
6170 void ReturnValue<T>::Set(const Persistent<S>& handle) {
6172 if (V8_UNLIKELY(handle.IsEmpty())) {
6173 *value_ = GetDefaultValue();
6175 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6179 template<typename T>
6180 template<typename S>
6181 void ReturnValue<T>::Set(const Handle<S> handle) {
6183 if (V8_UNLIKELY(handle.IsEmpty())) {
6184 *value_ = GetDefaultValue();
6186 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6190 template<typename T>
6191 void ReturnValue<T>::Set(double i) {
6192 TYPE_CHECK(T, Number);
6193 Set(Number::New(GetIsolate(), i));
6196 template<typename T>
6197 void ReturnValue<T>::Set(int32_t i) {
6198 TYPE_CHECK(T, Integer);
6199 typedef internal::Internals I;
6200 if (V8_LIKELY(I::IsValidSmi(i))) {
6201 *value_ = I::IntToSmi(i);
6204 Set(Integer::New(GetIsolate(), i));
6207 template<typename T>
6208 void ReturnValue<T>::Set(uint32_t i) {
6209 TYPE_CHECK(T, Integer);
6210 // Can't simply use INT32_MAX here for whatever reason.
6211 bool fits_into_int32_t = (i & (1U << 31)) == 0;
6212 if (V8_LIKELY(fits_into_int32_t)) {
6213 Set(static_cast<int32_t>(i));
6216 Set(Integer::NewFromUnsigned(GetIsolate(), i));
6219 template<typename T>
6220 void ReturnValue<T>::Set(bool value) {
6221 TYPE_CHECK(T, Boolean);
6222 typedef internal::Internals I;
6225 root_index = I::kTrueValueRootIndex;
6227 root_index = I::kFalseValueRootIndex;
6229 *value_ = *I::GetRoot(GetIsolate(), root_index);
6232 template<typename T>
6233 void ReturnValue<T>::SetNull() {
6234 TYPE_CHECK(T, Primitive);
6235 typedef internal::Internals I;
6236 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6239 template<typename T>
6240 void ReturnValue<T>::SetUndefined() {
6241 TYPE_CHECK(T, Primitive);
6242 typedef internal::Internals I;
6243 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6246 template<typename T>
6247 void ReturnValue<T>::SetEmptyString() {
6248 TYPE_CHECK(T, String);
6249 typedef internal::Internals I;
6250 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6253 template<typename T>
6254 Isolate* ReturnValue<T>::GetIsolate() {
6255 // Isolate is always the pointer below the default value on the stack.
6256 return *reinterpret_cast<Isolate**>(&value_[-2]);
6259 template<typename T>
6260 template<typename S>
6261 void ReturnValue<T>::Set(S* whatever) {
6262 // Uncompilable to prevent inadvertent misuse.
6263 TYPE_CHECK(S*, Primitive);
6266 template<typename T>
6267 internal::Object* ReturnValue<T>::GetDefaultValue() {
6268 // Default value is always the pointer below value_ on the stack.
6273 template<typename T>
6274 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6275 internal::Object** values,
6277 bool is_construct_call)
6278 : implicit_args_(implicit_args),
6281 is_construct_call_(is_construct_call) { }
6284 template<typename T>
6285 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6286 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6287 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6291 template<typename T>
6292 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6293 return Local<Function>(reinterpret_cast<Function*>(
6294 &implicit_args_[kCalleeIndex]));
6298 template<typename T>
6299 Local<Object> FunctionCallbackInfo<T>::This() const {
6300 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6304 template<typename T>
6305 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6306 return Local<Object>(reinterpret_cast<Object*>(
6307 &implicit_args_[kHolderIndex]));
6311 template<typename T>
6312 Local<Value> FunctionCallbackInfo<T>::Data() const {
6313 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6317 template<typename T>
6318 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6319 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6323 template<typename T>
6324 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6325 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6329 template<typename T>
6330 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6331 return is_construct_call_;
6335 template<typename T>
6336 int FunctionCallbackInfo<T>::Length() const {
6341 Handle<Value> ScriptOrigin::ResourceName() const {
6342 return resource_name_;
6346 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6347 return resource_line_offset_;
6351 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6352 return resource_column_offset_;
6356 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6357 return resource_is_shared_cross_origin_;
6361 Handle<Integer> ScriptOrigin::ScriptID() const {
6366 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6368 : source_string(string),
6369 resource_name(origin.ResourceName()),
6370 resource_line_offset(origin.ResourceLineOffset()),
6371 resource_column_offset(origin.ResourceColumnOffset()),
6372 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6373 cached_data(data) {}
6376 ScriptCompiler::Source::Source(Local<String> string,
6378 : source_string(string), cached_data(data) {}
6381 ScriptCompiler::Source::~Source() {
6386 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6392 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6393 return value ? True(isolate) : False(isolate);
6397 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6398 Set(v8::String::NewFromUtf8(isolate, name), value);
6402 Local<Value> Object::GetInternalField(int index) {
6403 #ifndef V8_ENABLE_CHECKS
6404 typedef internal::Object O;
6405 typedef internal::HeapObject HO;
6406 typedef internal::Internals I;
6407 O* obj = *reinterpret_cast<O**>(this);
6408 // Fast path: If the object is a plain JSObject, which is the common case, we
6409 // know where to find the internal fields and can return the value directly.
6410 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6411 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6412 O* value = I::ReadField<O*>(obj, offset);
6413 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6414 return Local<Value>(reinterpret_cast<Value*>(result));
6417 return SlowGetInternalField(index);
6421 void* Object::GetAlignedPointerFromInternalField(int index) {
6422 #ifndef V8_ENABLE_CHECKS
6423 typedef internal::Object O;
6424 typedef internal::Internals I;
6425 O* obj = *reinterpret_cast<O**>(this);
6426 // Fast path: If the object is a plain JSObject, which is the common case, we
6427 // know where to find the internal fields and can return the value directly.
6428 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6429 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6430 return I::ReadField<void*>(obj, offset);
6433 return SlowGetAlignedPointerFromInternalField(index);
6437 String* String::Cast(v8::Value* value) {
6438 #ifdef V8_ENABLE_CHECKS
6441 return static_cast<String*>(value);
6445 Local<String> String::Empty(Isolate* isolate) {
6446 typedef internal::Object* S;
6447 typedef internal::Internals I;
6448 I::CheckInitialized(isolate);
6449 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6450 return Local<String>(reinterpret_cast<String*>(slot));
6454 String::ExternalStringResource* String::GetExternalStringResource() const {
6455 typedef internal::Object O;
6456 typedef internal::Internals I;
6457 O* obj = *reinterpret_cast<O* const*>(this);
6458 String::ExternalStringResource* result;
6459 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6460 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6461 result = reinterpret_cast<String::ExternalStringResource*>(value);
6465 #ifdef V8_ENABLE_CHECKS
6466 VerifyExternalStringResource(result);
6472 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6473 String::Encoding* encoding_out) const {
6474 typedef internal::Object O;
6475 typedef internal::Internals I;
6476 O* obj = *reinterpret_cast<O* const*>(this);
6477 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6478 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6479 ExternalStringResourceBase* resource = NULL;
6480 if (type == I::kExternalOneByteRepresentationTag ||
6481 type == I::kExternalTwoByteRepresentationTag) {
6482 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6483 resource = static_cast<ExternalStringResourceBase*>(value);
6485 #ifdef V8_ENABLE_CHECKS
6486 VerifyExternalStringResourceBase(resource, *encoding_out);
6492 bool Value::IsUndefined() const {
6493 #ifdef V8_ENABLE_CHECKS
6494 return FullIsUndefined();
6496 return QuickIsUndefined();
6500 bool Value::QuickIsUndefined() const {
6501 typedef internal::Object O;
6502 typedef internal::Internals I;
6503 O* obj = *reinterpret_cast<O* const*>(this);
6504 if (!I::HasHeapObjectTag(obj)) return false;
6505 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6506 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6510 bool Value::IsNull() const {
6511 #ifdef V8_ENABLE_CHECKS
6512 return FullIsNull();
6514 return QuickIsNull();
6518 bool Value::QuickIsNull() const {
6519 typedef internal::Object O;
6520 typedef internal::Internals I;
6521 O* obj = *reinterpret_cast<O* const*>(this);
6522 if (!I::HasHeapObjectTag(obj)) return false;
6523 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6524 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6528 bool Value::IsString() const {
6529 #ifdef V8_ENABLE_CHECKS
6530 return FullIsString();
6532 return QuickIsString();
6536 bool Value::QuickIsString() const {
6537 typedef internal::Object O;
6538 typedef internal::Internals I;
6539 O* obj = *reinterpret_cast<O* const*>(this);
6540 if (!I::HasHeapObjectTag(obj)) return false;
6541 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6545 template <class T> Value* Value::Cast(T* value) {
6546 return static_cast<Value*>(value);
6550 Name* Name::Cast(v8::Value* value) {
6551 #ifdef V8_ENABLE_CHECKS
6554 return static_cast<Name*>(value);
6558 Symbol* Symbol::Cast(v8::Value* value) {
6559 #ifdef V8_ENABLE_CHECKS
6562 return static_cast<Symbol*>(value);
6566 Number* Number::Cast(v8::Value* value) {
6567 #ifdef V8_ENABLE_CHECKS
6570 return static_cast<Number*>(value);
6574 Integer* Integer::Cast(v8::Value* value) {
6575 #ifdef V8_ENABLE_CHECKS
6578 return static_cast<Integer*>(value);
6582 Date* Date::Cast(v8::Value* value) {
6583 #ifdef V8_ENABLE_CHECKS
6586 return static_cast<Date*>(value);
6590 StringObject* StringObject::Cast(v8::Value* value) {
6591 #ifdef V8_ENABLE_CHECKS
6594 return static_cast<StringObject*>(value);
6598 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6599 #ifdef V8_ENABLE_CHECKS
6602 return static_cast<SymbolObject*>(value);
6606 NumberObject* NumberObject::Cast(v8::Value* value) {
6607 #ifdef V8_ENABLE_CHECKS
6610 return static_cast<NumberObject*>(value);
6614 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6615 #ifdef V8_ENABLE_CHECKS
6618 return static_cast<BooleanObject*>(value);
6622 RegExp* RegExp::Cast(v8::Value* value) {
6623 #ifdef V8_ENABLE_CHECKS
6626 return static_cast<RegExp*>(value);
6630 Object* Object::Cast(v8::Value* value) {
6631 #ifdef V8_ENABLE_CHECKS
6634 return static_cast<Object*>(value);
6638 Array* Array::Cast(v8::Value* value) {
6639 #ifdef V8_ENABLE_CHECKS
6642 return static_cast<Array*>(value);
6646 Promise* Promise::Cast(v8::Value* value) {
6647 #ifdef V8_ENABLE_CHECKS
6650 return static_cast<Promise*>(value);
6654 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6655 #ifdef V8_ENABLE_CHECKS
6658 return static_cast<Promise::Resolver*>(value);
6662 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6663 #ifdef V8_ENABLE_CHECKS
6666 return static_cast<ArrayBuffer*>(value);
6670 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6671 #ifdef V8_ENABLE_CHECKS
6674 return static_cast<ArrayBufferView*>(value);
6678 TypedArray* TypedArray::Cast(v8::Value* value) {
6679 #ifdef V8_ENABLE_CHECKS
6682 return static_cast<TypedArray*>(value);
6686 Uint8Array* Uint8Array::Cast(v8::Value* value) {
6687 #ifdef V8_ENABLE_CHECKS
6690 return static_cast<Uint8Array*>(value);
6694 Int8Array* Int8Array::Cast(v8::Value* value) {
6695 #ifdef V8_ENABLE_CHECKS
6698 return static_cast<Int8Array*>(value);
6702 Uint16Array* Uint16Array::Cast(v8::Value* value) {
6703 #ifdef V8_ENABLE_CHECKS
6706 return static_cast<Uint16Array*>(value);
6710 Int16Array* Int16Array::Cast(v8::Value* value) {
6711 #ifdef V8_ENABLE_CHECKS
6714 return static_cast<Int16Array*>(value);
6718 Uint32Array* Uint32Array::Cast(v8::Value* value) {
6719 #ifdef V8_ENABLE_CHECKS
6722 return static_cast<Uint32Array*>(value);
6726 Int32Array* Int32Array::Cast(v8::Value* value) {
6727 #ifdef V8_ENABLE_CHECKS
6730 return static_cast<Int32Array*>(value);
6734 Float32Array* Float32Array::Cast(v8::Value* value) {
6735 #ifdef V8_ENABLE_CHECKS
6738 return static_cast<Float32Array*>(value);
6742 Float64Array* Float64Array::Cast(v8::Value* value) {
6743 #ifdef V8_ENABLE_CHECKS
6746 return static_cast<Float64Array*>(value);
6750 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6751 #ifdef V8_ENABLE_CHECKS
6754 return static_cast<Uint8ClampedArray*>(value);
6758 DataView* DataView::Cast(v8::Value* value) {
6759 #ifdef V8_ENABLE_CHECKS
6762 return static_cast<DataView*>(value);
6766 Function* Function::Cast(v8::Value* value) {
6767 #ifdef V8_ENABLE_CHECKS
6770 return static_cast<Function*>(value);
6774 External* External::Cast(v8::Value* value) {
6775 #ifdef V8_ENABLE_CHECKS
6778 return static_cast<External*>(value);
6782 template<typename T>
6783 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6784 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6788 template<typename T>
6789 Local<Value> PropertyCallbackInfo<T>::Data() const {
6790 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6794 template<typename T>
6795 Local<Object> PropertyCallbackInfo<T>::This() const {
6796 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
6800 template<typename T>
6801 Local<Object> PropertyCallbackInfo<T>::Holder() const {
6802 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6806 template<typename T>
6807 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6808 return ReturnValue<T>(&args_[kReturnValueIndex]);
6812 Handle<Primitive> Undefined(Isolate* isolate) {
6813 typedef internal::Object* S;
6814 typedef internal::Internals I;
6815 I::CheckInitialized(isolate);
6816 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6817 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6821 Handle<Primitive> Null(Isolate* isolate) {
6822 typedef internal::Object* S;
6823 typedef internal::Internals I;
6824 I::CheckInitialized(isolate);
6825 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6826 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6830 Handle<Boolean> True(Isolate* isolate) {
6831 typedef internal::Object* S;
6832 typedef internal::Internals I;
6833 I::CheckInitialized(isolate);
6834 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6835 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6839 Handle<Boolean> False(Isolate* isolate) {
6840 typedef internal::Object* S;
6841 typedef internal::Internals I;
6842 I::CheckInitialized(isolate);
6843 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6844 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6848 void Isolate::SetData(uint32_t slot, void* data) {
6849 typedef internal::Internals I;
6850 I::SetEmbedderData(this, slot, data);
6854 void* Isolate::GetData(uint32_t slot) {
6855 typedef internal::Internals I;
6856 return I::GetEmbedderData(this, slot);
6860 uint32_t Isolate::GetNumberOfDataSlots() {
6861 typedef internal::Internals I;
6862 return I::kNumIsolateDataSlots;
6866 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
6867 int64_t change_in_bytes) {
6868 typedef internal::Internals I;
6869 int64_t* amount_of_external_allocated_memory =
6870 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
6871 I::kAmountOfExternalAllocatedMemoryOffset);
6872 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
6873 reinterpret_cast<int64_t*>(
6874 reinterpret_cast<uint8_t*>(this) +
6875 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
6876 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
6877 if (change_in_bytes > 0 &&
6878 amount - *amount_of_external_allocated_memory_at_last_global_gc >
6879 I::kExternalAllocationLimit) {
6880 CollectAllGarbage("external memory allocation limit reached.");
6882 *amount_of_external_allocated_memory = amount;
6884 return *amount_of_external_allocated_memory;
6888 template<typename T>
6889 void Isolate::SetObjectGroupId(const Persistent<T>& object,
6891 TYPE_CHECK(Value, T);
6892 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6896 template<typename T>
6897 void Isolate::SetReferenceFromGroup(UniqueId id,
6898 const Persistent<T>& object) {
6899 TYPE_CHECK(Value, T);
6900 SetReferenceFromGroup(id,
6901 reinterpret_cast<v8::internal::Object**>(object.val_));
6905 template<typename T, typename S>
6906 void Isolate::SetReference(const Persistent<T>& parent,
6907 const Persistent<S>& child) {
6908 TYPE_CHECK(Object, T);
6909 TYPE_CHECK(Value, S);
6910 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6911 reinterpret_cast<v8::internal::Object**>(child.val_));
6915 Local<Value> Context::GetEmbedderData(int index) {
6916 #ifndef V8_ENABLE_CHECKS
6917 typedef internal::Object O;
6918 typedef internal::HeapObject HO;
6919 typedef internal::Internals I;
6920 HO* context = *reinterpret_cast<HO**>(this);
6922 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6923 return Local<Value>(reinterpret_cast<Value*>(result));
6925 return SlowGetEmbedderData(index);
6930 void* Context::GetAlignedPointerFromEmbedderData(int index) {
6931 #ifndef V8_ENABLE_CHECKS
6932 typedef internal::Internals I;
6933 return I::ReadEmbedderData<void*>(this, index);
6935 return SlowGetAlignedPointerFromEmbedderData(index);
6942 * A simple shell that takes a list of expressions on the
6943 * command-line and executes them.
6948 * \example process.cc