1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /** \mainpage V8 API Reference Guide
7 * V8 is Google's open source JavaScript engine.
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
12 * For other documentation see http://code.google.com/apis/v8/
20 // We reserve the V8_* prefix for macros defined in V8 public API and
21 // assume there are no name conflicts with the embedder's code.
25 // Setup for Windows DLL export/import. When building the V8 DLL the
26 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
27 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
28 // static library or building a program which uses the V8 static library neither
29 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
30 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
31 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
32 build configuration to ensure that at most one of these is set
35 #ifdef BUILDING_V8_SHARED
36 # define V8_EXPORT __declspec(dllexport)
38 # define V8_EXPORT __declspec(dllimport)
41 #endif // BUILDING_V8_SHARED
45 // Setup for Linux shared library export.
46 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
47 # ifdef BUILDING_V8_SHARED
48 # define V8_EXPORT __attribute__ ((visibility("default")))
59 * The v8 JavaScript engine.
63 class AccessorSignature;
71 class DeclaredAccessorDescriptor;
74 class FunctionTemplate;
76 class ImplementationUtilities;
83 class ObjectOperationDescriptor;
87 class RawOperationDescriptor;
100 template <class T> class Handle;
101 template <class T> class Local;
102 template <class T> class Eternal;
103 template<class T> class NonCopyablePersistentTraits;
104 template<class T> class PersistentBase;
106 class M = NonCopyablePersistentTraits<T> > class Persistent;
107 template<class T> class UniquePersistent;
108 template<class K, class V, class T> class PersistentValueMap;
109 template<class V, class T> class PersistentValueVector;
110 template<class T, class P> class WeakCallbackObject;
111 class FunctionTemplate;
112 class ObjectTemplate;
114 template<typename T> class FunctionCallbackInfo;
115 template<typename T> class PropertyCallbackInfo;
119 class DeclaredAccessorDescriptor;
120 class ObjectOperationDescriptor;
121 class RawOperationDescriptor;
122 class CallHandlerHelper;
123 class EscapableHandleScope;
124 template<typename T> class ReturnValue;
132 template<typename T> class CustomArguments;
133 class PropertyCallbackArguments;
134 class FunctionCallbackArguments;
140 * General purpose unique identifier.
144 explicit UniqueId(intptr_t data)
147 bool operator==(const UniqueId& other) const {
148 return data_ == other.data_;
151 bool operator!=(const UniqueId& other) const {
152 return data_ != other.data_;
155 bool operator<(const UniqueId& other) const {
156 return data_ < other.data_;
165 #define TYPE_CHECK(T, S) \
167 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
172 * An object reference managed by the v8 garbage collector.
174 * All objects returned from v8 have to be tracked by the garbage
175 * collector so that it knows that the objects are still alive. Also,
176 * because the garbage collector may move objects, it is unsafe to
177 * point directly to an object. Instead, all objects are stored in
178 * handles which are known by the garbage collector and updated
179 * whenever an object moves. Handles should always be passed by value
180 * (except in cases like out-parameters) and they should never be
181 * allocated on the heap.
183 * There are two types of handles: local and persistent handles.
184 * Local handles are light-weight and transient and typically used in
185 * local operations. They are managed by HandleScopes. Persistent
186 * handles can be used when storing objects across several independent
187 * operations and have to be explicitly deallocated when they're no
190 * It is safe to extract the object stored in the handle by
191 * dereferencing the handle (for instance, to extract the Object* from
192 * a Handle<Object>); the value will still be governed by a handle
193 * behind the scenes and the same rules apply to these values as to
196 template <class T> class Handle {
199 * Creates an empty handle.
201 V8_INLINE Handle() : val_(0) {}
204 * Creates a handle for the contents of the specified handle. This
205 * constructor allows you to pass handles as arguments by value and
206 * to assign between handles. However, if you try to assign between
207 * incompatible handles, for instance from a Handle<String> to a
208 * Handle<Number> it will cause a compile-time error. Assigning
209 * between compatible handles, for instance assigning a
210 * Handle<String> to a variable declared as Handle<Value>, is legal
211 * because String is a subclass of Value.
213 template <class S> V8_INLINE Handle(Handle<S> that)
214 : val_(reinterpret_cast<T*>(*that)) {
216 * This check fails when trying to convert between incompatible
217 * handles. For example, converting from a Handle<String> to a
224 * Returns true if the handle is empty.
226 V8_INLINE bool IsEmpty() const { return val_ == 0; }
229 * Sets the handle to be empty. IsEmpty() will then return true.
231 V8_INLINE void Clear() { val_ = 0; }
233 V8_INLINE T* operator->() const { return val_; }
235 V8_INLINE T* operator*() const { return val_; }
238 * Checks whether two handles are the same.
239 * Returns true if both are empty, or if the objects
240 * to which they refer are identical.
241 * The handles' references are not checked.
243 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
244 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
245 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
246 if (a == 0) return b == 0;
247 if (b == 0) return false;
251 template <class S> V8_INLINE bool operator==(
252 const PersistentBase<S>& that) const {
253 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
254 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
255 if (a == 0) return b == 0;
256 if (b == 0) return false;
261 * Checks whether two handles are different.
262 * Returns true if only one of the handles is empty, or if
263 * the objects to which they refer are different.
264 * The handles' references are not checked.
266 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
267 return !operator==(that);
270 template <class S> V8_INLINE bool operator!=(
271 const Persistent<S>& that) const {
272 return !operator==(that);
275 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
276 #ifdef V8_ENABLE_CHECKS
277 // If we're going to perform the type check then we have to check
278 // that the handle isn't empty before doing the checked cast.
279 if (that.IsEmpty()) return Handle<T>();
281 return Handle<T>(T::Cast(*that));
284 template <class S> V8_INLINE Handle<S> As() {
285 return Handle<S>::Cast(*this);
288 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
289 return New(isolate, that.val_);
291 V8_INLINE static Handle<T> New(Isolate* isolate,
292 const PersistentBase<T>& that) {
293 return New(isolate, that.val_);
298 template<class F, class M> friend class Persistent;
299 template<class F> friend class PersistentBase;
300 template<class F> friend class Handle;
301 template<class F> friend class Local;
302 template<class F> friend class FunctionCallbackInfo;
303 template<class F> friend class PropertyCallbackInfo;
304 template<class F> friend class internal::CustomArguments;
305 friend Handle<Primitive> Undefined(Isolate* isolate);
306 friend Handle<Primitive> Null(Isolate* isolate);
307 friend Handle<Boolean> True(Isolate* isolate);
308 friend Handle<Boolean> False(Isolate* isolate);
309 friend class Context;
310 friend class HandleScope;
312 friend class Private;
315 * Creates a new handle for the specified value.
317 V8_INLINE explicit Handle(T* val) : val_(val) {}
319 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
326 * A light-weight stack-allocated object handle. All operations
327 * that return objects from within v8 return them in local handles. They
328 * are created within HandleScopes, and all local handles allocated within a
329 * handle scope are destroyed when the handle scope is destroyed. Hence it
330 * is not necessary to explicitly deallocate local handles.
332 template <class T> class Local : public Handle<T> {
335 template <class S> V8_INLINE Local(Local<S> that)
336 : Handle<T>(reinterpret_cast<T*>(*that)) {
338 * This check fails when trying to convert between incompatible
339 * handles. For example, converting from a Handle<String> to a
346 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
347 #ifdef V8_ENABLE_CHECKS
348 // If we're going to perform the type check then we have to check
349 // that the handle isn't empty before doing the checked cast.
350 if (that.IsEmpty()) return Local<T>();
352 return Local<T>(T::Cast(*that));
354 template <class S> V8_INLINE Local(Handle<S> that)
355 : Handle<T>(reinterpret_cast<T*>(*that)) {
359 template <class S> V8_INLINE Local<S> As() {
360 return Local<S>::Cast(*this);
364 * Create a local handle for the content of another handle.
365 * The referee is kept alive by the local handle even when
366 * the original handle is destroyed/disposed.
368 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
369 V8_INLINE static Local<T> New(Isolate* isolate,
370 const PersistentBase<T>& that);
374 template<class F> friend class Eternal;
375 template<class F> friend class PersistentBase;
376 template<class F, class M> friend class Persistent;
377 template<class F> friend class Handle;
378 template<class F> friend class Local;
379 template<class F> friend class FunctionCallbackInfo;
380 template<class F> friend class PropertyCallbackInfo;
383 friend class Context;
384 template<class F> friend class internal::CustomArguments;
385 friend class HandleScope;
386 friend class EscapableHandleScope;
387 template<class F1, class F2, class F3> friend class PersistentValueMap;
388 template<class F1, class F2> friend class PersistentValueVector;
390 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
391 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
395 // Eternal handles are set-once handles that live for the life of the isolate.
396 template <class T> class Eternal {
398 V8_INLINE Eternal() : index_(kInitialValue) { }
400 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
401 Set(isolate, handle);
403 // Can only be safely called if already set.
404 V8_INLINE Local<T> Get(Isolate* isolate);
405 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
406 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
409 static const int kInitialValue = -1;
414 template<class T, class P>
415 class WeakCallbackData {
417 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
419 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
420 V8_INLINE Local<T> GetValue() const { return handle_; }
421 V8_INLINE P* GetParameter() const { return parameter_; }
424 friend class internal::GlobalHandles;
425 WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
426 : isolate_(isolate), handle_(handle), parameter_(parameter) { }
434 * An object reference that is independent of any handle scope. Where
435 * a Local handle only lives as long as the HandleScope in which it was
436 * allocated, a PersistentBase handle remains valid until it is explicitly
439 * A persistent handle contains a reference to a storage cell within
440 * the v8 engine which holds an object value and which is updated by
441 * the garbage collector whenever the object is moved. A new storage
442 * cell can be created using the constructor or PersistentBase::Reset and
443 * existing handles can be disposed using PersistentBase::Reset.
446 template <class T> class PersistentBase {
449 * If non-empty, destroy the underlying storage cell
450 * IsEmpty() will return true after this call.
452 V8_INLINE void Reset();
454 * If non-empty, destroy the underlying storage cell
455 * and create a new one with the contents of other if other is non empty
458 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
461 * If non-empty, destroy the underlying storage cell
462 * and create a new one with the contents of other if other is non empty
465 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
467 V8_INLINE bool IsEmpty() const { return val_ == 0; }
470 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
471 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
472 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
473 if (a == 0) return b == 0;
474 if (b == 0) return false;
478 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
479 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
480 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
481 if (a == 0) return b == 0;
482 if (b == 0) return false;
487 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
488 return !operator==(that);
491 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
492 return !operator==(that);
496 * Install a finalization callback on this object.
497 * NOTE: There is no guarantee as to *when* or even *if* the callback is
498 * invoked. The invocation is performed solely on a best effort basis.
499 * As always, GC-based finalization should *not* be relied upon for any
500 * critical form of resource management!
503 V8_INLINE void SetWeak(
505 typename WeakCallbackData<T, P>::Callback callback);
507 template<typename S, typename P>
508 V8_INLINE void SetWeak(
510 typename WeakCallbackData<S, P>::Callback callback);
513 V8_INLINE P* ClearWeak();
515 // TODO(dcarney): remove this.
516 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
519 * Marks the reference to this object independent. Garbage collector is free
520 * to ignore any object groups containing this object. Weak callback for an
521 * independent handle should not assume that it will be preceded by a global
522 * GC prologue callback or followed by a global GC epilogue callback.
524 V8_INLINE void MarkIndependent();
527 * Marks the reference to this object partially dependent. Partially dependent
528 * handles only depend on other partially dependent handles and these
529 * dependencies are provided through object groups. It provides a way to build
530 * smaller object groups for young objects that represent only a subset of all
531 * external dependencies. This mark is automatically cleared after each
532 * garbage collection.
534 V8_INLINE void MarkPartiallyDependent();
536 V8_INLINE bool IsIndependent() const;
538 /** Checks if the handle holds the only reference to an object. */
539 V8_INLINE bool IsNearDeath() const;
541 /** Returns true if the handle's reference is weak. */
542 V8_INLINE bool IsWeak() const;
545 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
546 * description in v8-profiler.h for details.
548 V8_INLINE void SetWrapperClassId(uint16_t class_id);
551 * Returns the class ID previously assigned to this handle or 0 if no class ID
552 * was previously assigned.
554 V8_INLINE uint16_t WrapperClassId() const;
557 friend class Isolate;
559 template<class F> friend class Handle;
560 template<class F> friend class Local;
561 template<class F1, class F2> friend class Persistent;
562 template<class F> friend class UniquePersistent;
563 template<class F> friend class PersistentBase;
564 template<class F> friend class ReturnValue;
565 template<class F1, class F2, class F3> friend class PersistentValueMap;
566 template<class F1, class F2> friend class PersistentValueVector;
569 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
570 PersistentBase(PersistentBase& other); // NOLINT
571 void operator=(PersistentBase&);
572 V8_INLINE static T* New(Isolate* isolate, T* that);
579 * Default traits for Persistent. This class does not allow
580 * use of the copy constructor or assignment operator.
581 * At present kResetInDestructor is not set, but that will change in a future
585 class NonCopyablePersistentTraits {
587 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
588 static const bool kResetInDestructor = false;
589 template<class S, class M>
590 V8_INLINE static void Copy(const Persistent<S, M>& source,
591 NonCopyablePersistent* dest) {
592 Uncompilable<Object>();
594 // TODO(dcarney): come up with a good compile error here.
595 template<class O> V8_INLINE static void Uncompilable() {
596 TYPE_CHECK(O, Primitive);
602 * Helper class traits to allow copying and assignment of Persistent.
603 * This will clone the contents of storage cell, but not any of the flags, etc.
606 struct CopyablePersistentTraits {
607 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
608 static const bool kResetInDestructor = true;
609 template<class S, class M>
610 static V8_INLINE void Copy(const Persistent<S, M>& source,
611 CopyablePersistent* dest) {
612 // do nothing, just allow copy
618 * A PersistentBase which allows copy and assignment.
620 * Copy, assignment and destructor bevavior is controlled by the traits
623 * Note: Persistent class hierarchy is subject to future changes.
625 template <class T, class M> class Persistent : public PersistentBase<T> {
628 * A Persistent with no storage cell.
630 V8_INLINE Persistent() : PersistentBase<T>(0) { }
632 * Construct a Persistent from a Handle.
633 * When the Handle is non-empty, a new storage cell is created
634 * pointing to the same object, and no flags are set.
636 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
637 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
641 * Construct a Persistent from a Persistent.
642 * When the Persistent is non-empty, a new storage cell is created
643 * pointing to the same object, and no flags are set.
645 template <class S, class M2>
646 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
647 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
651 * The copy constructors and assignment operator create a Persistent
652 * exactly as the Persistent constructor, but the Copy function from the
653 * traits class is called, allowing the setting of flags based on the
656 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
659 template <class S, class M2>
660 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
663 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
667 template <class S, class M2>
668 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
673 * The destructor will dispose the Persistent based on the
674 * kResetInDestructor flags in the traits class. Since not calling dispose
675 * can result in a memory leak, it is recommended to always set this flag.
677 V8_INLINE ~Persistent() {
678 if (M::kResetInDestructor) this->Reset();
681 // TODO(dcarney): this is pretty useless, fix or remove
683 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
684 #ifdef V8_ENABLE_CHECKS
685 // If we're going to perform the type check then we have to check
686 // that the handle isn't empty before doing the checked cast.
687 if (!that.IsEmpty()) T::Cast(*that);
689 return reinterpret_cast<Persistent<T>&>(that);
692 // TODO(dcarney): this is pretty useless, fix or remove
693 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
694 return Persistent<S>::Cast(*this);
697 // This will be removed.
698 V8_INLINE T* ClearAndLeak();
701 friend class Isolate;
703 template<class F> friend class Handle;
704 template<class F> friend class Local;
705 template<class F1, class F2> friend class Persistent;
706 template<class F> friend class ReturnValue;
708 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
709 V8_INLINE T* operator*() const { return this->val_; }
710 template<class S, class M2>
711 V8_INLINE void Copy(const Persistent<S, M2>& that);
716 * A PersistentBase which has move semantics.
718 * Note: Persistent class hierarchy is subject to future changes.
721 class UniquePersistent : public PersistentBase<T> {
723 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
724 UniquePersistent* object;
729 * A UniquePersistent with no storage cell.
731 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
733 * Construct a UniquePersistent from a Handle.
734 * When the Handle is non-empty, a new storage cell is created
735 * pointing to the same object, and no flags are set.
738 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
739 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
743 * Construct a UniquePersistent from a PersistentBase.
744 * When the Persistent is non-empty, a new storage cell is created
745 * pointing to the same object, and no flags are set.
748 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
749 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
755 V8_INLINE UniquePersistent(RValue rvalue)
756 : PersistentBase<T>(rvalue.object->val_) {
757 rvalue.object->val_ = 0;
759 V8_INLINE ~UniquePersistent() { this->Reset(); }
761 * Move via assignment.
764 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
767 this->val_ = rhs.val_;
772 * Cast operator for moves.
774 V8_INLINE operator RValue() { return RValue(this); }
776 * Pass allows returning uniques from functions, etc.
778 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
781 UniquePersistent(UniquePersistent&);
782 void operator=(UniquePersistent&);
787 * A stack-allocated class that governs a number of local handles.
788 * After a handle scope has been created, all local handles will be
789 * allocated within that handle scope until either the handle scope is
790 * deleted or another handle scope is created. If there is already a
791 * handle scope and a new one is created, all allocations will take
792 * place in the new handle scope until it is deleted. After that,
793 * new handles will again be allocated in the original handle scope.
795 * After the handle scope of a local handle has been deleted the
796 * garbage collector will no longer track the object stored in the
797 * handle and may deallocate it. The behavior of accessing a handle
798 * for which the handle scope has been deleted is undefined.
800 class V8_EXPORT HandleScope {
802 HandleScope(Isolate* isolate);
807 * Counts the number of allocated handles.
809 static int NumberOfHandles(Isolate* isolate);
811 V8_INLINE Isolate* GetIsolate() const {
812 return reinterpret_cast<Isolate*>(isolate_);
816 V8_INLINE HandleScope() {}
818 void Initialize(Isolate* isolate);
820 static internal::Object** CreateHandle(internal::Isolate* isolate,
821 internal::Object* value);
824 // Uses heap_object to obtain the current Isolate.
825 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
826 internal::Object* value);
828 // Make it hard to create heap-allocated or illegal handle scopes by
829 // disallowing certain operations.
830 HandleScope(const HandleScope&);
831 void operator=(const HandleScope&);
832 void* operator new(size_t size);
833 void operator delete(void*, size_t);
835 internal::Isolate* isolate_;
836 internal::Object** prev_next_;
837 internal::Object** prev_limit_;
839 // Local::New uses CreateHandle with an Isolate* parameter.
840 template<class F> friend class Local;
842 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
843 // a HeapObject* in their shortcuts.
845 friend class Context;
850 * A HandleScope which first allocates a handle in the current scope
851 * which will be later filled with the escape value.
853 class V8_EXPORT EscapableHandleScope : public HandleScope {
855 EscapableHandleScope(Isolate* isolate);
856 V8_INLINE ~EscapableHandleScope() {}
859 * Pushes the value into the previous scope and returns a handle to it.
860 * Cannot be called twice.
863 V8_INLINE Local<T> Escape(Local<T> value) {
864 internal::Object** slot =
865 Escape(reinterpret_cast<internal::Object**>(*value));
866 return Local<T>(reinterpret_cast<T*>(slot));
870 internal::Object** Escape(internal::Object** escape_value);
872 // Make it hard to create heap-allocated or illegal handle scopes by
873 // disallowing certain operations.
874 EscapableHandleScope(const EscapableHandleScope&);
875 void operator=(const EscapableHandleScope&);
876 void* operator new(size_t size);
877 void operator delete(void*, size_t);
879 internal::Object** escape_slot_;
884 * A simple Maybe type, representing an object which may or may not have a
889 Maybe() : has_value(false) {}
890 explicit Maybe(T t) : has_value(true), value(t) {}
891 Maybe(bool has, T t) : has_value(has), value(t) {}
898 // --- Special objects ---
902 * The superclass of values and API object templates.
904 class V8_EXPORT Data {
911 * The origin, within a file, of a script.
915 V8_INLINE ScriptOrigin(
916 Handle<Value> resource_name,
917 Handle<Integer> resource_line_offset = Handle<Integer>(),
918 Handle<Integer> resource_column_offset = Handle<Integer>(),
919 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>())
920 : resource_name_(resource_name),
921 resource_line_offset_(resource_line_offset),
922 resource_column_offset_(resource_column_offset),
923 resource_is_shared_cross_origin_(resource_is_shared_cross_origin) { }
924 V8_INLINE Handle<Value> ResourceName() const;
925 V8_INLINE Handle<Integer> ResourceLineOffset() const;
926 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
927 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
929 Handle<Value> resource_name_;
930 Handle<Integer> resource_line_offset_;
931 Handle<Integer> resource_column_offset_;
932 Handle<Boolean> resource_is_shared_cross_origin_;
937 * A compiled JavaScript script, not yet tied to a Context.
939 class V8_EXPORT UnboundScript {
942 * Binds the script to the currently entered context.
944 Local<Script> BindToCurrentContext();
947 Handle<Value> GetScriptName();
950 * Returns zero based line number of the code_pos location in the script.
951 * -1 will be returned if no information available.
953 int GetLineNumber(int code_pos);
955 static const int kNoScriptId = 0;
960 * A compiled JavaScript script, tied to a Context which was active when the
961 * script was compiled.
963 class V8_EXPORT Script {
966 * A shorthand for ScriptCompiler::Compile().
968 static Local<Script> Compile(Handle<String> source,
969 ScriptOrigin* origin = NULL);
971 // To be decprecated, use the Compile above.
972 static Local<Script> Compile(Handle<String> source,
973 Handle<String> file_name);
976 * Runs the script returning the resulting value. It will be run in the
977 * context in which it was created (ScriptCompiler::CompileBound or
978 * UnboundScript::BindToGlobalContext()).
983 * Returns the corresponding context-unbound script.
985 Local<UnboundScript> GetUnboundScript();
987 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
989 return GetUnboundScript()->GetId();
995 * For compiling scripts.
997 class V8_EXPORT ScriptCompiler {
1000 * Compilation data that the embedder can cache and pass back to speed up
1001 * future compilations. The data is produced if the CompilerOptions passed to
1002 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1003 * = true. The data to cache can then can be retrieved from
1006 struct V8_EXPORT CachedData {
1012 CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1014 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1015 // data and guarantees that it stays alive until the CachedData object is
1016 // destroyed. If the policy is BufferOwned, the given data will be deleted
1017 // (with delete[]) when the CachedData object is destroyed.
1018 CachedData(const uint8_t* data, int length,
1019 BufferPolicy buffer_policy = BufferNotOwned);
1021 // TODO(marja): Async compilation; add constructors which take a callback
1022 // which will be called when V8 no longer needs the data.
1023 const uint8_t* data;
1025 BufferPolicy buffer_policy;
1028 // Prevent copying. Not implemented.
1029 CachedData(const CachedData&);
1030 CachedData& operator=(const CachedData&);
1034 * Source code which can be then compiled to a UnboundScript or Script.
1038 // Source takes ownership of CachedData.
1039 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1040 CachedData* cached_data = NULL);
1041 V8_INLINE Source(Local<String> source_string,
1042 CachedData* cached_data = NULL);
1043 V8_INLINE ~Source();
1045 // Ownership of the CachedData or its buffers is *not* transferred to the
1046 // caller. The CachedData object is alive as long as the Source object is
1048 V8_INLINE const CachedData* GetCachedData() const;
1051 friend class ScriptCompiler;
1052 // Prevent copying. Not implemented.
1053 Source(const Source&);
1054 Source& operator=(const Source&);
1056 Local<String> source_string;
1058 // Origin information
1059 Handle<Value> resource_name;
1060 Handle<Integer> resource_line_offset;
1061 Handle<Integer> resource_column_offset;
1062 Handle<Boolean> resource_is_shared_cross_origin;
1064 // Cached data from previous compilation (if any), or generated during
1065 // compilation (if the generate_cached_data flag is passed to
1067 CachedData* cached_data;
1070 enum CompileOptions {
1072 kProduceDataToCache = 1 << 0
1076 * Compiles the specified script (context-independent).
1078 * \param source Script source code.
1079 * \return Compiled script object (context independent; for running it must be
1080 * bound to a context).
1082 static Local<UnboundScript> CompileUnbound(
1083 Isolate* isolate, Source* source,
1084 CompileOptions options = kNoCompileOptions);
1087 * Compiles the specified script (bound to current context).
1089 * \param source Script source code.
1090 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1091 * using pre_data speeds compilation if it's done multiple times.
1092 * Owned by caller, no references are kept when this function returns.
1093 * \return Compiled script object, bound to the context that was active
1094 * when this function was called. When run it will always use this
1097 static Local<Script> Compile(
1098 Isolate* isolate, Source* source,
1099 CompileOptions options = kNoCompileOptions);
1106 class V8_EXPORT Message {
1108 Local<String> Get() const;
1109 Local<String> GetSourceLine() const;
1112 * Returns the resource name for the script from where the function causing
1113 * the error originates.
1115 Handle<Value> GetScriptResourceName() const;
1118 * Exception stack trace. By default stack traces are not captured for
1119 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1120 * to change this option.
1122 Handle<StackTrace> GetStackTrace() const;
1125 * Returns the number, 1-based, of the line where the error occurred.
1127 int GetLineNumber() const;
1130 * Returns the index within the script of the first character where
1131 * the error occurred.
1133 int GetStartPosition() const;
1136 * Returns the index within the script of the last character where
1137 * the error occurred.
1139 int GetEndPosition() const;
1142 * Returns the index within the line of the first character where
1143 * the error occurred.
1145 int GetStartColumn() const;
1148 * Returns the index within the line of the last character where
1149 * the error occurred.
1151 int GetEndColumn() const;
1154 * Passes on the value set by the embedder when it fed the script from which
1155 * this Message was generated to V8.
1157 bool IsSharedCrossOrigin() const;
1159 // TODO(1245381): Print to a string instead of on a FILE.
1160 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1162 static const int kNoLineNumberInfo = 0;
1163 static const int kNoColumnInfo = 0;
1164 static const int kNoScriptIdInfo = 0;
1169 * Representation of a JavaScript stack trace. The information collected is a
1170 * snapshot of the execution stack and the information remains valid after
1171 * execution continues.
1173 class V8_EXPORT StackTrace {
1176 * Flags that determine what information is placed captured for each
1177 * StackFrame when grabbing the current stack trace.
1179 enum StackTraceOptions {
1181 kColumnOffset = 1 << 1 | kLineNumber,
1182 kScriptName = 1 << 2,
1183 kFunctionName = 1 << 3,
1185 kIsConstructor = 1 << 5,
1186 kScriptNameOrSourceURL = 1 << 6,
1188 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1189 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1190 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1194 * Returns a StackFrame at a particular index.
1196 Local<StackFrame> GetFrame(uint32_t index) const;
1199 * Returns the number of StackFrames.
1201 int GetFrameCount() const;
1204 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1206 Local<Array> AsArray();
1209 * Grab a snapshot of the current JavaScript execution stack.
1211 * \param frame_limit The maximum number of stack frames we want to capture.
1212 * \param options Enumerates the set of things we will capture for each
1215 static Local<StackTrace> CurrentStackTrace(
1218 StackTraceOptions options = kOverview);
1223 * A single JavaScript stack frame.
1225 class V8_EXPORT StackFrame {
1228 * Returns the number, 1-based, of the line for the associate function call.
1229 * This method will return Message::kNoLineNumberInfo if it is unable to
1230 * retrieve the line number, or if kLineNumber was not passed as an option
1231 * when capturing the StackTrace.
1233 int GetLineNumber() const;
1236 * Returns the 1-based column offset on the line for the associated function
1238 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1239 * the column number, or if kColumnOffset was not passed as an option when
1240 * capturing the StackTrace.
1242 int GetColumn() const;
1245 * Returns the id of the script for the function for this StackFrame.
1246 * This method will return Message::kNoScriptIdInfo if it is unable to
1247 * retrieve the script id, or if kScriptId was not passed as an option when
1248 * capturing the StackTrace.
1250 int GetScriptId() const;
1253 * Returns the name of the resource that contains the script for the
1254 * function for this StackFrame.
1256 Local<String> GetScriptName() const;
1259 * Returns the name of the resource that contains the script for the
1260 * function for this StackFrame or sourceURL value if the script name
1261 * is undefined and its source ends with //# sourceURL=... string or
1262 * deprecated //@ sourceURL=... string.
1264 Local<String> GetScriptNameOrSourceURL() const;
1267 * Returns the name of the function associated with this stack frame.
1269 Local<String> GetFunctionName() const;
1272 * Returns whether or not the associated function is compiled via a call to
1275 bool IsEval() const;
1278 * Returns whether or not the associated function is called as a
1279 * constructor via "new".
1281 bool IsConstructor() const;
1288 class V8_EXPORT JSON {
1291 * Tries to parse the string |json_string| and returns it as value if
1294 * \param json_string The string to parse.
1295 * \return The corresponding value if successfully parsed.
1297 static Local<Value> Parse(Local<String> json_string);
1305 * The superclass of all JavaScript values and objects.
1307 class V8_EXPORT Value : public Data {
1310 * Returns true if this value is the undefined value. See ECMA-262
1313 V8_INLINE bool IsUndefined() const;
1316 * Returns true if this value is the null value. See ECMA-262
1319 V8_INLINE bool IsNull() const;
1322 * Returns true if this value is true.
1324 bool IsTrue() const;
1327 * Returns true if this value is false.
1329 bool IsFalse() const;
1332 * Returns true if this value is an instance of the String type.
1335 V8_INLINE bool IsString() const;
1338 * Returns true if this value is a symbol.
1339 * This is an experimental feature.
1341 bool IsSymbol() const;
1344 * Returns true if this value is a function.
1346 bool IsFunction() const;
1349 * Returns true if this value is an array.
1351 bool IsArray() const;
1354 * Returns true if this value is an object.
1356 bool IsObject() const;
1359 * Returns true if this value is boolean.
1361 bool IsBoolean() const;
1364 * Returns true if this value is a number.
1366 bool IsNumber() const;
1369 * Returns true if this value is external.
1371 bool IsExternal() const;
1374 * Returns true if this value is a 32-bit signed integer.
1376 bool IsInt32() const;
1379 * Returns true if this value is a 32-bit unsigned integer.
1381 bool IsUint32() const;
1384 * Returns true if this value is a Date.
1386 bool IsDate() const;
1389 * Returns true if this value is a Boolean object.
1391 bool IsBooleanObject() const;
1394 * Returns true if this value is a Number object.
1396 bool IsNumberObject() const;
1399 * Returns true if this value is a String object.
1401 bool IsStringObject() const;
1404 * Returns true if this value is a Symbol object.
1405 * This is an experimental feature.
1407 bool IsSymbolObject() const;
1410 * Returns true if this value is a NativeError.
1412 bool IsNativeError() const;
1415 * Returns true if this value is a RegExp.
1417 bool IsRegExp() const;
1420 * Returns true if this value is a Promise.
1421 * This is an experimental feature.
1423 bool IsPromise() const;
1426 * Returns true if this value is an ArrayBuffer.
1427 * This is an experimental feature.
1429 bool IsArrayBuffer() const;
1432 * Returns true if this value is an ArrayBufferView.
1433 * This is an experimental feature.
1435 bool IsArrayBufferView() const;
1438 * Returns true if this value is one of TypedArrays.
1439 * This is an experimental feature.
1441 bool IsTypedArray() const;
1444 * Returns true if this value is an Uint8Array.
1445 * This is an experimental feature.
1447 bool IsUint8Array() const;
1450 * Returns true if this value is an Uint8ClampedArray.
1451 * This is an experimental feature.
1453 bool IsUint8ClampedArray() const;
1456 * Returns true if this value is an Int8Array.
1457 * This is an experimental feature.
1459 bool IsInt8Array() const;
1462 * Returns true if this value is an Uint16Array.
1463 * This is an experimental feature.
1465 bool IsUint16Array() const;
1468 * Returns true if this value is an Int16Array.
1469 * This is an experimental feature.
1471 bool IsInt16Array() const;
1474 * Returns true if this value is an Uint32Array.
1475 * This is an experimental feature.
1477 bool IsUint32Array() const;
1480 * Returns true if this value is an Int32Array.
1481 * This is an experimental feature.
1483 bool IsInt32Array() const;
1486 * Returns true if this value is a Float32Array.
1487 * This is an experimental feature.
1489 bool IsFloat32Array() const;
1492 * Returns true if this value is a Float32x4Array.
1493 * This is an experimental feature.
1495 bool IsFloat32x4Array() const;
1498 * Returns true if this value is a Float64x2Array.
1499 * This is an experimental feature.
1501 bool IsFloat64x2Array() const;
1504 * Returns true if this value is a Int32x4Array.
1505 * This is an experimental feature.
1507 bool IsInt32x4Array() const;
1510 * Returns true if this value is a Float64Array.
1511 * This is an experimental feature.
1513 bool IsFloat64Array() const;
1516 * Returns true if this value is a DataView.
1517 * This is an experimental feature.
1519 bool IsDataView() const;
1521 Local<Boolean> ToBoolean() const;
1522 Local<Number> ToNumber() const;
1523 Local<String> ToString() const;
1524 Local<String> ToDetailString() const;
1525 Local<Object> ToObject() const;
1526 Local<Integer> ToInteger() const;
1527 Local<Uint32> ToUint32() const;
1528 Local<Int32> ToInt32() const;
1531 * Attempts to convert a string to an array index.
1532 * Returns an empty handle if the conversion fails.
1534 Local<Uint32> ToArrayIndex() const;
1536 bool BooleanValue() const;
1537 double NumberValue() const;
1538 int64_t IntegerValue() const;
1539 uint32_t Uint32Value() const;
1540 int32_t Int32Value() const;
1543 bool Equals(Handle<Value> that) const;
1544 bool StrictEquals(Handle<Value> that) const;
1545 bool SameValue(Handle<Value> that) const;
1547 template <class T> V8_INLINE static Value* Cast(T* value);
1550 V8_INLINE bool QuickIsUndefined() const;
1551 V8_INLINE bool QuickIsNull() const;
1552 V8_INLINE bool QuickIsString() const;
1553 bool FullIsUndefined() const;
1554 bool FullIsNull() const;
1555 bool FullIsString() const;
1560 * The superclass of primitive values. See ECMA-262 4.3.2.
1562 class V8_EXPORT Primitive : public Value { };
1566 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1569 class V8_EXPORT Boolean : public Primitive {
1572 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1577 * A JavaScript string value (ECMA-262, 4.3.17).
1579 class V8_EXPORT String : public Primitive {
1582 UNKNOWN_ENCODING = 0x1,
1583 TWO_BYTE_ENCODING = 0x0,
1584 ASCII_ENCODING = 0x4,
1585 ONE_BYTE_ENCODING = 0x4
1588 * Returns the number of characters in this string.
1593 * Returns the number of bytes in the UTF-8 encoded
1594 * representation of this string.
1596 int Utf8Length() const;
1599 * Returns whether this string is known to contain only one byte data.
1600 * Does not read the string.
1601 * False negatives are possible.
1603 bool IsOneByte() const;
1606 * Returns whether this string contain only one byte data.
1607 * Will read the entire string in some cases.
1609 bool ContainsOnlyOneByte() const;
1612 * Write the contents of the string to an external buffer.
1613 * If no arguments are given, expects the buffer to be large
1614 * enough to hold the entire string and NULL terminator. Copies
1615 * the contents of the string and the NULL terminator into the
1618 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1619 * before the end of the buffer.
1621 * Copies up to length characters into the output buffer.
1622 * Only null-terminates if there is enough space in the buffer.
1624 * \param buffer The buffer into which the string will be copied.
1625 * \param start The starting position within the string at which
1627 * \param length The number of characters to copy from the string. For
1628 * WriteUtf8 the number of bytes in the buffer.
1629 * \param nchars_ref The number of characters written, can be NULL.
1630 * \param options Various options that might affect performance of this or
1631 * subsequent operations.
1632 * \return The number of characters copied to the buffer excluding the null
1633 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1634 * including the null terminator (if written).
1638 HINT_MANY_WRITES_EXPECTED = 1,
1639 NO_NULL_TERMINATION = 2,
1640 PRESERVE_ASCII_NULL = 4,
1641 // Used by WriteUtf8 to replace orphan surrogate code units with the
1642 // unicode replacement character. Needs to be set to guarantee valid UTF-8
1644 REPLACE_INVALID_UTF8 = 8
1647 // 16-bit character codes.
1648 int Write(uint16_t* buffer,
1651 int options = NO_OPTIONS) const;
1652 // One byte characters.
1653 int WriteOneByte(uint8_t* buffer,
1656 int options = NO_OPTIONS) const;
1657 // UTF-8 encoded characters.
1658 int WriteUtf8(char* buffer,
1660 int* nchars_ref = NULL,
1661 int options = NO_OPTIONS) const;
1664 * A zero length string.
1666 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1669 * Returns true if the string is external
1671 bool IsExternal() const;
1674 * Returns true if the string is both external and ASCII
1676 bool IsExternalAscii() const;
1678 class V8_EXPORT ExternalStringResourceBase { // NOLINT
1680 virtual ~ExternalStringResourceBase() {}
1683 ExternalStringResourceBase() {}
1686 * Internally V8 will call this Dispose method when the external string
1687 * resource is no longer needed. The default implementation will use the
1688 * delete operator. This method can be overridden in subclasses to
1689 * control how allocated external string resources are disposed.
1691 virtual void Dispose() { delete this; }
1694 // Disallow copying and assigning.
1695 ExternalStringResourceBase(const ExternalStringResourceBase&);
1696 void operator=(const ExternalStringResourceBase&);
1698 friend class v8::internal::Heap;
1702 * An ExternalStringResource is a wrapper around a two-byte string
1703 * buffer that resides outside V8's heap. Implement an
1704 * ExternalStringResource to manage the life cycle of the underlying
1705 * buffer. Note that the string data must be immutable.
1707 class V8_EXPORT ExternalStringResource
1708 : public ExternalStringResourceBase {
1711 * Override the destructor to manage the life cycle of the underlying
1714 virtual ~ExternalStringResource() {}
1717 * The string data from the underlying buffer.
1719 virtual const uint16_t* data() const = 0;
1722 * The length of the string. That is, the number of two-byte characters.
1724 virtual size_t length() const = 0;
1727 ExternalStringResource() {}
1731 * An ExternalAsciiStringResource is a wrapper around an ASCII
1732 * string buffer that resides outside V8's heap. Implement an
1733 * ExternalAsciiStringResource to manage the life cycle of the
1734 * underlying buffer. Note that the string data must be immutable
1735 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1736 * UTF-8, which would require special treatment internally in the
1737 * engine and, in the case of UTF-8, do not allow efficient indexing.
1738 * Use String::New or convert to 16 bit data for non-ASCII.
1741 class V8_EXPORT ExternalAsciiStringResource
1742 : public ExternalStringResourceBase {
1745 * Override the destructor to manage the life cycle of the underlying
1748 virtual ~ExternalAsciiStringResource() {}
1749 /** The string data from the underlying buffer.*/
1750 virtual const char* data() const = 0;
1751 /** The number of ASCII characters in the string.*/
1752 virtual size_t length() const = 0;
1754 ExternalAsciiStringResource() {}
1757 typedef ExternalAsciiStringResource ExternalOneByteStringResource;
1760 * If the string is an external string, return the ExternalStringResourceBase
1761 * regardless of the encoding, otherwise return NULL. The encoding of the
1762 * string is returned in encoding_out.
1764 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1765 Encoding* encoding_out) const;
1768 * Get the ExternalStringResource for an external string. Returns
1769 * NULL if IsExternal() doesn't return true.
1771 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1774 * Get the ExternalAsciiStringResource for an external ASCII string.
1775 * Returns NULL if IsExternalAscii() doesn't return true.
1777 const ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
1779 V8_INLINE static String* Cast(v8::Value* obj);
1781 enum NewStringType {
1782 kNormalString, kInternalizedString, kUndetectableString
1785 /** Allocates a new string from UTF-8 data.*/
1786 static Local<String> NewFromUtf8(Isolate* isolate,
1788 NewStringType type = kNormalString,
1791 /** Allocates a new string from Latin-1 data.*/
1792 static Local<String> NewFromOneByte(
1794 const uint8_t* data,
1795 NewStringType type = kNormalString,
1798 /** Allocates a new string from UTF-16 data.*/
1799 static Local<String> NewFromTwoByte(
1801 const uint16_t* data,
1802 NewStringType type = kNormalString,
1806 * Creates a new string by concatenating the left and the right strings
1807 * passed in as parameters.
1809 static Local<String> Concat(Handle<String> left, Handle<String> right);
1812 * Creates a new external string using the data defined in the given
1813 * resource. When the external string is no longer live on V8's heap the
1814 * resource will be disposed by calling its Dispose method. The caller of
1815 * this function should not otherwise delete or modify the resource. Neither
1816 * should the underlying buffer be deallocated or modified except through the
1817 * destructor of the external string resource.
1819 static Local<String> NewExternal(Isolate* isolate,
1820 ExternalStringResource* resource);
1823 * Associate an external string resource with this string by transforming it
1824 * in place so that existing references to this string in the JavaScript heap
1825 * will use the external string resource. The external string resource's
1826 * character contents need to be equivalent to this string.
1827 * Returns true if the string has been changed to be an external string.
1828 * The string is not modified if the operation fails. See NewExternal for
1829 * information on the lifetime of the resource.
1831 bool MakeExternal(ExternalStringResource* resource);
1834 * Creates a new external string using the ASCII data defined in the given
1835 * resource. When the external string is no longer live on V8's heap the
1836 * resource will be disposed by calling its Dispose method. The caller of
1837 * this function should not otherwise delete or modify the resource. Neither
1838 * should the underlying buffer be deallocated or modified except through the
1839 * destructor of the external string resource.
1841 static Local<String> NewExternal(Isolate* isolate,
1842 ExternalAsciiStringResource* resource);
1845 * Associate an external string resource with this string by transforming it
1846 * in place so that existing references to this string in the JavaScript heap
1847 * will use the external string resource. The external string resource's
1848 * character contents need to be equivalent to this string.
1849 * Returns true if the string has been changed to be an external string.
1850 * The string is not modified if the operation fails. See NewExternal for
1851 * information on the lifetime of the resource.
1853 bool MakeExternal(ExternalAsciiStringResource* resource);
1856 * Returns true if this string can be made external.
1858 bool CanMakeExternal();
1861 * Converts an object to a UTF-8-encoded character array. Useful if
1862 * you want to print the object. If conversion to a string fails
1863 * (e.g. due to an exception in the toString() method of the object)
1864 * then the length() method returns 0 and the * operator returns
1867 class V8_EXPORT Utf8Value {
1869 explicit Utf8Value(Handle<v8::Value> obj);
1871 char* operator*() { return str_; }
1872 const char* operator*() const { return str_; }
1873 int length() const { return length_; }
1878 // Disallow copying and assigning.
1879 Utf8Value(const Utf8Value&);
1880 void operator=(const Utf8Value&);
1884 * Converts an object to a two-byte string.
1885 * If conversion to a string fails (eg. due to an exception in the toString()
1886 * method of the object) then the length() method returns 0 and the * operator
1889 class V8_EXPORT Value {
1891 explicit Value(Handle<v8::Value> obj);
1893 uint16_t* operator*() { return str_; }
1894 const uint16_t* operator*() const { return str_; }
1895 int length() const { return length_; }
1900 // Disallow copying and assigning.
1901 Value(const Value&);
1902 void operator=(const Value&);
1906 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
1907 Encoding encoding) const;
1908 void VerifyExternalStringResource(ExternalStringResource* val) const;
1909 static void CheckCast(v8::Value* obj);
1914 * A JavaScript symbol (ECMA-262 edition 6)
1916 * This is an experimental feature. Use at your own risk.
1918 class V8_EXPORT Symbol : public Primitive {
1920 // Returns the print name string of the symbol, or undefined if none.
1921 Local<Value> Name() const;
1923 // Create a symbol. If name is not empty, it will be used as the description.
1924 static Local<Symbol> New(
1925 Isolate *isolate, Local<String> name = Local<String>());
1927 // Access global symbol registry.
1928 // Note that symbols created this way are never collected, so
1929 // they should only be used for statically fixed properties.
1930 // Also, there is only one global name space for the names used as keys.
1931 // To minimize the potential for clashes, use qualified names as keys.
1932 static Local<Symbol> For(Isolate *isolate, Local<String> name);
1934 // Retrieve a global symbol. Similar to |For|, but using a separate
1935 // registry that is not accessible by (and cannot clash with) JavaScript code.
1936 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
1938 V8_INLINE static Symbol* Cast(v8::Value* obj);
1941 static void CheckCast(v8::Value* obj);
1948 * This is an experimental feature. Use at your own risk.
1950 class V8_EXPORT Private : public Data {
1952 // Returns the print name string of the private symbol, or undefined if none.
1953 Local<Value> Name() const;
1955 // Create a private symbol. If name is not empty, it will be the description.
1956 static Local<Private> New(
1957 Isolate *isolate, Local<String> name = Local<String>());
1959 // Retrieve a global private symbol. If a symbol with this name has not
1960 // been retrieved in the same isolate before, it is created.
1961 // Note that private symbols created this way are never collected, so
1962 // they should only be used for statically fixed properties.
1963 // Also, there is only one global name space for the names used as keys.
1964 // To minimize the potential for clashes, use qualified names as keys,
1965 // e.g., "Class#property".
1966 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
1974 * A JavaScript number value (ECMA-262, 4.3.20)
1976 class V8_EXPORT Number : public Primitive {
1978 double Value() const;
1979 static Local<Number> New(Isolate* isolate, double value);
1980 V8_INLINE static Number* Cast(v8::Value* obj);
1983 static void CheckCast(v8::Value* obj);
1988 * A JavaScript value representing a signed integer.
1990 class V8_EXPORT Integer : public Number {
1992 static Local<Integer> New(Isolate* isolate, int32_t value);
1993 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
1994 int64_t Value() const;
1995 V8_INLINE static Integer* Cast(v8::Value* obj);
1998 static void CheckCast(v8::Value* obj);
2003 * A JavaScript value representing a 32-bit signed integer.
2005 class V8_EXPORT Int32 : public Integer {
2007 int32_t Value() const;
2014 * A JavaScript value representing a 32-bit unsigned integer.
2016 class V8_EXPORT Uint32 : public Integer {
2018 uint32_t Value() const;
2024 enum PropertyAttribute {
2031 enum ExternalArrayType {
2032 kExternalInt8Array = 1,
2033 kExternalUint8Array,
2034 kExternalInt16Array,
2035 kExternalUint16Array,
2036 kExternalInt32Array,
2037 kExternalInt32x4Array,
2038 kExternalUint32Array,
2039 kExternalFloat32Array,
2040 kExternalFloat32x4Array,
2041 kExternalFloat64x2Array,
2042 kExternalFloat64Array,
2043 kExternalUint8ClampedArray,
2045 // Legacy constant names
2046 kExternalByteArray = kExternalInt8Array,
2047 kExternalUnsignedByteArray = kExternalUint8Array,
2048 kExternalShortArray = kExternalInt16Array,
2049 kExternalUnsignedShortArray = kExternalUint16Array,
2050 kExternalIntArray = kExternalInt32Array,
2051 kExternalUnsignedIntArray = kExternalUint32Array,
2052 kExternalFloatArray = kExternalFloat32Array,
2053 kExternalDoubleArray = kExternalFloat64Array,
2054 kExternalPixelArray = kExternalUint8ClampedArray
2058 * Accessor[Getter|Setter] are used as callback functions when
2059 * setting|getting a particular property. See Object and ObjectTemplate's
2060 * method SetAccessor.
2062 typedef void (*AccessorGetterCallback)(
2063 Local<String> property,
2064 const PropertyCallbackInfo<Value>& info);
2067 typedef void (*AccessorSetterCallback)(
2068 Local<String> property,
2070 const PropertyCallbackInfo<void>& info);
2074 * Access control specifications.
2076 * Some accessors should be accessible across contexts. These
2077 * accessors have an explicit access control parameter which specifies
2078 * the kind of cross-context access that should be allowed.
2080 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2082 enum AccessControl {
2085 ALL_CAN_WRITE = 1 << 1,
2086 PROHIBITS_OVERWRITING = 1 << 2
2091 * A JavaScript object (ECMA-262, 4.3.3)
2093 class V8_EXPORT Object : public Value {
2095 bool Set(Handle<Value> key,
2096 Handle<Value> value,
2097 PropertyAttribute attribs = None);
2099 bool Set(uint32_t index, Handle<Value> value);
2101 // Sets an own property on this object bypassing interceptors and
2102 // overriding accessors or read-only properties.
2104 // Note that if the object has an interceptor the property will be set
2105 // locally, but since the interceptor takes precedence the local property
2106 // will only be returned if the interceptor doesn't return a value.
2108 // Note also that this only works for named properties.
2109 bool ForceSet(Handle<Value> key,
2110 Handle<Value> value,
2111 PropertyAttribute attribs = None);
2113 Local<Value> Get(Handle<Value> key);
2115 Local<Value> Get(uint32_t index);
2118 * Gets the property attributes of a property which can be None or
2119 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2120 * None when the property doesn't exist.
2122 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2124 bool Has(Handle<Value> key);
2126 bool Delete(Handle<Value> key);
2128 // Delete a property on this object bypassing interceptors and
2129 // ignoring dont-delete attributes.
2130 bool ForceDelete(Handle<Value> key);
2132 bool Has(uint32_t index);
2134 bool Delete(uint32_t index);
2136 bool SetAccessor(Handle<String> name,
2137 AccessorGetterCallback getter,
2138 AccessorSetterCallback setter = 0,
2139 Handle<Value> data = Handle<Value>(),
2140 AccessControl settings = DEFAULT,
2141 PropertyAttribute attribute = None);
2143 // This function is not yet stable and should not be used at this time.
2144 bool SetDeclaredAccessor(Local<String> name,
2145 Local<DeclaredAccessorDescriptor> descriptor,
2146 PropertyAttribute attribute = None,
2147 AccessControl settings = DEFAULT);
2149 void SetAccessorProperty(Local<String> name,
2150 Local<Function> getter,
2151 Handle<Function> setter = Handle<Function>(),
2152 PropertyAttribute attribute = None,
2153 AccessControl settings = DEFAULT);
2156 * Functionality for private properties.
2157 * This is an experimental feature, use at your own risk.
2158 * Note: Private properties are inherited. Do not rely on this, since it may
2161 bool HasPrivate(Handle<Private> key);
2162 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2163 bool DeletePrivate(Handle<Private> key);
2164 Local<Value> GetPrivate(Handle<Private> key);
2167 * Returns an array containing the names of the enumerable properties
2168 * of this object, including properties from prototype objects. The
2169 * array returned by this method contains the same values as would
2170 * be enumerated by a for-in statement over this object.
2172 Local<Array> GetPropertyNames();
2175 * This function has the same functionality as GetPropertyNames but
2176 * the returned array doesn't contain the names of properties from
2177 * prototype objects.
2179 Local<Array> GetOwnPropertyNames();
2182 * Get the prototype object. This does not skip objects marked to
2183 * be skipped by __proto__ and it does not consult the security
2186 Local<Value> GetPrototype();
2189 * Set the prototype object. This does not skip objects marked to
2190 * be skipped by __proto__ and it does not consult the security
2193 bool SetPrototype(Handle<Value> prototype);
2196 * Finds an instance of the given function template in the prototype
2199 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2202 * Call builtin Object.prototype.toString on this object.
2203 * This is different from Value::ToString() that may call
2204 * user-defined toString function. This one does not.
2206 Local<String> ObjectProtoToString();
2209 * Returns the function invoked as a constructor for this object.
2210 * May be the null value.
2212 Local<Value> GetConstructor();
2215 * Returns the name of the function invoked as a constructor for this object.
2217 Local<String> GetConstructorName();
2219 /** Gets the number of internal fields for this Object. */
2220 int InternalFieldCount();
2222 /** Same as above, but works for Persistents */
2223 V8_INLINE static int InternalFieldCount(
2224 const PersistentBase<Object>& object) {
2225 return object.val_->InternalFieldCount();
2228 /** Gets the value from an internal field. */
2229 V8_INLINE Local<Value> GetInternalField(int index);
2231 /** Sets the value in an internal field. */
2232 void SetInternalField(int index, Handle<Value> value);
2235 * Gets a 2-byte-aligned native pointer from an internal field. This field
2236 * must have been set by SetAlignedPointerInInternalField, everything else
2237 * leads to undefined behavior.
2239 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2241 /** Same as above, but works for Persistents */
2242 V8_INLINE static void* GetAlignedPointerFromInternalField(
2243 const PersistentBase<Object>& object, int index) {
2244 return object.val_->GetAlignedPointerFromInternalField(index);
2248 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2249 * a field, GetAlignedPointerFromInternalField must be used, everything else
2250 * leads to undefined behavior.
2252 void SetAlignedPointerInInternalField(int index, void* value);
2254 // Testers for local properties.
2255 bool HasOwnProperty(Handle<String> key);
2256 bool HasRealNamedProperty(Handle<String> key);
2257 bool HasRealIndexedProperty(uint32_t index);
2258 bool HasRealNamedCallbackProperty(Handle<String> key);
2261 * If result.IsEmpty() no real property was located in the prototype chain.
2262 * This means interceptors in the prototype chain are not called.
2264 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2267 * If result.IsEmpty() no real property was located on the object or
2268 * in the prototype chain.
2269 * This means interceptors in the prototype chain are not called.
2271 Local<Value> GetRealNamedProperty(Handle<String> key);
2273 /** Tests for a named lookup interceptor.*/
2274 bool HasNamedLookupInterceptor();
2276 /** Tests for an index lookup interceptor.*/
2277 bool HasIndexedLookupInterceptor();
2280 * Turns on access check on the object if the object is an instance of
2281 * a template that has access check callbacks. If an object has no
2282 * access check info, the object cannot be accessed by anyone.
2284 void TurnOnAccessCheck();
2287 * Returns the identity hash for this object. The current implementation
2288 * uses a hidden property on the object to store the identity hash.
2290 * The return value will never be 0. Also, it is not guaranteed to be
2293 int GetIdentityHash();
2296 * Access hidden properties on JavaScript objects. These properties are
2297 * hidden from the executing JavaScript and only accessible through the V8
2298 * C++ API. Hidden properties introduced by V8 internally (for example the
2299 * identity hash) are prefixed with "v8::".
2301 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2302 Local<Value> GetHiddenValue(Handle<String> key);
2303 bool DeleteHiddenValue(Handle<String> key);
2306 * Returns true if this is an instance of an api function (one
2307 * created from a function created from a function template) and has
2308 * been modified since it was created. Note that this method is
2309 * conservative and may return true for objects that haven't actually
2315 * Clone this object with a fast but shallow copy. Values will point
2316 * to the same values as the original object.
2318 Local<Object> Clone();
2321 * Returns the context in which the object was created.
2323 Local<Context> CreationContext();
2326 * Set the backing store of the indexed properties to be managed by the
2327 * embedding layer. Access to the indexed properties will follow the rules
2328 * spelled out in CanvasPixelArray.
2329 * Note: The embedding program still owns the data and needs to ensure that
2330 * the backing store is preserved while V8 has a reference.
2332 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2333 bool HasIndexedPropertiesInPixelData();
2334 uint8_t* GetIndexedPropertiesPixelData();
2335 int GetIndexedPropertiesPixelDataLength();
2338 * Set the backing store of the indexed properties to be managed by the
2339 * embedding layer. Access to the indexed properties will follow the rules
2340 * spelled out for the CanvasArray subtypes in the WebGL specification.
2341 * Note: The embedding program still owns the data and needs to ensure that
2342 * the backing store is preserved while V8 has a reference.
2344 void SetIndexedPropertiesToExternalArrayData(void* data,
2345 ExternalArrayType array_type,
2346 int number_of_elements);
2347 bool HasIndexedPropertiesInExternalArrayData();
2348 void* GetIndexedPropertiesExternalArrayData();
2349 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2350 int GetIndexedPropertiesExternalArrayDataLength();
2353 * Checks whether a callback is set by the
2354 * ObjectTemplate::SetCallAsFunctionHandler method.
2355 * When an Object is callable this method returns true.
2360 * Call an Object as a function if a callback is set by the
2361 * ObjectTemplate::SetCallAsFunctionHandler method.
2363 Local<Value> CallAsFunction(Handle<Value> recv,
2365 Handle<Value> argv[]);
2368 * Call an Object as a constructor if a callback is set by the
2369 * ObjectTemplate::SetCallAsFunctionHandler method.
2370 * Note: This method behaves like the Function::NewInstance method.
2372 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2374 static Local<Object> New(Isolate* isolate);
2376 V8_INLINE static Object* Cast(Value* obj);
2380 static void CheckCast(Value* obj);
2381 Local<Value> SlowGetInternalField(int index);
2382 void* SlowGetAlignedPointerFromInternalField(int index);
2387 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2389 class V8_EXPORT Array : public Object {
2391 uint32_t Length() const;
2394 * Clones an element at index |index|. Returns an empty
2395 * handle if cloning fails (for any reason).
2397 Local<Object> CloneElementAt(uint32_t index);
2400 * Creates a JavaScript array with the given length. If the length
2401 * is negative the returned array will have length 0.
2403 static Local<Array> New(Isolate* isolate, int length = 0);
2405 V8_INLINE static Array* Cast(Value* obj);
2408 static void CheckCast(Value* obj);
2412 template<typename T>
2415 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2416 : value_(that.value_) {
2420 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2421 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2422 // Fast primitive setters
2423 V8_INLINE void Set(bool value);
2424 V8_INLINE void Set(double i);
2425 V8_INLINE void Set(int32_t i);
2426 V8_INLINE void Set(uint32_t i);
2427 // Fast JS primitive setters
2428 V8_INLINE void SetNull();
2429 V8_INLINE void SetUndefined();
2430 V8_INLINE void SetEmptyString();
2431 // Convenience getter for Isolate
2432 V8_INLINE Isolate* GetIsolate();
2434 // Pointer setter: Uncompilable to prevent inadvertent misuse.
2435 template <typename S>
2436 V8_INLINE void Set(S* whatever);
2439 template<class F> friend class ReturnValue;
2440 template<class F> friend class FunctionCallbackInfo;
2441 template<class F> friend class PropertyCallbackInfo;
2442 template<class F, class G, class H> friend class PersistentValueMap;
2443 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2444 V8_INLINE internal::Object* GetDefaultValue();
2445 V8_INLINE explicit ReturnValue(internal::Object** slot);
2446 internal::Object** value_;
2451 * The argument information given to function call callbacks. This
2452 * class provides access to information about the context of the call,
2453 * including the receiver, the number and values of arguments, and
2454 * the holder of the function.
2456 template<typename T>
2457 class FunctionCallbackInfo {
2459 V8_INLINE int Length() const;
2460 V8_INLINE Local<Value> operator[](int i) const;
2461 V8_INLINE Local<Function> Callee() const;
2462 V8_INLINE Local<Object> This() const;
2463 V8_INLINE Local<Object> Holder() const;
2464 V8_INLINE bool IsConstructCall() const;
2465 V8_INLINE Local<Value> Data() const;
2466 V8_INLINE Isolate* GetIsolate() const;
2467 V8_INLINE ReturnValue<T> GetReturnValue() const;
2468 // This shouldn't be public, but the arm compiler needs it.
2469 static const int kArgsLength = 7;
2472 friend class internal::FunctionCallbackArguments;
2473 friend class internal::CustomArguments<FunctionCallbackInfo>;
2474 static const int kHolderIndex = 0;
2475 static const int kIsolateIndex = 1;
2476 static const int kReturnValueDefaultValueIndex = 2;
2477 static const int kReturnValueIndex = 3;
2478 static const int kDataIndex = 4;
2479 static const int kCalleeIndex = 5;
2480 static const int kContextSaveIndex = 6;
2482 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2483 internal::Object** values,
2485 bool is_construct_call);
2486 internal::Object** implicit_args_;
2487 internal::Object** values_;
2489 bool is_construct_call_;
2494 * The information passed to a property callback about the context
2495 * of the property access.
2497 template<typename T>
2498 class PropertyCallbackInfo {
2500 V8_INLINE Isolate* GetIsolate() const;
2501 V8_INLINE Local<Value> Data() const;
2502 V8_INLINE Local<Object> This() const;
2503 V8_INLINE Local<Object> Holder() const;
2504 V8_INLINE ReturnValue<T> GetReturnValue() const;
2505 // This shouldn't be public, but the arm compiler needs it.
2506 static const int kArgsLength = 6;
2509 friend class MacroAssembler;
2510 friend class internal::PropertyCallbackArguments;
2511 friend class internal::CustomArguments<PropertyCallbackInfo>;
2512 static const int kHolderIndex = 0;
2513 static const int kIsolateIndex = 1;
2514 static const int kReturnValueDefaultValueIndex = 2;
2515 static const int kReturnValueIndex = 3;
2516 static const int kDataIndex = 4;
2517 static const int kThisIndex = 5;
2519 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2520 internal::Object** args_;
2524 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2528 * A JavaScript function object (ECMA-262, 15.3).
2530 class V8_EXPORT Function : public Object {
2533 * Create a function in the current execution context
2534 * for a given FunctionCallback.
2536 static Local<Function> New(Isolate* isolate,
2537 FunctionCallback callback,
2538 Local<Value> data = Local<Value>(),
2541 Local<Object> NewInstance() const;
2542 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2543 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2544 void SetName(Handle<String> name);
2545 Handle<Value> GetName() const;
2548 * Name inferred from variable or property assignment of this function.
2549 * Used to facilitate debugging and profiling of JavaScript code written
2550 * in an OO style, where many functions are anonymous but are assigned
2551 * to object properties.
2553 Handle<Value> GetInferredName() const;
2556 * User-defined name assigned to the "displayName" property of this function.
2557 * Used to facilitate debugging and profiling of JavaScript code.
2559 Handle<Value> GetDisplayName() const;
2562 * Returns zero based line number of function body and
2563 * kLineOffsetNotFound if no information available.
2565 int GetScriptLineNumber() const;
2567 * Returns zero based column number of function body and
2568 * kLineOffsetNotFound if no information available.
2570 int GetScriptColumnNumber() const;
2573 * Tells whether this function is builtin.
2575 bool IsBuiltin() const;
2580 int ScriptId() const;
2583 * Returns the original function if this function is bound, else returns
2586 Local<Value> GetBoundFunction() const;
2588 ScriptOrigin GetScriptOrigin() const;
2589 V8_INLINE static Function* Cast(Value* obj);
2590 static const int kLineOffsetNotFound;
2594 static void CheckCast(Value* obj);
2599 * An instance of the built-in Promise constructor (ES6 draft).
2600 * This API is experimental. Only works with --harmony flag.
2602 class V8_EXPORT Promise : public Object {
2604 class V8_EXPORT Resolver : public Object {
2607 * Create a new resolver, along with an associated promise in pending state.
2609 static Local<Resolver> New(Isolate* isolate);
2612 * Extract the associated promise.
2614 Local<Promise> GetPromise();
2617 * Resolve/reject the associated promise with a given value.
2618 * Ignored if the promise is no longer pending.
2620 void Resolve(Handle<Value> value);
2621 void Reject(Handle<Value> value);
2623 V8_INLINE static Resolver* Cast(Value* obj);
2627 static void CheckCast(Value* obj);
2631 * Register a resolution/rejection handler with a promise.
2632 * The handler is given the respective resolution/rejection value as
2633 * an argument. If the promise is already resolved/rejected, the handler is
2634 * invoked at the end of turn.
2636 Local<Promise> Chain(Handle<Function> handler);
2637 Local<Promise> Catch(Handle<Function> handler);
2638 Local<Promise> Then(Handle<Function> handler);
2640 V8_INLINE static Promise* Cast(Value* obj);
2644 static void CheckCast(Value* obj);
2648 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2649 // The number of required internal fields can be defined by embedder.
2650 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2654 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2655 * This API is experimental and may change significantly.
2657 class V8_EXPORT ArrayBuffer : public Object {
2660 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2661 * The allocator is a global V8 setting. It should be set with
2662 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2664 * This API is experimental and may change significantly.
2666 class V8_EXPORT Allocator { // NOLINT
2668 virtual ~Allocator() {}
2671 * Allocate |length| bytes. Return NULL if allocation is not successful.
2672 * Memory should be initialized to zeroes.
2674 virtual void* Allocate(size_t length) = 0;
2677 * Allocate |length| bytes. Return NULL if allocation is not successful.
2678 * Memory does not have to be initialized.
2680 virtual void* AllocateUninitialized(size_t length) = 0;
2682 * Free the memory block of size |length|, pointed to by |data|.
2683 * That memory is guaranteed to be previously allocated by |Allocate|.
2685 virtual void Free(void* data, size_t length) = 0;
2689 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2690 * returns an instance of this class, populated, with a pointer to data
2693 * The Data pointer of ArrayBuffer::Contents is always allocated with
2694 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2696 * This API is experimental and may change significantly.
2698 class V8_EXPORT Contents { // NOLINT
2700 Contents() : data_(NULL), byte_length_(0) {}
2702 void* Data() const { return data_; }
2703 size_t ByteLength() const { return byte_length_; }
2707 size_t byte_length_;
2709 friend class ArrayBuffer;
2714 * Data length in bytes.
2716 size_t ByteLength() const;
2719 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2720 * Allocated memory will be owned by a created ArrayBuffer and
2721 * will be deallocated when it is garbage-collected,
2722 * unless the object is externalized.
2724 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2727 * Create a new ArrayBuffer over an existing memory block.
2728 * The created array buffer is immediately in externalized state.
2729 * The memory block will not be reclaimed when a created ArrayBuffer
2730 * is garbage-collected.
2732 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2733 size_t byte_length);
2736 * Returns true if ArrayBuffer is extrenalized, that is, does not
2737 * own its memory block.
2739 bool IsExternal() const;
2742 * Neuters this ArrayBuffer and all its views (typed arrays).
2743 * Neutering sets the byte length of the buffer and all typed arrays to zero,
2744 * preventing JavaScript from ever accessing underlying backing store.
2745 * ArrayBuffer should have been externalized.
2750 * Make this ArrayBuffer external. The pointer to underlying memory block
2751 * and byte length are returned as |Contents| structure. After ArrayBuffer
2752 * had been etxrenalized, it does no longer owns the memory block. The caller
2753 * should take steps to free memory when it is no longer needed.
2755 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2756 * that has been set with V8::SetArrayBufferAllocator.
2758 Contents Externalize();
2760 V8_INLINE static ArrayBuffer* Cast(Value* obj);
2762 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2766 static void CheckCast(Value* obj);
2770 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2771 // The number of required internal fields can be defined by embedder.
2772 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2777 * A base class for an instance of one of "views" over ArrayBuffer,
2778 * including TypedArrays and DataView (ES6 draft 15.13).
2780 * This API is experimental and may change significantly.
2782 class V8_EXPORT ArrayBufferView : public Object {
2785 * Returns underlying ArrayBuffer.
2787 Local<ArrayBuffer> Buffer();
2789 * Byte offset in |Buffer|.
2791 size_t ByteOffset();
2793 * Size of a view in bytes.
2795 size_t ByteLength();
2797 V8_INLINE static ArrayBufferView* Cast(Value* obj);
2799 static const int kInternalFieldCount =
2800 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2804 static void CheckCast(Value* obj);
2809 * A base class for an instance of TypedArray series of constructors
2810 * (ES6 draft 15.13.6).
2811 * This API is experimental and may change significantly.
2813 class V8_EXPORT TypedArray : public ArrayBufferView {
2816 * Number of elements in this typed array
2817 * (e.g. for Int16Array, |ByteLength|/2).
2821 V8_INLINE static TypedArray* Cast(Value* obj);
2825 static void CheckCast(Value* obj);
2830 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
2831 * This API is experimental and may change significantly.
2833 class V8_EXPORT Uint8Array : public TypedArray {
2835 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
2836 size_t byte_offset, size_t length);
2837 V8_INLINE static Uint8Array* Cast(Value* obj);
2841 static void CheckCast(Value* obj);
2846 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
2847 * This API is experimental and may change significantly.
2849 class V8_EXPORT Uint8ClampedArray : public TypedArray {
2851 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
2852 size_t byte_offset, size_t length);
2853 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
2856 Uint8ClampedArray();
2857 static void CheckCast(Value* obj);
2861 * An instance of Int8Array constructor (ES6 draft 15.13.6).
2862 * This API is experimental and may change significantly.
2864 class V8_EXPORT Int8Array : public TypedArray {
2866 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
2867 size_t byte_offset, size_t length);
2868 V8_INLINE static Int8Array* Cast(Value* obj);
2872 static void CheckCast(Value* obj);
2877 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
2878 * This API is experimental and may change significantly.
2880 class V8_EXPORT Uint16Array : public TypedArray {
2882 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
2883 size_t byte_offset, size_t length);
2884 V8_INLINE static Uint16Array* Cast(Value* obj);
2888 static void CheckCast(Value* obj);
2893 * An instance of Int16Array constructor (ES6 draft 15.13.6).
2894 * This API is experimental and may change significantly.
2896 class V8_EXPORT Int16Array : public TypedArray {
2898 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
2899 size_t byte_offset, size_t length);
2900 V8_INLINE static Int16Array* Cast(Value* obj);
2904 static void CheckCast(Value* obj);
2909 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
2910 * This API is experimental and may change significantly.
2912 class V8_EXPORT Uint32Array : public TypedArray {
2914 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
2915 size_t byte_offset, size_t length);
2916 V8_INLINE static Uint32Array* Cast(Value* obj);
2920 static void CheckCast(Value* obj);
2925 * An instance of Int32Array constructor (ES6 draft 15.13.6).
2926 * This API is experimental and may change significantly.
2928 class V8_EXPORT Int32Array : public TypedArray {
2930 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
2931 size_t byte_offset, size_t length);
2932 V8_INLINE static Int32Array* Cast(Value* obj);
2936 static void CheckCast(Value* obj);
2941 * An instance of Float32Array constructor (ES6 draft 15.13.6).
2942 * This API is experimental and may change significantly.
2944 class V8_EXPORT Float32Array : public TypedArray {
2946 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
2947 size_t byte_offset, size_t length);
2948 V8_INLINE static Float32Array* Cast(Value* obj);
2952 static void CheckCast(Value* obj);
2956 class V8_EXPORT Float32x4Array : public TypedArray {
2958 static Local<Float32x4Array> New(Handle<ArrayBuffer> array_buffer,
2959 size_t byte_offset, size_t length);
2960 V8_INLINE static Float32x4Array* Cast(Value* obj);
2964 static void CheckCast(Value* obj);
2968 class V8_EXPORT Float64x2Array : public TypedArray {
2970 static Local<Float64x2Array> New(Handle<ArrayBuffer> array_buffer,
2971 size_t byte_offset, size_t length);
2972 V8_INLINE static Float64x2Array* Cast(Value* obj);
2976 static void CheckCast(Value* obj);
2980 class V8_EXPORT Int32x4Array : public TypedArray {
2982 static Local<Int32x4Array> New(Handle<ArrayBuffer> array_buffer,
2983 size_t byte_offset, size_t length);
2984 V8_INLINE static Int32x4Array* Cast(Value* obj);
2988 static void CheckCast(Value* obj);
2993 * An instance of Float64Array constructor (ES6 draft 15.13.6).
2994 * This API is experimental and may change significantly.
2996 class V8_EXPORT Float64Array : public TypedArray {
2998 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
2999 size_t byte_offset, size_t length);
3000 V8_INLINE static Float64Array* Cast(Value* obj);
3004 static void CheckCast(Value* obj);
3009 * An instance of DataView constructor (ES6 draft 15.13.7).
3010 * This API is experimental and may change significantly.
3012 class V8_EXPORT DataView : public ArrayBufferView {
3014 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3015 size_t byte_offset, size_t length);
3016 V8_INLINE static DataView* Cast(Value* obj);
3020 static void CheckCast(Value* obj);
3025 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3027 class V8_EXPORT Date : public Object {
3029 static Local<Value> New(Isolate* isolate, double time);
3032 * A specialization of Value::NumberValue that is more efficient
3033 * because we know the structure of this object.
3035 double ValueOf() const;
3037 V8_INLINE static Date* Cast(v8::Value* obj);
3040 * Notification that the embedder has changed the time zone,
3041 * daylight savings time, or other date / time configuration
3042 * parameters. V8 keeps a cache of various values used for
3043 * date / time computation. This notification will reset
3044 * those cached values for the current context so that date /
3045 * time configuration changes would be reflected in the Date
3048 * This API should not be called more than needed as it will
3049 * negatively impact the performance of date operations.
3051 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3054 static void CheckCast(v8::Value* obj);
3059 * A Number object (ECMA-262, 4.3.21).
3061 class V8_EXPORT NumberObject : public Object {
3063 static Local<Value> New(Isolate* isolate, double value);
3065 double ValueOf() const;
3067 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3070 static void CheckCast(v8::Value* obj);
3075 * A Boolean object (ECMA-262, 4.3.15).
3077 class V8_EXPORT BooleanObject : public Object {
3079 static Local<Value> New(bool value);
3081 bool ValueOf() const;
3083 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3086 static void CheckCast(v8::Value* obj);
3091 * A String object (ECMA-262, 4.3.18).
3093 class V8_EXPORT StringObject : public Object {
3095 static Local<Value> New(Handle<String> value);
3097 Local<String> ValueOf() const;
3099 V8_INLINE static StringObject* Cast(v8::Value* obj);
3102 static void CheckCast(v8::Value* obj);
3107 * A Symbol object (ECMA-262 edition 6).
3109 * This is an experimental feature. Use at your own risk.
3111 class V8_EXPORT SymbolObject : public Object {
3113 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3115 Local<Symbol> ValueOf() const;
3117 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3120 static void CheckCast(v8::Value* obj);
3125 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3127 class V8_EXPORT RegExp : public Object {
3130 * Regular expression flag bits. They can be or'ed to enable a set
3141 * Creates a regular expression from the given pattern string and
3142 * the flags bit field. May throw a JavaScript exception as
3143 * described in ECMA-262, 15.10.4.1.
3146 * RegExp::New(v8::String::New("foo"),
3147 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3148 * is equivalent to evaluating "/foo/gm".
3150 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3153 * Returns the value of the source property: a string representing
3154 * the regular expression.
3156 Local<String> GetSource() const;
3159 * Returns the flags bit field.
3161 Flags GetFlags() const;
3163 V8_INLINE static RegExp* Cast(v8::Value* obj);
3166 static void CheckCast(v8::Value* obj);
3171 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3172 * to associate C++ data structures with JavaScript objects.
3174 class V8_EXPORT External : public Value {
3176 static Local<External> New(Isolate* isolate, void* value);
3177 V8_INLINE static External* Cast(Value* obj);
3178 void* Value() const;
3180 static void CheckCast(v8::Value* obj);
3184 // --- Templates ---
3188 * The superclass of object and function templates.
3190 class V8_EXPORT Template : public Data {
3192 /** Adds a property to each instance created by this template.*/
3193 void Set(Handle<String> name, Handle<Data> value,
3194 PropertyAttribute attributes = None);
3195 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3197 void SetAccessorProperty(
3199 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3200 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3201 PropertyAttribute attribute = None,
3202 AccessControl settings = DEFAULT);
3205 * Whenever the property with the given name is accessed on objects
3206 * created from this Template the getter and setter callbacks
3207 * are called instead of getting and setting the property directly
3208 * on the JavaScript object.
3210 * \param name The name of the property for which an accessor is added.
3211 * \param getter The callback to invoke when getting the property.
3212 * \param setter The callback to invoke when setting the property.
3213 * \param data A piece of data that will be passed to the getter and setter
3214 * callbacks whenever they are invoked.
3215 * \param settings Access control settings for the accessor. This is a bit
3216 * field consisting of one of more of
3217 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3218 * The default is to not allow cross-context access.
3219 * ALL_CAN_READ means that all cross-context reads are allowed.
3220 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3221 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3222 * cross-context access.
3223 * \param attribute The attributes of the property for which an accessor
3225 * \param signature The signature describes valid receivers for the accessor
3226 * and is used to perform implicit instance checks against them. If the
3227 * receiver is incompatible (i.e. is not an instance of the constructor as
3228 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3229 * thrown and no callback is invoked.
3231 void SetNativeDataProperty(Local<String> name,
3232 AccessorGetterCallback getter,
3233 AccessorSetterCallback setter = 0,
3234 // TODO(dcarney): gcc can't handle Local below
3235 Handle<Value> data = Handle<Value>(),
3236 PropertyAttribute attribute = None,
3237 Local<AccessorSignature> signature =
3238 Local<AccessorSignature>(),
3239 AccessControl settings = DEFAULT);
3241 // This function is not yet stable and should not be used at this time.
3242 bool SetDeclaredAccessor(Local<String> name,
3243 Local<DeclaredAccessorDescriptor> descriptor,
3244 PropertyAttribute attribute = None,
3245 Local<AccessorSignature> signature =
3246 Local<AccessorSignature>(),
3247 AccessControl settings = DEFAULT);
3252 friend class ObjectTemplate;
3253 friend class FunctionTemplate;
3258 * NamedProperty[Getter|Setter] are used as interceptors on object.
3259 * See ObjectTemplate::SetNamedPropertyHandler.
3261 typedef void (*NamedPropertyGetterCallback)(
3262 Local<String> property,
3263 const PropertyCallbackInfo<Value>& info);
3267 * Returns the value if the setter intercepts the request.
3268 * Otherwise, returns an empty handle.
3270 typedef void (*NamedPropertySetterCallback)(
3271 Local<String> property,
3273 const PropertyCallbackInfo<Value>& info);
3277 * Returns a non-empty handle if the interceptor intercepts the request.
3278 * The result is an integer encoding property attributes (like v8::None,
3279 * v8::DontEnum, etc.)
3281 typedef void (*NamedPropertyQueryCallback)(
3282 Local<String> property,
3283 const PropertyCallbackInfo<Integer>& info);
3287 * Returns a non-empty handle if the deleter intercepts the request.
3288 * The return value is true if the property could be deleted and false
3291 typedef void (*NamedPropertyDeleterCallback)(
3292 Local<String> property,
3293 const PropertyCallbackInfo<Boolean>& info);
3297 * Returns an array containing the names of the properties the named
3298 * property getter intercepts.
3300 typedef void (*NamedPropertyEnumeratorCallback)(
3301 const PropertyCallbackInfo<Array>& info);
3305 * Returns the value of the property if the getter intercepts the
3306 * request. Otherwise, returns an empty handle.
3308 typedef void (*IndexedPropertyGetterCallback)(
3310 const PropertyCallbackInfo<Value>& info);
3314 * Returns the value if the setter intercepts the request.
3315 * Otherwise, returns an empty handle.
3317 typedef void (*IndexedPropertySetterCallback)(
3320 const PropertyCallbackInfo<Value>& info);
3324 * Returns a non-empty handle if the interceptor intercepts the request.
3325 * The result is an integer encoding property attributes.
3327 typedef void (*IndexedPropertyQueryCallback)(
3329 const PropertyCallbackInfo<Integer>& info);
3333 * Returns a non-empty handle if the deleter intercepts the request.
3334 * The return value is true if the property could be deleted and false
3337 typedef void (*IndexedPropertyDeleterCallback)(
3339 const PropertyCallbackInfo<Boolean>& info);
3343 * Returns an array containing the indices of the properties the
3344 * indexed property getter intercepts.
3346 typedef void (*IndexedPropertyEnumeratorCallback)(
3347 const PropertyCallbackInfo<Array>& info);
3351 * Access type specification.
3363 * Returns true if cross-context access should be allowed to the named
3364 * property with the given key on the host object.
3366 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3373 * Returns true if cross-context access should be allowed to the indexed
3374 * property with the given index on the host object.
3376 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3383 * A FunctionTemplate is used to create functions at runtime. There
3384 * can only be one function created from a FunctionTemplate in a
3385 * context. The lifetime of the created function is equal to the
3386 * lifetime of the context. So in case the embedder needs to create
3387 * temporary functions that can be collected using Scripts is
3390 * A FunctionTemplate can have properties, these properties are added to the
3391 * function object when it is created.
3393 * A FunctionTemplate has a corresponding instance template which is
3394 * used to create object instances when the function is used as a
3395 * constructor. Properties added to the instance template are added to
3396 * each object instance.
3398 * A FunctionTemplate can have a prototype template. The prototype template
3399 * is used to create the prototype object of the function.
3401 * The following example shows how to use a FunctionTemplate:
3404 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3405 * t->Set("func_property", v8::Number::New(1));
3407 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3408 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3409 * proto_t->Set("proto_const", v8::Number::New(2));
3411 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3412 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3413 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3414 * instance_t->Set("instance_property", Number::New(3));
3416 * v8::Local<v8::Function> function = t->GetFunction();
3417 * v8::Local<v8::Object> instance = function->NewInstance();
3420 * Let's use "function" as the JS variable name of the function object
3421 * and "instance" for the instance object created above. The function
3422 * and the instance will have the following properties:
3425 * func_property in function == true;
3426 * function.func_property == 1;
3428 * function.prototype.proto_method() invokes 'InvokeCallback'
3429 * function.prototype.proto_const == 2;
3431 * instance instanceof function == true;
3432 * instance.instance_accessor calls 'InstanceAccessorCallback'
3433 * instance.instance_property == 3;
3436 * A FunctionTemplate can inherit from another one by calling the
3437 * FunctionTemplate::Inherit method. The following graph illustrates
3438 * the semantics of inheritance:
3441 * FunctionTemplate Parent -> Parent() . prototype -> { }
3443 * | Inherit(Parent) | .__proto__
3445 * FunctionTemplate Child -> Child() . prototype -> { }
3448 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3449 * object of the Child() function has __proto__ pointing to the
3450 * Parent() function's prototype object. An instance of the Child
3451 * function has all properties on Parent's instance templates.
3453 * Let Parent be the FunctionTemplate initialized in the previous
3454 * section and create a Child FunctionTemplate by:
3457 * Local<FunctionTemplate> parent = t;
3458 * Local<FunctionTemplate> child = FunctionTemplate::New();
3459 * child->Inherit(parent);
3461 * Local<Function> child_function = child->GetFunction();
3462 * Local<Object> child_instance = child_function->NewInstance();
3465 * The Child function and Child instance will have the following
3469 * child_func.prototype.__proto__ == function.prototype;
3470 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3471 * child_instance.instance_property == 3;
3474 class V8_EXPORT FunctionTemplate : public Template {
3476 /** Creates a function template.*/
3477 static Local<FunctionTemplate> New(
3479 FunctionCallback callback = 0,
3480 Handle<Value> data = Handle<Value>(),
3481 Handle<Signature> signature = Handle<Signature>(),
3484 /** Returns the unique function instance in the current execution context.*/
3485 Local<Function> GetFunction();
3488 * Set the call-handler callback for a FunctionTemplate. This
3489 * callback is called whenever the function created from this
3490 * FunctionTemplate is called.
3492 void SetCallHandler(FunctionCallback callback,
3493 Handle<Value> data = Handle<Value>());
3495 /** Set the predefined length property for the FunctionTemplate. */
3496 void SetLength(int length);
3498 /** Get the InstanceTemplate. */
3499 Local<ObjectTemplate> InstanceTemplate();
3501 /** Causes the function template to inherit from a parent function template.*/
3502 void Inherit(Handle<FunctionTemplate> parent);
3505 * A PrototypeTemplate is the template used to create the prototype object
3506 * of the function created by this template.
3508 Local<ObjectTemplate> PrototypeTemplate();
3511 * Set the class name of the FunctionTemplate. This is used for
3512 * printing objects created with the function created from the
3513 * FunctionTemplate as its constructor.
3515 void SetClassName(Handle<String> name);
3518 * Determines whether the __proto__ accessor ignores instances of
3519 * the function template. If instances of the function template are
3520 * ignored, __proto__ skips all instances and instead returns the
3521 * next object in the prototype chain.
3523 * Call with a value of true to make the __proto__ accessor ignore
3524 * instances of the function template. Call with a value of false
3525 * to make the __proto__ accessor not ignore instances of the
3526 * function template. By default, instances of a function template
3529 void SetHiddenPrototype(bool value);
3532 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3533 * of functions created from this FunctionTemplate to true.
3535 void ReadOnlyPrototype();
3538 * Removes the prototype property from functions created from this
3541 void RemovePrototype();
3544 * Returns true if the given object is an instance of this function
3547 bool HasInstance(Handle<Value> object);
3551 friend class Context;
3552 friend class ObjectTemplate;
3557 * An ObjectTemplate is used to create objects at runtime.
3559 * Properties added to an ObjectTemplate are added to each object
3560 * created from the ObjectTemplate.
3562 class V8_EXPORT ObjectTemplate : public Template {
3564 /** Creates an ObjectTemplate. */
3565 static Local<ObjectTemplate> New(Isolate* isolate);
3566 // Will be deprecated soon.
3567 static Local<ObjectTemplate> New();
3569 /** Creates a new instance of this template.*/
3570 Local<Object> NewInstance();
3573 * Sets an accessor on the object template.
3575 * Whenever the property with the given name is accessed on objects
3576 * created from this ObjectTemplate the getter and setter callbacks
3577 * are called instead of getting and setting the property directly
3578 * on the JavaScript object.
3580 * \param name The name of the property for which an accessor is added.
3581 * \param getter The callback to invoke when getting the property.
3582 * \param setter The callback to invoke when setting the property.
3583 * \param data A piece of data that will be passed to the getter and setter
3584 * callbacks whenever they are invoked.
3585 * \param settings Access control settings for the accessor. This is a bit
3586 * field consisting of one of more of
3587 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3588 * The default is to not allow cross-context access.
3589 * ALL_CAN_READ means that all cross-context reads are allowed.
3590 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3591 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3592 * cross-context access.
3593 * \param attribute The attributes of the property for which an accessor
3595 * \param signature The signature describes valid receivers for the accessor
3596 * and is used to perform implicit instance checks against them. If the
3597 * receiver is incompatible (i.e. is not an instance of the constructor as
3598 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3599 * thrown and no callback is invoked.
3601 void SetAccessor(Handle<String> name,
3602 AccessorGetterCallback getter,
3603 AccessorSetterCallback setter = 0,
3604 Handle<Value> data = Handle<Value>(),
3605 AccessControl settings = DEFAULT,
3606 PropertyAttribute attribute = None,
3607 Handle<AccessorSignature> signature =
3608 Handle<AccessorSignature>());
3611 * Sets a named property handler on the object template.
3613 * Whenever a named property is accessed on objects created from
3614 * this object template, the provided callback is invoked instead of
3615 * accessing the property directly on the JavaScript object.
3617 * \param getter The callback to invoke when getting a property.
3618 * \param setter The callback to invoke when setting a property.
3619 * \param query The callback to invoke to check if a property is present,
3620 * and if present, get its attributes.
3621 * \param deleter The callback to invoke when deleting a property.
3622 * \param enumerator The callback to invoke to enumerate all the named
3623 * properties of an object.
3624 * \param data A piece of data that will be passed to the callbacks
3625 * whenever they are invoked.
3627 void SetNamedPropertyHandler(
3628 NamedPropertyGetterCallback getter,
3629 NamedPropertySetterCallback setter = 0,
3630 NamedPropertyQueryCallback query = 0,
3631 NamedPropertyDeleterCallback deleter = 0,
3632 NamedPropertyEnumeratorCallback enumerator = 0,
3633 Handle<Value> data = Handle<Value>());
3636 * Sets an indexed property handler on the object template.
3638 * Whenever an indexed property is accessed on objects created from
3639 * this object template, the provided callback is invoked instead of
3640 * accessing the property directly on the JavaScript object.
3642 * \param getter The callback to invoke when getting a property.
3643 * \param setter The callback to invoke when setting a property.
3644 * \param query The callback to invoke to check if an object has a property.
3645 * \param deleter The callback to invoke when deleting a property.
3646 * \param enumerator The callback to invoke to enumerate all the indexed
3647 * properties of an object.
3648 * \param data A piece of data that will be passed to the callbacks
3649 * whenever they are invoked.
3651 void SetIndexedPropertyHandler(
3652 IndexedPropertyGetterCallback getter,
3653 IndexedPropertySetterCallback setter = 0,
3654 IndexedPropertyQueryCallback query = 0,
3655 IndexedPropertyDeleterCallback deleter = 0,
3656 IndexedPropertyEnumeratorCallback enumerator = 0,
3657 Handle<Value> data = Handle<Value>());
3660 * Sets the callback to be used when calling instances created from
3661 * this template as a function. If no callback is set, instances
3662 * behave like normal JavaScript objects that cannot be called as a
3665 void SetCallAsFunctionHandler(FunctionCallback callback,
3666 Handle<Value> data = Handle<Value>());
3669 * Mark object instances of the template as undetectable.
3671 * In many ways, undetectable objects behave as though they are not
3672 * there. They behave like 'undefined' in conditionals and when
3673 * printed. However, properties can be accessed and called as on
3676 void MarkAsUndetectable();
3679 * Sets access check callbacks on the object template.
3681 * When accessing properties on instances of this object template,
3682 * the access check callback will be called to determine whether or
3683 * not to allow cross-context access to the properties.
3684 * The last parameter specifies whether access checks are turned
3685 * on by default on instances. If access checks are off by default,
3686 * they can be turned on on individual instances by calling
3687 * Object::TurnOnAccessCheck().
3689 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3690 IndexedSecurityCallback indexed_handler,
3691 Handle<Value> data = Handle<Value>(),
3692 bool turned_on_by_default = true);
3695 * Gets the number of internal fields for objects generated from
3698 int InternalFieldCount();
3701 * Sets the number of internal fields for objects generated from
3704 void SetInternalFieldCount(int value);
3708 static Local<ObjectTemplate> New(internal::Isolate* isolate,
3709 Handle<FunctionTemplate> constructor);
3710 friend class FunctionTemplate;
3715 * A Signature specifies which receivers and arguments are valid
3716 * parameters to a function.
3718 class V8_EXPORT Signature : public Data {
3720 static Local<Signature> New(Isolate* isolate,
3721 Handle<FunctionTemplate> receiver =
3722 Handle<FunctionTemplate>(),
3724 Handle<FunctionTemplate> argv[] = 0);
3732 * An AccessorSignature specifies which receivers are valid parameters
3733 * to an accessor callback.
3735 class V8_EXPORT AccessorSignature : public Data {
3737 static Local<AccessorSignature> New(Isolate* isolate,
3738 Handle<FunctionTemplate> receiver =
3739 Handle<FunctionTemplate>());
3742 AccessorSignature();
3746 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3748 DeclaredAccessorDescriptor();
3752 class V8_EXPORT ObjectOperationDescriptor : public Data {
3754 // This function is not yet stable and should not be used at this time.
3755 static Local<RawOperationDescriptor> NewInternalFieldDereference(
3757 int internal_field);
3759 ObjectOperationDescriptor();
3763 enum DeclaredAccessorDescriptorDataType {
3764 kDescriptorBoolType,
3765 kDescriptorInt8Type, kDescriptorUint8Type,
3766 kDescriptorInt16Type, kDescriptorUint16Type,
3767 kDescriptorInt32Type, kDescriptorUint32Type,
3768 kDescriptorFloatType, kDescriptorDoubleType
3772 class V8_EXPORT RawOperationDescriptor : public Data {
3774 Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3775 Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3776 Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3777 int16_t byte_offset);
3778 Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3779 void* compare_value);
3780 Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3782 DeclaredAccessorDescriptorDataType data_type,
3783 uint8_t bool_offset = 0);
3784 Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3786 uint8_t compare_value);
3787 Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3790 uint16_t compare_value);
3791 Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3794 uint32_t compare_value);
3797 RawOperationDescriptor();
3802 * A utility for determining the type of objects based on the template
3803 * they were constructed from.
3805 class V8_EXPORT TypeSwitch : public Data {
3807 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3808 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3809 int match(Handle<Value> value);
3815 // --- Extensions ---
3817 class V8_EXPORT ExternalAsciiStringResourceImpl
3818 : public String::ExternalAsciiStringResource {
3820 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
3821 ExternalAsciiStringResourceImpl(const char* data, size_t length)
3822 : data_(data), length_(length) {}
3823 const char* data() const { return data_; }
3824 size_t length() const { return length_; }
3834 class V8_EXPORT Extension { // NOLINT
3836 // Note that the strings passed into this constructor must live as long
3837 // as the Extension itself.
3838 Extension(const char* name,
3839 const char* source = 0,
3841 const char** deps = 0,
3842 int source_length = -1);
3843 virtual ~Extension() { }
3844 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
3845 v8::Isolate* isolate, v8::Handle<v8::String> name) {
3846 return v8::Handle<v8::FunctionTemplate>();
3849 const char* name() const { return name_; }
3850 size_t source_length() const { return source_length_; }
3851 const String::ExternalAsciiStringResource* source() const {
3853 int dependency_count() { return dep_count_; }
3854 const char** dependencies() { return deps_; }
3855 void set_auto_enable(bool value) { auto_enable_ = value; }
3856 bool auto_enable() { return auto_enable_; }
3860 size_t source_length_; // expected to initialize before source_
3861 ExternalAsciiStringResourceImpl source_;
3866 // Disallow copying and assigning.
3867 Extension(const Extension&);
3868 void operator=(const Extension&);
3872 void V8_EXPORT RegisterExtension(Extension* extension);
3877 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
3878 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
3879 V8_INLINE Handle<Boolean> True(Isolate* isolate);
3880 V8_INLINE Handle<Boolean> False(Isolate* isolate);
3884 * A set of constraints that specifies the limits of the runtime's memory use.
3885 * You must set the heap size before initializing the VM - the size cannot be
3886 * adjusted after the VM is initialized.
3888 * If you are using threads then you should hold the V8::Locker lock while
3889 * setting the stack limit and you must set a non-default stack limit separately
3892 class V8_EXPORT ResourceConstraints {
3894 ResourceConstraints();
3897 * Configures the constraints with reasonable default values based on the
3898 * capabilities of the current device the VM is running on.
3900 * \param physical_memory The total amount of physical memory on the current
3902 * \param virtual_memory_limit The amount of virtual memory on the current
3903 * device, in bytes, or zero, if there is no limit.
3904 * \param number_of_processors The number of CPUs available on the current
3907 void ConfigureDefaults(uint64_t physical_memory,
3908 uint64_t virtual_memory_limit,
3909 uint32_t number_of_processors);
3911 int max_semi_space_size() const { return max_semi_space_size_; }
3912 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
3913 int max_old_space_size() const { return max_old_space_size_; }
3914 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
3915 int max_executable_size() const { return max_executable_size_; }
3916 void set_max_executable_size(int value) { max_executable_size_ = value; }
3917 uint32_t* stack_limit() const { return stack_limit_; }
3918 // Sets an address beyond which the VM's stack may not grow.
3919 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
3920 int max_available_threads() const { return max_available_threads_; }
3921 // Set the number of threads available to V8, assuming at least 1.
3922 void set_max_available_threads(int value) {
3923 max_available_threads_ = value;
3925 size_t code_range_size() const { return code_range_size_; }
3926 void set_code_range_size(size_t value) {
3927 code_range_size_ = value;
3931 int max_semi_space_size_;
3932 int max_old_space_size_;
3933 int max_executable_size_;
3934 uint32_t* stack_limit_;
3935 int max_available_threads_;
3936 size_t code_range_size_;
3941 * Sets the given ResourceConstraints on the given Isolate.
3943 bool V8_EXPORT SetResourceConstraints(Isolate* isolate,
3944 ResourceConstraints* constraints);
3947 // --- Exceptions ---
3950 typedef void (*FatalErrorCallback)(const char* location, const char* message);
3953 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
3957 typedef void (*LogEventCallback)(const char* name, int event);
3960 * Create new error objects by calling the corresponding error object
3961 * constructor with the message.
3963 class V8_EXPORT Exception {
3965 static Local<Value> RangeError(Handle<String> message);
3966 static Local<Value> ReferenceError(Handle<String> message);
3967 static Local<Value> SyntaxError(Handle<String> message);
3968 static Local<Value> TypeError(Handle<String> message);
3969 static Local<Value> Error(Handle<String> message);
3973 // --- Counters Callbacks ---
3975 typedef int* (*CounterLookupCallback)(const char* name);
3977 typedef void* (*CreateHistogramCallback)(const char* name,
3982 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
3984 // --- Memory Allocation Callback ---
3986 kObjectSpaceNewSpace = 1 << 0,
3987 kObjectSpaceOldPointerSpace = 1 << 1,
3988 kObjectSpaceOldDataSpace = 1 << 2,
3989 kObjectSpaceCodeSpace = 1 << 3,
3990 kObjectSpaceMapSpace = 1 << 4,
3991 kObjectSpaceLoSpace = 1 << 5,
3993 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
3994 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
3998 enum AllocationAction {
3999 kAllocationActionAllocate = 1 << 0,
4000 kAllocationActionFree = 1 << 1,
4001 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4004 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4005 AllocationAction action,
4008 // --- Leave Script Callback ---
4009 typedef void (*CallCompletedCallback)();
4011 // --- Microtask Callback ---
4012 typedef void (*MicrotaskCallback)(void* data);
4014 // --- Failed Access Check Callback ---
4015 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4019 // --- AllowCodeGenerationFromStrings callbacks ---
4022 * Callback to check if code generation from strings is allowed. See
4023 * Context::AllowCodeGenerationFromStrings.
4025 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4027 // --- Garbage Collection Callbacks ---
4030 * Applications can register callback functions which will be called
4031 * before and after a garbage collection. Allocations are not
4032 * allowed in the callback functions, you therefore cannot manipulate
4033 * objects (set or delete properties for example) since it is possible
4034 * such operations will result in the allocation of objects.
4037 kGCTypeScavenge = 1 << 0,
4038 kGCTypeMarkSweepCompact = 1 << 1,
4039 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4042 enum GCCallbackFlags {
4043 kNoGCCallbackFlags = 0,
4044 kGCCallbackFlagCompacted = 1 << 0,
4045 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4046 kGCCallbackFlagForced = 1 << 2
4049 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4050 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4052 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4056 * Collection of V8 heap information.
4058 * Instances of this class can be passed to v8::V8::HeapStatistics to
4059 * get heap statistics from V8.
4061 class V8_EXPORT HeapStatistics {
4064 size_t total_heap_size() { return total_heap_size_; }
4065 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4066 size_t total_physical_size() { return total_physical_size_; }
4067 size_t used_heap_size() { return used_heap_size_; }
4068 size_t heap_size_limit() { return heap_size_limit_; }
4071 size_t total_heap_size_;
4072 size_t total_heap_size_executable_;
4073 size_t total_physical_size_;
4074 size_t used_heap_size_;
4075 size_t heap_size_limit_;
4078 friend class Isolate;
4082 class RetainedObjectInfo;
4085 * Isolate represents an isolated instance of the V8 engine. V8
4086 * isolates have completely separate states. Objects from one isolate
4087 * must not be used in other isolates. When V8 is initialized a
4088 * default isolate is implicitly created and entered. The embedder
4089 * can create additional isolates and use them in parallel in multiple
4090 * threads. An isolate can be entered by at most one thread at any
4091 * given time. The Locker/Unlocker API must be used to synchronize.
4093 class V8_EXPORT Isolate {
4096 * Stack-allocated class which sets the isolate for all operations
4097 * executed within a local scope.
4099 class V8_EXPORT Scope {
4101 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4105 ~Scope() { isolate_->Exit(); }
4108 Isolate* const isolate_;
4110 // Prevent copying of Scope objects.
4111 Scope(const Scope&);
4112 Scope& operator=(const Scope&);
4117 * Assert that no Javascript code is invoked.
4119 class V8_EXPORT DisallowJavascriptExecutionScope {
4121 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4123 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4124 ~DisallowJavascriptExecutionScope();
4130 // Prevent copying of Scope objects.
4131 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4132 DisallowJavascriptExecutionScope& operator=(
4133 const DisallowJavascriptExecutionScope&);
4138 * Introduce exception to DisallowJavascriptExecutionScope.
4140 class V8_EXPORT AllowJavascriptExecutionScope {
4142 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4143 ~AllowJavascriptExecutionScope();
4146 void* internal_throws_;
4147 void* internal_assert_;
4149 // Prevent copying of Scope objects.
4150 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4151 AllowJavascriptExecutionScope& operator=(
4152 const AllowJavascriptExecutionScope&);
4156 * Do not run microtasks while this scope is active, even if microtasks are
4157 * automatically executed otherwise.
4159 class V8_EXPORT SuppressMicrotaskExecutionScope {
4161 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4162 ~SuppressMicrotaskExecutionScope();
4165 internal::Isolate* isolate_;
4167 // Prevent copying of Scope objects.
4168 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4169 SuppressMicrotaskExecutionScope& operator=(
4170 const SuppressMicrotaskExecutionScope&);
4174 * Types of garbage collections that can be requested via
4175 * RequestGarbageCollectionForTesting.
4177 enum GarbageCollectionType {
4178 kFullGarbageCollection,
4179 kMinorGarbageCollection
4183 * Creates a new isolate. Does not change the currently entered
4186 * When an isolate is no longer used its resources should be freed
4187 * by calling Dispose(). Using the delete operator is not allowed.
4189 static Isolate* New();
4192 * Returns the entered isolate for the current thread or NULL in
4193 * case there is no current isolate.
4195 static Isolate* GetCurrent();
4198 * Methods below this point require holding a lock (using Locker) in
4199 * a multi-threaded environment.
4203 * Sets this isolate as the entered one for the current thread.
4204 * Saves the previously entered one (if any), so that it can be
4205 * restored when exiting. Re-entering an isolate is allowed.
4210 * Exits this isolate by restoring the previously entered one in the
4211 * current thread. The isolate may still stay the same, if it was
4212 * entered more than once.
4214 * Requires: this == Isolate::GetCurrent().
4219 * Disposes the isolate. The isolate must not be entered by any
4220 * thread to be disposable.
4225 * Associate embedder-specific data with the isolate. |slot| has to be
4226 * between 0 and GetNumberOfDataSlots() - 1.
4228 V8_INLINE void SetData(uint32_t slot, void* data);
4231 * Retrieve embedder-specific data from the isolate.
4232 * Returns NULL if SetData has never been called for the given |slot|.
4234 V8_INLINE void* GetData(uint32_t slot);
4237 * Returns the maximum number of available embedder data slots. Valid slots
4238 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4240 V8_INLINE static uint32_t GetNumberOfDataSlots();
4243 * Get statistics about the heap memory usage.
4245 void GetHeapStatistics(HeapStatistics* heap_statistics);
4248 * Adjusts the amount of registered external memory. Used to give V8 an
4249 * indication of the amount of externally allocated memory that is kept alive
4250 * by JavaScript objects. V8 uses this to decide when to perform global
4251 * garbage collections. Registering externally allocated memory will trigger
4252 * global garbage collections more often than it would otherwise in an attempt
4253 * to garbage collect the JavaScript objects that keep the externally
4254 * allocated memory alive.
4256 * \param change_in_bytes the change in externally allocated memory that is
4257 * kept alive by JavaScript objects.
4258 * \returns the adjusted value.
4261 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4264 * Returns heap profiler for this isolate. Will return NULL until the isolate
4267 HeapProfiler* GetHeapProfiler();
4270 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4271 * is initialized. It is the embedder's responsibility to stop all CPU
4272 * profiling activities if it has started any.
4274 CpuProfiler* GetCpuProfiler();
4276 /** Returns true if this isolate has a current context. */
4279 /** Returns the context that is on the top of the stack. */
4280 Local<Context> GetCurrentContext();
4283 * Returns the context of the calling JavaScript code. That is the
4284 * context of the top-most JavaScript frame. If there are no
4285 * JavaScript frames an empty handle is returned.
4287 Local<Context> GetCallingContext();
4289 /** Returns the last entered context. */
4290 Local<Context> GetEnteredContext();
4293 * Schedules an exception to be thrown when returning to JavaScript. When an
4294 * exception has been scheduled it is illegal to invoke any JavaScript
4295 * operation; the caller must return immediately and only after the exception
4296 * has been handled does it become legal to invoke JavaScript operations.
4298 Local<Value> ThrowException(Local<Value> exception);
4301 * Allows the host application to group objects together. If one
4302 * object in the group is alive, all objects in the group are alive.
4303 * After each garbage collection, object groups are removed. It is
4304 * intended to be used in the before-garbage-collection callback
4305 * function, for instance to simulate DOM tree connections among JS
4306 * wrapper objects. Object groups for all dependent handles need to
4307 * be provided for kGCTypeMarkSweepCompact collections, for all other
4308 * garbage collection types it is sufficient to provide object groups
4309 * for partially dependent handles only.
4311 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4315 * Allows the host application to declare implicit references from an object
4316 * group to an object. If the objects of the object group are alive, the child
4317 * object is alive too. After each garbage collection, all implicit references
4318 * are removed. It is intended to be used in the before-garbage-collection
4319 * callback function.
4321 template<typename T> void SetReferenceFromGroup(UniqueId id,
4322 const Persistent<T>& child);
4325 * Allows the host application to declare implicit references from an object
4326 * to another object. If the parent object is alive, the child object is alive
4327 * too. After each garbage collection, all implicit references are removed. It
4328 * is intended to be used in the before-garbage-collection callback function.
4330 template<typename T, typename S>
4331 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4333 typedef void (*GCPrologueCallback)(Isolate* isolate,
4335 GCCallbackFlags flags);
4336 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4338 GCCallbackFlags flags);
4341 * Enables the host application to receive a notification before a
4342 * garbage collection. Allocations are allowed in the callback function,
4343 * but the callback is not re-entrant: if the allocation inside it will
4344 * trigger the garbage collection, the callback won't be called again.
4345 * It is possible to specify the GCType filter for your callback. But it is
4346 * not possible to register the same callback function two times with
4347 * different GCType filters.
4349 void AddGCPrologueCallback(
4350 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4353 * This function removes callback which was installed by
4354 * AddGCPrologueCallback function.
4356 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4359 * Enables the host application to receive a notification after a
4360 * garbage collection. Allocations are allowed in the callback function,
4361 * but the callback is not re-entrant: if the allocation inside it will
4362 * trigger the garbage collection, the callback won't be called again.
4363 * It is possible to specify the GCType filter for your callback. But it is
4364 * not possible to register the same callback function two times with
4365 * different GCType filters.
4367 void AddGCEpilogueCallback(
4368 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4371 * This function removes callback which was installed by
4372 * AddGCEpilogueCallback function.
4374 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4377 * Request V8 to interrupt long running JavaScript code and invoke
4378 * the given |callback| passing the given |data| to it. After |callback|
4379 * returns control will be returned to the JavaScript code.
4380 * At any given moment V8 can remember only a single callback for the very
4381 * last interrupt request.
4382 * Can be called from another thread without acquiring a |Locker|.
4383 * Registered |callback| must not reenter interrupted Isolate.
4385 void RequestInterrupt(InterruptCallback callback, void* data);
4388 * Clear interrupt request created by |RequestInterrupt|.
4389 * Can be called from another thread without acquiring a |Locker|.
4391 void ClearInterrupt();
4394 * Request garbage collection in this Isolate. It is only valid to call this
4395 * function if --expose_gc was specified.
4397 * This should only be used for testing purposes and not to enforce a garbage
4398 * collection schedule. It has strong negative impact on the garbage
4399 * collection performance. Use IdleNotification() or LowMemoryNotification()
4400 * instead to influence the garbage collection schedule.
4402 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4405 * Set the callback to invoke for logging event.
4407 void SetEventLogger(LogEventCallback that);
4410 * Adds a callback to notify the host application when a script finished
4411 * running. If a script re-enters the runtime during executing, the
4412 * CallCompletedCallback is only invoked when the outer-most script
4413 * execution ends. Executing scripts inside the callback do not trigger
4414 * further callbacks.
4416 void AddCallCompletedCallback(CallCompletedCallback callback);
4419 * Removes callback that was installed by AddCallCompletedCallback.
4421 void RemoveCallCompletedCallback(CallCompletedCallback callback);
4424 * Experimental: Runs the Microtask Work Queue until empty
4425 * Any exceptions thrown by microtask callbacks are swallowed.
4427 void RunMicrotasks();
4430 * Experimental: Enqueues the callback to the Microtask Work Queue
4432 void EnqueueMicrotask(Handle<Function> microtask);
4435 * Experimental: Enqueues the callback to the Microtask Work Queue
4437 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
4440 * Experimental: Controls whether the Microtask Work Queue is automatically
4441 * run when the script call depth decrements to zero.
4443 void SetAutorunMicrotasks(bool autorun);
4446 * Experimental: Returns whether the Microtask Work Queue is automatically
4447 * run when the script call depth decrements to zero.
4449 bool WillAutorunMicrotasks() const;
4452 * Enables the host application to provide a mechanism for recording
4453 * statistics counters.
4455 void SetCounterFunction(CounterLookupCallback);
4458 * Enables the host application to provide a mechanism for recording
4459 * histograms. The CreateHistogram function returns a
4460 * histogram which will later be passed to the AddHistogramSample
4463 void SetCreateHistogramFunction(CreateHistogramCallback);
4464 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4467 template<class K, class V, class Traits> friend class PersistentValueMap;
4470 Isolate(const Isolate&);
4472 Isolate& operator=(const Isolate&);
4473 void* operator new(size_t size);
4474 void operator delete(void*, size_t);
4476 void SetObjectGroupId(internal::Object** object, UniqueId id);
4477 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4478 void SetReference(internal::Object** parent, internal::Object** child);
4479 void CollectAllGarbage(const char* gc_reason);
4482 class V8_EXPORT StartupData {
4484 enum CompressionAlgorithm {
4490 int compressed_size;
4496 * A helper class for driving V8 startup data decompression. It is based on
4497 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
4498 * for an embedder to use this class, instead, API functions can be used
4501 * For an example of the class usage, see the "shell.cc" sample application.
4503 class V8_EXPORT StartupDataDecompressor { // NOLINT
4505 StartupDataDecompressor();
4506 virtual ~StartupDataDecompressor();
4510 virtual int DecompressData(char* raw_data,
4512 const char* compressed_data,
4513 int compressed_data_size) = 0;
4521 * EntropySource is used as a callback function when v8 needs a source
4524 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4528 * ReturnAddressLocationResolver is used as a callback function when v8 is
4529 * resolving the location of a return address on the stack. Profilers that
4530 * change the return address on the stack can use this to resolve the stack
4531 * location to whereever the profiler stashed the original return address.
4533 * \param return_addr_location points to a location on stack where a machine
4534 * return address resides.
4535 * \returns either return_addr_location, or else a pointer to the profiler's
4536 * copy of the original return address.
4538 * \note the resolver function must not cause garbage collection.
4540 typedef uintptr_t (*ReturnAddressLocationResolver)(
4541 uintptr_t return_addr_location);
4545 * FunctionEntryHook is the type of the profile entry hook called at entry to
4546 * any generated function when function-level profiling is enabled.
4548 * \param function the address of the function that's being entered.
4549 * \param return_addr_location points to a location on stack where the machine
4550 * return address resides. This can be used to identify the caller of
4551 * \p function, and/or modified to divert execution when \p function exits.
4553 * \note the entry hook must not cause garbage collection.
4555 typedef void (*FunctionEntryHook)(uintptr_t function,
4556 uintptr_t return_addr_location);
4560 * A JIT code event is issued each time code is added, moved or removed.
4562 * \note removal events are not currently issued.
4564 struct JitCodeEvent {
4569 CODE_ADD_LINE_POS_INFO,
4570 CODE_START_LINE_INFO_RECORDING,
4571 CODE_END_LINE_INFO_RECORDING
4573 // Definition of the code position type. The "POSITION" type means the place
4574 // in the source code which are of interest when making stack traces to
4575 // pin-point the source location of a stack frame as close as possible.
4576 // The "STATEMENT_POSITION" means the place at the beginning of each
4577 // statement, and is used to indicate possible break locations.
4585 // Start of the instructions.
4587 // Size of the instructions.
4589 // Script info for CODE_ADDED event.
4590 Handle<Script> script;
4591 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4592 // code line information which is returned from the
4593 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4594 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4598 // Name of the object associated with the code, note that the string is not
4601 // Number of chars in str.
4605 struct line_info_t {
4610 // The position type.
4611 PositionType position_type;
4615 // Only valid for CODE_ADDED.
4618 // Only valid for CODE_ADD_LINE_POS_INFO
4619 struct line_info_t line_info;
4621 // New location of instructions. Only valid for CODE_MOVED.
4622 void* new_code_start;
4627 * Option flags passed to the SetJitCodeEventHandler function.
4629 enum JitCodeEventOptions {
4630 kJitCodeEventDefault = 0,
4631 // Generate callbacks for already existent code.
4632 kJitCodeEventEnumExisting = 1
4637 * Callback function passed to SetJitCodeEventHandler.
4639 * \param event code add, move or removal event.
4641 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4645 * Interface for iterating through all external resources in the heap.
4647 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4649 virtual ~ExternalResourceVisitor() {}
4650 virtual void VisitExternalString(Handle<String> string) {}
4655 * Interface for iterating through all the persistent handles in the heap.
4657 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4659 virtual ~PersistentHandleVisitor() {}
4660 virtual void VisitPersistentHandle(Persistent<Value>* value,
4661 uint16_t class_id) {}
4666 * Container class for static utility functions.
4668 class V8_EXPORT V8 {
4670 /** Set the callback to invoke in case of fatal errors. */
4671 static void SetFatalErrorHandler(FatalErrorCallback that);
4674 * Set the callback to invoke to check if code generation from
4675 * strings should be allowed.
4677 static void SetAllowCodeGenerationFromStringsCallback(
4678 AllowCodeGenerationFromStringsCallback that);
4681 * Set allocator to use for ArrayBuffer memory.
4682 * The allocator should be set only once. The allocator should be set
4683 * before any code tha uses ArrayBuffers is executed.
4684 * This allocator is used in all isolates.
4686 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4689 * Check if V8 is dead and therefore unusable. This is the case after
4690 * fatal errors such as out-of-memory situations.
4692 static bool IsDead();
4695 * The following 4 functions are to be used when V8 is built with
4696 * the 'compress_startup_data' flag enabled. In this case, the
4697 * embedder must decompress startup data prior to initializing V8.
4699 * This is how interaction with V8 should look like:
4700 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4701 * v8::StartupData* compressed_data =
4702 * new v8::StartupData[compressed_data_count];
4703 * v8::V8::GetCompressedStartupData(compressed_data);
4704 * ... decompress data (compressed_data can be updated in-place) ...
4705 * v8::V8::SetDecompressedStartupData(compressed_data);
4706 * ... now V8 can be initialized
4707 * ... make sure the decompressed data stays valid until V8 shutdown
4709 * A helper class StartupDataDecompressor is provided. It implements
4710 * the protocol of the interaction described above, and can be used in
4711 * most cases instead of calling these API functions directly.
4713 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4714 static int GetCompressedStartupDataCount();
4715 static void GetCompressedStartupData(StartupData* compressed_data);
4716 static void SetDecompressedStartupData(StartupData* decompressed_data);
4719 * Adds a message listener.
4721 * The same message listener can be added more than once and in that
4722 * case it will be called more than once for each message.
4724 * If data is specified, it will be passed to the callback when it is called.
4725 * Otherwise, the exception object will be passed to the callback instead.
4727 static bool AddMessageListener(MessageCallback that,
4728 Handle<Value> data = Handle<Value>());
4731 * Remove all message listeners from the specified callback function.
4733 static void RemoveMessageListeners(MessageCallback that);
4736 * Tells V8 to capture current stack trace when uncaught exception occurs
4737 * and report it to the message listeners. The option is off by default.
4739 static void SetCaptureStackTraceForUncaughtExceptions(
4741 int frame_limit = 10,
4742 StackTrace::StackTraceOptions options = StackTrace::kOverview);
4745 * Sets V8 flags from a string.
4747 static void SetFlagsFromString(const char* str, int length);
4750 * Sets V8 flags from the command line.
4752 static void SetFlagsFromCommandLine(int* argc,
4756 /** Get the version string. */
4757 static const char* GetVersion();
4760 * Enables the host application to provide a mechanism for recording
4761 * statistics counters.
4763 * Deprecated, use Isolate::SetCounterFunction instead.
4765 static void SetCounterFunction(CounterLookupCallback);
4768 * Enables the host application to provide a mechanism for recording
4769 * histograms. The CreateHistogram function returns a
4770 * histogram which will later be passed to the AddHistogramSample
4773 * Deprecated, use Isolate::SetCreateHistogramFunction instead.
4774 * Isolate::SetAddHistogramSampleFunction instead.
4776 static void SetCreateHistogramFunction(CreateHistogramCallback);
4778 /** Deprecated, use Isolate::SetAddHistogramSampleFunction instead. */
4779 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4781 /** Callback function for reporting failed access checks.*/
4782 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
4785 * Enables the host application to receive a notification before a
4786 * garbage collection. Allocations are not allowed in the
4787 * callback function, you therefore cannot manipulate objects (set
4788 * or delete properties for example) since it is possible such
4789 * operations will result in the allocation of objects. It is possible
4790 * to specify the GCType filter for your callback. But it is not possible to
4791 * register the same callback function two times with different
4794 static void AddGCPrologueCallback(
4795 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4798 * This function removes callback which was installed by
4799 * AddGCPrologueCallback function.
4801 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
4804 * Enables the host application to receive a notification after a
4805 * garbage collection. Allocations are not allowed in the
4806 * callback function, you therefore cannot manipulate objects (set
4807 * or delete properties for example) since it is possible such
4808 * operations will result in the allocation of objects. It is possible
4809 * to specify the GCType filter for your callback. But it is not possible to
4810 * register the same callback function two times with different
4813 static void AddGCEpilogueCallback(
4814 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4817 * This function removes callback which was installed by
4818 * AddGCEpilogueCallback function.
4820 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4823 * Enables the host application to provide a mechanism to be notified
4824 * and perform custom logging when V8 Allocates Executable Memory.
4826 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
4828 AllocationAction action);
4831 * Removes callback that was installed by AddMemoryAllocationCallback.
4833 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
4836 * Initializes from snapshot if possible. Otherwise, attempts to
4837 * initialize from scratch. This function is called implicitly if
4838 * you use the API without calling it first.
4840 static bool Initialize();
4843 * Allows the host application to provide a callback which can be used
4844 * as a source of entropy for random number generators.
4846 static void SetEntropySource(EntropySource source);
4849 * Allows the host application to provide a callback that allows v8 to
4850 * cooperate with a profiler that rewrites return addresses on stack.
4852 static void SetReturnAddressLocationResolver(
4853 ReturnAddressLocationResolver return_address_resolver);
4856 * Allows the host application to provide the address of a function that's
4857 * invoked on entry to every V8-generated function.
4858 * Note that \p entry_hook is invoked at the very start of each
4859 * generated function.
4861 * \param isolate the isolate to operate on.
4862 * \param entry_hook a function that will be invoked on entry to every
4863 * V8-generated function.
4864 * \returns true on success on supported platforms, false on failure.
4865 * \note Setting an entry hook can only be done very early in an isolates
4866 * lifetime, and once set, the entry hook cannot be revoked.
4868 static bool SetFunctionEntryHook(Isolate* isolate,
4869 FunctionEntryHook entry_hook);
4872 * Allows the host application to provide the address of a function that is
4873 * notified each time code is added, moved or removed.
4875 * \param options options for the JIT code event handler.
4876 * \param event_handler the JIT code event handler, which will be invoked
4877 * each time code is added, moved or removed.
4878 * \note \p event_handler won't get notified of existent code.
4879 * \note since code removal notifications are not currently issued, the
4880 * \p event_handler may get notifications of code that overlaps earlier
4881 * code notifications. This happens when code areas are reused, and the
4882 * earlier overlapping code areas should therefore be discarded.
4883 * \note the events passed to \p event_handler and the strings they point to
4884 * are not guaranteed to live past each call. The \p event_handler must
4885 * copy strings and other parameters it needs to keep around.
4886 * \note the set of events declared in JitCodeEvent::EventType is expected to
4887 * grow over time, and the JitCodeEvent structure is expected to accrue
4888 * new members. The \p event_handler function must ignore event codes
4889 * it does not recognize to maintain future compatibility.
4891 static void SetJitCodeEventHandler(JitCodeEventOptions options,
4892 JitCodeEventHandler event_handler);
4895 * Forcefully terminate the current thread of JavaScript execution
4896 * in the given isolate.
4898 * This method can be used by any thread even if that thread has not
4899 * acquired the V8 lock with a Locker object.
4901 * \param isolate The isolate in which to terminate the current JS execution.
4903 static void TerminateExecution(Isolate* isolate);
4906 * Is V8 terminating JavaScript execution.
4908 * Returns true if JavaScript execution is currently terminating
4909 * because of a call to TerminateExecution. In that case there are
4910 * still JavaScript frames on the stack and the termination
4911 * exception is still active.
4913 * \param isolate The isolate in which to check.
4915 static bool IsExecutionTerminating(Isolate* isolate = NULL);
4918 * Resume execution capability in the given isolate, whose execution
4919 * was previously forcefully terminated using TerminateExecution().
4921 * When execution is forcefully terminated using TerminateExecution(),
4922 * the isolate can not resume execution until all JavaScript frames
4923 * have propagated the uncatchable exception which is generated. This
4924 * method allows the program embedding the engine to handle the
4925 * termination event and resume execution capability, even if
4926 * JavaScript frames remain on the stack.
4928 * This method can be used by any thread even if that thread has not
4929 * acquired the V8 lock with a Locker object.
4931 * \param isolate The isolate in which to resume execution capability.
4933 static void CancelTerminateExecution(Isolate* isolate);
4936 * Releases any resources used by v8 and stops any utility threads
4937 * that may be running. Note that disposing v8 is permanent, it
4938 * cannot be reinitialized.
4940 * It should generally not be necessary to dispose v8 before exiting
4941 * a process, this should happen automatically. It is only necessary
4942 * to use if the process needs the resources taken up by v8.
4944 static bool Dispose();
4947 * Iterates through all external resources referenced from current isolate
4948 * heap. GC is not invoked prior to iterating, therefore there is no
4949 * guarantee that visited objects are still alive.
4951 static void VisitExternalResources(ExternalResourceVisitor* visitor);
4954 * Iterates through all the persistent handles in the current isolate's heap
4955 * that have class_ids.
4957 static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
4960 * Iterates through all the persistent handles in the current isolate's heap
4961 * that have class_ids and are candidates to be marked as partially dependent
4962 * handles. This will visit handles to young objects created since the last
4963 * garbage collection but is free to visit an arbitrary superset of these
4966 static void VisitHandlesForPartialDependence(
4967 Isolate* isolate, PersistentHandleVisitor* visitor);
4970 * Optional notification that the embedder is idle.
4971 * V8 uses the notification to reduce memory footprint.
4972 * This call can be used repeatedly if the embedder remains idle.
4973 * Returns true if the embedder should stop calling IdleNotification
4974 * until real work has been done. This indicates that V8 has done
4975 * as much cleanup as it will be able to do.
4977 * The hint argument specifies the amount of work to be done in the function
4978 * on scale from 1 to 1000. There is no guarantee that the actual work will
4981 static bool IdleNotification(int hint = 1000);
4984 * Optional notification that the system is running low on memory.
4985 * V8 uses these notifications to attempt to free memory.
4987 static void LowMemoryNotification();
4990 * Optional notification that a context has been disposed. V8 uses
4991 * these notifications to guide the GC heuristic. Returns the number
4992 * of context disposals - including this one - since the last time
4993 * V8 had a chance to clean up.
4995 static int ContextDisposedNotification();
4998 * Initialize the ICU library bundled with V8. The embedder should only
4999 * invoke this method when using the bundled ICU. Returns true on success.
5001 * If V8 was compiled with the ICU data in an external file, the location
5002 * of the data file has to be provided.
5004 static bool InitializeICU(const char* icu_data_file = NULL);
5007 * Sets the v8::Platform to use. This should be invoked before V8 is
5010 static void InitializePlatform(Platform* platform);
5013 * Clears all references to the v8::Platform. This should be invoked after
5016 static void ShutdownPlatform();
5021 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5022 internal::Object** handle);
5023 static internal::Object** CopyPersistent(internal::Object** handle);
5024 static void DisposeGlobal(internal::Object** global_handle);
5025 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5026 static void MakeWeak(internal::Object** global_handle,
5028 WeakCallback weak_callback);
5029 static void* ClearWeak(internal::Object** global_handle);
5030 static void Eternalize(Isolate* isolate,
5033 static Local<Value> GetEternal(Isolate* isolate, int index);
5035 template <class T> friend class Handle;
5036 template <class T> friend class Local;
5037 template <class T> friend class Eternal;
5038 template <class T> friend class PersistentBase;
5039 template <class T, class M> friend class Persistent;
5040 friend class Context;
5045 * An external exception handler.
5047 class V8_EXPORT TryCatch {
5050 * Creates a new try/catch block and registers it with v8. Note that
5051 * all TryCatch blocks should be stack allocated because the memory
5052 * location itself is compared against JavaScript try/catch blocks.
5057 * Unregisters and deletes this try/catch block.
5062 * Returns true if an exception has been caught by this try/catch block.
5064 bool HasCaught() const;
5067 * For certain types of exceptions, it makes no sense to continue execution.
5069 * If CanContinue returns false, the correct action is to perform any C++
5070 * cleanup needed and then return. If CanContinue returns false and
5071 * HasTerminated returns true, it is possible to call
5072 * CancelTerminateExecution in order to continue calling into the engine.
5074 bool CanContinue() const;
5077 * Returns true if an exception has been caught due to script execution
5080 * There is no JavaScript representation of an execution termination
5081 * exception. Such exceptions are thrown when the TerminateExecution
5082 * methods are called to terminate a long-running script.
5084 * If such an exception has been thrown, HasTerminated will return true,
5085 * indicating that it is possible to call CancelTerminateExecution in order
5086 * to continue calling into the engine.
5088 bool HasTerminated() const;
5091 * Throws the exception caught by this TryCatch in a way that avoids
5092 * it being caught again by this same TryCatch. As with ThrowException
5093 * it is illegal to execute any JavaScript operations after calling
5094 * ReThrow; the caller must return immediately to where the exception
5097 Handle<Value> ReThrow();
5100 * Returns the exception caught by this try/catch block. If no exception has
5101 * been caught an empty handle is returned.
5103 * The returned handle is valid until this TryCatch block has been destroyed.
5105 Local<Value> Exception() const;
5108 * Returns the .stack property of the thrown object. If no .stack
5109 * property is present an empty handle is returned.
5111 Local<Value> StackTrace() const;
5114 * Returns the message associated with this exception. If there is
5115 * no message associated an empty handle is returned.
5117 * The returned handle is valid until this TryCatch block has been
5120 Local<v8::Message> Message() const;
5123 * Clears any exceptions that may have been caught by this try/catch block.
5124 * After this method has been called, HasCaught() will return false.
5126 * It is not necessary to clear a try/catch block before using it again; if
5127 * another exception is thrown the previously caught exception will just be
5128 * overwritten. However, it is often a good idea since it makes it easier
5129 * to determine which operation threw a given exception.
5134 * Set verbosity of the external exception handler.
5136 * By default, exceptions that are caught by an external exception
5137 * handler are not reported. Call SetVerbose with true on an
5138 * external exception handler to have exceptions caught by the
5139 * handler reported as if they were not caught.
5141 void SetVerbose(bool value);
5144 * Set whether or not this TryCatch should capture a Message object
5145 * which holds source information about where the exception
5146 * occurred. True by default.
5148 void SetCaptureMessage(bool value);
5151 * There are cases when the raw address of C++ TryCatch object cannot be
5152 * used for comparisons with addresses into the JS stack. The cases are:
5153 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5154 * 2) Address sanitizer allocates local C++ object in the heap when
5155 * UseAfterReturn mode is enabled.
5156 * This method returns address that can be used for comparisons with
5157 * addresses into the JS stack. When neither simulator nor ASAN's
5158 * UseAfterReturn is enabled, then the address returned will be the address
5159 * of the C++ try catch handler itself.
5161 static void* JSStackComparableAddress(v8::TryCatch* handler) {
5162 if (handler == NULL) return NULL;
5163 return handler->js_stack_comparable_address_;
5167 // Make it hard to create heap-allocated TryCatch blocks.
5168 TryCatch(const TryCatch&);
5169 void operator=(const TryCatch&);
5170 void* operator new(size_t size);
5171 void operator delete(void*, size_t);
5173 v8::internal::Isolate* isolate_;
5174 v8::TryCatch* next_;
5177 void* message_script_;
5178 void* js_stack_comparable_address_;
5179 int message_start_pos_;
5180 int message_end_pos_;
5181 bool is_verbose_ : 1;
5182 bool can_continue_ : 1;
5183 bool capture_message_ : 1;
5185 bool has_terminated_ : 1;
5187 friend class v8::internal::Isolate;
5195 * A container for extension names.
5197 class V8_EXPORT ExtensionConfiguration {
5199 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
5200 ExtensionConfiguration(int name_count, const char* names[])
5201 : name_count_(name_count), names_(names) { }
5203 const char** begin() const { return &names_[0]; }
5204 const char** end() const { return &names_[name_count_]; }
5207 const int name_count_;
5208 const char** names_;
5213 * A sandboxed execution context with its own set of built-in objects
5216 class V8_EXPORT Context {
5219 * Returns the global proxy object.
5221 * Global proxy object is a thin wrapper whose prototype points to actual
5222 * context's global object with the properties like Object, etc. This is done
5223 * that way for security reasons (for more details see
5224 * https://wiki.mozilla.org/Gecko:SplitWindow).
5226 * Please note that changes to global proxy object prototype most probably
5227 * would break VM---v8 expects only global object as a prototype of global
5230 Local<Object> Global();
5233 * Detaches the global object from its context before
5234 * the global object can be reused to create a new context.
5236 void DetachGlobal();
5239 * Creates a new context and returns a handle to the newly allocated
5242 * \param isolate The isolate in which to create the context.
5244 * \param extensions An optional extension configuration containing
5245 * the extensions to be installed in the newly created context.
5247 * \param global_template An optional object template from which the
5248 * global object for the newly created context will be created.
5250 * \param global_object An optional global object to be reused for
5251 * the newly created context. This global object must have been
5252 * created by a previous call to Context::New with the same global
5253 * template. The state of the global object will be completely reset
5254 * and only object identify will remain.
5256 static Local<Context> New(
5258 ExtensionConfiguration* extensions = NULL,
5259 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5260 Handle<Value> global_object = Handle<Value>());
5263 * Sets the security token for the context. To access an object in
5264 * another context, the security tokens must match.
5266 void SetSecurityToken(Handle<Value> token);
5268 /** Restores the security token to the default value. */
5269 void UseDefaultSecurityToken();
5271 /** Returns the security token of this context.*/
5272 Handle<Value> GetSecurityToken();
5275 * Enter this context. After entering a context, all code compiled
5276 * and run is compiled and run in this context. If another context
5277 * is already entered, this old context is saved so it can be
5278 * restored when the new context is exited.
5283 * Exit this context. Exiting the current context restores the
5284 * context that was in place when entering the current context.
5289 * Returns true if the context has experienced an out of memory situation.
5290 * Since V8 always treats OOM as fatal error, this can no longer return true.
5291 * Therefore this is now deprecated.
5293 V8_DEPRECATED("This can no longer happen. OOM is a fatal error.",
5294 bool HasOutOfMemoryException()) { return false; }
5296 /** Returns an isolate associated with a current context. */
5297 v8::Isolate* GetIsolate();
5300 * Gets the embedder data with the given index, which must have been set by a
5301 * previous call to SetEmbedderData with the same index. Note that index 0
5302 * currently has a special meaning for Chrome's debugger.
5304 V8_INLINE Local<Value> GetEmbedderData(int index);
5307 * Sets the embedder data with the given index, growing the data as
5308 * needed. Note that index 0 currently has a special meaning for Chrome's
5311 void SetEmbedderData(int index, Handle<Value> value);
5314 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5315 * index, which must have bees set by a previous call to
5316 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5317 * currently has a special meaning for Chrome's debugger.
5319 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5322 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5323 * index, growing the data as needed. Note that index 0 currently has a
5324 * special meaning for Chrome's debugger.
5326 void SetAlignedPointerInEmbedderData(int index, void* value);
5329 * Control whether code generation from strings is allowed. Calling
5330 * this method with false will disable 'eval' and the 'Function'
5331 * constructor for code running in this context. If 'eval' or the
5332 * 'Function' constructor are used an exception will be thrown.
5334 * If code generation from strings is not allowed the
5335 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5336 * set before blocking the call to 'eval' or the 'Function'
5337 * constructor. If that callback returns true, the call will be
5338 * allowed, otherwise an exception will be thrown. If no callback is
5339 * set an exception will be thrown.
5341 void AllowCodeGenerationFromStrings(bool allow);
5344 * Returns true if code generation from strings is allowed for the context.
5345 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5347 bool IsCodeGenerationFromStringsAllowed();
5350 * Sets the error description for the exception that is thrown when
5351 * code generation from strings is not allowed and 'eval' or the 'Function'
5352 * constructor are called.
5354 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5357 * Stack-allocated class which sets the execution context for all
5358 * operations executed within a local scope.
5362 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5365 V8_INLINE ~Scope() { context_->Exit(); }
5368 Handle<Context> context_;
5373 friend class Script;
5374 friend class Object;
5375 friend class Function;
5377 Local<Value> SlowGetEmbedderData(int index);
5378 void* SlowGetAlignedPointerFromEmbedderData(int index);
5383 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5384 * to use any given V8 isolate, see the comments in the Isolate class. The
5385 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5386 * object pointers obtained from V8 handles while in the particular V8 isolate.
5387 * It is up to the user of V8 to ensure, perhaps with locking, that this
5388 * constraint is not violated. In addition to any other synchronization
5389 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5390 * used to signal thead switches to V8.
5392 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5393 * construction and destruction, the current thread is allowed to use the locked
5394 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5395 * any time. In other words, the scope of a v8::Locker is a critical section.
5401 * v8::Locker locker(isolate);
5402 * v8::Isolate::Scope isolate_scope(isolate);
5404 * // Code using V8 and isolate goes here.
5406 * } // Destructor called here
5409 * If you wish to stop using V8 in a thread A you can do this either by
5410 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5416 * v8::Unlocker unlocker(isolate);
5418 * // Code not using V8 goes here while V8 can run in another thread.
5420 * } // Destructor called here.
5424 * The Unlocker object is intended for use in a long-running callback from V8,
5425 * where you want to release the V8 lock for other threads to use.
5427 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5428 * given thread. This can be useful if you have code that can be called either
5429 * from code that holds the lock or from code that does not. The Unlocker is
5430 * not recursive so you can not have several Unlockers on the stack at once, and
5431 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5433 * An unlocker will unlock several lockers if it has to and reinstate the
5434 * correct depth of locking on its destruction, e.g.:
5439 * v8::Locker locker(isolate);
5440 * Isolate::Scope isolate_scope(isolate);
5443 * v8::Locker another_locker(isolate);
5444 * // V8 still locked (2 levels).
5447 * v8::Unlocker unlocker(isolate);
5451 * // V8 locked again (2 levels).
5453 * // V8 still locked (1 level).
5455 * // V8 Now no longer locked.
5458 class V8_EXPORT Unlocker {
5461 * Initialize Unlocker for a given Isolate.
5463 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5467 void Initialize(Isolate* isolate);
5469 internal::Isolate* isolate_;
5473 class V8_EXPORT Locker {
5476 * Initialize Locker for a given Isolate.
5478 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5483 * Returns whether or not the locker for a given isolate, is locked by the
5486 static bool IsLocked(Isolate* isolate);
5489 * Returns whether v8::Locker is being used by this V8 instance.
5491 static bool IsActive();
5494 void Initialize(Isolate* isolate);
5498 internal::Isolate* isolate_;
5500 static bool active_;
5502 // Disallow copying and assigning.
5503 Locker(const Locker&);
5504 void operator=(const Locker&);
5508 // --- Implementation ---
5511 namespace internal {
5513 const int kApiPointerSize = sizeof(void*); // NOLINT
5514 const int kApiIntSize = sizeof(int); // NOLINT
5515 const int kApiInt64Size = sizeof(int64_t); // NOLINT
5517 // Tag information for HeapObject.
5518 const int kHeapObjectTag = 1;
5519 const int kHeapObjectTagSize = 2;
5520 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5522 // Tag information for Smi.
5523 const int kSmiTag = 0;
5524 const int kSmiTagSize = 1;
5525 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5527 template <size_t ptr_size> struct SmiTagging;
5529 template<int kSmiShiftSize>
5530 V8_INLINE internal::Object* IntToSmi(int value) {
5531 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5532 intptr_t tagged_value =
5533 (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
5534 return reinterpret_cast<internal::Object*>(tagged_value);
5537 // Smi constants for 32-bit systems.
5538 template <> struct SmiTagging<4> {
5539 static const int kSmiShiftSize = 0;
5540 static const int kSmiValueSize = 31;
5541 V8_INLINE static int SmiToInt(internal::Object* value) {
5542 int shift_bits = kSmiTagSize + kSmiShiftSize;
5543 // Throw away top 32 bits and shift down (requires >> to be sign extending).
5544 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5546 V8_INLINE static internal::Object* IntToSmi(int value) {
5547 return internal::IntToSmi<kSmiShiftSize>(value);
5549 V8_INLINE static bool IsValidSmi(intptr_t value) {
5550 // To be representable as an tagged small integer, the two
5551 // most-significant bits of 'value' must be either 00 or 11 due to
5552 // sign-extension. To check this we add 01 to the two
5553 // most-significant bits, and check if the most-significant bit is 0
5555 // CAUTION: The original code below:
5556 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5557 // may lead to incorrect results according to the C language spec, and
5558 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5559 // compiler may produce undefined results in case of signed integer
5560 // overflow. The computation must be done w/ unsigned ints.
5561 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5565 // Smi constants for 64-bit systems.
5566 template <> struct SmiTagging<8> {
5567 static const int kSmiShiftSize = 31;
5568 static const int kSmiValueSize = 32;
5569 V8_INLINE static int SmiToInt(internal::Object* value) {
5570 int shift_bits = kSmiTagSize + kSmiShiftSize;
5571 // Shift down and throw away top 32 bits.
5572 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5574 V8_INLINE static internal::Object* IntToSmi(int value) {
5575 return internal::IntToSmi<kSmiShiftSize>(value);
5577 V8_INLINE static bool IsValidSmi(intptr_t value) {
5578 // To be representable as a long smi, the value must be a 32-bit integer.
5579 return (value == static_cast<int32_t>(value));
5583 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5584 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5585 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5586 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5587 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5590 * This class exports constants and functionality from within v8 that
5591 * is necessary to implement inline functions in the v8 api. Don't
5592 * depend on functions and constants defined here.
5596 // These values match non-compiler-dependent values defined within
5597 // the implementation of v8.
5598 static const int kHeapObjectMapOffset = 0;
5599 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
5600 static const int kStringResourceOffset = 3 * kApiPointerSize;
5602 static const int kOddballKindOffset = 3 * kApiPointerSize;
5603 static const int kForeignAddressOffset = kApiPointerSize;
5604 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5605 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5606 static const int kContextHeaderSize = 2 * kApiPointerSize;
5607 static const int kContextEmbedderDataIndex = 89;
5608 static const int kFullStringRepresentationMask = 0x07;
5609 static const int kStringEncodingMask = 0x4;
5610 static const int kExternalTwoByteRepresentationTag = 0x02;
5611 static const int kExternalAsciiRepresentationTag = 0x06;
5613 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
5614 static const int kAmountOfExternalAllocatedMemoryOffset =
5615 4 * kApiPointerSize;
5616 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
5617 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
5618 static const int kIsolateRootsOffset =
5619 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
5621 static const int kUndefinedValueRootIndex = 5;
5622 static const int kNullValueRootIndex = 7;
5623 static const int kTrueValueRootIndex = 8;
5624 static const int kFalseValueRootIndex = 9;
5625 static const int kEmptyStringRootIndex = 175;
5627 // The external allocation limit should be below 256 MB on all architectures
5628 // to avoid that resource-constrained embedders run low on memory.
5629 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
5631 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5632 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5633 static const int kNodeStateMask = 0xf;
5634 static const int kNodeStateIsWeakValue = 2;
5635 static const int kNodeStateIsPendingValue = 3;
5636 static const int kNodeStateIsNearDeathValue = 4;
5637 static const int kNodeIsIndependentShift = 4;
5638 static const int kNodeIsPartiallyDependentShift = 5;
5640 static const int kJSObjectType = 0xc1;
5641 static const int kFirstNonstringType = 0x80;
5642 static const int kOddballType = 0x83;
5643 static const int kForeignType = 0x87;
5645 static const int kUndefinedOddballKind = 5;
5646 static const int kNullOddballKind = 3;
5648 static const uint32_t kNumIsolateDataSlots = 4;
5650 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5651 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5652 #ifdef V8_ENABLE_CHECKS
5653 CheckInitializedImpl(isolate);
5657 V8_INLINE static bool HasHeapObjectTag(internal::Object* value) {
5658 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5662 V8_INLINE static int SmiValue(internal::Object* value) {
5663 return PlatformSmiTagging::SmiToInt(value);
5666 V8_INLINE static internal::Object* IntToSmi(int value) {
5667 return PlatformSmiTagging::IntToSmi(value);
5670 V8_INLINE static bool IsValidSmi(intptr_t value) {
5671 return PlatformSmiTagging::IsValidSmi(value);
5674 V8_INLINE static int GetInstanceType(internal::Object* obj) {
5675 typedef internal::Object O;
5676 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5677 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
5680 V8_INLINE static int GetOddballKind(internal::Object* obj) {
5681 typedef internal::Object O;
5682 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5685 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5686 int representation = (instance_type & kFullStringRepresentationMask);
5687 return representation == kExternalTwoByteRepresentationTag;
5690 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5691 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5692 return *addr & static_cast<uint8_t>(1U << shift);
5695 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5696 bool value, int shift) {
5697 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5698 uint8_t mask = static_cast<uint8_t>(1 << shift);
5699 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5702 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5703 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5704 return *addr & kNodeStateMask;
5707 V8_INLINE static void UpdateNodeState(internal::Object** obj,
5709 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5710 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5713 V8_INLINE static void SetEmbedderData(v8::Isolate *isolate,
5716 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
5717 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5718 *reinterpret_cast<void**>(addr) = data;
5721 V8_INLINE static void* GetEmbedderData(v8::Isolate* isolate, uint32_t slot) {
5722 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
5723 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5724 return *reinterpret_cast<void**>(addr);
5727 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5729 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5730 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5733 template <typename T>
5734 V8_INLINE static T ReadField(internal::Object* ptr, int offset) {
5735 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
5736 return *reinterpret_cast<T*>(addr);
5739 template <typename T>
5740 V8_INLINE static T ReadEmbedderData(v8::Context* context, int index) {
5741 typedef internal::Object O;
5742 typedef internal::Internals I;
5743 O* ctx = *reinterpret_cast<O**>(context);
5744 int embedder_data_offset = I::kContextHeaderSize +
5745 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5746 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5748 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5749 return I::ReadField<T>(embedder_data, value_offset);
5753 } // namespace internal
5757 Local<T>::Local() : Handle<T>() { }
5761 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5762 return New(isolate, that.val_);
5766 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
5767 return New(isolate, that.val_);
5771 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5772 if (that == NULL) return Handle<T>();
5774 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5775 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5776 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5781 Local<T> Local<T>::New(Isolate* isolate, T* that) {
5782 if (that == NULL) return Local<T>();
5784 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5785 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5786 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5792 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5794 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
5799 Local<T> Eternal<T>::Get(Isolate* isolate) {
5800 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
5805 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
5806 if (that == NULL) return NULL;
5807 internal::Object** p = reinterpret_cast<internal::Object**>(that);
5808 return reinterpret_cast<T*>(
5809 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
5814 template <class T, class M>
5815 template <class S, class M2>
5816 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
5819 if (that.IsEmpty()) return;
5820 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
5821 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
5822 M::Copy(that, this);
5827 bool PersistentBase<T>::IsIndependent() const {
5828 typedef internal::Internals I;
5829 if (this->IsEmpty()) return false;
5830 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5831 I::kNodeIsIndependentShift);
5836 bool PersistentBase<T>::IsNearDeath() const {
5837 typedef internal::Internals I;
5838 if (this->IsEmpty()) return false;
5839 uint8_t node_state =
5840 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
5841 return node_state == I::kNodeStateIsNearDeathValue ||
5842 node_state == I::kNodeStateIsPendingValue;
5847 bool PersistentBase<T>::IsWeak() const {
5848 typedef internal::Internals I;
5849 if (this->IsEmpty()) return false;
5850 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
5851 I::kNodeStateIsWeakValue;
5856 void PersistentBase<T>::Reset() {
5857 if (this->IsEmpty()) return;
5858 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
5865 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
5868 if (other.IsEmpty()) return;
5869 this->val_ = New(isolate, other.val_);
5875 void PersistentBase<T>::Reset(Isolate* isolate,
5876 const PersistentBase<S>& other) {
5879 if (other.IsEmpty()) return;
5880 this->val_ = New(isolate, other.val_);
5885 template <typename S, typename P>
5886 void PersistentBase<T>::SetWeak(
5888 typename WeakCallbackData<S, P>::Callback callback) {
5890 typedef typename WeakCallbackData<Value, void>::Callback Callback;
5891 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
5893 reinterpret_cast<Callback>(callback));
5898 template <typename P>
5899 void PersistentBase<T>::SetWeak(
5901 typename WeakCallbackData<T, P>::Callback callback) {
5902 SetWeak<T, P>(parameter, callback);
5907 template<typename P>
5908 P* PersistentBase<T>::ClearWeak() {
5909 return reinterpret_cast<P*>(
5910 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
5915 void PersistentBase<T>::MarkIndependent() {
5916 typedef internal::Internals I;
5917 if (this->IsEmpty()) return;
5918 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5920 I::kNodeIsIndependentShift);
5925 void PersistentBase<T>::MarkPartiallyDependent() {
5926 typedef internal::Internals I;
5927 if (this->IsEmpty()) return;
5928 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5930 I::kNodeIsPartiallyDependentShift);
5934 template <class T, class M>
5935 T* Persistent<T, M>::ClearAndLeak() {
5944 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
5945 typedef internal::Internals I;
5946 if (this->IsEmpty()) return;
5947 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5948 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5949 *reinterpret_cast<uint16_t*>(addr) = class_id;
5954 uint16_t PersistentBase<T>::WrapperClassId() const {
5955 typedef internal::Internals I;
5956 if (this->IsEmpty()) return 0;
5957 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5958 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5959 return *reinterpret_cast<uint16_t*>(addr);
5963 template<typename T>
5964 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
5966 template<typename T>
5967 template<typename S>
5968 void ReturnValue<T>::Set(const Persistent<S>& handle) {
5970 if (V8_UNLIKELY(handle.IsEmpty())) {
5971 *value_ = GetDefaultValue();
5973 *value_ = *reinterpret_cast<internal::Object**>(*handle);
5977 template<typename T>
5978 template<typename S>
5979 void ReturnValue<T>::Set(const Handle<S> handle) {
5981 if (V8_UNLIKELY(handle.IsEmpty())) {
5982 *value_ = GetDefaultValue();
5984 *value_ = *reinterpret_cast<internal::Object**>(*handle);
5988 template<typename T>
5989 void ReturnValue<T>::Set(double i) {
5990 TYPE_CHECK(T, Number);
5991 Set(Number::New(GetIsolate(), i));
5994 template<typename T>
5995 void ReturnValue<T>::Set(int32_t i) {
5996 TYPE_CHECK(T, Integer);
5997 typedef internal::Internals I;
5998 if (V8_LIKELY(I::IsValidSmi(i))) {
5999 *value_ = I::IntToSmi(i);
6002 Set(Integer::New(GetIsolate(), i));
6005 template<typename T>
6006 void ReturnValue<T>::Set(uint32_t i) {
6007 TYPE_CHECK(T, Integer);
6008 // Can't simply use INT32_MAX here for whatever reason.
6009 bool fits_into_int32_t = (i & (1U << 31)) == 0;
6010 if (V8_LIKELY(fits_into_int32_t)) {
6011 Set(static_cast<int32_t>(i));
6014 Set(Integer::NewFromUnsigned(GetIsolate(), i));
6017 template<typename T>
6018 void ReturnValue<T>::Set(bool value) {
6019 TYPE_CHECK(T, Boolean);
6020 typedef internal::Internals I;
6023 root_index = I::kTrueValueRootIndex;
6025 root_index = I::kFalseValueRootIndex;
6027 *value_ = *I::GetRoot(GetIsolate(), root_index);
6030 template<typename T>
6031 void ReturnValue<T>::SetNull() {
6032 TYPE_CHECK(T, Primitive);
6033 typedef internal::Internals I;
6034 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6037 template<typename T>
6038 void ReturnValue<T>::SetUndefined() {
6039 TYPE_CHECK(T, Primitive);
6040 typedef internal::Internals I;
6041 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6044 template<typename T>
6045 void ReturnValue<T>::SetEmptyString() {
6046 TYPE_CHECK(T, String);
6047 typedef internal::Internals I;
6048 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6051 template<typename T>
6052 Isolate* ReturnValue<T>::GetIsolate() {
6053 // Isolate is always the pointer below the default value on the stack.
6054 return *reinterpret_cast<Isolate**>(&value_[-2]);
6057 template<typename T>
6058 template<typename S>
6059 void ReturnValue<T>::Set(S* whatever) {
6060 // Uncompilable to prevent inadvertent misuse.
6061 TYPE_CHECK(S*, Primitive);
6064 template<typename T>
6065 internal::Object* ReturnValue<T>::GetDefaultValue() {
6066 // Default value is always the pointer below value_ on the stack.
6071 template<typename T>
6072 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6073 internal::Object** values,
6075 bool is_construct_call)
6076 : implicit_args_(implicit_args),
6079 is_construct_call_(is_construct_call) { }
6082 template<typename T>
6083 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6084 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6085 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6089 template<typename T>
6090 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6091 return Local<Function>(reinterpret_cast<Function*>(
6092 &implicit_args_[kCalleeIndex]));
6096 template<typename T>
6097 Local<Object> FunctionCallbackInfo<T>::This() const {
6098 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6102 template<typename T>
6103 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6104 return Local<Object>(reinterpret_cast<Object*>(
6105 &implicit_args_[kHolderIndex]));
6109 template<typename T>
6110 Local<Value> FunctionCallbackInfo<T>::Data() const {
6111 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6115 template<typename T>
6116 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6117 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6121 template<typename T>
6122 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6123 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6127 template<typename T>
6128 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6129 return is_construct_call_;
6133 template<typename T>
6134 int FunctionCallbackInfo<T>::Length() const {
6139 Handle<Value> ScriptOrigin::ResourceName() const {
6140 return resource_name_;
6144 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6145 return resource_line_offset_;
6149 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6150 return resource_column_offset_;
6153 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6154 return resource_is_shared_cross_origin_;
6158 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6160 : source_string(string),
6161 resource_name(origin.ResourceName()),
6162 resource_line_offset(origin.ResourceLineOffset()),
6163 resource_column_offset(origin.ResourceColumnOffset()),
6164 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6165 cached_data(data) {}
6168 ScriptCompiler::Source::Source(Local<String> string,
6170 : source_string(string), cached_data(data) {}
6173 ScriptCompiler::Source::~Source() {
6178 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6184 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6185 return value ? True(isolate) : False(isolate);
6189 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6190 Set(v8::String::NewFromUtf8(isolate, name), value);
6194 Local<Value> Object::GetInternalField(int index) {
6195 #ifndef V8_ENABLE_CHECKS
6196 typedef internal::Object O;
6197 typedef internal::HeapObject HO;
6198 typedef internal::Internals I;
6199 O* obj = *reinterpret_cast<O**>(this);
6200 // Fast path: If the object is a plain JSObject, which is the common case, we
6201 // know where to find the internal fields and can return the value directly.
6202 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6203 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6204 O* value = I::ReadField<O*>(obj, offset);
6205 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6206 return Local<Value>(reinterpret_cast<Value*>(result));
6209 return SlowGetInternalField(index);
6213 void* Object::GetAlignedPointerFromInternalField(int index) {
6214 #ifndef V8_ENABLE_CHECKS
6215 typedef internal::Object O;
6216 typedef internal::Internals I;
6217 O* obj = *reinterpret_cast<O**>(this);
6218 // Fast path: If the object is a plain JSObject, which is the common case, we
6219 // know where to find the internal fields and can return the value directly.
6220 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6221 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6222 return I::ReadField<void*>(obj, offset);
6225 return SlowGetAlignedPointerFromInternalField(index);
6229 String* String::Cast(v8::Value* value) {
6230 #ifdef V8_ENABLE_CHECKS
6233 return static_cast<String*>(value);
6237 Local<String> String::Empty(Isolate* isolate) {
6238 typedef internal::Object* S;
6239 typedef internal::Internals I;
6240 I::CheckInitialized(isolate);
6241 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6242 return Local<String>(reinterpret_cast<String*>(slot));
6246 String::ExternalStringResource* String::GetExternalStringResource() const {
6247 typedef internal::Object O;
6248 typedef internal::Internals I;
6249 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6250 String::ExternalStringResource* result;
6251 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6252 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6253 result = reinterpret_cast<String::ExternalStringResource*>(value);
6257 #ifdef V8_ENABLE_CHECKS
6258 VerifyExternalStringResource(result);
6264 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6265 String::Encoding* encoding_out) const {
6266 typedef internal::Object O;
6267 typedef internal::Internals I;
6268 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6269 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6270 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6271 ExternalStringResourceBase* resource = NULL;
6272 if (type == I::kExternalAsciiRepresentationTag ||
6273 type == I::kExternalTwoByteRepresentationTag) {
6274 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6275 resource = static_cast<ExternalStringResourceBase*>(value);
6277 #ifdef V8_ENABLE_CHECKS
6278 VerifyExternalStringResourceBase(resource, *encoding_out);
6284 bool Value::IsUndefined() const {
6285 #ifdef V8_ENABLE_CHECKS
6286 return FullIsUndefined();
6288 return QuickIsUndefined();
6292 bool Value::QuickIsUndefined() const {
6293 typedef internal::Object O;
6294 typedef internal::Internals I;
6295 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6296 if (!I::HasHeapObjectTag(obj)) return false;
6297 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6298 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6302 bool Value::IsNull() const {
6303 #ifdef V8_ENABLE_CHECKS
6304 return FullIsNull();
6306 return QuickIsNull();
6310 bool Value::QuickIsNull() const {
6311 typedef internal::Object O;
6312 typedef internal::Internals I;
6313 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6314 if (!I::HasHeapObjectTag(obj)) return false;
6315 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6316 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6320 bool Value::IsString() const {
6321 #ifdef V8_ENABLE_CHECKS
6322 return FullIsString();
6324 return QuickIsString();
6328 bool Value::QuickIsString() const {
6329 typedef internal::Object O;
6330 typedef internal::Internals I;
6331 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6332 if (!I::HasHeapObjectTag(obj)) return false;
6333 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6337 template <class T> Value* Value::Cast(T* value) {
6338 return static_cast<Value*>(value);
6342 Symbol* Symbol::Cast(v8::Value* value) {
6343 #ifdef V8_ENABLE_CHECKS
6346 return static_cast<Symbol*>(value);
6350 Number* Number::Cast(v8::Value* value) {
6351 #ifdef V8_ENABLE_CHECKS
6354 return static_cast<Number*>(value);
6358 Integer* Integer::Cast(v8::Value* value) {
6359 #ifdef V8_ENABLE_CHECKS
6362 return static_cast<Integer*>(value);
6366 Date* Date::Cast(v8::Value* value) {
6367 #ifdef V8_ENABLE_CHECKS
6370 return static_cast<Date*>(value);
6374 StringObject* StringObject::Cast(v8::Value* value) {
6375 #ifdef V8_ENABLE_CHECKS
6378 return static_cast<StringObject*>(value);
6382 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6383 #ifdef V8_ENABLE_CHECKS
6386 return static_cast<SymbolObject*>(value);
6390 NumberObject* NumberObject::Cast(v8::Value* value) {
6391 #ifdef V8_ENABLE_CHECKS
6394 return static_cast<NumberObject*>(value);
6398 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6399 #ifdef V8_ENABLE_CHECKS
6402 return static_cast<BooleanObject*>(value);
6406 RegExp* RegExp::Cast(v8::Value* value) {
6407 #ifdef V8_ENABLE_CHECKS
6410 return static_cast<RegExp*>(value);
6414 Object* Object::Cast(v8::Value* value) {
6415 #ifdef V8_ENABLE_CHECKS
6418 return static_cast<Object*>(value);
6422 Array* Array::Cast(v8::Value* value) {
6423 #ifdef V8_ENABLE_CHECKS
6426 return static_cast<Array*>(value);
6430 Promise* Promise::Cast(v8::Value* value) {
6431 #ifdef V8_ENABLE_CHECKS
6434 return static_cast<Promise*>(value);
6438 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6439 #ifdef V8_ENABLE_CHECKS
6442 return static_cast<Promise::Resolver*>(value);
6446 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6447 #ifdef V8_ENABLE_CHECKS
6450 return static_cast<ArrayBuffer*>(value);
6454 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6455 #ifdef V8_ENABLE_CHECKS
6458 return static_cast<ArrayBufferView*>(value);
6462 TypedArray* TypedArray::Cast(v8::Value* value) {
6463 #ifdef V8_ENABLE_CHECKS
6466 return static_cast<TypedArray*>(value);
6470 Uint8Array* Uint8Array::Cast(v8::Value* value) {
6471 #ifdef V8_ENABLE_CHECKS
6474 return static_cast<Uint8Array*>(value);
6478 Int8Array* Int8Array::Cast(v8::Value* value) {
6479 #ifdef V8_ENABLE_CHECKS
6482 return static_cast<Int8Array*>(value);
6486 Uint16Array* Uint16Array::Cast(v8::Value* value) {
6487 #ifdef V8_ENABLE_CHECKS
6490 return static_cast<Uint16Array*>(value);
6494 Int16Array* Int16Array::Cast(v8::Value* value) {
6495 #ifdef V8_ENABLE_CHECKS
6498 return static_cast<Int16Array*>(value);
6502 Uint32Array* Uint32Array::Cast(v8::Value* value) {
6503 #ifdef V8_ENABLE_CHECKS
6506 return static_cast<Uint32Array*>(value);
6510 Int32Array* Int32Array::Cast(v8::Value* value) {
6511 #ifdef V8_ENABLE_CHECKS
6514 return static_cast<Int32Array*>(value);
6518 Float32Array* Float32Array::Cast(v8::Value* value) {
6519 #ifdef V8_ENABLE_CHECKS
6522 return static_cast<Float32Array*>(value);
6526 Float32x4Array* Float32x4Array::Cast(v8::Value* value) {
6527 #ifdef V8_ENABLE_CHECKS
6530 return static_cast<Float32x4Array*>(value);
6534 Float64x2Array* Float64x2Array::Cast(v8::Value* value) {
6535 #ifdef V8_ENABLE_CHECKS
6538 return static_cast<Float64x2Array*>(value);
6542 Int32x4Array* Int32x4Array::Cast(v8::Value* value) {
6543 #ifdef V8_ENABLE_CHECKS
6546 return static_cast<Int32x4Array*>(value);
6550 Float64Array* Float64Array::Cast(v8::Value* value) {
6551 #ifdef V8_ENABLE_CHECKS
6554 return static_cast<Float64Array*>(value);
6558 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6559 #ifdef V8_ENABLE_CHECKS
6562 return static_cast<Uint8ClampedArray*>(value);
6566 DataView* DataView::Cast(v8::Value* value) {
6567 #ifdef V8_ENABLE_CHECKS
6570 return static_cast<DataView*>(value);
6574 Function* Function::Cast(v8::Value* value) {
6575 #ifdef V8_ENABLE_CHECKS
6578 return static_cast<Function*>(value);
6582 External* External::Cast(v8::Value* value) {
6583 #ifdef V8_ENABLE_CHECKS
6586 return static_cast<External*>(value);
6590 template<typename T>
6591 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6592 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6596 template<typename T>
6597 Local<Value> PropertyCallbackInfo<T>::Data() const {
6598 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6602 template<typename T>
6603 Local<Object> PropertyCallbackInfo<T>::This() const {
6604 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
6608 template<typename T>
6609 Local<Object> PropertyCallbackInfo<T>::Holder() const {
6610 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6614 template<typename T>
6615 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6616 return ReturnValue<T>(&args_[kReturnValueIndex]);
6620 Handle<Primitive> Undefined(Isolate* isolate) {
6621 typedef internal::Object* S;
6622 typedef internal::Internals I;
6623 I::CheckInitialized(isolate);
6624 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6625 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6629 Handle<Primitive> Null(Isolate* isolate) {
6630 typedef internal::Object* S;
6631 typedef internal::Internals I;
6632 I::CheckInitialized(isolate);
6633 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6634 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6638 Handle<Boolean> True(Isolate* isolate) {
6639 typedef internal::Object* S;
6640 typedef internal::Internals I;
6641 I::CheckInitialized(isolate);
6642 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6643 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6647 Handle<Boolean> False(Isolate* isolate) {
6648 typedef internal::Object* S;
6649 typedef internal::Internals I;
6650 I::CheckInitialized(isolate);
6651 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6652 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6656 void Isolate::SetData(uint32_t slot, void* data) {
6657 typedef internal::Internals I;
6658 I::SetEmbedderData(this, slot, data);
6662 void* Isolate::GetData(uint32_t slot) {
6663 typedef internal::Internals I;
6664 return I::GetEmbedderData(this, slot);
6668 uint32_t Isolate::GetNumberOfDataSlots() {
6669 typedef internal::Internals I;
6670 return I::kNumIsolateDataSlots;
6674 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
6675 int64_t change_in_bytes) {
6676 typedef internal::Internals I;
6677 int64_t* amount_of_external_allocated_memory =
6678 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
6679 I::kAmountOfExternalAllocatedMemoryOffset);
6680 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
6681 reinterpret_cast<int64_t*>(
6682 reinterpret_cast<uint8_t*>(this) +
6683 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
6684 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
6685 if (change_in_bytes > 0 &&
6686 amount - *amount_of_external_allocated_memory_at_last_global_gc >
6687 I::kExternalAllocationLimit) {
6688 CollectAllGarbage("external memory allocation limit reached.");
6690 *amount_of_external_allocated_memory = amount;
6692 return *amount_of_external_allocated_memory;
6696 template<typename T>
6697 void Isolate::SetObjectGroupId(const Persistent<T>& object,
6699 TYPE_CHECK(Value, T);
6700 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6704 template<typename T>
6705 void Isolate::SetReferenceFromGroup(UniqueId id,
6706 const Persistent<T>& object) {
6707 TYPE_CHECK(Value, T);
6708 SetReferenceFromGroup(id,
6709 reinterpret_cast<v8::internal::Object**>(object.val_));
6713 template<typename T, typename S>
6714 void Isolate::SetReference(const Persistent<T>& parent,
6715 const Persistent<S>& child) {
6716 TYPE_CHECK(Object, T);
6717 TYPE_CHECK(Value, S);
6718 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6719 reinterpret_cast<v8::internal::Object**>(child.val_));
6723 Local<Value> Context::GetEmbedderData(int index) {
6724 #ifndef V8_ENABLE_CHECKS
6725 typedef internal::Object O;
6726 typedef internal::HeapObject HO;
6727 typedef internal::Internals I;
6728 HO* context = *reinterpret_cast<HO**>(this);
6730 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6731 return Local<Value>(reinterpret_cast<Value*>(result));
6733 return SlowGetEmbedderData(index);
6738 void* Context::GetAlignedPointerFromEmbedderData(int index) {
6739 #ifndef V8_ENABLE_CHECKS
6740 typedef internal::Internals I;
6741 return I::ReadEmbedderData<void*>(this, index);
6743 return SlowGetAlignedPointerFromEmbedderData(index);
6750 * A simple shell that takes a list of expressions on the
6751 * command-line and executes them.
6756 * \example process.cc