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/
24 // We reserve the V8_* prefix for macros defined in V8 public API and
25 // assume there are no name conflicts with the embedder's code.
29 // Setup for Windows DLL export/import. When building the V8 DLL the
30 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
31 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
32 // static library or building a program which uses the V8 static library neither
33 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
34 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
35 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
36 build configuration to ensure that at most one of these is set
39 #ifdef BUILDING_V8_SHARED
40 # define V8_EXPORT __declspec(dllexport)
42 # define V8_EXPORT __declspec(dllimport)
45 #endif // BUILDING_V8_SHARED
49 // Setup for Linux shared library export.
50 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
51 # ifdef BUILDING_V8_SHARED
52 # define V8_EXPORT __attribute__ ((visibility("default")))
63 * The v8 JavaScript engine.
67 class AccessorSignature;
75 class DeclaredAccessorDescriptor;
78 class FunctionTemplate;
80 class ImplementationUtilities;
88 class ObjectOperationDescriptor;
93 class RawOperationDescriptor;
106 template <class T> class Handle;
107 template <class T> class Local;
108 template <class T> class Eternal;
109 template<class T> class NonCopyablePersistentTraits;
110 template<class T> class PersistentBase;
112 class M = NonCopyablePersistentTraits<T> > class Persistent;
113 template<class T> class UniquePersistent;
114 template<class K, class V, class T> class PersistentValueMap;
115 template<class V, class T> class PersistentValueVector;
116 template<class T, class P> class WeakCallbackObject;
117 class FunctionTemplate;
118 class ObjectTemplate;
120 template<typename T> class FunctionCallbackInfo;
121 template<typename T> class PropertyCallbackInfo;
125 class DeclaredAccessorDescriptor;
126 class ObjectOperationDescriptor;
127 class RawOperationDescriptor;
128 class CallHandlerHelper;
129 class EscapableHandleScope;
130 template<typename T> class ReturnValue;
138 struct StreamedSource;
139 template<typename T> class CustomArguments;
140 class PropertyCallbackArguments;
141 class FunctionCallbackArguments;
147 * General purpose unique identifier.
151 explicit UniqueId(intptr_t data)
154 bool operator==(const UniqueId& other) const {
155 return data_ == other.data_;
158 bool operator!=(const UniqueId& other) const {
159 return data_ != other.data_;
162 bool operator<(const UniqueId& other) const {
163 return data_ < other.data_;
172 #define TYPE_CHECK(T, S) \
174 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
179 * An object reference managed by the v8 garbage collector.
181 * All objects returned from v8 have to be tracked by the garbage
182 * collector so that it knows that the objects are still alive. Also,
183 * because the garbage collector may move objects, it is unsafe to
184 * point directly to an object. Instead, all objects are stored in
185 * handles which are known by the garbage collector and updated
186 * whenever an object moves. Handles should always be passed by value
187 * (except in cases like out-parameters) and they should never be
188 * allocated on the heap.
190 * There are two types of handles: local and persistent handles.
191 * Local handles are light-weight and transient and typically used in
192 * local operations. They are managed by HandleScopes. Persistent
193 * handles can be used when storing objects across several independent
194 * operations and have to be explicitly deallocated when they're no
197 * It is safe to extract the object stored in the handle by
198 * dereferencing the handle (for instance, to extract the Object* from
199 * a Handle<Object>); the value will still be governed by a handle
200 * behind the scenes and the same rules apply to these values as to
203 template <class T> class Handle {
206 * Creates an empty handle.
208 V8_INLINE Handle() : val_(0) {}
211 * Creates a handle for the contents of the specified handle. This
212 * constructor allows you to pass handles as arguments by value and
213 * to assign between handles. However, if you try to assign between
214 * incompatible handles, for instance from a Handle<String> to a
215 * Handle<Number> it will cause a compile-time error. Assigning
216 * between compatible handles, for instance assigning a
217 * Handle<String> to a variable declared as Handle<Value>, is legal
218 * because String is a subclass of Value.
220 template <class S> V8_INLINE Handle(Handle<S> that)
221 : val_(reinterpret_cast<T*>(*that)) {
223 * This check fails when trying to convert between incompatible
224 * handles. For example, converting from a Handle<String> to a
231 * Returns true if the handle is empty.
233 V8_INLINE bool IsEmpty() const { return val_ == 0; }
236 * Sets the handle to be empty. IsEmpty() will then return true.
238 V8_INLINE void Clear() { val_ = 0; }
240 V8_INLINE T* operator->() const { return val_; }
242 V8_INLINE T* operator*() const { return val_; }
245 * Checks whether two handles are the same.
246 * Returns true if both are empty, or if the objects
247 * to which they refer are identical.
248 * The handles' references are not checked.
250 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
251 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
252 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
253 if (a == 0) return b == 0;
254 if (b == 0) return false;
258 template <class S> V8_INLINE bool operator==(
259 const PersistentBase<S>& that) const {
260 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
261 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
262 if (a == 0) return b == 0;
263 if (b == 0) return false;
268 * Checks whether two handles are different.
269 * Returns true if only one of the handles is empty, or if
270 * the objects to which they refer are different.
271 * The handles' references are not checked.
273 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
274 return !operator==(that);
277 template <class S> V8_INLINE bool operator!=(
278 const Persistent<S>& that) const {
279 return !operator==(that);
282 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
283 #ifdef V8_ENABLE_CHECKS
284 // If we're going to perform the type check then we have to check
285 // that the handle isn't empty before doing the checked cast.
286 if (that.IsEmpty()) return Handle<T>();
288 return Handle<T>(T::Cast(*that));
291 template <class S> V8_INLINE Handle<S> As() {
292 return Handle<S>::Cast(*this);
295 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
296 return New(isolate, that.val_);
298 V8_INLINE static Handle<T> New(Isolate* isolate,
299 const PersistentBase<T>& that) {
300 return New(isolate, that.val_);
305 template<class F, class M> friend class Persistent;
306 template<class F> friend class PersistentBase;
307 template<class F> friend class Handle;
308 template<class F> friend class Local;
309 template<class F> friend class FunctionCallbackInfo;
310 template<class F> friend class PropertyCallbackInfo;
311 template<class F> friend class internal::CustomArguments;
312 friend Handle<Primitive> Undefined(Isolate* isolate);
313 friend Handle<Primitive> Null(Isolate* isolate);
314 friend Handle<Boolean> True(Isolate* isolate);
315 friend Handle<Boolean> False(Isolate* isolate);
316 friend class Context;
317 friend class HandleScope;
319 friend class Private;
322 * Creates a new handle for the specified value.
324 V8_INLINE explicit Handle(T* val) : val_(val) {}
326 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
333 * A light-weight stack-allocated object handle. All operations
334 * that return objects from within v8 return them in local handles. They
335 * are created within HandleScopes, and all local handles allocated within a
336 * handle scope are destroyed when the handle scope is destroyed. Hence it
337 * is not necessary to explicitly deallocate local handles.
339 template <class T> class Local : public Handle<T> {
342 template <class S> V8_INLINE Local(Local<S> that)
343 : Handle<T>(reinterpret_cast<T*>(*that)) {
345 * This check fails when trying to convert between incompatible
346 * handles. For example, converting from a Handle<String> to a
353 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
354 #ifdef V8_ENABLE_CHECKS
355 // If we're going to perform the type check then we have to check
356 // that the handle isn't empty before doing the checked cast.
357 if (that.IsEmpty()) return Local<T>();
359 return Local<T>(T::Cast(*that));
361 template <class S> V8_INLINE Local(Handle<S> that)
362 : Handle<T>(reinterpret_cast<T*>(*that)) {
366 template <class S> V8_INLINE Local<S> As() {
367 return Local<S>::Cast(*this);
371 * Create a local handle for the content of another handle.
372 * The referee is kept alive by the local handle even when
373 * the original handle is destroyed/disposed.
375 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
376 V8_INLINE static Local<T> New(Isolate* isolate,
377 const PersistentBase<T>& that);
381 template<class F> friend class Eternal;
382 template<class F> friend class PersistentBase;
383 template<class F, class M> friend class Persistent;
384 template<class F> friend class Handle;
385 template<class F> friend class Local;
386 template<class F> friend class FunctionCallbackInfo;
387 template<class F> friend class PropertyCallbackInfo;
390 friend class Context;
391 template<class F> friend class internal::CustomArguments;
392 friend class HandleScope;
393 friend class EscapableHandleScope;
394 template<class F1, class F2, class F3> friend class PersistentValueMap;
395 template<class F1, class F2> friend class PersistentValueVector;
397 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
398 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
402 // Eternal handles are set-once handles that live for the life of the isolate.
403 template <class T> class Eternal {
405 V8_INLINE Eternal() : index_(kInitialValue) { }
407 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
408 Set(isolate, handle);
410 // Can only be safely called if already set.
411 V8_INLINE Local<T> Get(Isolate* isolate);
412 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
413 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
416 static const int kInitialValue = -1;
421 template<class T, class P>
422 class WeakCallbackData {
424 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
426 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
427 V8_INLINE Local<T> GetValue() const { return handle_; }
428 V8_INLINE P* GetParameter() const { return parameter_; }
431 friend class internal::GlobalHandles;
432 WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
433 : isolate_(isolate), handle_(handle), parameter_(parameter) { }
441 * An object reference that is independent of any handle scope. Where
442 * a Local handle only lives as long as the HandleScope in which it was
443 * allocated, a PersistentBase handle remains valid until it is explicitly
446 * A persistent handle contains a reference to a storage cell within
447 * the v8 engine which holds an object value and which is updated by
448 * the garbage collector whenever the object is moved. A new storage
449 * cell can be created using the constructor or PersistentBase::Reset and
450 * existing handles can be disposed using PersistentBase::Reset.
453 template <class T> class PersistentBase {
456 * If non-empty, destroy the underlying storage cell
457 * IsEmpty() will return true after this call.
459 V8_INLINE void Reset();
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 Handle<S>& other);
468 * If non-empty, destroy the underlying storage cell
469 * and create a new one with the contents of other if other is non empty
472 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
474 V8_INLINE bool IsEmpty() const { return val_ == 0; }
477 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
478 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
479 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
480 if (a == 0) return b == 0;
481 if (b == 0) return false;
485 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
486 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
487 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
488 if (a == 0) return b == 0;
489 if (b == 0) return false;
494 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
495 return !operator==(that);
498 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
499 return !operator==(that);
503 * Install a finalization callback on this object.
504 * NOTE: There is no guarantee as to *when* or even *if* the callback is
505 * invoked. The invocation is performed solely on a best effort basis.
506 * As always, GC-based finalization should *not* be relied upon for any
507 * critical form of resource management!
510 V8_INLINE void SetWeak(
512 typename WeakCallbackData<T, P>::Callback callback);
514 template<typename S, typename P>
515 V8_INLINE void SetWeak(
517 typename WeakCallbackData<S, P>::Callback callback);
519 // Phantom persistents work like weak persistents, except that the pointer to
520 // the object being collected is not available in the finalization callback.
521 // This enables the garbage collector to collect the object and any objects
522 // it references transitively in one GC cycle.
523 template <typename P>
524 V8_INLINE void SetPhantom(P* parameter,
525 typename WeakCallbackData<T, P>::Callback callback);
527 template <typename S, typename P>
528 V8_INLINE void SetPhantom(P* parameter,
529 typename WeakCallbackData<S, P>::Callback callback);
532 V8_INLINE P* ClearWeak();
534 // TODO(dcarney): remove this.
535 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
538 * Marks the reference to this object independent. Garbage collector is free
539 * to ignore any object groups containing this object. Weak callback for an
540 * independent handle should not assume that it will be preceded by a global
541 * GC prologue callback or followed by a global GC epilogue callback.
543 V8_INLINE void MarkIndependent();
546 * Marks the reference to this object partially dependent. Partially dependent
547 * handles only depend on other partially dependent handles and these
548 * dependencies are provided through object groups. It provides a way to build
549 * smaller object groups for young objects that represent only a subset of all
550 * external dependencies. This mark is automatically cleared after each
551 * garbage collection.
553 V8_INLINE void MarkPartiallyDependent();
555 V8_INLINE bool IsIndependent() const;
557 /** Checks if the handle holds the only reference to an object. */
558 V8_INLINE bool IsNearDeath() const;
560 /** Returns true if the handle's reference is weak. */
561 V8_INLINE bool IsWeak() const;
564 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
565 * description in v8-profiler.h for details.
567 V8_INLINE void SetWrapperClassId(uint16_t class_id);
570 * Returns the class ID previously assigned to this handle or 0 if no class ID
571 * was previously assigned.
573 V8_INLINE uint16_t WrapperClassId() const;
576 friend class Isolate;
578 template<class F> friend class Handle;
579 template<class F> friend class Local;
580 template<class F1, class F2> friend class Persistent;
581 template<class F> friend class UniquePersistent;
582 template<class F> friend class PersistentBase;
583 template<class F> friend class ReturnValue;
584 template<class F1, class F2, class F3> friend class PersistentValueMap;
585 template<class F1, class F2> friend class PersistentValueVector;
588 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
589 PersistentBase(PersistentBase& other); // NOLINT
590 void operator=(PersistentBase&);
591 V8_INLINE static T* New(Isolate* isolate, T* that);
598 * Default traits for Persistent. This class does not allow
599 * use of the copy constructor or assignment operator.
600 * At present kResetInDestructor is not set, but that will change in a future
604 class NonCopyablePersistentTraits {
606 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
607 static const bool kResetInDestructor = false;
608 template<class S, class M>
609 V8_INLINE static void Copy(const Persistent<S, M>& source,
610 NonCopyablePersistent* dest) {
611 Uncompilable<Object>();
613 // TODO(dcarney): come up with a good compile error here.
614 template<class O> V8_INLINE static void Uncompilable() {
615 TYPE_CHECK(O, Primitive);
621 * Helper class traits to allow copying and assignment of Persistent.
622 * This will clone the contents of storage cell, but not any of the flags, etc.
625 struct CopyablePersistentTraits {
626 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
627 static const bool kResetInDestructor = true;
628 template<class S, class M>
629 static V8_INLINE void Copy(const Persistent<S, M>& source,
630 CopyablePersistent* dest) {
631 // do nothing, just allow copy
637 * A PersistentBase which allows copy and assignment.
639 * Copy, assignment and destructor bevavior is controlled by the traits
642 * Note: Persistent class hierarchy is subject to future changes.
644 template <class T, class M> class Persistent : public PersistentBase<T> {
647 * A Persistent with no storage cell.
649 V8_INLINE Persistent() : PersistentBase<T>(0) { }
651 * Construct a Persistent from a Handle.
652 * When the Handle is non-empty, a new storage cell is created
653 * pointing to the same object, and no flags are set.
655 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
656 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
660 * Construct a Persistent from a Persistent.
661 * When the Persistent is non-empty, a new storage cell is created
662 * pointing to the same object, and no flags are set.
664 template <class S, class M2>
665 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
666 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
670 * The copy constructors and assignment operator create a Persistent
671 * exactly as the Persistent constructor, but the Copy function from the
672 * traits class is called, allowing the setting of flags based on the
675 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
678 template <class S, class M2>
679 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
682 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
686 template <class S, class M2>
687 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
692 * The destructor will dispose the Persistent based on the
693 * kResetInDestructor flags in the traits class. Since not calling dispose
694 * can result in a memory leak, it is recommended to always set this flag.
696 V8_INLINE ~Persistent() {
697 if (M::kResetInDestructor) this->Reset();
700 // TODO(dcarney): this is pretty useless, fix or remove
702 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
703 #ifdef V8_ENABLE_CHECKS
704 // If we're going to perform the type check then we have to check
705 // that the handle isn't empty before doing the checked cast.
706 if (!that.IsEmpty()) T::Cast(*that);
708 return reinterpret_cast<Persistent<T>&>(that);
711 // TODO(dcarney): this is pretty useless, fix or remove
712 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
713 return Persistent<S>::Cast(*this);
717 friend class Isolate;
719 template<class F> friend class Handle;
720 template<class F> friend class Local;
721 template<class F1, class F2> friend class Persistent;
722 template<class F> friend class ReturnValue;
724 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
725 V8_INLINE T* operator*() const { return this->val_; }
726 template<class S, class M2>
727 V8_INLINE void Copy(const Persistent<S, M2>& that);
732 * A PersistentBase which has move semantics.
734 * Note: Persistent class hierarchy is subject to future changes.
737 class UniquePersistent : public PersistentBase<T> {
739 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
740 UniquePersistent* object;
745 * A UniquePersistent with no storage cell.
747 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
749 * Construct a UniquePersistent from a Handle.
750 * When the Handle is non-empty, a new storage cell is created
751 * pointing to the same object, and no flags are set.
754 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
755 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
759 * Construct a UniquePersistent from a PersistentBase.
760 * When the Persistent is non-empty, a new storage cell is created
761 * pointing to the same object, and no flags are set.
764 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
765 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
771 V8_INLINE UniquePersistent(RValue rvalue)
772 : PersistentBase<T>(rvalue.object->val_) {
773 rvalue.object->val_ = 0;
775 V8_INLINE ~UniquePersistent() { this->Reset(); }
777 * Move via assignment.
780 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
783 this->val_ = rhs.val_;
788 * Cast operator for moves.
790 V8_INLINE operator RValue() { return RValue(this); }
792 * Pass allows returning uniques from functions, etc.
794 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
797 UniquePersistent(UniquePersistent&);
798 void operator=(UniquePersistent&);
803 * A stack-allocated class that governs a number of local handles.
804 * After a handle scope has been created, all local handles will be
805 * allocated within that handle scope until either the handle scope is
806 * deleted or another handle scope is created. If there is already a
807 * handle scope and a new one is created, all allocations will take
808 * place in the new handle scope until it is deleted. After that,
809 * new handles will again be allocated in the original handle scope.
811 * After the handle scope of a local handle has been deleted the
812 * garbage collector will no longer track the object stored in the
813 * handle and may deallocate it. The behavior of accessing a handle
814 * for which the handle scope has been deleted is undefined.
816 class V8_EXPORT HandleScope {
818 HandleScope(Isolate* isolate);
823 * Counts the number of allocated handles.
825 static int NumberOfHandles(Isolate* isolate);
827 V8_INLINE Isolate* GetIsolate() const {
828 return reinterpret_cast<Isolate*>(isolate_);
832 V8_INLINE HandleScope() {}
834 void Initialize(Isolate* isolate);
836 static internal::Object** CreateHandle(internal::Isolate* isolate,
837 internal::Object* value);
840 // Uses heap_object to obtain the current Isolate.
841 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
842 internal::Object* value);
844 // Make it hard to create heap-allocated or illegal handle scopes by
845 // disallowing certain operations.
846 HandleScope(const HandleScope&);
847 void operator=(const HandleScope&);
848 void* operator new(size_t size);
849 void operator delete(void*, size_t);
851 internal::Isolate* isolate_;
852 internal::Object** prev_next_;
853 internal::Object** prev_limit_;
855 // Local::New uses CreateHandle with an Isolate* parameter.
856 template<class F> friend class Local;
858 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
859 // a HeapObject* in their shortcuts.
861 friend class Context;
866 * A HandleScope which first allocates a handle in the current scope
867 * which will be later filled with the escape value.
869 class V8_EXPORT EscapableHandleScope : public HandleScope {
871 EscapableHandleScope(Isolate* isolate);
872 V8_INLINE ~EscapableHandleScope() {}
875 * Pushes the value into the previous scope and returns a handle to it.
876 * Cannot be called twice.
879 V8_INLINE Local<T> Escape(Local<T> value) {
880 internal::Object** slot =
881 Escape(reinterpret_cast<internal::Object**>(*value));
882 return Local<T>(reinterpret_cast<T*>(slot));
886 internal::Object** Escape(internal::Object** escape_value);
888 // Make it hard to create heap-allocated or illegal handle scopes by
889 // disallowing certain operations.
890 EscapableHandleScope(const EscapableHandleScope&);
891 void operator=(const EscapableHandleScope&);
892 void* operator new(size_t size);
893 void operator delete(void*, size_t);
895 internal::Object** escape_slot_;
900 * A simple Maybe type, representing an object which may or may not have a
905 Maybe() : has_value(false) {}
906 explicit Maybe(T t) : has_value(true), value(t) {}
907 Maybe(bool has, T t) : has_value(has), value(t) {}
914 // Convenience wrapper.
916 inline Maybe<T> maybe(T t) {
921 // --- Special objects ---
925 * The superclass of values and API object templates.
927 class V8_EXPORT Data {
934 * The origin, within a file, of a script.
938 V8_INLINE ScriptOrigin(
939 Handle<Value> resource_name,
940 Handle<Integer> resource_line_offset = Handle<Integer>(),
941 Handle<Integer> resource_column_offset = Handle<Integer>(),
942 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
943 Handle<Integer> script_id = Handle<Integer>())
944 : resource_name_(resource_name),
945 resource_line_offset_(resource_line_offset),
946 resource_column_offset_(resource_column_offset),
947 resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
948 script_id_(script_id) { }
949 V8_INLINE Handle<Value> ResourceName() const;
950 V8_INLINE Handle<Integer> ResourceLineOffset() const;
951 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
952 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
953 V8_INLINE Handle<Integer> ScriptID() const;
955 Handle<Value> resource_name_;
956 Handle<Integer> resource_line_offset_;
957 Handle<Integer> resource_column_offset_;
958 Handle<Boolean> resource_is_shared_cross_origin_;
959 Handle<Integer> script_id_;
964 * A compiled JavaScript script, not yet tied to a Context.
966 class V8_EXPORT UnboundScript {
969 * Binds the script to the currently entered context.
971 Local<Script> BindToCurrentContext();
974 Handle<Value> GetScriptName();
977 * Data read from magic sourceURL comments.
979 Handle<Value> GetSourceURL();
981 * Data read from magic sourceMappingURL comments.
983 Handle<Value> GetSourceMappingURL();
986 * Returns zero based line number of the code_pos location in the script.
987 * -1 will be returned if no information available.
989 int GetLineNumber(int code_pos);
991 static const int kNoScriptId = 0;
996 * A compiled JavaScript script, tied to a Context which was active when the
997 * script was compiled.
999 class V8_EXPORT Script {
1002 * A shorthand for ScriptCompiler::Compile().
1004 static Local<Script> Compile(Handle<String> source,
1005 ScriptOrigin* origin = NULL);
1007 // To be decprecated, use the Compile above.
1008 static Local<Script> Compile(Handle<String> source,
1009 Handle<String> file_name);
1012 * Runs the script returning the resulting value. It will be run in the
1013 * context in which it was created (ScriptCompiler::CompileBound or
1014 * UnboundScript::BindToGlobalContext()).
1019 * Returns the corresponding context-unbound script.
1021 Local<UnboundScript> GetUnboundScript();
1023 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1025 return GetUnboundScript()->GetId();
1031 * For compiling scripts.
1033 class V8_EXPORT ScriptCompiler {
1036 * Compilation data that the embedder can cache and pass back to speed up
1037 * future compilations. The data is produced if the CompilerOptions passed to
1038 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1039 * = true. The data to cache can then can be retrieved from
1042 struct V8_EXPORT CachedData {
1048 CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1050 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1051 // data and guarantees that it stays alive until the CachedData object is
1052 // destroyed. If the policy is BufferOwned, the given data will be deleted
1053 // (with delete[]) when the CachedData object is destroyed.
1054 CachedData(const uint8_t* data, int length,
1055 BufferPolicy buffer_policy = BufferNotOwned);
1057 // TODO(marja): Async compilation; add constructors which take a callback
1058 // which will be called when V8 no longer needs the data.
1059 const uint8_t* data;
1061 BufferPolicy buffer_policy;
1064 // Prevent copying. Not implemented.
1065 CachedData(const CachedData&);
1066 CachedData& operator=(const CachedData&);
1070 * Source code which can be then compiled to a UnboundScript or Script.
1074 // Source takes ownership of CachedData.
1075 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1076 CachedData* cached_data = NULL);
1077 V8_INLINE Source(Local<String> source_string,
1078 CachedData* cached_data = NULL);
1079 V8_INLINE ~Source();
1081 // Ownership of the CachedData or its buffers is *not* transferred to the
1082 // caller. The CachedData object is alive as long as the Source object is
1084 V8_INLINE const CachedData* GetCachedData() const;
1087 friend class ScriptCompiler;
1088 // Prevent copying. Not implemented.
1089 Source(const Source&);
1090 Source& operator=(const Source&);
1092 Local<String> source_string;
1094 // Origin information
1095 Handle<Value> resource_name;
1096 Handle<Integer> resource_line_offset;
1097 Handle<Integer> resource_column_offset;
1098 Handle<Boolean> resource_is_shared_cross_origin;
1100 // Cached data from previous compilation (if a kConsume*Cache flag is
1101 // set), or hold newly generated cache data (kProduce*Cache flags) are
1102 // set when calling a compile method.
1103 CachedData* cached_data;
1107 * For streaming incomplete script data to V8. The embedder should implement a
1108 * subclass of this class.
1110 class ExternalSourceStream {
1112 virtual ~ExternalSourceStream() {}
1115 * V8 calls this to request the next chunk of data from the embedder. This
1116 * function will be called on a background thread, so it's OK to block and
1117 * wait for the data, if the embedder doesn't have data yet. Returns the
1118 * length of the data returned. When the data ends, GetMoreData should
1119 * return 0. Caller takes ownership of the data.
1121 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1122 * two data chunks, but doesn't handle multi-byte characters split between
1123 * more than two data chunks. The embedder can avoid this problem by always
1124 * returning at least 2 bytes of data.
1126 * If the embedder wants to cancel the streaming, they should make the next
1127 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1128 * probably, parsing will fail). The streaming task will return as soon as
1129 * V8 has parsed the data it received so far.
1131 virtual size_t GetMoreData(const uint8_t** src) = 0;
1136 * Source code which can be streamed into V8 in pieces. It will be parsed
1137 * while streaming. It can be compiled after the streaming is complete.
1138 * StreamedSource must be kept alive while the streaming task is ran (see
1139 * ScriptStreamingTask below).
1141 class V8_EXPORT StreamedSource {
1143 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1145 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1148 // Ownership of the CachedData or its buffers is *not* transferred to the
1149 // caller. The CachedData object is alive as long as the StreamedSource
1151 const CachedData* GetCachedData() const;
1153 internal::StreamedSource* impl() const { return impl_; }
1156 // Prevent copying. Not implemented.
1157 StreamedSource(const StreamedSource&);
1158 StreamedSource& operator=(const StreamedSource&);
1160 internal::StreamedSource* impl_;
1164 * A streaming task which the embedder must run on a background thread to
1165 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1167 class ScriptStreamingTask {
1169 virtual ~ScriptStreamingTask() {}
1170 virtual void Run() = 0;
1173 enum CompileOptions {
1174 kNoCompileOptions = 0,
1175 kProduceParserCache,
1176 kConsumeParserCache,
1180 // Support the previous API for a transition period.
1185 * Compiles the specified script (context-independent).
1186 * Cached data as part of the source object can be optionally produced to be
1187 * consumed later to speed up compilation of identical source scripts.
1189 * Note that when producing cached data, the source must point to NULL for
1190 * cached data. When consuming cached data, the cached data must have been
1191 * produced by the same version of V8.
1193 * \param source Script source code.
1194 * \return Compiled script object (context independent; for running it must be
1195 * bound to a context).
1197 static Local<UnboundScript> CompileUnbound(
1198 Isolate* isolate, Source* source,
1199 CompileOptions options = kNoCompileOptions);
1202 * Compiles the specified script (bound to current context).
1204 * \param source Script source code.
1205 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1206 * using pre_data speeds compilation if it's done multiple times.
1207 * Owned by caller, no references are kept when this function returns.
1208 * \return Compiled script object, bound to the context that was active
1209 * when this function was called. When run it will always use this
1212 static Local<Script> Compile(
1213 Isolate* isolate, Source* source,
1214 CompileOptions options = kNoCompileOptions);
1217 * Returns a task which streams script data into V8, or NULL if the script
1218 * cannot be streamed. The user is responsible for running the task on a
1219 * background thread and deleting it. When ran, the task starts parsing the
1220 * script, and it will request data from the StreamedSource as needed. When
1221 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1222 * can be compiled (see Compile below).
1224 * This API allows to start the streaming with as little data as possible, and
1225 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1227 static ScriptStreamingTask* StartStreamingScript(
1228 Isolate* isolate, StreamedSource* source,
1229 CompileOptions options = kNoCompileOptions);
1232 * Compiles a streamed script (bound to current context).
1234 * This can only be called after the streaming has finished
1235 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1236 * during streaming, so the embedder needs to pass the full source here.
1238 static Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1239 Handle<String> full_source_string,
1240 const ScriptOrigin& origin);
1247 class V8_EXPORT Message {
1249 Local<String> Get() const;
1250 Local<String> GetSourceLine() const;
1253 * Returns the origin for the script from where the function causing the
1256 ScriptOrigin GetScriptOrigin() const;
1259 * Returns the resource name for the script from where the function causing
1260 * the error originates.
1262 Handle<Value> GetScriptResourceName() const;
1265 * Exception stack trace. By default stack traces are not captured for
1266 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1267 * to change this option.
1269 Handle<StackTrace> GetStackTrace() const;
1272 * Returns the number, 1-based, of the line where the error occurred.
1274 int GetLineNumber() const;
1277 * Returns the index within the script of the first character where
1278 * the error occurred.
1280 int GetStartPosition() const;
1283 * Returns the index within the script of the last character where
1284 * the error occurred.
1286 int GetEndPosition() const;
1289 * Returns the index within the line of the first character where
1290 * the error occurred.
1292 int GetStartColumn() const;
1295 * Returns the index within the line of the last character where
1296 * the error occurred.
1298 int GetEndColumn() const;
1301 * Passes on the value set by the embedder when it fed the script from which
1302 * this Message was generated to V8.
1304 bool IsSharedCrossOrigin() const;
1306 // TODO(1245381): Print to a string instead of on a FILE.
1307 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1309 static const int kNoLineNumberInfo = 0;
1310 static const int kNoColumnInfo = 0;
1311 static const int kNoScriptIdInfo = 0;
1316 * Representation of a JavaScript stack trace. The information collected is a
1317 * snapshot of the execution stack and the information remains valid after
1318 * execution continues.
1320 class V8_EXPORT StackTrace {
1323 * Flags that determine what information is placed captured for each
1324 * StackFrame when grabbing the current stack trace.
1326 enum StackTraceOptions {
1328 kColumnOffset = 1 << 1 | kLineNumber,
1329 kScriptName = 1 << 2,
1330 kFunctionName = 1 << 3,
1332 kIsConstructor = 1 << 5,
1333 kScriptNameOrSourceURL = 1 << 6,
1335 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1336 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1337 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1341 * Returns a StackFrame at a particular index.
1343 Local<StackFrame> GetFrame(uint32_t index) const;
1346 * Returns the number of StackFrames.
1348 int GetFrameCount() const;
1351 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1353 Local<Array> AsArray();
1356 * Grab a snapshot of the current JavaScript execution stack.
1358 * \param frame_limit The maximum number of stack frames we want to capture.
1359 * \param options Enumerates the set of things we will capture for each
1362 static Local<StackTrace> CurrentStackTrace(
1365 StackTraceOptions options = kOverview);
1370 * A single JavaScript stack frame.
1372 class V8_EXPORT StackFrame {
1375 * Returns the number, 1-based, of the line for the associate function call.
1376 * This method will return Message::kNoLineNumberInfo if it is unable to
1377 * retrieve the line number, or if kLineNumber was not passed as an option
1378 * when capturing the StackTrace.
1380 int GetLineNumber() const;
1383 * Returns the 1-based column offset on the line for the associated function
1385 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1386 * the column number, or if kColumnOffset was not passed as an option when
1387 * capturing the StackTrace.
1389 int GetColumn() const;
1392 * Returns the id of the script for the function for this StackFrame.
1393 * This method will return Message::kNoScriptIdInfo if it is unable to
1394 * retrieve the script id, or if kScriptId was not passed as an option when
1395 * capturing the StackTrace.
1397 int GetScriptId() const;
1400 * Returns the name of the resource that contains the script for the
1401 * function for this StackFrame.
1403 Local<String> GetScriptName() const;
1406 * Returns the name of the resource that contains the script for the
1407 * function for this StackFrame or sourceURL value if the script name
1408 * is undefined and its source ends with //# sourceURL=... string or
1409 * deprecated //@ sourceURL=... string.
1411 Local<String> GetScriptNameOrSourceURL() const;
1414 * Returns the name of the function associated with this stack frame.
1416 Local<String> GetFunctionName() const;
1419 * Returns whether or not the associated function is compiled via a call to
1422 bool IsEval() const;
1425 * Returns whether or not the associated function is called as a
1426 * constructor via "new".
1428 bool IsConstructor() const;
1432 // A StateTag represents a possible state of the VM.
1433 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1436 // A RegisterState represents the current state of registers used
1437 // by the sampling profiler API.
1438 struct RegisterState {
1439 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1440 void* pc; // Instruction pointer.
1441 void* sp; // Stack pointer.
1442 void* fp; // Frame pointer.
1446 // The output structure filled up by GetStackSample API function.
1448 size_t frames_count;
1456 class V8_EXPORT JSON {
1459 * Tries to parse the string |json_string| and returns it as value if
1462 * \param json_string The string to parse.
1463 * \return The corresponding value if successfully parsed.
1465 static Local<Value> Parse(Local<String> json_string);
1473 * The superclass of all JavaScript values and objects.
1475 class V8_EXPORT Value : public Data {
1478 * Returns true if this value is the undefined value. See ECMA-262
1481 V8_INLINE bool IsUndefined() const;
1484 * Returns true if this value is the null value. See ECMA-262
1487 V8_INLINE bool IsNull() const;
1490 * Returns true if this value is true.
1492 bool IsTrue() const;
1495 * Returns true if this value is false.
1497 bool IsFalse() const;
1500 * Returns true if this value is a symbol or a string.
1501 * This is an experimental feature.
1503 bool IsName() const;
1506 * Returns true if this value is an instance of the String type.
1509 V8_INLINE bool IsString() const;
1512 * Returns true if this value is a symbol.
1513 * This is an experimental feature.
1515 bool IsSymbol() const;
1518 * Returns true if this value is a function.
1520 bool IsFunction() const;
1523 * Returns true if this value is an array.
1525 bool IsArray() const;
1528 * Returns true if this value is an object.
1530 bool IsObject() const;
1533 * Returns true if this value is boolean.
1535 bool IsBoolean() const;
1538 * Returns true if this value is a number.
1540 bool IsNumber() const;
1543 * Returns true if this value is external.
1545 bool IsExternal() const;
1548 * Returns true if this value is a 32-bit signed integer.
1550 bool IsInt32() const;
1553 * Returns true if this value is a 32-bit unsigned integer.
1555 bool IsUint32() const;
1558 * Returns true if this value is a Date.
1560 bool IsDate() const;
1563 * Returns true if this value is an Arguments object.
1565 bool IsArgumentsObject() const;
1568 * Returns true if this value is a Boolean object.
1570 bool IsBooleanObject() const;
1573 * Returns true if this value is a Number object.
1575 bool IsNumberObject() const;
1578 * Returns true if this value is a String object.
1580 bool IsStringObject() const;
1583 * Returns true if this value is a Symbol object.
1584 * This is an experimental feature.
1586 bool IsSymbolObject() const;
1589 * Returns true if this value is a NativeError.
1591 bool IsNativeError() const;
1594 * Returns true if this value is a RegExp.
1596 bool IsRegExp() const;
1599 * Returns true if this value is a Generator function.
1600 * This is an experimental feature.
1602 bool IsGeneratorFunction() const;
1605 * Returns true if this value is a Generator object (iterator).
1606 * This is an experimental feature.
1608 bool IsGeneratorObject() const;
1611 * Returns true if this value is a Promise.
1612 * This is an experimental feature.
1614 bool IsPromise() const;
1617 * Returns true if this value is a Map.
1618 * This is an experimental feature.
1623 * Returns true if this value is a Set.
1624 * This is an experimental feature.
1629 * Returns true if this value is a Map Iterator.
1630 * This is an experimental feature.
1632 bool IsMapIterator() const;
1635 * Returns true if this value is a Set Iterator.
1636 * This is an experimental feature.
1638 bool IsSetIterator() const;
1641 * Returns true if this value is a WeakMap.
1642 * This is an experimental feature.
1644 bool IsWeakMap() const;
1647 * Returns true if this value is a WeakSet.
1648 * This is an experimental feature.
1650 bool IsWeakSet() const;
1653 * Returns true if this value is an ArrayBuffer.
1654 * This is an experimental feature.
1656 bool IsArrayBuffer() const;
1659 * Returns true if this value is an ArrayBufferView.
1660 * This is an experimental feature.
1662 bool IsArrayBufferView() const;
1665 * Returns true if this value is one of TypedArrays.
1666 * This is an experimental feature.
1668 bool IsTypedArray() const;
1671 * Returns true if this value is an Uint8Array.
1672 * This is an experimental feature.
1674 bool IsUint8Array() const;
1677 * Returns true if this value is an Uint8ClampedArray.
1678 * This is an experimental feature.
1680 bool IsUint8ClampedArray() const;
1683 * Returns true if this value is an Int8Array.
1684 * This is an experimental feature.
1686 bool IsInt8Array() const;
1689 * Returns true if this value is an Uint16Array.
1690 * This is an experimental feature.
1692 bool IsUint16Array() const;
1695 * Returns true if this value is an Int16Array.
1696 * This is an experimental feature.
1698 bool IsInt16Array() const;
1701 * Returns true if this value is an Uint32Array.
1702 * This is an experimental feature.
1704 bool IsUint32Array() const;
1707 * Returns true if this value is an Int32Array.
1708 * This is an experimental feature.
1710 bool IsInt32Array() const;
1713 * Returns true if this value is a Float32Array.
1714 * This is an experimental feature.
1716 bool IsFloat32Array() const;
1719 * Returns true if this value is a Float64Array.
1720 * This is an experimental feature.
1722 bool IsFloat64Array() const;
1725 * Returns true if this value is a DataView.
1726 * This is an experimental feature.
1728 bool IsDataView() const;
1730 Local<Boolean> ToBoolean(Isolate* isolate) const;
1731 Local<Number> ToNumber(Isolate* isolate) const;
1732 Local<String> ToString(Isolate* isolate) const;
1733 Local<String> ToDetailString(Isolate* isolate) const;
1734 Local<Object> ToObject(Isolate* isolate) const;
1735 Local<Integer> ToInteger(Isolate* isolate) const;
1736 Local<Uint32> ToUint32(Isolate* isolate) const;
1737 Local<Int32> ToInt32(Isolate* isolate) const;
1739 // TODO(dcarney): deprecate all these.
1740 inline Local<Boolean> ToBoolean() const;
1741 inline Local<Number> ToNumber() const;
1742 inline Local<String> ToString() const;
1743 inline Local<String> ToDetailString() const;
1744 inline Local<Object> ToObject() const;
1745 inline Local<Integer> ToInteger() const;
1746 inline Local<Uint32> ToUint32() const;
1747 inline Local<Int32> ToInt32() const;
1750 * Attempts to convert a string to an array index.
1751 * Returns an empty handle if the conversion fails.
1753 Local<Uint32> ToArrayIndex() const;
1755 bool BooleanValue() const;
1756 double NumberValue() const;
1757 int64_t IntegerValue() const;
1758 uint32_t Uint32Value() const;
1759 int32_t Int32Value() const;
1762 bool Equals(Handle<Value> that) const;
1763 bool StrictEquals(Handle<Value> that) const;
1764 bool SameValue(Handle<Value> that) const;
1766 template <class T> V8_INLINE static Value* Cast(T* value);
1769 V8_INLINE bool QuickIsUndefined() const;
1770 V8_INLINE bool QuickIsNull() const;
1771 V8_INLINE bool QuickIsString() const;
1772 bool FullIsUndefined() const;
1773 bool FullIsNull() const;
1774 bool FullIsString() const;
1779 * The superclass of primitive values. See ECMA-262 4.3.2.
1781 class V8_EXPORT Primitive : public Value { };
1785 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1788 class V8_EXPORT Boolean : public Primitive {
1791 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1796 * A superclass for symbols and strings.
1798 class V8_EXPORT Name : public Primitive {
1800 V8_INLINE static Name* Cast(v8::Value* obj);
1802 static void CheckCast(v8::Value* obj);
1807 * A JavaScript string value (ECMA-262, 4.3.17).
1809 class V8_EXPORT String : public Name {
1812 UNKNOWN_ENCODING = 0x1,
1813 TWO_BYTE_ENCODING = 0x0,
1814 ONE_BYTE_ENCODING = 0x4
1817 * Returns the number of characters in this string.
1822 * Returns the number of bytes in the UTF-8 encoded
1823 * representation of this string.
1825 int Utf8Length() const;
1828 * Returns whether this string is known to contain only one byte data.
1829 * Does not read the string.
1830 * False negatives are possible.
1832 bool IsOneByte() const;
1835 * Returns whether this string contain only one byte data.
1836 * Will read the entire string in some cases.
1838 bool ContainsOnlyOneByte() const;
1841 * Write the contents of the string to an external buffer.
1842 * If no arguments are given, expects the buffer to be large
1843 * enough to hold the entire string and NULL terminator. Copies
1844 * the contents of the string and the NULL terminator into the
1847 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1848 * before the end of the buffer.
1850 * Copies up to length characters into the output buffer.
1851 * Only null-terminates if there is enough space in the buffer.
1853 * \param buffer The buffer into which the string will be copied.
1854 * \param start The starting position within the string at which
1856 * \param length The number of characters to copy from the string. For
1857 * WriteUtf8 the number of bytes in the buffer.
1858 * \param nchars_ref The number of characters written, can be NULL.
1859 * \param options Various options that might affect performance of this or
1860 * subsequent operations.
1861 * \return The number of characters copied to the buffer excluding the null
1862 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1863 * including the null terminator (if written).
1867 HINT_MANY_WRITES_EXPECTED = 1,
1868 NO_NULL_TERMINATION = 2,
1869 PRESERVE_ONE_BYTE_NULL = 4,
1870 // Used by WriteUtf8 to replace orphan surrogate code units with the
1871 // unicode replacement character. Needs to be set to guarantee valid UTF-8
1873 REPLACE_INVALID_UTF8 = 8
1876 // 16-bit character codes.
1877 int Write(uint16_t* buffer,
1880 int options = NO_OPTIONS) const;
1881 // One byte characters.
1882 int WriteOneByte(uint8_t* buffer,
1885 int options = NO_OPTIONS) const;
1886 // UTF-8 encoded characters.
1887 int WriteUtf8(char* buffer,
1889 int* nchars_ref = NULL,
1890 int options = NO_OPTIONS) const;
1893 * A zero length string.
1895 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1898 * Returns true if the string is external
1900 bool IsExternal() const;
1903 * Returns true if the string is both external and one-byte.
1905 bool IsExternalOneByte() const;
1907 class V8_EXPORT ExternalStringResourceBase { // NOLINT
1909 virtual ~ExternalStringResourceBase() {}
1912 ExternalStringResourceBase() {}
1915 * Internally V8 will call this Dispose method when the external string
1916 * resource is no longer needed. The default implementation will use the
1917 * delete operator. This method can be overridden in subclasses to
1918 * control how allocated external string resources are disposed.
1920 virtual void Dispose() { delete this; }
1923 // Disallow copying and assigning.
1924 ExternalStringResourceBase(const ExternalStringResourceBase&);
1925 void operator=(const ExternalStringResourceBase&);
1927 friend class v8::internal::Heap;
1931 * An ExternalStringResource is a wrapper around a two-byte string
1932 * buffer that resides outside V8's heap. Implement an
1933 * ExternalStringResource to manage the life cycle of the underlying
1934 * buffer. Note that the string data must be immutable.
1936 class V8_EXPORT ExternalStringResource
1937 : public ExternalStringResourceBase {
1940 * Override the destructor to manage the life cycle of the underlying
1943 virtual ~ExternalStringResource() {}
1946 * The string data from the underlying buffer.
1948 virtual const uint16_t* data() const = 0;
1951 * The length of the string. That is, the number of two-byte characters.
1953 virtual size_t length() const = 0;
1956 ExternalStringResource() {}
1960 * An ExternalOneByteStringResource is a wrapper around an one-byte
1961 * string buffer that resides outside V8's heap. Implement an
1962 * ExternalOneByteStringResource to manage the life cycle of the
1963 * underlying buffer. Note that the string data must be immutable
1964 * and that the data must be Latin-1 and not UTF-8, which would require
1965 * special treatment internally in the engine and do not allow efficient
1966 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
1969 class V8_EXPORT ExternalOneByteStringResource
1970 : public ExternalStringResourceBase {
1973 * Override the destructor to manage the life cycle of the underlying
1976 virtual ~ExternalOneByteStringResource() {}
1977 /** The string data from the underlying buffer.*/
1978 virtual const char* data() const = 0;
1979 /** The number of Latin-1 characters in the string.*/
1980 virtual size_t length() const = 0;
1982 ExternalOneByteStringResource() {}
1986 * If the string is an external string, return the ExternalStringResourceBase
1987 * regardless of the encoding, otherwise return NULL. The encoding of the
1988 * string is returned in encoding_out.
1990 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1991 Encoding* encoding_out) const;
1994 * Get the ExternalStringResource for an external string. Returns
1995 * NULL if IsExternal() doesn't return true.
1997 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2000 * Get the ExternalOneByteStringResource for an external one-byte string.
2001 * Returns NULL if IsExternalOneByte() doesn't return true.
2003 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2005 V8_INLINE static String* Cast(v8::Value* obj);
2007 enum NewStringType {
2008 kNormalString, kInternalizedString, kUndetectableString
2011 /** Allocates a new string from UTF-8 data.*/
2012 static Local<String> NewFromUtf8(Isolate* isolate,
2014 NewStringType type = kNormalString,
2017 /** Allocates a new string from Latin-1 data.*/
2018 static Local<String> NewFromOneByte(
2020 const uint8_t* data,
2021 NewStringType type = kNormalString,
2024 /** Allocates a new string from UTF-16 data.*/
2025 static Local<String> NewFromTwoByte(
2027 const uint16_t* data,
2028 NewStringType type = kNormalString,
2032 * Creates a new string by concatenating the left and the right strings
2033 * passed in as parameters.
2035 static Local<String> Concat(Handle<String> left, Handle<String> right);
2038 * Creates a new external string using the data defined in the given
2039 * resource. When the external string is no longer live on V8's heap the
2040 * resource will be disposed by calling its Dispose method. The caller of
2041 * this function should not otherwise delete or modify the resource. Neither
2042 * should the underlying buffer be deallocated or modified except through the
2043 * destructor of the external string resource.
2045 static Local<String> NewExternal(Isolate* isolate,
2046 ExternalStringResource* resource);
2049 * Associate an external string resource with this string by transforming it
2050 * in place so that existing references to this string in the JavaScript heap
2051 * will use the external string resource. The external string resource's
2052 * character contents need to be equivalent to this string.
2053 * Returns true if the string has been changed to be an external string.
2054 * The string is not modified if the operation fails. See NewExternal for
2055 * information on the lifetime of the resource.
2057 bool MakeExternal(ExternalStringResource* resource);
2060 * Creates a new external string using the one-byte data defined in the given
2061 * resource. When the external string is no longer live on V8's heap the
2062 * resource will be disposed by calling its Dispose method. The caller of
2063 * this function should not otherwise delete or modify the resource. Neither
2064 * should the underlying buffer be deallocated or modified except through the
2065 * destructor of the external string resource.
2067 static Local<String> NewExternal(Isolate* isolate,
2068 ExternalOneByteStringResource* resource);
2071 * Associate an external string resource with this string by transforming it
2072 * in place so that existing references to this string in the JavaScript heap
2073 * will use the external string resource. The external string resource's
2074 * character contents need to be equivalent to this string.
2075 * Returns true if the string has been changed to be an external string.
2076 * The string is not modified if the operation fails. See NewExternal for
2077 * information on the lifetime of the resource.
2079 bool MakeExternal(ExternalOneByteStringResource* resource);
2082 * Returns true if this string can be made external.
2084 bool CanMakeExternal();
2087 * Converts an object to a UTF-8-encoded character array. Useful if
2088 * you want to print the object. If conversion to a string fails
2089 * (e.g. due to an exception in the toString() method of the object)
2090 * then the length() method returns 0 and the * operator returns
2093 class V8_EXPORT Utf8Value {
2095 explicit Utf8Value(Handle<v8::Value> obj);
2097 char* operator*() { return str_; }
2098 const char* operator*() const { return str_; }
2099 int length() const { return length_; }
2104 // Disallow copying and assigning.
2105 Utf8Value(const Utf8Value&);
2106 void operator=(const Utf8Value&);
2110 * Converts an object to a two-byte string.
2111 * If conversion to a string fails (eg. due to an exception in the toString()
2112 * method of the object) then the length() method returns 0 and the * operator
2115 class V8_EXPORT Value {
2117 explicit Value(Handle<v8::Value> obj);
2119 uint16_t* operator*() { return str_; }
2120 const uint16_t* operator*() const { return str_; }
2121 int length() const { return length_; }
2126 // Disallow copying and assigning.
2127 Value(const Value&);
2128 void operator=(const Value&);
2132 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2133 Encoding encoding) const;
2134 void VerifyExternalStringResource(ExternalStringResource* val) const;
2135 static void CheckCast(v8::Value* obj);
2140 * A JavaScript symbol (ECMA-262 edition 6)
2142 * This is an experimental feature. Use at your own risk.
2144 class V8_EXPORT Symbol : public Name {
2146 // Returns the print name string of the symbol, or undefined if none.
2147 Local<Value> Name() const;
2149 // Create a symbol. If name is not empty, it will be used as the description.
2150 static Local<Symbol> New(
2151 Isolate *isolate, Local<String> name = Local<String>());
2153 // Access global symbol registry.
2154 // Note that symbols created this way are never collected, so
2155 // they should only be used for statically fixed properties.
2156 // Also, there is only one global name space for the names used as keys.
2157 // To minimize the potential for clashes, use qualified names as keys.
2158 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2160 // Retrieve a global symbol. Similar to |For|, but using a separate
2161 // registry that is not accessible by (and cannot clash with) JavaScript code.
2162 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2164 // Well-known symbols
2165 static Local<Symbol> GetIterator(Isolate* isolate);
2166 static Local<Symbol> GetUnscopables(Isolate* isolate);
2167 static Local<Symbol> GetToStringTag(Isolate* isolate);
2169 V8_INLINE static Symbol* Cast(v8::Value* obj);
2173 static void CheckCast(v8::Value* obj);
2180 * This is an experimental feature. Use at your own risk.
2182 class V8_EXPORT Private : public Data {
2184 // Returns the print name string of the private symbol, or undefined if none.
2185 Local<Value> Name() const;
2187 // Create a private symbol. If name is not empty, it will be the description.
2188 static Local<Private> New(
2189 Isolate *isolate, Local<String> name = Local<String>());
2191 // Retrieve a global private symbol. If a symbol with this name has not
2192 // been retrieved in the same isolate before, it is created.
2193 // Note that private symbols created this way are never collected, so
2194 // they should only be used for statically fixed properties.
2195 // Also, there is only one global name space for the names used as keys.
2196 // To minimize the potential for clashes, use qualified names as keys,
2197 // e.g., "Class#property".
2198 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2206 * A JavaScript number value (ECMA-262, 4.3.20)
2208 class V8_EXPORT Number : public Primitive {
2210 double Value() const;
2211 static Local<Number> New(Isolate* isolate, double value);
2212 V8_INLINE static Number* Cast(v8::Value* obj);
2215 static void CheckCast(v8::Value* obj);
2220 * A JavaScript value representing a signed integer.
2222 class V8_EXPORT Integer : public Number {
2224 static Local<Integer> New(Isolate* isolate, int32_t value);
2225 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2226 int64_t Value() const;
2227 V8_INLINE static Integer* Cast(v8::Value* obj);
2230 static void CheckCast(v8::Value* obj);
2235 * A JavaScript value representing a 32-bit signed integer.
2237 class V8_EXPORT Int32 : public Integer {
2239 int32_t Value() const;
2246 * A JavaScript value representing a 32-bit unsigned integer.
2248 class V8_EXPORT Uint32 : public Integer {
2250 uint32_t Value() const;
2256 enum PropertyAttribute {
2263 enum ExternalArrayType {
2264 kExternalInt8Array = 1,
2265 kExternalUint8Array,
2266 kExternalInt16Array,
2267 kExternalUint16Array,
2268 kExternalInt32Array,
2269 kExternalUint32Array,
2270 kExternalFloat32Array,
2271 kExternalFloat64Array,
2272 kExternalUint8ClampedArray,
2274 // Legacy constant names
2275 kExternalByteArray = kExternalInt8Array,
2276 kExternalUnsignedByteArray = kExternalUint8Array,
2277 kExternalShortArray = kExternalInt16Array,
2278 kExternalUnsignedShortArray = kExternalUint16Array,
2279 kExternalIntArray = kExternalInt32Array,
2280 kExternalUnsignedIntArray = kExternalUint32Array,
2281 kExternalFloatArray = kExternalFloat32Array,
2282 kExternalDoubleArray = kExternalFloat64Array,
2283 kExternalPixelArray = kExternalUint8ClampedArray
2287 * Accessor[Getter|Setter] are used as callback functions when
2288 * setting|getting a particular property. See Object and ObjectTemplate's
2289 * method SetAccessor.
2291 typedef void (*AccessorGetterCallback)(
2292 Local<String> property,
2293 const PropertyCallbackInfo<Value>& info);
2294 typedef void (*AccessorNameGetterCallback)(
2295 Local<Name> property,
2296 const PropertyCallbackInfo<Value>& info);
2299 typedef void (*AccessorSetterCallback)(
2300 Local<String> property,
2302 const PropertyCallbackInfo<void>& info);
2303 typedef void (*AccessorNameSetterCallback)(
2304 Local<Name> property,
2306 const PropertyCallbackInfo<void>& info);
2310 * Access control specifications.
2312 * Some accessors should be accessible across contexts. These
2313 * accessors have an explicit access control parameter which specifies
2314 * the kind of cross-context access that should be allowed.
2316 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2318 enum AccessControl {
2321 ALL_CAN_WRITE = 1 << 1,
2322 PROHIBITS_OVERWRITING = 1 << 2
2327 * A JavaScript object (ECMA-262, 4.3.3)
2329 class V8_EXPORT Object : public Value {
2331 bool Set(Handle<Value> key, Handle<Value> value);
2333 bool Set(uint32_t index, Handle<Value> value);
2335 // Sets an own property on this object bypassing interceptors and
2336 // overriding accessors or read-only properties.
2338 // Note that if the object has an interceptor the property will be set
2339 // locally, but since the interceptor takes precedence the local property
2340 // will only be returned if the interceptor doesn't return a value.
2342 // Note also that this only works for named properties.
2343 bool ForceSet(Handle<Value> key,
2344 Handle<Value> value,
2345 PropertyAttribute attribs = None);
2347 Local<Value> Get(Handle<Value> key);
2349 Local<Value> Get(uint32_t index);
2352 * Gets the property attributes of a property which can be None or
2353 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2354 * None when the property doesn't exist.
2356 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2359 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2361 Local<Value> GetOwnPropertyDescriptor(Local<String> key);
2363 bool Has(Handle<Value> key);
2365 bool Delete(Handle<Value> key);
2367 // Delete a property on this object bypassing interceptors and
2368 // ignoring dont-delete attributes.
2369 bool ForceDelete(Handle<Value> key);
2371 bool Has(uint32_t index);
2373 bool Delete(uint32_t index);
2375 bool SetAccessor(Handle<String> name,
2376 AccessorGetterCallback getter,
2377 AccessorSetterCallback setter = 0,
2378 Handle<Value> data = Handle<Value>(),
2379 AccessControl settings = DEFAULT,
2380 PropertyAttribute attribute = None);
2381 bool SetAccessor(Handle<Name> name,
2382 AccessorNameGetterCallback getter,
2383 AccessorNameSetterCallback setter = 0,
2384 Handle<Value> data = Handle<Value>(),
2385 AccessControl settings = DEFAULT,
2386 PropertyAttribute attribute = None);
2388 // This function is not yet stable and should not be used at this time.
2389 bool SetDeclaredAccessor(Local<Name> name,
2390 Local<DeclaredAccessorDescriptor> descriptor,
2391 PropertyAttribute attribute = None,
2392 AccessControl settings = DEFAULT);
2394 void SetAccessorProperty(Local<Name> name,
2395 Local<Function> getter,
2396 Handle<Function> setter = Handle<Function>(),
2397 PropertyAttribute attribute = None,
2398 AccessControl settings = DEFAULT);
2401 * Functionality for private properties.
2402 * This is an experimental feature, use at your own risk.
2403 * Note: Private properties are inherited. Do not rely on this, since it may
2406 bool HasPrivate(Handle<Private> key);
2407 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2408 bool DeletePrivate(Handle<Private> key);
2409 Local<Value> GetPrivate(Handle<Private> key);
2412 * Returns an array containing the names of the enumerable properties
2413 * of this object, including properties from prototype objects. The
2414 * array returned by this method contains the same values as would
2415 * be enumerated by a for-in statement over this object.
2417 Local<Array> GetPropertyNames();
2420 * This function has the same functionality as GetPropertyNames but
2421 * the returned array doesn't contain the names of properties from
2422 * prototype objects.
2424 Local<Array> GetOwnPropertyNames();
2427 * Get the prototype object. This does not skip objects marked to
2428 * be skipped by __proto__ and it does not consult the security
2431 Local<Value> GetPrototype();
2434 * Set the prototype object. This does not skip objects marked to
2435 * be skipped by __proto__ and it does not consult the security
2438 bool SetPrototype(Handle<Value> prototype);
2441 * Finds an instance of the given function template in the prototype
2444 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2447 * Call builtin Object.prototype.toString on this object.
2448 * This is different from Value::ToString() that may call
2449 * user-defined toString function. This one does not.
2451 Local<String> ObjectProtoToString();
2454 * Returns the name of the function invoked as a constructor for this object.
2456 Local<String> GetConstructorName();
2458 /** Gets the number of internal fields for this Object. */
2459 int InternalFieldCount();
2461 /** Same as above, but works for Persistents */
2462 V8_INLINE static int InternalFieldCount(
2463 const PersistentBase<Object>& object) {
2464 return object.val_->InternalFieldCount();
2467 /** Gets the value from an internal field. */
2468 V8_INLINE Local<Value> GetInternalField(int index);
2470 /** Sets the value in an internal field. */
2471 void SetInternalField(int index, Handle<Value> value);
2474 * Gets a 2-byte-aligned native pointer from an internal field. This field
2475 * must have been set by SetAlignedPointerInInternalField, everything else
2476 * leads to undefined behavior.
2478 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2480 /** Same as above, but works for Persistents */
2481 V8_INLINE static void* GetAlignedPointerFromInternalField(
2482 const PersistentBase<Object>& object, int index) {
2483 return object.val_->GetAlignedPointerFromInternalField(index);
2487 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2488 * a field, GetAlignedPointerFromInternalField must be used, everything else
2489 * leads to undefined behavior.
2491 void SetAlignedPointerInInternalField(int index, void* value);
2493 // Testers for local properties.
2494 bool HasOwnProperty(Handle<String> key);
2495 bool HasRealNamedProperty(Handle<String> key);
2496 bool HasRealIndexedProperty(uint32_t index);
2497 bool HasRealNamedCallbackProperty(Handle<String> key);
2500 * If result.IsEmpty() no real property was located in the prototype chain.
2501 * This means interceptors in the prototype chain are not called.
2503 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2506 * If result.IsEmpty() no real property was located on the object or
2507 * in the prototype chain.
2508 * This means interceptors in the prototype chain are not called.
2510 Local<Value> GetRealNamedProperty(Handle<String> key);
2512 /** Tests for a named lookup interceptor.*/
2513 bool HasNamedLookupInterceptor();
2515 /** Tests for an index lookup interceptor.*/
2516 bool HasIndexedLookupInterceptor();
2519 * Turns on access check on the object if the object is an instance of
2520 * a template that has access check callbacks. If an object has no
2521 * access check info, the object cannot be accessed by anyone.
2523 void TurnOnAccessCheck();
2526 * Returns the identity hash for this object. The current implementation
2527 * uses a hidden property on the object to store the identity hash.
2529 * The return value will never be 0. Also, it is not guaranteed to be
2532 int GetIdentityHash();
2535 * Access hidden properties on JavaScript objects. These properties are
2536 * hidden from the executing JavaScript and only accessible through the V8
2537 * C++ API. Hidden properties introduced by V8 internally (for example the
2538 * identity hash) are prefixed with "v8::".
2540 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2541 Local<Value> GetHiddenValue(Handle<String> key);
2542 bool DeleteHiddenValue(Handle<String> key);
2545 * Clone this object with a fast but shallow copy. Values will point
2546 * to the same values as the original object.
2548 Local<Object> Clone();
2551 * Returns the context in which the object was created.
2553 Local<Context> CreationContext();
2556 * Set the backing store of the indexed properties to be managed by the
2557 * embedding layer. Access to the indexed properties will follow the rules
2558 * spelled out in CanvasPixelArray.
2559 * Note: The embedding program still owns the data and needs to ensure that
2560 * the backing store is preserved while V8 has a reference.
2562 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2563 bool HasIndexedPropertiesInPixelData();
2564 uint8_t* GetIndexedPropertiesPixelData();
2565 int GetIndexedPropertiesPixelDataLength();
2568 * Set the backing store of the indexed properties to be managed by the
2569 * embedding layer. Access to the indexed properties will follow the rules
2570 * spelled out for the CanvasArray subtypes in the WebGL specification.
2571 * Note: The embedding program still owns the data and needs to ensure that
2572 * the backing store is preserved while V8 has a reference.
2574 void SetIndexedPropertiesToExternalArrayData(void* data,
2575 ExternalArrayType array_type,
2576 int number_of_elements);
2577 bool HasIndexedPropertiesInExternalArrayData();
2578 void* GetIndexedPropertiesExternalArrayData();
2579 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2580 int GetIndexedPropertiesExternalArrayDataLength();
2583 * Checks whether a callback is set by the
2584 * ObjectTemplate::SetCallAsFunctionHandler method.
2585 * When an Object is callable this method returns true.
2590 * Call an Object as a function if a callback is set by the
2591 * ObjectTemplate::SetCallAsFunctionHandler method.
2593 Local<Value> CallAsFunction(Handle<Value> recv,
2595 Handle<Value> argv[]);
2598 * Call an Object as a constructor if a callback is set by the
2599 * ObjectTemplate::SetCallAsFunctionHandler method.
2600 * Note: This method behaves like the Function::NewInstance method.
2602 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2605 * Return the isolate to which the Object belongs to.
2607 Isolate* GetIsolate();
2609 static Local<Object> New(Isolate* isolate);
2611 V8_INLINE static Object* Cast(Value* obj);
2615 static void CheckCast(Value* obj);
2616 Local<Value> SlowGetInternalField(int index);
2617 void* SlowGetAlignedPointerFromInternalField(int index);
2622 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2624 class V8_EXPORT Array : public Object {
2626 uint32_t Length() const;
2629 * Clones an element at index |index|. Returns an empty
2630 * handle if cloning fails (for any reason).
2632 Local<Object> CloneElementAt(uint32_t index);
2635 * Creates a JavaScript array with the given length. If the length
2636 * is negative the returned array will have length 0.
2638 static Local<Array> New(Isolate* isolate, int length = 0);
2640 V8_INLINE static Array* Cast(Value* obj);
2643 static void CheckCast(Value* obj);
2647 template<typename T>
2650 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2651 : value_(that.value_) {
2655 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2656 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2657 // Fast primitive setters
2658 V8_INLINE void Set(bool value);
2659 V8_INLINE void Set(double i);
2660 V8_INLINE void Set(int32_t i);
2661 V8_INLINE void Set(uint32_t i);
2662 // Fast JS primitive setters
2663 V8_INLINE void SetNull();
2664 V8_INLINE void SetUndefined();
2665 V8_INLINE void SetEmptyString();
2666 // Convenience getter for Isolate
2667 V8_INLINE Isolate* GetIsolate();
2669 // Pointer setter: Uncompilable to prevent inadvertent misuse.
2670 template <typename S>
2671 V8_INLINE void Set(S* whatever);
2674 template<class F> friend class ReturnValue;
2675 template<class F> friend class FunctionCallbackInfo;
2676 template<class F> friend class PropertyCallbackInfo;
2677 template<class F, class G, class H> friend class PersistentValueMap;
2678 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2679 V8_INLINE internal::Object* GetDefaultValue();
2680 V8_INLINE explicit ReturnValue(internal::Object** slot);
2681 internal::Object** value_;
2686 * The argument information given to function call callbacks. This
2687 * class provides access to information about the context of the call,
2688 * including the receiver, the number and values of arguments, and
2689 * the holder of the function.
2691 template<typename T>
2692 class FunctionCallbackInfo {
2694 V8_INLINE int Length() const;
2695 V8_INLINE Local<Value> operator[](int i) const;
2696 V8_INLINE Local<Function> Callee() const;
2697 V8_INLINE Local<Object> This() const;
2698 V8_INLINE Local<Object> Holder() const;
2699 V8_INLINE bool IsConstructCall() const;
2700 V8_INLINE Local<Value> Data() const;
2701 V8_INLINE Isolate* GetIsolate() const;
2702 V8_INLINE ReturnValue<T> GetReturnValue() const;
2703 // This shouldn't be public, but the arm compiler needs it.
2704 static const int kArgsLength = 7;
2707 friend class internal::FunctionCallbackArguments;
2708 friend class internal::CustomArguments<FunctionCallbackInfo>;
2709 static const int kHolderIndex = 0;
2710 static const int kIsolateIndex = 1;
2711 static const int kReturnValueDefaultValueIndex = 2;
2712 static const int kReturnValueIndex = 3;
2713 static const int kDataIndex = 4;
2714 static const int kCalleeIndex = 5;
2715 static const int kContextSaveIndex = 6;
2717 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2718 internal::Object** values,
2720 bool is_construct_call);
2721 internal::Object** implicit_args_;
2722 internal::Object** values_;
2724 bool is_construct_call_;
2729 * The information passed to a property callback about the context
2730 * of the property access.
2732 template<typename T>
2733 class PropertyCallbackInfo {
2735 V8_INLINE Isolate* GetIsolate() const;
2736 V8_INLINE Local<Value> Data() const;
2737 V8_INLINE Local<Object> This() const;
2738 V8_INLINE Local<Object> Holder() const;
2739 V8_INLINE ReturnValue<T> GetReturnValue() const;
2740 // This shouldn't be public, but the arm compiler needs it.
2741 static const int kArgsLength = 6;
2744 friend class MacroAssembler;
2745 friend class internal::PropertyCallbackArguments;
2746 friend class internal::CustomArguments<PropertyCallbackInfo>;
2747 static const int kHolderIndex = 0;
2748 static const int kIsolateIndex = 1;
2749 static const int kReturnValueDefaultValueIndex = 2;
2750 static const int kReturnValueIndex = 3;
2751 static const int kDataIndex = 4;
2752 static const int kThisIndex = 5;
2754 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2755 internal::Object** args_;
2759 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2763 * A JavaScript function object (ECMA-262, 15.3).
2765 class V8_EXPORT Function : public Object {
2768 * Create a function in the current execution context
2769 * for a given FunctionCallback.
2771 static Local<Function> New(Isolate* isolate,
2772 FunctionCallback callback,
2773 Local<Value> data = Local<Value>(),
2776 Local<Object> NewInstance() const;
2777 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2778 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2779 void SetName(Handle<String> name);
2780 Handle<Value> GetName() const;
2783 * Name inferred from variable or property assignment of this function.
2784 * Used to facilitate debugging and profiling of JavaScript code written
2785 * in an OO style, where many functions are anonymous but are assigned
2786 * to object properties.
2788 Handle<Value> GetInferredName() const;
2791 * User-defined name assigned to the "displayName" property of this function.
2792 * Used to facilitate debugging and profiling of JavaScript code.
2794 Handle<Value> GetDisplayName() const;
2797 * Returns zero based line number of function body and
2798 * kLineOffsetNotFound if no information available.
2800 int GetScriptLineNumber() const;
2802 * Returns zero based column number of function body and
2803 * kLineOffsetNotFound if no information available.
2805 int GetScriptColumnNumber() const;
2808 * Tells whether this function is builtin.
2810 bool IsBuiltin() const;
2815 int ScriptId() const;
2818 * Returns the original function if this function is bound, else returns
2821 Local<Value> GetBoundFunction() const;
2823 ScriptOrigin GetScriptOrigin() const;
2824 V8_INLINE static Function* Cast(Value* obj);
2825 static const int kLineOffsetNotFound;
2829 static void CheckCast(Value* obj);
2834 * An instance of the built-in Promise constructor (ES6 draft).
2835 * This API is experimental. Only works with --harmony flag.
2837 class V8_EXPORT Promise : public Object {
2839 class V8_EXPORT Resolver : public Object {
2842 * Create a new resolver, along with an associated promise in pending state.
2844 static Local<Resolver> New(Isolate* isolate);
2847 * Extract the associated promise.
2849 Local<Promise> GetPromise();
2852 * Resolve/reject the associated promise with a given value.
2853 * Ignored if the promise is no longer pending.
2855 void Resolve(Handle<Value> value);
2856 void Reject(Handle<Value> value);
2858 V8_INLINE static Resolver* Cast(Value* obj);
2862 static void CheckCast(Value* obj);
2866 * Register a resolution/rejection handler with a promise.
2867 * The handler is given the respective resolution/rejection value as
2868 * an argument. If the promise is already resolved/rejected, the handler is
2869 * invoked at the end of turn.
2871 Local<Promise> Chain(Handle<Function> handler);
2872 Local<Promise> Catch(Handle<Function> handler);
2873 Local<Promise> Then(Handle<Function> handler);
2876 * Returns true if the promise has at least one derived promise, and
2877 * therefore resolve/reject handlers (including default handler).
2881 V8_INLINE static Promise* Cast(Value* obj);
2885 static void CheckCast(Value* obj);
2889 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2890 // The number of required internal fields can be defined by embedder.
2891 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2895 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2896 * This API is experimental and may change significantly.
2898 class V8_EXPORT ArrayBuffer : public Object {
2901 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2902 * The allocator is a global V8 setting. It should be set with
2903 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2905 * This API is experimental and may change significantly.
2907 class V8_EXPORT Allocator { // NOLINT
2909 virtual ~Allocator() {}
2912 * Allocate |length| bytes. Return NULL if allocation is not successful.
2913 * Memory should be initialized to zeroes.
2915 virtual void* Allocate(size_t length) = 0;
2918 * Allocate |length| bytes. Return NULL if allocation is not successful.
2919 * Memory does not have to be initialized.
2921 virtual void* AllocateUninitialized(size_t length) = 0;
2923 * Free the memory block of size |length|, pointed to by |data|.
2924 * That memory is guaranteed to be previously allocated by |Allocate|.
2926 virtual void Free(void* data, size_t length) = 0;
2930 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2931 * returns an instance of this class, populated, with a pointer to data
2934 * The Data pointer of ArrayBuffer::Contents is always allocated with
2935 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2937 * This API is experimental and may change significantly.
2939 class V8_EXPORT Contents { // NOLINT
2941 Contents() : data_(NULL), byte_length_(0) {}
2943 void* Data() const { return data_; }
2944 size_t ByteLength() const { return byte_length_; }
2948 size_t byte_length_;
2950 friend class ArrayBuffer;
2955 * Data length in bytes.
2957 size_t ByteLength() const;
2960 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2961 * Allocated memory will be owned by a created ArrayBuffer and
2962 * will be deallocated when it is garbage-collected,
2963 * unless the object is externalized.
2965 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2968 * Create a new ArrayBuffer over an existing memory block.
2969 * The created array buffer is immediately in externalized state.
2970 * The memory block will not be reclaimed when a created ArrayBuffer
2971 * is garbage-collected.
2973 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2974 size_t byte_length);
2977 * Returns true if ArrayBuffer is extrenalized, that is, does not
2978 * own its memory block.
2980 bool IsExternal() const;
2983 * Returns true if this ArrayBuffer may be neutered.
2985 bool IsNeuterable() const;
2988 * Neuters this ArrayBuffer and all its views (typed arrays).
2989 * Neutering sets the byte length of the buffer and all typed arrays to zero,
2990 * preventing JavaScript from ever accessing underlying backing store.
2991 * ArrayBuffer should have been externalized and must be neuterable.
2996 * Make this ArrayBuffer external. The pointer to underlying memory block
2997 * and byte length are returned as |Contents| structure. After ArrayBuffer
2998 * had been etxrenalized, it does no longer owns the memory block. The caller
2999 * should take steps to free memory when it is no longer needed.
3001 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3002 * that has been set with V8::SetArrayBufferAllocator.
3004 Contents Externalize();
3006 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3008 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3012 static void CheckCast(Value* obj);
3016 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3017 // The number of required internal fields can be defined by embedder.
3018 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3023 * A base class for an instance of one of "views" over ArrayBuffer,
3024 * including TypedArrays and DataView (ES6 draft 15.13).
3026 * This API is experimental and may change significantly.
3028 class V8_EXPORT ArrayBufferView : public Object {
3031 * Returns underlying ArrayBuffer.
3033 Local<ArrayBuffer> Buffer();
3035 * Byte offset in |Buffer|.
3037 size_t ByteOffset();
3039 * Size of a view in bytes.
3041 size_t ByteLength();
3043 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3045 static const int kInternalFieldCount =
3046 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3050 static void CheckCast(Value* obj);
3055 * A base class for an instance of TypedArray series of constructors
3056 * (ES6 draft 15.13.6).
3057 * This API is experimental and may change significantly.
3059 class V8_EXPORT TypedArray : public ArrayBufferView {
3062 * Number of elements in this typed array
3063 * (e.g. for Int16Array, |ByteLength|/2).
3067 V8_INLINE static TypedArray* Cast(Value* obj);
3071 static void CheckCast(Value* obj);
3076 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3077 * This API is experimental and may change significantly.
3079 class V8_EXPORT Uint8Array : public TypedArray {
3081 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
3082 size_t byte_offset, size_t length);
3083 V8_INLINE static Uint8Array* Cast(Value* obj);
3087 static void CheckCast(Value* obj);
3092 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3093 * This API is experimental and may change significantly.
3095 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3097 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
3098 size_t byte_offset, size_t length);
3099 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3102 Uint8ClampedArray();
3103 static void CheckCast(Value* obj);
3107 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3108 * This API is experimental and may change significantly.
3110 class V8_EXPORT Int8Array : public TypedArray {
3112 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
3113 size_t byte_offset, size_t length);
3114 V8_INLINE static Int8Array* Cast(Value* obj);
3118 static void CheckCast(Value* obj);
3123 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3124 * This API is experimental and may change significantly.
3126 class V8_EXPORT Uint16Array : public TypedArray {
3128 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
3129 size_t byte_offset, size_t length);
3130 V8_INLINE static Uint16Array* Cast(Value* obj);
3134 static void CheckCast(Value* obj);
3139 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3140 * This API is experimental and may change significantly.
3142 class V8_EXPORT Int16Array : public TypedArray {
3144 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
3145 size_t byte_offset, size_t length);
3146 V8_INLINE static Int16Array* Cast(Value* obj);
3150 static void CheckCast(Value* obj);
3155 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3156 * This API is experimental and may change significantly.
3158 class V8_EXPORT Uint32Array : public TypedArray {
3160 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
3161 size_t byte_offset, size_t length);
3162 V8_INLINE static Uint32Array* Cast(Value* obj);
3166 static void CheckCast(Value* obj);
3171 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3172 * This API is experimental and may change significantly.
3174 class V8_EXPORT Int32Array : public TypedArray {
3176 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
3177 size_t byte_offset, size_t length);
3178 V8_INLINE static Int32Array* Cast(Value* obj);
3182 static void CheckCast(Value* obj);
3187 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3188 * This API is experimental and may change significantly.
3190 class V8_EXPORT Float32Array : public TypedArray {
3192 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
3193 size_t byte_offset, size_t length);
3194 V8_INLINE static Float32Array* Cast(Value* obj);
3198 static void CheckCast(Value* obj);
3203 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3204 * This API is experimental and may change significantly.
3206 class V8_EXPORT Float64Array : public TypedArray {
3208 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3209 size_t byte_offset, size_t length);
3210 V8_INLINE static Float64Array* Cast(Value* obj);
3214 static void CheckCast(Value* obj);
3219 * An instance of DataView constructor (ES6 draft 15.13.7).
3220 * This API is experimental and may change significantly.
3222 class V8_EXPORT DataView : public ArrayBufferView {
3224 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3225 size_t byte_offset, size_t length);
3226 V8_INLINE static DataView* Cast(Value* obj);
3230 static void CheckCast(Value* obj);
3235 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3237 class V8_EXPORT Date : public Object {
3239 static Local<Value> New(Isolate* isolate, double time);
3242 * A specialization of Value::NumberValue that is more efficient
3243 * because we know the structure of this object.
3245 double ValueOf() const;
3247 V8_INLINE static Date* Cast(v8::Value* obj);
3250 * Notification that the embedder has changed the time zone,
3251 * daylight savings time, or other date / time configuration
3252 * parameters. V8 keeps a cache of various values used for
3253 * date / time computation. This notification will reset
3254 * those cached values for the current context so that date /
3255 * time configuration changes would be reflected in the Date
3258 * This API should not be called more than needed as it will
3259 * negatively impact the performance of date operations.
3261 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3264 static void CheckCast(v8::Value* obj);
3269 * A Number object (ECMA-262, 4.3.21).
3271 class V8_EXPORT NumberObject : public Object {
3273 static Local<Value> New(Isolate* isolate, double value);
3275 double ValueOf() const;
3277 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3280 static void CheckCast(v8::Value* obj);
3285 * A Boolean object (ECMA-262, 4.3.15).
3287 class V8_EXPORT BooleanObject : public Object {
3289 static Local<Value> New(bool value);
3291 bool ValueOf() const;
3293 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3296 static void CheckCast(v8::Value* obj);
3301 * A String object (ECMA-262, 4.3.18).
3303 class V8_EXPORT StringObject : public Object {
3305 static Local<Value> New(Handle<String> value);
3307 Local<String> ValueOf() const;
3309 V8_INLINE static StringObject* Cast(v8::Value* obj);
3312 static void CheckCast(v8::Value* obj);
3317 * A Symbol object (ECMA-262 edition 6).
3319 * This is an experimental feature. Use at your own risk.
3321 class V8_EXPORT SymbolObject : public Object {
3323 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3325 Local<Symbol> ValueOf() const;
3327 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3330 static void CheckCast(v8::Value* obj);
3335 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3337 class V8_EXPORT RegExp : public Object {
3340 * Regular expression flag bits. They can be or'ed to enable a set
3351 * Creates a regular expression from the given pattern string and
3352 * the flags bit field. May throw a JavaScript exception as
3353 * described in ECMA-262, 15.10.4.1.
3356 * RegExp::New(v8::String::New("foo"),
3357 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3358 * is equivalent to evaluating "/foo/gm".
3360 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3363 * Returns the value of the source property: a string representing
3364 * the regular expression.
3366 Local<String> GetSource() const;
3369 * Returns the flags bit field.
3371 Flags GetFlags() const;
3373 V8_INLINE static RegExp* Cast(v8::Value* obj);
3376 static void CheckCast(v8::Value* obj);
3381 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3382 * to associate C++ data structures with JavaScript objects.
3384 class V8_EXPORT External : public Value {
3386 static Local<External> New(Isolate* isolate, void* value);
3387 V8_INLINE static External* Cast(Value* obj);
3388 void* Value() const;
3390 static void CheckCast(v8::Value* obj);
3394 // --- Templates ---
3398 * The superclass of object and function templates.
3400 class V8_EXPORT Template : public Data {
3402 /** Adds a property to each instance created by this template.*/
3403 void Set(Handle<Name> name, Handle<Data> value,
3404 PropertyAttribute attributes = None);
3405 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3407 void SetAccessorProperty(
3409 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3410 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3411 PropertyAttribute attribute = None,
3412 AccessControl settings = DEFAULT);
3415 * Whenever the property with the given name is accessed on objects
3416 * created from this Template the getter and setter callbacks
3417 * are called instead of getting and setting the property directly
3418 * on the JavaScript object.
3420 * \param name The name of the property for which an accessor is added.
3421 * \param getter The callback to invoke when getting the property.
3422 * \param setter The callback to invoke when setting the property.
3423 * \param data A piece of data that will be passed to the getter and setter
3424 * callbacks whenever they are invoked.
3425 * \param settings Access control settings for the accessor. This is a bit
3426 * field consisting of one of more of
3427 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3428 * The default is to not allow cross-context access.
3429 * ALL_CAN_READ means that all cross-context reads are allowed.
3430 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3431 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3432 * cross-context access.
3433 * \param attribute The attributes of the property for which an accessor
3435 * \param signature The signature describes valid receivers for the accessor
3436 * and is used to perform implicit instance checks against them. If the
3437 * receiver is incompatible (i.e. is not an instance of the constructor as
3438 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3439 * thrown and no callback is invoked.
3441 void SetNativeDataProperty(Local<String> name,
3442 AccessorGetterCallback getter,
3443 AccessorSetterCallback setter = 0,
3444 // TODO(dcarney): gcc can't handle Local below
3445 Handle<Value> data = Handle<Value>(),
3446 PropertyAttribute attribute = None,
3447 Local<AccessorSignature> signature =
3448 Local<AccessorSignature>(),
3449 AccessControl settings = DEFAULT);
3450 void SetNativeDataProperty(Local<Name> name,
3451 AccessorNameGetterCallback getter,
3452 AccessorNameSetterCallback setter = 0,
3453 // TODO(dcarney): gcc can't handle Local below
3454 Handle<Value> data = Handle<Value>(),
3455 PropertyAttribute attribute = None,
3456 Local<AccessorSignature> signature =
3457 Local<AccessorSignature>(),
3458 AccessControl settings = DEFAULT);
3460 // This function is not yet stable and should not be used at this time.
3461 bool SetDeclaredAccessor(Local<Name> name,
3462 Local<DeclaredAccessorDescriptor> descriptor,
3463 PropertyAttribute attribute = None,
3464 Local<AccessorSignature> signature =
3465 Local<AccessorSignature>(),
3466 AccessControl settings = DEFAULT);
3471 friend class ObjectTemplate;
3472 friend class FunctionTemplate;
3477 * NamedProperty[Getter|Setter] are used as interceptors on object.
3478 * See ObjectTemplate::SetNamedPropertyHandler.
3480 typedef void (*NamedPropertyGetterCallback)(
3481 Local<String> property,
3482 const PropertyCallbackInfo<Value>& info);
3486 * Returns the value if the setter intercepts the request.
3487 * Otherwise, returns an empty handle.
3489 typedef void (*NamedPropertySetterCallback)(
3490 Local<String> property,
3492 const PropertyCallbackInfo<Value>& info);
3496 * Returns a non-empty handle if the interceptor intercepts the request.
3497 * The result is an integer encoding property attributes (like v8::None,
3498 * v8::DontEnum, etc.)
3500 typedef void (*NamedPropertyQueryCallback)(
3501 Local<String> property,
3502 const PropertyCallbackInfo<Integer>& info);
3506 * Returns a non-empty handle if the deleter intercepts the request.
3507 * The return value is true if the property could be deleted and false
3510 typedef void (*NamedPropertyDeleterCallback)(
3511 Local<String> property,
3512 const PropertyCallbackInfo<Boolean>& info);
3516 * Returns an array containing the names of the properties the named
3517 * property getter intercepts.
3519 typedef void (*NamedPropertyEnumeratorCallback)(
3520 const PropertyCallbackInfo<Array>& info);
3524 * Returns the value of the property if the getter intercepts the
3525 * request. Otherwise, returns an empty handle.
3527 typedef void (*IndexedPropertyGetterCallback)(
3529 const PropertyCallbackInfo<Value>& info);
3533 * Returns the value if the setter intercepts the request.
3534 * Otherwise, returns an empty handle.
3536 typedef void (*IndexedPropertySetterCallback)(
3539 const PropertyCallbackInfo<Value>& info);
3543 * Returns a non-empty handle if the interceptor intercepts the request.
3544 * The result is an integer encoding property attributes.
3546 typedef void (*IndexedPropertyQueryCallback)(
3548 const PropertyCallbackInfo<Integer>& info);
3552 * Returns a non-empty handle if the deleter intercepts the request.
3553 * The return value is true if the property could be deleted and false
3556 typedef void (*IndexedPropertyDeleterCallback)(
3558 const PropertyCallbackInfo<Boolean>& info);
3562 * Returns an array containing the indices of the properties the
3563 * indexed property getter intercepts.
3565 typedef void (*IndexedPropertyEnumeratorCallback)(
3566 const PropertyCallbackInfo<Array>& info);
3570 * Access type specification.
3582 * Returns true if cross-context access should be allowed to the named
3583 * property with the given key on the host object.
3585 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3592 * Returns true if cross-context access should be allowed to the indexed
3593 * property with the given index on the host object.
3595 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3602 * A FunctionTemplate is used to create functions at runtime. There
3603 * can only be one function created from a FunctionTemplate in a
3604 * context. The lifetime of the created function is equal to the
3605 * lifetime of the context. So in case the embedder needs to create
3606 * temporary functions that can be collected using Scripts is
3609 * A FunctionTemplate can have properties, these properties are added to the
3610 * function object when it is created.
3612 * A FunctionTemplate has a corresponding instance template which is
3613 * used to create object instances when the function is used as a
3614 * constructor. Properties added to the instance template are added to
3615 * each object instance.
3617 * A FunctionTemplate can have a prototype template. The prototype template
3618 * is used to create the prototype object of the function.
3620 * The following example shows how to use a FunctionTemplate:
3623 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3624 * t->Set("func_property", v8::Number::New(1));
3626 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3627 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3628 * proto_t->Set("proto_const", v8::Number::New(2));
3630 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3631 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3632 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3633 * instance_t->Set("instance_property", Number::New(3));
3635 * v8::Local<v8::Function> function = t->GetFunction();
3636 * v8::Local<v8::Object> instance = function->NewInstance();
3639 * Let's use "function" as the JS variable name of the function object
3640 * and "instance" for the instance object created above. The function
3641 * and the instance will have the following properties:
3644 * func_property in function == true;
3645 * function.func_property == 1;
3647 * function.prototype.proto_method() invokes 'InvokeCallback'
3648 * function.prototype.proto_const == 2;
3650 * instance instanceof function == true;
3651 * instance.instance_accessor calls 'InstanceAccessorCallback'
3652 * instance.instance_property == 3;
3655 * A FunctionTemplate can inherit from another one by calling the
3656 * FunctionTemplate::Inherit method. The following graph illustrates
3657 * the semantics of inheritance:
3660 * FunctionTemplate Parent -> Parent() . prototype -> { }
3662 * | Inherit(Parent) | .__proto__
3664 * FunctionTemplate Child -> Child() . prototype -> { }
3667 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3668 * object of the Child() function has __proto__ pointing to the
3669 * Parent() function's prototype object. An instance of the Child
3670 * function has all properties on Parent's instance templates.
3672 * Let Parent be the FunctionTemplate initialized in the previous
3673 * section and create a Child FunctionTemplate by:
3676 * Local<FunctionTemplate> parent = t;
3677 * Local<FunctionTemplate> child = FunctionTemplate::New();
3678 * child->Inherit(parent);
3680 * Local<Function> child_function = child->GetFunction();
3681 * Local<Object> child_instance = child_function->NewInstance();
3684 * The Child function and Child instance will have the following
3688 * child_func.prototype.__proto__ == function.prototype;
3689 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3690 * child_instance.instance_property == 3;
3693 class V8_EXPORT FunctionTemplate : public Template {
3695 /** Creates a function template.*/
3696 static Local<FunctionTemplate> New(
3698 FunctionCallback callback = 0,
3699 Handle<Value> data = Handle<Value>(),
3700 Handle<Signature> signature = Handle<Signature>(),
3703 /** Returns the unique function instance in the current execution context.*/
3704 Local<Function> GetFunction();
3707 * Set the call-handler callback for a FunctionTemplate. This
3708 * callback is called whenever the function created from this
3709 * FunctionTemplate is called.
3711 void SetCallHandler(FunctionCallback callback,
3712 Handle<Value> data = Handle<Value>());
3714 /** Set the predefined length property for the FunctionTemplate. */
3715 void SetLength(int length);
3717 /** Get the InstanceTemplate. */
3718 Local<ObjectTemplate> InstanceTemplate();
3720 /** Causes the function template to inherit from a parent function template.*/
3721 void Inherit(Handle<FunctionTemplate> parent);
3724 * A PrototypeTemplate is the template used to create the prototype object
3725 * of the function created by this template.
3727 Local<ObjectTemplate> PrototypeTemplate();
3730 * Set the class name of the FunctionTemplate. This is used for
3731 * printing objects created with the function created from the
3732 * FunctionTemplate as its constructor.
3734 void SetClassName(Handle<String> name);
3737 * Determines whether the __proto__ accessor ignores instances of
3738 * the function template. If instances of the function template are
3739 * ignored, __proto__ skips all instances and instead returns the
3740 * next object in the prototype chain.
3742 * Call with a value of true to make the __proto__ accessor ignore
3743 * instances of the function template. Call with a value of false
3744 * to make the __proto__ accessor not ignore instances of the
3745 * function template. By default, instances of a function template
3748 void SetHiddenPrototype(bool value);
3751 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3752 * of functions created from this FunctionTemplate to true.
3754 void ReadOnlyPrototype();
3757 * Removes the prototype property from functions created from this
3760 void RemovePrototype();
3763 * Returns true if the given object is an instance of this function
3766 bool HasInstance(Handle<Value> object);
3770 friend class Context;
3771 friend class ObjectTemplate;
3776 * An ObjectTemplate is used to create objects at runtime.
3778 * Properties added to an ObjectTemplate are added to each object
3779 * created from the ObjectTemplate.
3781 class V8_EXPORT ObjectTemplate : public Template {
3783 /** Creates an ObjectTemplate. */
3784 static Local<ObjectTemplate> New(Isolate* isolate);
3785 // Will be deprecated soon.
3786 static Local<ObjectTemplate> New();
3788 /** Creates a new instance of this template.*/
3789 Local<Object> NewInstance();
3792 * Sets an accessor on the object template.
3794 * Whenever the property with the given name is accessed on objects
3795 * created from this ObjectTemplate the getter and setter callbacks
3796 * are called instead of getting and setting the property directly
3797 * on the JavaScript object.
3799 * \param name The name of the property for which an accessor is added.
3800 * \param getter The callback to invoke when getting the property.
3801 * \param setter The callback to invoke when setting the property.
3802 * \param data A piece of data that will be passed to the getter and setter
3803 * callbacks whenever they are invoked.
3804 * \param settings Access control settings for the accessor. This is a bit
3805 * field consisting of one of more of
3806 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3807 * The default is to not allow cross-context access.
3808 * ALL_CAN_READ means that all cross-context reads are allowed.
3809 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3810 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3811 * cross-context access.
3812 * \param attribute The attributes of the property for which an accessor
3814 * \param signature The signature describes valid receivers for the accessor
3815 * and is used to perform implicit instance checks against them. If the
3816 * receiver is incompatible (i.e. is not an instance of the constructor as
3817 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3818 * thrown and no callback is invoked.
3820 void SetAccessor(Handle<String> name,
3821 AccessorGetterCallback getter,
3822 AccessorSetterCallback setter = 0,
3823 Handle<Value> data = Handle<Value>(),
3824 AccessControl settings = DEFAULT,
3825 PropertyAttribute attribute = None,
3826 Handle<AccessorSignature> signature =
3827 Handle<AccessorSignature>());
3828 void SetAccessor(Handle<Name> name,
3829 AccessorNameGetterCallback getter,
3830 AccessorNameSetterCallback setter = 0,
3831 Handle<Value> data = Handle<Value>(),
3832 AccessControl settings = DEFAULT,
3833 PropertyAttribute attribute = None,
3834 Handle<AccessorSignature> signature =
3835 Handle<AccessorSignature>());
3838 * Sets a named property handler on the object template.
3840 * Whenever a property whose name is a string is accessed on objects created
3841 * from this object template, the provided callback is invoked instead of
3842 * accessing the property directly on the JavaScript object.
3844 * \param getter The callback to invoke when getting a property.
3845 * \param setter The callback to invoke when setting a property.
3846 * \param query The callback to invoke to check if a property is present,
3847 * and if present, get its attributes.
3848 * \param deleter The callback to invoke when deleting a property.
3849 * \param enumerator The callback to invoke to enumerate all the named
3850 * properties of an object.
3851 * \param data A piece of data that will be passed to the callbacks
3852 * whenever they are invoked.
3854 void SetNamedPropertyHandler(
3855 NamedPropertyGetterCallback getter,
3856 NamedPropertySetterCallback setter = 0,
3857 NamedPropertyQueryCallback query = 0,
3858 NamedPropertyDeleterCallback deleter = 0,
3859 NamedPropertyEnumeratorCallback enumerator = 0,
3860 Handle<Value> data = Handle<Value>());
3863 * Sets an indexed property handler on the object template.
3865 * Whenever an indexed property is accessed on objects created from
3866 * this object template, the provided callback is invoked instead of
3867 * accessing the property directly on the JavaScript object.
3869 * \param getter The callback to invoke when getting a property.
3870 * \param setter The callback to invoke when setting a property.
3871 * \param query The callback to invoke to check if an object has a property.
3872 * \param deleter The callback to invoke when deleting a property.
3873 * \param enumerator The callback to invoke to enumerate all the indexed
3874 * properties of an object.
3875 * \param data A piece of data that will be passed to the callbacks
3876 * whenever they are invoked.
3878 void SetIndexedPropertyHandler(
3879 IndexedPropertyGetterCallback getter,
3880 IndexedPropertySetterCallback setter = 0,
3881 IndexedPropertyQueryCallback query = 0,
3882 IndexedPropertyDeleterCallback deleter = 0,
3883 IndexedPropertyEnumeratorCallback enumerator = 0,
3884 Handle<Value> data = Handle<Value>());
3887 * Sets the callback to be used when calling instances created from
3888 * this template as a function. If no callback is set, instances
3889 * behave like normal JavaScript objects that cannot be called as a
3892 void SetCallAsFunctionHandler(FunctionCallback callback,
3893 Handle<Value> data = Handle<Value>());
3896 * Mark object instances of the template as undetectable.
3898 * In many ways, undetectable objects behave as though they are not
3899 * there. They behave like 'undefined' in conditionals and when
3900 * printed. However, properties can be accessed and called as on
3903 void MarkAsUndetectable();
3906 * Sets access check callbacks on the object template.
3908 * When accessing properties on instances of this object template,
3909 * the access check callback will be called to determine whether or
3910 * not to allow cross-context access to the properties.
3911 * The last parameter specifies whether access checks are turned
3912 * on by default on instances. If access checks are off by default,
3913 * they can be turned on on individual instances by calling
3914 * Object::TurnOnAccessCheck().
3916 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3917 IndexedSecurityCallback indexed_handler,
3918 Handle<Value> data = Handle<Value>(),
3919 bool turned_on_by_default = true);
3922 * Gets the number of internal fields for objects generated from
3925 int InternalFieldCount();
3928 * Sets the number of internal fields for objects generated from
3931 void SetInternalFieldCount(int value);
3935 static Local<ObjectTemplate> New(internal::Isolate* isolate,
3936 Handle<FunctionTemplate> constructor);
3937 friend class FunctionTemplate;
3942 * A Signature specifies which receivers and arguments are valid
3943 * parameters to a function.
3945 class V8_EXPORT Signature : public Data {
3947 static Local<Signature> New(Isolate* isolate,
3948 Handle<FunctionTemplate> receiver =
3949 Handle<FunctionTemplate>(),
3951 Handle<FunctionTemplate> argv[] = 0);
3959 * An AccessorSignature specifies which receivers are valid parameters
3960 * to an accessor callback.
3962 class V8_EXPORT AccessorSignature : public Data {
3964 static Local<AccessorSignature> New(Isolate* isolate,
3965 Handle<FunctionTemplate> receiver =
3966 Handle<FunctionTemplate>());
3969 AccessorSignature();
3973 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3975 DeclaredAccessorDescriptor();
3979 class V8_EXPORT ObjectOperationDescriptor : public Data {
3981 // This function is not yet stable and should not be used at this time.
3982 static Local<RawOperationDescriptor> NewInternalFieldDereference(
3984 int internal_field);
3986 ObjectOperationDescriptor();
3990 enum DeclaredAccessorDescriptorDataType {
3991 kDescriptorBoolType,
3992 kDescriptorInt8Type, kDescriptorUint8Type,
3993 kDescriptorInt16Type, kDescriptorUint16Type,
3994 kDescriptorInt32Type, kDescriptorUint32Type,
3995 kDescriptorFloatType, kDescriptorDoubleType
3999 class V8_EXPORT RawOperationDescriptor : public Data {
4001 Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
4002 Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
4003 Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
4004 int16_t byte_offset);
4005 Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
4006 void* compare_value);
4007 Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
4009 DeclaredAccessorDescriptorDataType data_type,
4010 uint8_t bool_offset = 0);
4011 Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
4013 uint8_t compare_value);
4014 Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
4017 uint16_t compare_value);
4018 Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
4021 uint32_t compare_value);
4024 RawOperationDescriptor();
4029 * A utility for determining the type of objects based on the template
4030 * they were constructed from.
4032 class V8_EXPORT TypeSwitch : public Data {
4034 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
4035 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
4036 int match(Handle<Value> value);
4042 // --- Extensions ---
4044 class V8_EXPORT ExternalOneByteStringResourceImpl
4045 : public String::ExternalOneByteStringResource {
4047 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4048 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4049 : data_(data), length_(length) {}
4050 const char* data() const { return data_; }
4051 size_t length() const { return length_; }
4061 class V8_EXPORT Extension { // NOLINT
4063 // Note that the strings passed into this constructor must live as long
4064 // as the Extension itself.
4065 Extension(const char* name,
4066 const char* source = 0,
4068 const char** deps = 0,
4069 int source_length = -1);
4070 virtual ~Extension() { }
4071 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
4072 v8::Isolate* isolate, v8::Handle<v8::String> name) {
4073 return v8::Handle<v8::FunctionTemplate>();
4076 const char* name() const { return name_; }
4077 size_t source_length() const { return source_length_; }
4078 const String::ExternalOneByteStringResource* source() const {
4080 int dependency_count() { return dep_count_; }
4081 const char** dependencies() { return deps_; }
4082 void set_auto_enable(bool value) { auto_enable_ = value; }
4083 bool auto_enable() { return auto_enable_; }
4087 size_t source_length_; // expected to initialize before source_
4088 ExternalOneByteStringResourceImpl source_;
4093 // Disallow copying and assigning.
4094 Extension(const Extension&);
4095 void operator=(const Extension&);
4099 void V8_EXPORT RegisterExtension(Extension* extension);
4104 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
4105 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
4106 V8_INLINE Handle<Boolean> True(Isolate* isolate);
4107 V8_INLINE Handle<Boolean> False(Isolate* isolate);
4111 * A set of constraints that specifies the limits of the runtime's memory use.
4112 * You must set the heap size before initializing the VM - the size cannot be
4113 * adjusted after the VM is initialized.
4115 * If you are using threads then you should hold the V8::Locker lock while
4116 * setting the stack limit and you must set a non-default stack limit separately
4119 class V8_EXPORT ResourceConstraints {
4121 ResourceConstraints();
4124 * Configures the constraints with reasonable default values based on the
4125 * capabilities of the current device the VM is running on.
4127 * \param physical_memory The total amount of physical memory on the current
4129 * \param virtual_memory_limit The amount of virtual memory on the current
4130 * device, in bytes, or zero, if there is no limit.
4131 * \param number_of_processors The number of CPUs available on the current
4134 void ConfigureDefaults(uint64_t physical_memory,
4135 uint64_t virtual_memory_limit,
4136 uint32_t number_of_processors);
4138 int max_semi_space_size() const { return max_semi_space_size_; }
4139 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4140 int max_old_space_size() const { return max_old_space_size_; }
4141 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4142 int max_executable_size() const { return max_executable_size_; }
4143 void set_max_executable_size(int value) { max_executable_size_ = value; }
4144 uint32_t* stack_limit() const { return stack_limit_; }
4145 // Sets an address beyond which the VM's stack may not grow.
4146 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4147 int max_available_threads() const { return max_available_threads_; }
4148 // Set the number of threads available to V8, assuming at least 1.
4149 void set_max_available_threads(int value) {
4150 max_available_threads_ = value;
4152 size_t code_range_size() const { return code_range_size_; }
4153 void set_code_range_size(size_t value) {
4154 code_range_size_ = value;
4158 int max_semi_space_size_;
4159 int max_old_space_size_;
4160 int max_executable_size_;
4161 uint32_t* stack_limit_;
4162 int max_available_threads_;
4163 size_t code_range_size_;
4167 // --- Exceptions ---
4170 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4173 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
4177 typedef void (*LogEventCallback)(const char* name, int event);
4180 * Create new error objects by calling the corresponding error object
4181 * constructor with the message.
4183 class V8_EXPORT Exception {
4185 static Local<Value> RangeError(Handle<String> message);
4186 static Local<Value> ReferenceError(Handle<String> message);
4187 static Local<Value> SyntaxError(Handle<String> message);
4188 static Local<Value> TypeError(Handle<String> message);
4189 static Local<Value> Error(Handle<String> message);
4191 static Local<Message> GetMessage(Handle<Value> exception);
4193 // DEPRECATED. Use GetMessage()->GetStackTrace()
4194 static Local<StackTrace> GetStackTrace(Handle<Value> exception);
4198 // --- Counters Callbacks ---
4200 typedef int* (*CounterLookupCallback)(const char* name);
4202 typedef void* (*CreateHistogramCallback)(const char* name,
4207 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4209 // --- Memory Allocation Callback ---
4211 kObjectSpaceNewSpace = 1 << 0,
4212 kObjectSpaceOldPointerSpace = 1 << 1,
4213 kObjectSpaceOldDataSpace = 1 << 2,
4214 kObjectSpaceCodeSpace = 1 << 3,
4215 kObjectSpaceMapSpace = 1 << 4,
4216 kObjectSpaceLoSpace = 1 << 5,
4218 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4219 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4223 enum AllocationAction {
4224 kAllocationActionAllocate = 1 << 0,
4225 kAllocationActionFree = 1 << 1,
4226 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4229 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4230 AllocationAction action,
4233 // --- Leave Script Callback ---
4234 typedef void (*CallCompletedCallback)();
4236 // --- Promise Reject Callback ---
4237 enum PromiseRejectEvent {
4238 kPromiseRejectWithNoHandler = 0,
4239 kPromiseHandlerAddedAfterReject = 1
4242 class PromiseRejectMessage {
4244 PromiseRejectMessage(Handle<Promise> promise, PromiseRejectEvent event,
4245 Handle<Value> value, Handle<StackTrace> stack_trace)
4246 : promise_(promise),
4249 stack_trace_(stack_trace) {}
4251 V8_INLINE Handle<Promise> GetPromise() const { return promise_; }
4252 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4253 V8_INLINE Handle<Value> GetValue() const { return value_; }
4255 // DEPRECATED. Use v8::Exception::GetMessage(GetValue())->GetStackTrace()
4256 V8_INLINE Handle<StackTrace> GetStackTrace() const { return stack_trace_; }
4259 Handle<Promise> promise_;
4260 PromiseRejectEvent event_;
4261 Handle<Value> value_;
4262 Handle<StackTrace> stack_trace_;
4265 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4267 // --- Microtask Callback ---
4268 typedef void (*MicrotaskCallback)(void* data);
4270 // --- Failed Access Check Callback ---
4271 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4275 // --- AllowCodeGenerationFromStrings callbacks ---
4278 * Callback to check if code generation from strings is allowed. See
4279 * Context::AllowCodeGenerationFromStrings.
4281 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4283 // --- Garbage Collection Callbacks ---
4286 * Applications can register callback functions which will be called
4287 * before and after a garbage collection. Allocations are not
4288 * allowed in the callback functions, you therefore cannot manipulate
4289 * objects (set or delete properties for example) since it is possible
4290 * such operations will result in the allocation of objects.
4293 kGCTypeScavenge = 1 << 0,
4294 kGCTypeMarkSweepCompact = 1 << 1,
4295 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4298 enum GCCallbackFlags {
4299 kNoGCCallbackFlags = 0,
4300 kGCCallbackFlagCompacted = 1 << 0,
4301 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4302 kGCCallbackFlagForced = 1 << 2
4305 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4306 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4308 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4312 * Collection of V8 heap information.
4314 * Instances of this class can be passed to v8::V8::HeapStatistics to
4315 * get heap statistics from V8.
4317 class V8_EXPORT HeapStatistics {
4320 size_t total_heap_size() { return total_heap_size_; }
4321 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4322 size_t total_physical_size() { return total_physical_size_; }
4323 size_t used_heap_size() { return used_heap_size_; }
4324 size_t heap_size_limit() { return heap_size_limit_; }
4327 size_t total_heap_size_;
4328 size_t total_heap_size_executable_;
4329 size_t total_physical_size_;
4330 size_t used_heap_size_;
4331 size_t heap_size_limit_;
4334 friend class Isolate;
4338 class RetainedObjectInfo;
4342 * FunctionEntryHook is the type of the profile entry hook called at entry to
4343 * any generated function when function-level profiling is enabled.
4345 * \param function the address of the function that's being entered.
4346 * \param return_addr_location points to a location on stack where the machine
4347 * return address resides. This can be used to identify the caller of
4348 * \p function, and/or modified to divert execution when \p function exits.
4350 * \note the entry hook must not cause garbage collection.
4352 typedef void (*FunctionEntryHook)(uintptr_t function,
4353 uintptr_t return_addr_location);
4356 * A JIT code event is issued each time code is added, moved or removed.
4358 * \note removal events are not currently issued.
4360 struct JitCodeEvent {
4365 CODE_ADD_LINE_POS_INFO,
4366 CODE_START_LINE_INFO_RECORDING,
4367 CODE_END_LINE_INFO_RECORDING
4369 // Definition of the code position type. The "POSITION" type means the place
4370 // in the source code which are of interest when making stack traces to
4371 // pin-point the source location of a stack frame as close as possible.
4372 // The "STATEMENT_POSITION" means the place at the beginning of each
4373 // statement, and is used to indicate possible break locations.
4374 enum PositionType { POSITION, STATEMENT_POSITION };
4378 // Start of the instructions.
4380 // Size of the instructions.
4382 // Script info for CODE_ADDED event.
4383 Handle<UnboundScript> script;
4384 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4385 // code line information which is returned from the
4386 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4387 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4391 // Name of the object associated with the code, note that the string is not
4394 // Number of chars in str.
4398 struct line_info_t {
4403 // The position type.
4404 PositionType position_type;
4408 // Only valid for CODE_ADDED.
4411 // Only valid for CODE_ADD_LINE_POS_INFO
4412 struct line_info_t line_info;
4414 // New location of instructions. Only valid for CODE_MOVED.
4415 void* new_code_start;
4420 * Option flags passed to the SetJitCodeEventHandler function.
4422 enum JitCodeEventOptions {
4423 kJitCodeEventDefault = 0,
4424 // Generate callbacks for already existent code.
4425 kJitCodeEventEnumExisting = 1
4430 * Callback function passed to SetJitCodeEventHandler.
4432 * \param event code add, move or removal event.
4434 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4438 * Interface for iterating through all external resources in the heap.
4440 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4442 virtual ~ExternalResourceVisitor() {}
4443 virtual void VisitExternalString(Handle<String> string) {}
4448 * Interface for iterating through all the persistent handles in the heap.
4450 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4452 virtual ~PersistentHandleVisitor() {}
4453 virtual void VisitPersistentHandle(Persistent<Value>* value,
4454 uint16_t class_id) {}
4459 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
4460 * completely separate states. Objects from one isolate must not be used in
4461 * other isolates. The embedder can create multiple isolates and use them in
4462 * parallel in multiple threads. An isolate can be entered by at most one
4463 * thread at any given time. The Locker/Unlocker API must be used to
4466 class V8_EXPORT Isolate {
4469 * Initial configuration parameters for a new Isolate.
4471 struct CreateParams {
4474 code_event_handler(NULL),
4475 enable_serializer(false) {}
4478 * The optional entry_hook allows the host application to provide the
4479 * address of a function that's invoked on entry to every V8-generated
4480 * function. Note that entry_hook is invoked at the very start of each
4481 * generated function. Furthermore, if an entry_hook is given, V8 will
4482 * always run without a context snapshot.
4484 FunctionEntryHook entry_hook;
4487 * Allows the host application to provide the address of a function that is
4488 * notified each time code is added, moved or removed.
4490 JitCodeEventHandler code_event_handler;
4493 * ResourceConstraints to use for the new Isolate.
4495 ResourceConstraints constraints;
4498 * This flag currently renders the Isolate unusable.
4500 bool enable_serializer;
4505 * Stack-allocated class which sets the isolate for all operations
4506 * executed within a local scope.
4508 class V8_EXPORT Scope {
4510 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4514 ~Scope() { isolate_->Exit(); }
4517 Isolate* const isolate_;
4519 // Prevent copying of Scope objects.
4520 Scope(const Scope&);
4521 Scope& operator=(const Scope&);
4526 * Assert that no Javascript code is invoked.
4528 class V8_EXPORT DisallowJavascriptExecutionScope {
4530 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4532 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4533 ~DisallowJavascriptExecutionScope();
4539 // Prevent copying of Scope objects.
4540 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4541 DisallowJavascriptExecutionScope& operator=(
4542 const DisallowJavascriptExecutionScope&);
4547 * Introduce exception to DisallowJavascriptExecutionScope.
4549 class V8_EXPORT AllowJavascriptExecutionScope {
4551 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4552 ~AllowJavascriptExecutionScope();
4555 void* internal_throws_;
4556 void* internal_assert_;
4558 // Prevent copying of Scope objects.
4559 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4560 AllowJavascriptExecutionScope& operator=(
4561 const AllowJavascriptExecutionScope&);
4565 * Do not run microtasks while this scope is active, even if microtasks are
4566 * automatically executed otherwise.
4568 class V8_EXPORT SuppressMicrotaskExecutionScope {
4570 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4571 ~SuppressMicrotaskExecutionScope();
4574 internal::Isolate* isolate_;
4576 // Prevent copying of Scope objects.
4577 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4578 SuppressMicrotaskExecutionScope& operator=(
4579 const SuppressMicrotaskExecutionScope&);
4583 * Types of garbage collections that can be requested via
4584 * RequestGarbageCollectionForTesting.
4586 enum GarbageCollectionType {
4587 kFullGarbageCollection,
4588 kMinorGarbageCollection
4592 * Features reported via the SetUseCounterCallback callback. Do not chang
4593 * assigned numbers of existing items; add new features to the end of this
4596 enum UseCounterFeature {
4599 kUseCounterFeatureCount // This enum value must be last.
4602 typedef void (*UseCounterCallback)(Isolate* isolate,
4603 UseCounterFeature feature);
4607 * Creates a new isolate. Does not change the currently entered
4610 * When an isolate is no longer used its resources should be freed
4611 * by calling Dispose(). Using the delete operator is not allowed.
4613 * V8::Initialize() must have run prior to this.
4615 static Isolate* New(const CreateParams& params = CreateParams());
4618 * Returns the entered isolate for the current thread or NULL in
4619 * case there is no current isolate.
4621 static Isolate* GetCurrent();
4624 * Methods below this point require holding a lock (using Locker) in
4625 * a multi-threaded environment.
4629 * Sets this isolate as the entered one for the current thread.
4630 * Saves the previously entered one (if any), so that it can be
4631 * restored when exiting. Re-entering an isolate is allowed.
4636 * Exits this isolate by restoring the previously entered one in the
4637 * current thread. The isolate may still stay the same, if it was
4638 * entered more than once.
4640 * Requires: this == Isolate::GetCurrent().
4645 * Disposes the isolate. The isolate must not be entered by any
4646 * thread to be disposable.
4651 * Associate embedder-specific data with the isolate. |slot| has to be
4652 * between 0 and GetNumberOfDataSlots() - 1.
4654 V8_INLINE void SetData(uint32_t slot, void* data);
4657 * Retrieve embedder-specific data from the isolate.
4658 * Returns NULL if SetData has never been called for the given |slot|.
4660 V8_INLINE void* GetData(uint32_t slot);
4663 * Returns the maximum number of available embedder data slots. Valid slots
4664 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4666 V8_INLINE static uint32_t GetNumberOfDataSlots();
4669 * Get statistics about the heap memory usage.
4671 void GetHeapStatistics(HeapStatistics* heap_statistics);
4674 * Get a call stack sample from the isolate.
4675 * \param state Execution state.
4676 * \param frames Caller allocated buffer to store stack frames.
4677 * \param frames_limit Maximum number of frames to capture. The buffer must
4678 * be large enough to hold the number of frames.
4679 * \param sample_info The sample info is filled up by the function
4680 * provides number of actual captured stack frames and
4681 * the current VM state.
4682 * \note GetStackSample should only be called when the JS thread is paused or
4683 * interrupted. Otherwise the behavior is undefined.
4685 void GetStackSample(const RegisterState& state, void** frames,
4686 size_t frames_limit, SampleInfo* sample_info);
4689 * Adjusts the amount of registered external memory. Used to give V8 an
4690 * indication of the amount of externally allocated memory that is kept alive
4691 * by JavaScript objects. V8 uses this to decide when to perform global
4692 * garbage collections. Registering externally allocated memory will trigger
4693 * global garbage collections more often than it would otherwise in an attempt
4694 * to garbage collect the JavaScript objects that keep the externally
4695 * allocated memory alive.
4697 * \param change_in_bytes the change in externally allocated memory that is
4698 * kept alive by JavaScript objects.
4699 * \returns the adjusted value.
4702 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4705 * Returns heap profiler for this isolate. Will return NULL until the isolate
4708 HeapProfiler* GetHeapProfiler();
4711 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4712 * is initialized. It is the embedder's responsibility to stop all CPU
4713 * profiling activities if it has started any.
4715 CpuProfiler* GetCpuProfiler();
4717 /** Returns true if this isolate has a current context. */
4720 /** Returns the context that is on the top of the stack. */
4721 Local<Context> GetCurrentContext();
4724 * Returns the context of the calling JavaScript code. That is the
4725 * context of the top-most JavaScript frame. If there are no
4726 * JavaScript frames an empty handle is returned.
4728 Local<Context> GetCallingContext();
4730 /** Returns the last entered context. */
4731 Local<Context> GetEnteredContext();
4734 * Schedules an exception to be thrown when returning to JavaScript. When an
4735 * exception has been scheduled it is illegal to invoke any JavaScript
4736 * operation; the caller must return immediately and only after the exception
4737 * has been handled does it become legal to invoke JavaScript operations.
4739 Local<Value> ThrowException(Local<Value> exception);
4742 * Allows the host application to group objects together. If one
4743 * object in the group is alive, all objects in the group are alive.
4744 * After each garbage collection, object groups are removed. It is
4745 * intended to be used in the before-garbage-collection callback
4746 * function, for instance to simulate DOM tree connections among JS
4747 * wrapper objects. Object groups for all dependent handles need to
4748 * be provided for kGCTypeMarkSweepCompact collections, for all other
4749 * garbage collection types it is sufficient to provide object groups
4750 * for partially dependent handles only.
4752 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4756 * Allows the host application to declare implicit references from an object
4757 * group to an object. If the objects of the object group are alive, the child
4758 * object is alive too. After each garbage collection, all implicit references
4759 * are removed. It is intended to be used in the before-garbage-collection
4760 * callback function.
4762 template<typename T> void SetReferenceFromGroup(UniqueId id,
4763 const Persistent<T>& child);
4766 * Allows the host application to declare implicit references from an object
4767 * to another object. If the parent object is alive, the child object is alive
4768 * too. After each garbage collection, all implicit references are removed. It
4769 * is intended to be used in the before-garbage-collection callback function.
4771 template<typename T, typename S>
4772 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4774 typedef void (*GCPrologueCallback)(Isolate* isolate,
4776 GCCallbackFlags flags);
4777 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4779 GCCallbackFlags flags);
4782 * Enables the host application to receive a notification before a
4783 * garbage collection. Allocations are allowed in the callback function,
4784 * but the callback is not re-entrant: if the allocation inside it will
4785 * trigger the garbage collection, the callback won't be called again.
4786 * It is possible to specify the GCType filter for your callback. But it is
4787 * not possible to register the same callback function two times with
4788 * different GCType filters.
4790 void AddGCPrologueCallback(
4791 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4794 * This function removes callback which was installed by
4795 * AddGCPrologueCallback function.
4797 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4800 * Enables the host application to receive a notification after a
4801 * garbage collection. Allocations are allowed in the callback function,
4802 * but the callback is not re-entrant: if the allocation inside it will
4803 * trigger the garbage collection, the callback won't be called again.
4804 * It is possible to specify the GCType filter for your callback. But it is
4805 * not possible to register the same callback function two times with
4806 * different GCType filters.
4808 void AddGCEpilogueCallback(
4809 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4812 * This function removes callback which was installed by
4813 * AddGCEpilogueCallback function.
4815 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4819 * Forcefully terminate the current thread of JavaScript execution
4820 * in the given isolate.
4822 * This method can be used by any thread even if that thread has not
4823 * acquired the V8 lock with a Locker object.
4825 void TerminateExecution();
4828 * Is V8 terminating JavaScript execution.
4830 * Returns true if JavaScript execution is currently terminating
4831 * because of a call to TerminateExecution. In that case there are
4832 * still JavaScript frames on the stack and the termination
4833 * exception is still active.
4835 bool IsExecutionTerminating();
4838 * Resume execution capability in the given isolate, whose execution
4839 * was previously forcefully terminated using TerminateExecution().
4841 * When execution is forcefully terminated using TerminateExecution(),
4842 * the isolate can not resume execution until all JavaScript frames
4843 * have propagated the uncatchable exception which is generated. This
4844 * method allows the program embedding the engine to handle the
4845 * termination event and resume execution capability, even if
4846 * JavaScript frames remain on the stack.
4848 * This method can be used by any thread even if that thread has not
4849 * acquired the V8 lock with a Locker object.
4851 void CancelTerminateExecution();
4854 * Request V8 to interrupt long running JavaScript code and invoke
4855 * the given |callback| passing the given |data| to it. After |callback|
4856 * returns control will be returned to the JavaScript code.
4857 * At any given moment V8 can remember only a single callback for the very
4858 * last interrupt request.
4859 * Can be called from another thread without acquiring a |Locker|.
4860 * Registered |callback| must not reenter interrupted Isolate.
4862 void RequestInterrupt(InterruptCallback callback, void* data);
4865 * Clear interrupt request created by |RequestInterrupt|.
4866 * Can be called from another thread without acquiring a |Locker|.
4868 void ClearInterrupt();
4871 * Request garbage collection in this Isolate. It is only valid to call this
4872 * function if --expose_gc was specified.
4874 * This should only be used for testing purposes and not to enforce a garbage
4875 * collection schedule. It has strong negative impact on the garbage
4876 * collection performance. Use IdleNotification() or LowMemoryNotification()
4877 * instead to influence the garbage collection schedule.
4879 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4882 * Set the callback to invoke for logging event.
4884 void SetEventLogger(LogEventCallback that);
4887 * Adds a callback to notify the host application when a script finished
4888 * running. If a script re-enters the runtime during executing, the
4889 * CallCompletedCallback is only invoked when the outer-most script
4890 * execution ends. Executing scripts inside the callback do not trigger
4891 * further callbacks.
4893 void AddCallCompletedCallback(CallCompletedCallback callback);
4896 * Removes callback that was installed by AddCallCompletedCallback.
4898 void RemoveCallCompletedCallback(CallCompletedCallback callback);
4902 * Set callback to notify about promise reject with no handler, or
4903 * revocation of such a previous notification once the handler is added.
4905 void SetPromiseRejectCallback(PromiseRejectCallback callback);
4908 * Experimental: Runs the Microtask Work Queue until empty
4909 * Any exceptions thrown by microtask callbacks are swallowed.
4911 void RunMicrotasks();
4914 * Experimental: Enqueues the callback to the Microtask Work Queue
4916 void EnqueueMicrotask(Handle<Function> microtask);
4919 * Experimental: Enqueues the callback to the Microtask Work Queue
4921 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
4924 * Experimental: Controls whether the Microtask Work Queue is automatically
4925 * run when the script call depth decrements to zero.
4927 void SetAutorunMicrotasks(bool autorun);
4930 * Experimental: Returns whether the Microtask Work Queue is automatically
4931 * run when the script call depth decrements to zero.
4933 bool WillAutorunMicrotasks() const;
4936 * Sets a callback for counting the number of times a feature of V8 is used.
4938 void SetUseCounterCallback(UseCounterCallback callback);
4941 * Enables the host application to provide a mechanism for recording
4942 * statistics counters.
4944 void SetCounterFunction(CounterLookupCallback);
4947 * Enables the host application to provide a mechanism for recording
4948 * histograms. The CreateHistogram function returns a
4949 * histogram which will later be passed to the AddHistogramSample
4952 void SetCreateHistogramFunction(CreateHistogramCallback);
4953 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4956 * Optional notification that the embedder is idle.
4957 * V8 uses the notification to reduce memory footprint.
4958 * This call can be used repeatedly if the embedder remains idle.
4959 * Returns true if the embedder should stop calling IdleNotification
4960 * until real work has been done. This indicates that V8 has done
4961 * as much cleanup as it will be able to do.
4963 * The idle_time_in_ms argument specifies the time V8 has to do reduce
4964 * the memory footprint. There is no guarantee that the actual work will be
4965 * done within the time limit.
4967 bool IdleNotification(int idle_time_in_ms);
4970 * Optional notification that the system is running low on memory.
4971 * V8 uses these notifications to attempt to free memory.
4973 void LowMemoryNotification();
4976 * Optional notification that a context has been disposed. V8 uses
4977 * these notifications to guide the GC heuristic. Returns the number
4978 * of context disposals - including this one - since the last time
4979 * V8 had a chance to clean up.
4981 int ContextDisposedNotification();
4984 * Allows the host application to provide the address of a function that is
4985 * notified each time code is added, moved or removed.
4987 * \param options options for the JIT code event handler.
4988 * \param event_handler the JIT code event handler, which will be invoked
4989 * each time code is added, moved or removed.
4990 * \note \p event_handler won't get notified of existent code.
4991 * \note since code removal notifications are not currently issued, the
4992 * \p event_handler may get notifications of code that overlaps earlier
4993 * code notifications. This happens when code areas are reused, and the
4994 * earlier overlapping code areas should therefore be discarded.
4995 * \note the events passed to \p event_handler and the strings they point to
4996 * are not guaranteed to live past each call. The \p event_handler must
4997 * copy strings and other parameters it needs to keep around.
4998 * \note the set of events declared in JitCodeEvent::EventType is expected to
4999 * grow over time, and the JitCodeEvent structure is expected to accrue
5000 * new members. The \p event_handler function must ignore event codes
5001 * it does not recognize to maintain future compatibility.
5002 * \note Use Isolate::CreateParams to get events for code executed during
5005 void SetJitCodeEventHandler(JitCodeEventOptions options,
5006 JitCodeEventHandler event_handler);
5009 * Modifies the stack limit for this Isolate.
5011 * \param stack_limit An address beyond which the Vm's stack may not grow.
5013 * \note If you are using threads then you should hold the V8::Locker lock
5014 * while setting the stack limit and you must set a non-default stack
5015 * limit separately for each thread.
5017 void SetStackLimit(uintptr_t stack_limit);
5020 * Returns a memory range that can potentially contain jitted code.
5022 * On Win64, embedders are advised to install function table callbacks for
5023 * these ranges, as default SEH won't be able to unwind through jitted code.
5025 * The first page of the code range is reserved for the embedder and is
5026 * committed, writable, and executable.
5028 * Might be empty on other platforms.
5030 * https://code.google.com/p/v8/issues/detail?id=3598
5032 void GetCodeRange(void** start, size_t* length_in_bytes);
5034 /** Set the callback to invoke in case of fatal errors. */
5035 void SetFatalErrorHandler(FatalErrorCallback that);
5038 * Set the callback to invoke to check if code generation from
5039 * strings should be allowed.
5041 void SetAllowCodeGenerationFromStringsCallback(
5042 AllowCodeGenerationFromStringsCallback callback);
5045 * Check if V8 is dead and therefore unusable. This is the case after
5046 * fatal errors such as out-of-memory situations.
5051 * Adds a message listener.
5053 * The same message listener can be added more than once and in that
5054 * case it will be called more than once for each message.
5056 * If data is specified, it will be passed to the callback when it is called.
5057 * Otherwise, the exception object will be passed to the callback instead.
5059 bool AddMessageListener(MessageCallback that,
5060 Handle<Value> data = Handle<Value>());
5063 * Remove all message listeners from the specified callback function.
5065 void RemoveMessageListeners(MessageCallback that);
5067 /** Callback function for reporting failed access checks.*/
5068 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5071 * Tells V8 to capture current stack trace when uncaught exception occurs
5072 * and report it to the message listeners. The option is off by default.
5074 void SetCaptureStackTraceForUncaughtExceptions(
5075 bool capture, int frame_limit = 10,
5076 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5079 * Enables the host application to provide a mechanism to be notified
5080 * and perform custom logging when V8 Allocates Executable Memory.
5082 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5083 ObjectSpace space, AllocationAction action);
5086 * Removes callback that was installed by AddMemoryAllocationCallback.
5088 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5091 * Iterates through all external resources referenced from current isolate
5092 * heap. GC is not invoked prior to iterating, therefore there is no
5093 * guarantee that visited objects are still alive.
5095 void VisitExternalResources(ExternalResourceVisitor* visitor);
5098 * Iterates through all the persistent handles in the current isolate's heap
5099 * that have class_ids.
5101 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5104 * Iterates through all the persistent handles in the current isolate's heap
5105 * that have class_ids and are candidates to be marked as partially dependent
5106 * handles. This will visit handles to young objects created since the last
5107 * garbage collection but is free to visit an arbitrary superset of these
5110 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5113 template<class K, class V, class Traits> friend class PersistentValueMap;
5116 Isolate(const Isolate&);
5118 Isolate& operator=(const Isolate&);
5119 void* operator new(size_t size);
5120 void operator delete(void*, size_t);
5122 void SetObjectGroupId(internal::Object** object, UniqueId id);
5123 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5124 void SetReference(internal::Object** parent, internal::Object** child);
5125 void CollectAllGarbage(const char* gc_reason);
5128 class V8_EXPORT StartupData {
5130 enum CompressionAlgorithm {
5136 int compressed_size;
5142 * A helper class for driving V8 startup data decompression. It is based on
5143 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
5144 * for an embedder to use this class, instead, API functions can be used
5147 * For an example of the class usage, see the "shell.cc" sample application.
5149 class V8_EXPORT StartupDataDecompressor { // NOLINT
5151 StartupDataDecompressor();
5152 virtual ~StartupDataDecompressor();
5156 virtual int DecompressData(char* raw_data,
5158 const char* compressed_data,
5159 int compressed_data_size) = 0;
5167 * EntropySource is used as a callback function when v8 needs a source
5170 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5174 * ReturnAddressLocationResolver is used as a callback function when v8 is
5175 * resolving the location of a return address on the stack. Profilers that
5176 * change the return address on the stack can use this to resolve the stack
5177 * location to whereever the profiler stashed the original return address.
5179 * \param return_addr_location points to a location on stack where a machine
5180 * return address resides.
5181 * \returns either return_addr_location, or else a pointer to the profiler's
5182 * copy of the original return address.
5184 * \note the resolver function must not cause garbage collection.
5186 typedef uintptr_t (*ReturnAddressLocationResolver)(
5187 uintptr_t return_addr_location);
5191 * Container class for static utility functions.
5193 class V8_EXPORT V8 {
5195 /** Set the callback to invoke in case of fatal errors. */
5196 // TODO(dcarney): deprecate this.
5197 V8_INLINE static void SetFatalErrorHandler(FatalErrorCallback that);
5200 * Set the callback to invoke to check if code generation from
5201 * strings should be allowed.
5203 // TODO(dcarney): deprecate this.
5204 V8_INLINE static void SetAllowCodeGenerationFromStringsCallback(
5205 AllowCodeGenerationFromStringsCallback that);
5208 * Set allocator to use for ArrayBuffer memory.
5209 * The allocator should be set only once. The allocator should be set
5210 * before any code tha uses ArrayBuffers is executed.
5211 * This allocator is used in all isolates.
5213 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
5216 * Check if V8 is dead and therefore unusable. This is the case after
5217 * fatal errors such as out-of-memory situations.
5219 // TODO(dcarney): deprecate this.
5220 V8_INLINE static bool IsDead();
5223 * The following 4 functions are to be used when V8 is built with
5224 * the 'compress_startup_data' flag enabled. In this case, the
5225 * embedder must decompress startup data prior to initializing V8.
5227 * This is how interaction with V8 should look like:
5228 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
5229 * v8::StartupData* compressed_data =
5230 * new v8::StartupData[compressed_data_count];
5231 * v8::V8::GetCompressedStartupData(compressed_data);
5232 * ... decompress data (compressed_data can be updated in-place) ...
5233 * v8::V8::SetDecompressedStartupData(compressed_data);
5234 * ... now V8 can be initialized
5235 * ... make sure the decompressed data stays valid until V8 shutdown
5237 * A helper class StartupDataDecompressor is provided. It implements
5238 * the protocol of the interaction described above, and can be used in
5239 * most cases instead of calling these API functions directly.
5241 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
5242 static int GetCompressedStartupDataCount();
5243 static void GetCompressedStartupData(StartupData* compressed_data);
5244 static void SetDecompressedStartupData(StartupData* decompressed_data);
5247 * Hand startup data to V8, in case the embedder has chosen to build
5248 * V8 with external startup data.
5251 * - By default the startup data is linked into the V8 library, in which
5252 * case this function is not meaningful.
5253 * - If this needs to be called, it needs to be called before V8
5254 * tries to make use of its built-ins.
5255 * - To avoid unnecessary copies of data, V8 will point directly into the
5256 * given data blob, so pretty please keep it around until V8 exit.
5257 * - Compression of the startup blob might be useful, but needs to
5258 * handled entirely on the embedders' side.
5259 * - The call will abort if the data is invalid.
5261 static void SetNativesDataBlob(StartupData* startup_blob);
5262 static void SetSnapshotDataBlob(StartupData* startup_blob);
5265 * Adds a message listener.
5267 * The same message listener can be added more than once and in that
5268 * case it will be called more than once for each message.
5270 * If data is specified, it will be passed to the callback when it is called.
5271 * Otherwise, the exception object will be passed to the callback instead.
5273 // TODO(dcarney): deprecate this.
5274 V8_INLINE static bool AddMessageListener(
5275 MessageCallback that, Handle<Value> data = Handle<Value>());
5278 * Remove all message listeners from the specified callback function.
5280 // TODO(dcarney): deprecate this.
5281 V8_INLINE static void RemoveMessageListeners(MessageCallback that);
5284 * Tells V8 to capture current stack trace when uncaught exception occurs
5285 * and report it to the message listeners. The option is off by default.
5287 // TODO(dcarney): deprecate this.
5288 V8_INLINE static void SetCaptureStackTraceForUncaughtExceptions(
5289 bool capture, int frame_limit = 10,
5290 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5293 * Sets V8 flags from a string.
5295 static void SetFlagsFromString(const char* str, int length);
5298 * Sets V8 flags from the command line.
5300 static void SetFlagsFromCommandLine(int* argc,
5304 /** Get the version string. */
5305 static const char* GetVersion();
5307 /** Callback function for reporting failed access checks.*/
5308 // TODO(dcarney): deprecate this.
5309 V8_INLINE static void SetFailedAccessCheckCallbackFunction(
5310 FailedAccessCheckCallback);
5313 * Enables the host application to receive a notification before a
5314 * garbage collection. Allocations are not allowed in the
5315 * callback function, you therefore cannot manipulate objects (set
5316 * or delete properties for example) since it is possible such
5317 * operations will result in the allocation of objects. It is possible
5318 * to specify the GCType filter for your callback. But it is not possible to
5319 * register the same callback function two times with different
5322 // TODO(dcarney): deprecate this.
5323 static void AddGCPrologueCallback(
5324 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5327 * This function removes callback which was installed by
5328 * AddGCPrologueCallback function.
5330 // TODO(dcarney): deprecate this.
5331 V8_INLINE static void RemoveGCPrologueCallback(GCPrologueCallback callback);
5334 * Enables the host application to receive a notification after a
5335 * garbage collection. Allocations are not allowed in the
5336 * callback function, you therefore cannot manipulate objects (set
5337 * or delete properties for example) since it is possible such
5338 * operations will result in the allocation of objects. It is possible
5339 * to specify the GCType filter for your callback. But it is not possible to
5340 * register the same callback function two times with different
5343 // TODO(dcarney): deprecate this.
5344 static void AddGCEpilogueCallback(
5345 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5348 * This function removes callback which was installed by
5349 * AddGCEpilogueCallback function.
5351 // TODO(dcarney): deprecate this.
5352 V8_INLINE static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5355 * Enables the host application to provide a mechanism to be notified
5356 * and perform custom logging when V8 Allocates Executable Memory.
5358 // TODO(dcarney): deprecate this.
5359 V8_INLINE static void AddMemoryAllocationCallback(
5360 MemoryAllocationCallback callback, ObjectSpace space,
5361 AllocationAction action);
5364 * Removes callback that was installed by AddMemoryAllocationCallback.
5366 // TODO(dcarney): deprecate this.
5367 V8_INLINE static void RemoveMemoryAllocationCallback(
5368 MemoryAllocationCallback callback);
5371 * Initializes V8. This function needs to be called before the first Isolate
5372 * is created. It always returns true.
5374 static bool Initialize();
5377 * Allows the host application to provide a callback which can be used
5378 * as a source of entropy for random number generators.
5380 static void SetEntropySource(EntropySource source);
5383 * Allows the host application to provide a callback that allows v8 to
5384 * cooperate with a profiler that rewrites return addresses on stack.
5386 static void SetReturnAddressLocationResolver(
5387 ReturnAddressLocationResolver return_address_resolver);
5390 * Forcefully terminate the current thread of JavaScript execution
5391 * in the given isolate.
5393 * This method can be used by any thread even if that thread has not
5394 * acquired the V8 lock with a Locker object.
5396 * \param isolate The isolate in which to terminate the current JS execution.
5398 // TODO(dcarney): deprecate this.
5399 V8_INLINE static void TerminateExecution(Isolate* isolate);
5402 * Is V8 terminating JavaScript execution.
5404 * Returns true if JavaScript execution is currently terminating
5405 * because of a call to TerminateExecution. In that case there are
5406 * still JavaScript frames on the stack and the termination
5407 * exception is still active.
5409 * \param isolate The isolate in which to check.
5411 // TODO(dcarney): deprecate this.
5412 V8_INLINE static bool IsExecutionTerminating(Isolate* isolate = NULL);
5415 * Resume execution capability in the given isolate, whose execution
5416 * was previously forcefully terminated using TerminateExecution().
5418 * When execution is forcefully terminated using TerminateExecution(),
5419 * the isolate can not resume execution until all JavaScript frames
5420 * have propagated the uncatchable exception which is generated. This
5421 * method allows the program embedding the engine to handle the
5422 * termination event and resume execution capability, even if
5423 * JavaScript frames remain on the stack.
5425 * This method can be used by any thread even if that thread has not
5426 * acquired the V8 lock with a Locker object.
5428 * \param isolate The isolate in which to resume execution capability.
5430 // TODO(dcarney): deprecate this.
5431 V8_INLINE static void CancelTerminateExecution(Isolate* isolate);
5434 * Releases any resources used by v8 and stops any utility threads
5435 * that may be running. Note that disposing v8 is permanent, it
5436 * cannot be reinitialized.
5438 * It should generally not be necessary to dispose v8 before exiting
5439 * a process, this should happen automatically. It is only necessary
5440 * to use if the process needs the resources taken up by v8.
5442 static bool Dispose();
5445 * Iterates through all external resources referenced from current isolate
5446 * heap. GC is not invoked prior to iterating, therefore there is no
5447 * guarantee that visited objects are still alive.
5449 // TODO(dcarney): deprecate this.
5450 V8_INLINE static void VisitExternalResources(
5451 ExternalResourceVisitor* visitor);
5454 * Iterates through all the persistent handles in the current isolate's heap
5455 * that have class_ids.
5457 // TODO(dcarney): deprecate this.
5458 V8_INLINE static void VisitHandlesWithClassIds(
5459 PersistentHandleVisitor* visitor);
5462 * Iterates through all the persistent handles in isolate's heap that have
5465 // TODO(dcarney): deprecate this.
5466 V8_INLINE static void VisitHandlesWithClassIds(
5467 Isolate* isolate, PersistentHandleVisitor* visitor);
5470 * Iterates through all the persistent handles in the current isolate's heap
5471 * that have class_ids and are candidates to be marked as partially dependent
5472 * handles. This will visit handles to young objects created since the last
5473 * garbage collection but is free to visit an arbitrary superset of these
5476 // TODO(dcarney): deprecate this.
5477 V8_INLINE static void VisitHandlesForPartialDependence(
5478 Isolate* isolate, PersistentHandleVisitor* visitor);
5481 * Initialize the ICU library bundled with V8. The embedder should only
5482 * invoke this method when using the bundled ICU. Returns true on success.
5484 * If V8 was compiled with the ICU data in an external file, the location
5485 * of the data file has to be provided.
5487 static bool InitializeICU(const char* icu_data_file = NULL);
5490 * Sets the v8::Platform to use. This should be invoked before V8 is
5493 static void InitializePlatform(Platform* platform);
5496 * Clears all references to the v8::Platform. This should be invoked after
5499 static void ShutdownPlatform();
5504 enum WeakHandleType { PhantomHandle, NonphantomHandle };
5506 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5507 internal::Object** handle);
5508 static internal::Object** CopyPersistent(internal::Object** handle);
5509 static void DisposeGlobal(internal::Object** global_handle);
5510 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5511 static void MakeWeak(internal::Object** global_handle, void* data,
5512 WeakCallback weak_callback, WeakHandleType phantom);
5513 static void* ClearWeak(internal::Object** global_handle);
5514 static void Eternalize(Isolate* isolate,
5517 static Local<Value> GetEternal(Isolate* isolate, int index);
5519 template <class T> friend class Handle;
5520 template <class T> friend class Local;
5521 template <class T> friend class Eternal;
5522 template <class T> friend class PersistentBase;
5523 template <class T, class M> friend class Persistent;
5524 friend class Context;
5529 * An external exception handler.
5531 class V8_EXPORT TryCatch {
5534 * Creates a new try/catch block and registers it with v8. Note that
5535 * all TryCatch blocks should be stack allocated because the memory
5536 * location itself is compared against JavaScript try/catch blocks.
5538 // TODO(dcarney): deprecate.
5542 * Creates a new try/catch block and registers it with v8. Note that
5543 * all TryCatch blocks should be stack allocated because the memory
5544 * location itself is compared against JavaScript try/catch blocks.
5546 TryCatch(Isolate* isolate);
5549 * Unregisters and deletes this try/catch block.
5554 * Returns true if an exception has been caught by this try/catch block.
5556 bool HasCaught() const;
5559 * For certain types of exceptions, it makes no sense to continue execution.
5561 * If CanContinue returns false, the correct action is to perform any C++
5562 * cleanup needed and then return. If CanContinue returns false and
5563 * HasTerminated returns true, it is possible to call
5564 * CancelTerminateExecution in order to continue calling into the engine.
5566 bool CanContinue() const;
5569 * Returns true if an exception has been caught due to script execution
5572 * There is no JavaScript representation of an execution termination
5573 * exception. Such exceptions are thrown when the TerminateExecution
5574 * methods are called to terminate a long-running script.
5576 * If such an exception has been thrown, HasTerminated will return true,
5577 * indicating that it is possible to call CancelTerminateExecution in order
5578 * to continue calling into the engine.
5580 bool HasTerminated() const;
5583 * Throws the exception caught by this TryCatch in a way that avoids
5584 * it being caught again by this same TryCatch. As with ThrowException
5585 * it is illegal to execute any JavaScript operations after calling
5586 * ReThrow; the caller must return immediately to where the exception
5589 Handle<Value> ReThrow();
5592 * Returns the exception caught by this try/catch block. If no exception has
5593 * been caught an empty handle is returned.
5595 * The returned handle is valid until this TryCatch block has been destroyed.
5597 Local<Value> Exception() const;
5600 * Returns the .stack property of the thrown object. If no .stack
5601 * property is present an empty handle is returned.
5603 Local<Value> StackTrace() const;
5606 * Returns the message associated with this exception. If there is
5607 * no message associated an empty handle is returned.
5609 * The returned handle is valid until this TryCatch block has been
5612 Local<v8::Message> Message() const;
5615 * Clears any exceptions that may have been caught by this try/catch block.
5616 * After this method has been called, HasCaught() will return false. Cancels
5617 * the scheduled exception if it is caught and ReThrow() is not called before.
5619 * It is not necessary to clear a try/catch block before using it again; if
5620 * another exception is thrown the previously caught exception will just be
5621 * overwritten. However, it is often a good idea since it makes it easier
5622 * to determine which operation threw a given exception.
5627 * Set verbosity of the external exception handler.
5629 * By default, exceptions that are caught by an external exception
5630 * handler are not reported. Call SetVerbose with true on an
5631 * external exception handler to have exceptions caught by the
5632 * handler reported as if they were not caught.
5634 void SetVerbose(bool value);
5637 * Set whether or not this TryCatch should capture a Message object
5638 * which holds source information about where the exception
5639 * occurred. True by default.
5641 void SetCaptureMessage(bool value);
5644 * There are cases when the raw address of C++ TryCatch object cannot be
5645 * used for comparisons with addresses into the JS stack. The cases are:
5646 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5647 * 2) Address sanitizer allocates local C++ object in the heap when
5648 * UseAfterReturn mode is enabled.
5649 * This method returns address that can be used for comparisons with
5650 * addresses into the JS stack. When neither simulator nor ASAN's
5651 * UseAfterReturn is enabled, then the address returned will be the address
5652 * of the C++ try catch handler itself.
5654 static void* JSStackComparableAddress(v8::TryCatch* handler) {
5655 if (handler == NULL) return NULL;
5656 return handler->js_stack_comparable_address_;
5660 void ResetInternal();
5662 // Make it hard to create heap-allocated TryCatch blocks.
5663 TryCatch(const TryCatch&);
5664 void operator=(const TryCatch&);
5665 void* operator new(size_t size);
5666 void operator delete(void*, size_t);
5668 v8::internal::Isolate* isolate_;
5669 v8::TryCatch* next_;
5672 void* message_script_;
5673 void* js_stack_comparable_address_;
5674 int message_start_pos_;
5675 int message_end_pos_;
5676 bool is_verbose_ : 1;
5677 bool can_continue_ : 1;
5678 bool capture_message_ : 1;
5680 bool has_terminated_ : 1;
5682 friend class v8::internal::Isolate;
5690 * A container for extension names.
5692 class V8_EXPORT ExtensionConfiguration {
5694 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
5695 ExtensionConfiguration(int name_count, const char* names[])
5696 : name_count_(name_count), names_(names) { }
5698 const char** begin() const { return &names_[0]; }
5699 const char** end() const { return &names_[name_count_]; }
5702 const int name_count_;
5703 const char** names_;
5708 * A sandboxed execution context with its own set of built-in objects
5711 class V8_EXPORT Context {
5714 * Returns the global proxy object.
5716 * Global proxy object is a thin wrapper whose prototype points to actual
5717 * context's global object with the properties like Object, etc. This is done
5718 * that way for security reasons (for more details see
5719 * https://wiki.mozilla.org/Gecko:SplitWindow).
5721 * Please note that changes to global proxy object prototype most probably
5722 * would break VM---v8 expects only global object as a prototype of global
5725 Local<Object> Global();
5728 * Detaches the global object from its context before
5729 * the global object can be reused to create a new context.
5731 void DetachGlobal();
5734 * Creates a new context and returns a handle to the newly allocated
5737 * \param isolate The isolate in which to create the context.
5739 * \param extensions An optional extension configuration containing
5740 * the extensions to be installed in the newly created context.
5742 * \param global_template An optional object template from which the
5743 * global object for the newly created context will be created.
5745 * \param global_object An optional global object to be reused for
5746 * the newly created context. This global object must have been
5747 * created by a previous call to Context::New with the same global
5748 * template. The state of the global object will be completely reset
5749 * and only object identify will remain.
5751 static Local<Context> New(
5753 ExtensionConfiguration* extensions = NULL,
5754 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5755 Handle<Value> global_object = Handle<Value>());
5758 * Sets the security token for the context. To access an object in
5759 * another context, the security tokens must match.
5761 void SetSecurityToken(Handle<Value> token);
5763 /** Restores the security token to the default value. */
5764 void UseDefaultSecurityToken();
5766 /** Returns the security token of this context.*/
5767 Handle<Value> GetSecurityToken();
5770 * Enter this context. After entering a context, all code compiled
5771 * and run is compiled and run in this context. If another context
5772 * is already entered, this old context is saved so it can be
5773 * restored when the new context is exited.
5778 * Exit this context. Exiting the current context restores the
5779 * context that was in place when entering the current context.
5783 /** Returns an isolate associated with a current context. */
5784 v8::Isolate* GetIsolate();
5787 * Gets the embedder data with the given index, which must have been set by a
5788 * previous call to SetEmbedderData with the same index. Note that index 0
5789 * currently has a special meaning for Chrome's debugger.
5791 V8_INLINE Local<Value> GetEmbedderData(int index);
5794 * Sets the embedder data with the given index, growing the data as
5795 * needed. Note that index 0 currently has a special meaning for Chrome's
5798 void SetEmbedderData(int index, Handle<Value> value);
5801 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5802 * index, which must have bees set by a previous call to
5803 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5804 * currently has a special meaning for Chrome's debugger.
5806 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5809 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5810 * index, growing the data as needed. Note that index 0 currently has a
5811 * special meaning for Chrome's debugger.
5813 void SetAlignedPointerInEmbedderData(int index, void* value);
5816 * Control whether code generation from strings is allowed. Calling
5817 * this method with false will disable 'eval' and the 'Function'
5818 * constructor for code running in this context. If 'eval' or the
5819 * 'Function' constructor are used an exception will be thrown.
5821 * If code generation from strings is not allowed the
5822 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5823 * set before blocking the call to 'eval' or the 'Function'
5824 * constructor. If that callback returns true, the call will be
5825 * allowed, otherwise an exception will be thrown. If no callback is
5826 * set an exception will be thrown.
5828 void AllowCodeGenerationFromStrings(bool allow);
5831 * Returns true if code generation from strings is allowed for the context.
5832 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5834 bool IsCodeGenerationFromStringsAllowed();
5837 * Sets the error description for the exception that is thrown when
5838 * code generation from strings is not allowed and 'eval' or the 'Function'
5839 * constructor are called.
5841 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5844 * Stack-allocated class which sets the execution context for all
5845 * operations executed within a local scope.
5849 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5852 V8_INLINE ~Scope() { context_->Exit(); }
5855 Handle<Context> context_;
5860 friend class Script;
5861 friend class Object;
5862 friend class Function;
5864 Local<Value> SlowGetEmbedderData(int index);
5865 void* SlowGetAlignedPointerFromEmbedderData(int index);
5870 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5871 * to use any given V8 isolate, see the comments in the Isolate class. The
5872 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5873 * object pointers obtained from V8 handles while in the particular V8 isolate.
5874 * It is up to the user of V8 to ensure, perhaps with locking, that this
5875 * constraint is not violated. In addition to any other synchronization
5876 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5877 * used to signal thead switches to V8.
5879 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5880 * construction and destruction, the current thread is allowed to use the locked
5881 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5882 * any time. In other words, the scope of a v8::Locker is a critical section.
5888 * v8::Locker locker(isolate);
5889 * v8::Isolate::Scope isolate_scope(isolate);
5891 * // Code using V8 and isolate goes here.
5893 * } // Destructor called here
5896 * If you wish to stop using V8 in a thread A you can do this either by
5897 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5903 * v8::Unlocker unlocker(isolate);
5905 * // Code not using V8 goes here while V8 can run in another thread.
5907 * } // Destructor called here.
5911 * The Unlocker object is intended for use in a long-running callback from V8,
5912 * where you want to release the V8 lock for other threads to use.
5914 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5915 * given thread. This can be useful if you have code that can be called either
5916 * from code that holds the lock or from code that does not. The Unlocker is
5917 * not recursive so you can not have several Unlockers on the stack at once, and
5918 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5920 * An unlocker will unlock several lockers if it has to and reinstate the
5921 * correct depth of locking on its destruction, e.g.:
5926 * v8::Locker locker(isolate);
5927 * Isolate::Scope isolate_scope(isolate);
5930 * v8::Locker another_locker(isolate);
5931 * // V8 still locked (2 levels).
5934 * v8::Unlocker unlocker(isolate);
5938 * // V8 locked again (2 levels).
5940 * // V8 still locked (1 level).
5942 * // V8 Now no longer locked.
5945 class V8_EXPORT Unlocker {
5948 * Initialize Unlocker for a given Isolate.
5950 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5954 void Initialize(Isolate* isolate);
5956 internal::Isolate* isolate_;
5960 class V8_EXPORT Locker {
5963 * Initialize Locker for a given Isolate.
5965 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5970 * Returns whether or not the locker for a given isolate, is locked by the
5973 static bool IsLocked(Isolate* isolate);
5976 * Returns whether v8::Locker is being used by this V8 instance.
5978 static bool IsActive();
5981 void Initialize(Isolate* isolate);
5985 internal::Isolate* isolate_;
5987 // Disallow copying and assigning.
5988 Locker(const Locker&);
5989 void operator=(const Locker&);
5993 // --- Implementation ---
5996 namespace internal {
5998 const int kApiPointerSize = sizeof(void*); // NOLINT
5999 const int kApiIntSize = sizeof(int); // NOLINT
6000 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6002 // Tag information for HeapObject.
6003 const int kHeapObjectTag = 1;
6004 const int kHeapObjectTagSize = 2;
6005 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6007 // Tag information for Smi.
6008 const int kSmiTag = 0;
6009 const int kSmiTagSize = 1;
6010 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6012 template <size_t ptr_size> struct SmiTagging;
6014 template<int kSmiShiftSize>
6015 V8_INLINE internal::Object* IntToSmi(int value) {
6016 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6017 uintptr_t tagged_value =
6018 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6019 return reinterpret_cast<internal::Object*>(tagged_value);
6022 // Smi constants for 32-bit systems.
6023 template <> struct SmiTagging<4> {
6024 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6025 static int SmiShiftSize() { return kSmiShiftSize; }
6026 static int SmiValueSize() { return kSmiValueSize; }
6027 V8_INLINE static int SmiToInt(const internal::Object* value) {
6028 int shift_bits = kSmiTagSize + kSmiShiftSize;
6029 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6030 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6032 V8_INLINE static internal::Object* IntToSmi(int value) {
6033 return internal::IntToSmi<kSmiShiftSize>(value);
6035 V8_INLINE static bool IsValidSmi(intptr_t value) {
6036 // To be representable as an tagged small integer, the two
6037 // most-significant bits of 'value' must be either 00 or 11 due to
6038 // sign-extension. To check this we add 01 to the two
6039 // most-significant bits, and check if the most-significant bit is 0
6041 // CAUTION: The original code below:
6042 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6043 // may lead to incorrect results according to the C language spec, and
6044 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6045 // compiler may produce undefined results in case of signed integer
6046 // overflow. The computation must be done w/ unsigned ints.
6047 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6051 // Smi constants for 64-bit systems.
6052 template <> struct SmiTagging<8> {
6053 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6054 static int SmiShiftSize() { return kSmiShiftSize; }
6055 static int SmiValueSize() { return kSmiValueSize; }
6056 V8_INLINE static int SmiToInt(const internal::Object* value) {
6057 int shift_bits = kSmiTagSize + kSmiShiftSize;
6058 // Shift down and throw away top 32 bits.
6059 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6061 V8_INLINE static internal::Object* IntToSmi(int value) {
6062 return internal::IntToSmi<kSmiShiftSize>(value);
6064 V8_INLINE static bool IsValidSmi(intptr_t value) {
6065 // To be representable as a long smi, the value must be a 32-bit integer.
6066 return (value == static_cast<int32_t>(value));
6070 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6071 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6072 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6073 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6074 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6077 * This class exports constants and functionality from within v8 that
6078 * is necessary to implement inline functions in the v8 api. Don't
6079 * depend on functions and constants defined here.
6083 // These values match non-compiler-dependent values defined within
6084 // the implementation of v8.
6085 static const int kHeapObjectMapOffset = 0;
6086 static const int kMapInstanceTypeAndBitFieldOffset =
6087 1 * kApiPointerSize + kApiIntSize;
6088 static const int kStringResourceOffset = 3 * kApiPointerSize;
6090 static const int kOddballKindOffset = 3 * kApiPointerSize;
6091 static const int kForeignAddressOffset = kApiPointerSize;
6092 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6093 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6094 static const int kContextHeaderSize = 2 * kApiPointerSize;
6095 static const int kContextEmbedderDataIndex = 76;
6096 static const int kFullStringRepresentationMask = 0x07;
6097 static const int kStringEncodingMask = 0x4;
6098 static const int kExternalTwoByteRepresentationTag = 0x02;
6099 static const int kExternalOneByteRepresentationTag = 0x06;
6101 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6102 static const int kAmountOfExternalAllocatedMemoryOffset =
6103 4 * kApiPointerSize;
6104 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6105 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6106 static const int kIsolateRootsOffset =
6107 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6109 static const int kUndefinedValueRootIndex = 5;
6110 static const int kNullValueRootIndex = 7;
6111 static const int kTrueValueRootIndex = 8;
6112 static const int kFalseValueRootIndex = 9;
6113 static const int kEmptyStringRootIndex = 154;
6115 // The external allocation limit should be below 256 MB on all architectures
6116 // to avoid that resource-constrained embedders run low on memory.
6117 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6119 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6120 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6121 static const int kNodeStateMask = 0xf;
6122 static const int kNodeStateIsWeakValue = 2;
6123 static const int kNodeStateIsPendingValue = 3;
6124 static const int kNodeStateIsNearDeathValue = 4;
6125 static const int kNodeIsIndependentShift = 4;
6126 static const int kNodeIsPartiallyDependentShift = 5;
6128 static const int kJSObjectType = 0xbd;
6129 static const int kFirstNonstringType = 0x80;
6130 static const int kOddballType = 0x83;
6131 static const int kForeignType = 0x88;
6133 static const int kUndefinedOddballKind = 5;
6134 static const int kNullOddballKind = 3;
6136 static const uint32_t kNumIsolateDataSlots = 4;
6138 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
6139 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
6140 #ifdef V8_ENABLE_CHECKS
6141 CheckInitializedImpl(isolate);
6145 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
6146 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
6150 V8_INLINE static int SmiValue(const internal::Object* value) {
6151 return PlatformSmiTagging::SmiToInt(value);
6154 V8_INLINE static internal::Object* IntToSmi(int value) {
6155 return PlatformSmiTagging::IntToSmi(value);
6158 V8_INLINE static bool IsValidSmi(intptr_t value) {
6159 return PlatformSmiTagging::IsValidSmi(value);
6162 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
6163 typedef internal::Object O;
6164 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
6165 // Map::InstanceType is defined so that it will always be loaded into
6166 // the LS 8 bits of one 16-bit word, regardless of endianess.
6167 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
6170 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
6171 typedef internal::Object O;
6172 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
6175 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
6176 int representation = (instance_type & kFullStringRepresentationMask);
6177 return representation == kExternalTwoByteRepresentationTag;
6180 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
6181 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6182 return *addr & static_cast<uint8_t>(1U << shift);
6185 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
6186 bool value, int shift) {
6187 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6188 uint8_t mask = static_cast<uint8_t>(1U << shift);
6189 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
6192 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
6193 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6194 return *addr & kNodeStateMask;
6197 V8_INLINE static void UpdateNodeState(internal::Object** obj,
6199 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6200 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
6203 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
6206 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
6207 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
6208 *reinterpret_cast<void**>(addr) = data;
6211 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
6213 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
6214 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
6215 return *reinterpret_cast<void* const*>(addr);
6218 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
6220 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
6221 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
6224 template <typename T>
6225 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
6226 const uint8_t* addr =
6227 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
6228 return *reinterpret_cast<const T*>(addr);
6231 template <typename T>
6232 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
6233 typedef internal::Object O;
6234 typedef internal::Internals I;
6235 O* ctx = *reinterpret_cast<O* const*>(context);
6236 int embedder_data_offset = I::kContextHeaderSize +
6237 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
6238 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
6240 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
6241 return I::ReadField<T>(embedder_data, value_offset);
6245 } // namespace internal
6249 Local<T>::Local() : Handle<T>() { }
6253 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
6254 return New(isolate, that.val_);
6258 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
6259 return New(isolate, that.val_);
6263 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
6264 if (that == NULL) return Handle<T>();
6266 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
6267 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
6268 reinterpret_cast<internal::Isolate*>(isolate), *p)));
6273 Local<T> Local<T>::New(Isolate* isolate, T* that) {
6274 if (that == NULL) return Local<T>();
6276 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
6277 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
6278 reinterpret_cast<internal::Isolate*>(isolate), *p)));
6284 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
6286 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
6291 Local<T> Eternal<T>::Get(Isolate* isolate) {
6292 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
6297 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
6298 if (that == NULL) return NULL;
6299 internal::Object** p = reinterpret_cast<internal::Object**>(that);
6300 return reinterpret_cast<T*>(
6301 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
6306 template <class T, class M>
6307 template <class S, class M2>
6308 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
6311 if (that.IsEmpty()) return;
6312 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
6313 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
6314 M::Copy(that, this);
6319 bool PersistentBase<T>::IsIndependent() const {
6320 typedef internal::Internals I;
6321 if (this->IsEmpty()) return false;
6322 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6323 I::kNodeIsIndependentShift);
6328 bool PersistentBase<T>::IsNearDeath() const {
6329 typedef internal::Internals I;
6330 if (this->IsEmpty()) return false;
6331 uint8_t node_state =
6332 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
6333 return node_state == I::kNodeStateIsNearDeathValue ||
6334 node_state == I::kNodeStateIsPendingValue;
6339 bool PersistentBase<T>::IsWeak() const {
6340 typedef internal::Internals I;
6341 if (this->IsEmpty()) return false;
6342 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
6343 I::kNodeStateIsWeakValue;
6348 void PersistentBase<T>::Reset() {
6349 if (this->IsEmpty()) return;
6350 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
6357 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
6360 if (other.IsEmpty()) return;
6361 this->val_ = New(isolate, other.val_);
6367 void PersistentBase<T>::Reset(Isolate* isolate,
6368 const PersistentBase<S>& other) {
6371 if (other.IsEmpty()) return;
6372 this->val_ = New(isolate, other.val_);
6377 template <typename S, typename P>
6378 void PersistentBase<T>::SetWeak(
6380 typename WeakCallbackData<S, P>::Callback callback) {
6382 typedef typename WeakCallbackData<Value, void>::Callback Callback;
6383 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
6384 reinterpret_cast<Callback>(callback), V8::NonphantomHandle);
6389 template <typename P>
6390 void PersistentBase<T>::SetWeak(
6392 typename WeakCallbackData<T, P>::Callback callback) {
6393 SetWeak<T, P>(parameter, callback);
6398 template <typename S, typename P>
6399 void PersistentBase<T>::SetPhantom(
6400 P* parameter, typename WeakCallbackData<S, P>::Callback callback) {
6402 typedef typename WeakCallbackData<Value, void>::Callback Callback;
6403 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
6404 reinterpret_cast<Callback>(callback), V8::PhantomHandle);
6409 template <typename P>
6410 void PersistentBase<T>::SetPhantom(
6411 P* parameter, typename WeakCallbackData<T, P>::Callback callback) {
6412 SetPhantom<T, P>(parameter, callback);
6417 template <typename P>
6418 P* PersistentBase<T>::ClearWeak() {
6419 return reinterpret_cast<P*>(
6420 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
6425 void PersistentBase<T>::MarkIndependent() {
6426 typedef internal::Internals I;
6427 if (this->IsEmpty()) return;
6428 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6430 I::kNodeIsIndependentShift);
6435 void PersistentBase<T>::MarkPartiallyDependent() {
6436 typedef internal::Internals I;
6437 if (this->IsEmpty()) return;
6438 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6440 I::kNodeIsPartiallyDependentShift);
6445 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
6446 typedef internal::Internals I;
6447 if (this->IsEmpty()) return;
6448 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6449 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6450 *reinterpret_cast<uint16_t*>(addr) = class_id;
6455 uint16_t PersistentBase<T>::WrapperClassId() const {
6456 typedef internal::Internals I;
6457 if (this->IsEmpty()) return 0;
6458 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6459 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6460 return *reinterpret_cast<uint16_t*>(addr);
6464 template<typename T>
6465 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
6467 template<typename T>
6468 template<typename S>
6469 void ReturnValue<T>::Set(const Persistent<S>& handle) {
6471 if (V8_UNLIKELY(handle.IsEmpty())) {
6472 *value_ = GetDefaultValue();
6474 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6478 template<typename T>
6479 template<typename S>
6480 void ReturnValue<T>::Set(const Handle<S> handle) {
6482 if (V8_UNLIKELY(handle.IsEmpty())) {
6483 *value_ = GetDefaultValue();
6485 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6489 template<typename T>
6490 void ReturnValue<T>::Set(double i) {
6491 TYPE_CHECK(T, Number);
6492 Set(Number::New(GetIsolate(), i));
6495 template<typename T>
6496 void ReturnValue<T>::Set(int32_t i) {
6497 TYPE_CHECK(T, Integer);
6498 typedef internal::Internals I;
6499 if (V8_LIKELY(I::IsValidSmi(i))) {
6500 *value_ = I::IntToSmi(i);
6503 Set(Integer::New(GetIsolate(), i));
6506 template<typename T>
6507 void ReturnValue<T>::Set(uint32_t i) {
6508 TYPE_CHECK(T, Integer);
6509 // Can't simply use INT32_MAX here for whatever reason.
6510 bool fits_into_int32_t = (i & (1U << 31)) == 0;
6511 if (V8_LIKELY(fits_into_int32_t)) {
6512 Set(static_cast<int32_t>(i));
6515 Set(Integer::NewFromUnsigned(GetIsolate(), i));
6518 template<typename T>
6519 void ReturnValue<T>::Set(bool value) {
6520 TYPE_CHECK(T, Boolean);
6521 typedef internal::Internals I;
6524 root_index = I::kTrueValueRootIndex;
6526 root_index = I::kFalseValueRootIndex;
6528 *value_ = *I::GetRoot(GetIsolate(), root_index);
6531 template<typename T>
6532 void ReturnValue<T>::SetNull() {
6533 TYPE_CHECK(T, Primitive);
6534 typedef internal::Internals I;
6535 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6538 template<typename T>
6539 void ReturnValue<T>::SetUndefined() {
6540 TYPE_CHECK(T, Primitive);
6541 typedef internal::Internals I;
6542 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6545 template<typename T>
6546 void ReturnValue<T>::SetEmptyString() {
6547 TYPE_CHECK(T, String);
6548 typedef internal::Internals I;
6549 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6552 template<typename T>
6553 Isolate* ReturnValue<T>::GetIsolate() {
6554 // Isolate is always the pointer below the default value on the stack.
6555 return *reinterpret_cast<Isolate**>(&value_[-2]);
6558 template<typename T>
6559 template<typename S>
6560 void ReturnValue<T>::Set(S* whatever) {
6561 // Uncompilable to prevent inadvertent misuse.
6562 TYPE_CHECK(S*, Primitive);
6565 template<typename T>
6566 internal::Object* ReturnValue<T>::GetDefaultValue() {
6567 // Default value is always the pointer below value_ on the stack.
6572 template<typename T>
6573 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6574 internal::Object** values,
6576 bool is_construct_call)
6577 : implicit_args_(implicit_args),
6580 is_construct_call_(is_construct_call) { }
6583 template<typename T>
6584 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6585 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6586 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6590 template<typename T>
6591 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6592 return Local<Function>(reinterpret_cast<Function*>(
6593 &implicit_args_[kCalleeIndex]));
6597 template<typename T>
6598 Local<Object> FunctionCallbackInfo<T>::This() const {
6599 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6603 template<typename T>
6604 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6605 return Local<Object>(reinterpret_cast<Object*>(
6606 &implicit_args_[kHolderIndex]));
6610 template<typename T>
6611 Local<Value> FunctionCallbackInfo<T>::Data() const {
6612 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6616 template<typename T>
6617 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6618 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6622 template<typename T>
6623 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6624 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6628 template<typename T>
6629 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6630 return is_construct_call_;
6634 template<typename T>
6635 int FunctionCallbackInfo<T>::Length() const {
6640 Handle<Value> ScriptOrigin::ResourceName() const {
6641 return resource_name_;
6645 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6646 return resource_line_offset_;
6650 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6651 return resource_column_offset_;
6655 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6656 return resource_is_shared_cross_origin_;
6660 Handle<Integer> ScriptOrigin::ScriptID() const {
6665 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6667 : source_string(string),
6668 resource_name(origin.ResourceName()),
6669 resource_line_offset(origin.ResourceLineOffset()),
6670 resource_column_offset(origin.ResourceColumnOffset()),
6671 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6672 cached_data(data) {}
6675 ScriptCompiler::Source::Source(Local<String> string,
6677 : source_string(string), cached_data(data) {}
6680 ScriptCompiler::Source::~Source() {
6685 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6691 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6692 return value ? True(isolate) : False(isolate);
6696 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6697 Set(v8::String::NewFromUtf8(isolate, name), value);
6701 Local<Value> Object::GetInternalField(int index) {
6702 #ifndef V8_ENABLE_CHECKS
6703 typedef internal::Object O;
6704 typedef internal::HeapObject HO;
6705 typedef internal::Internals I;
6706 O* obj = *reinterpret_cast<O**>(this);
6707 // Fast path: If the object is a plain JSObject, which is the common case, we
6708 // know where to find the internal fields and can return the value directly.
6709 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6710 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6711 O* value = I::ReadField<O*>(obj, offset);
6712 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6713 return Local<Value>(reinterpret_cast<Value*>(result));
6716 return SlowGetInternalField(index);
6720 void* Object::GetAlignedPointerFromInternalField(int index) {
6721 #ifndef V8_ENABLE_CHECKS
6722 typedef internal::Object O;
6723 typedef internal::Internals I;
6724 O* obj = *reinterpret_cast<O**>(this);
6725 // Fast path: If the object is a plain JSObject, which is the common case, we
6726 // know where to find the internal fields and can return the value directly.
6727 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6728 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6729 return I::ReadField<void*>(obj, offset);
6732 return SlowGetAlignedPointerFromInternalField(index);
6736 String* String::Cast(v8::Value* value) {
6737 #ifdef V8_ENABLE_CHECKS
6740 return static_cast<String*>(value);
6744 Local<String> String::Empty(Isolate* isolate) {
6745 typedef internal::Object* S;
6746 typedef internal::Internals I;
6747 I::CheckInitialized(isolate);
6748 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6749 return Local<String>(reinterpret_cast<String*>(slot));
6753 String::ExternalStringResource* String::GetExternalStringResource() const {
6754 typedef internal::Object O;
6755 typedef internal::Internals I;
6756 O* obj = *reinterpret_cast<O* const*>(this);
6757 String::ExternalStringResource* result;
6758 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6759 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6760 result = reinterpret_cast<String::ExternalStringResource*>(value);
6764 #ifdef V8_ENABLE_CHECKS
6765 VerifyExternalStringResource(result);
6771 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6772 String::Encoding* encoding_out) const {
6773 typedef internal::Object O;
6774 typedef internal::Internals I;
6775 O* obj = *reinterpret_cast<O* const*>(this);
6776 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6777 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6778 ExternalStringResourceBase* resource = NULL;
6779 if (type == I::kExternalOneByteRepresentationTag ||
6780 type == I::kExternalTwoByteRepresentationTag) {
6781 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6782 resource = static_cast<ExternalStringResourceBase*>(value);
6784 #ifdef V8_ENABLE_CHECKS
6785 VerifyExternalStringResourceBase(resource, *encoding_out);
6791 bool Value::IsUndefined() const {
6792 #ifdef V8_ENABLE_CHECKS
6793 return FullIsUndefined();
6795 return QuickIsUndefined();
6799 bool Value::QuickIsUndefined() const {
6800 typedef internal::Object O;
6801 typedef internal::Internals I;
6802 O* obj = *reinterpret_cast<O* const*>(this);
6803 if (!I::HasHeapObjectTag(obj)) return false;
6804 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6805 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6809 bool Value::IsNull() const {
6810 #ifdef V8_ENABLE_CHECKS
6811 return FullIsNull();
6813 return QuickIsNull();
6817 bool Value::QuickIsNull() const {
6818 typedef internal::Object O;
6819 typedef internal::Internals I;
6820 O* obj = *reinterpret_cast<O* const*>(this);
6821 if (!I::HasHeapObjectTag(obj)) return false;
6822 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6823 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6827 bool Value::IsString() const {
6828 #ifdef V8_ENABLE_CHECKS
6829 return FullIsString();
6831 return QuickIsString();
6835 bool Value::QuickIsString() const {
6836 typedef internal::Object O;
6837 typedef internal::Internals I;
6838 O* obj = *reinterpret_cast<O* const*>(this);
6839 if (!I::HasHeapObjectTag(obj)) return false;
6840 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6844 template <class T> Value* Value::Cast(T* value) {
6845 return static_cast<Value*>(value);
6849 Local<Boolean> Value::ToBoolean() const {
6850 return ToBoolean(Isolate::GetCurrent());
6854 Local<Number> Value::ToNumber() const {
6855 return ToNumber(Isolate::GetCurrent());
6859 Local<String> Value::ToString() const {
6860 return ToString(Isolate::GetCurrent());
6864 Local<String> Value::ToDetailString() const {
6865 return ToDetailString(Isolate::GetCurrent());
6869 Local<Object> Value::ToObject() const {
6870 return ToObject(Isolate::GetCurrent());
6874 Local<Integer> Value::ToInteger() const {
6875 return ToInteger(Isolate::GetCurrent());
6879 Local<Uint32> Value::ToUint32() const {
6880 return ToUint32(Isolate::GetCurrent());
6884 Local<Int32> Value::ToInt32() const { return ToInt32(Isolate::GetCurrent()); }
6887 Name* Name::Cast(v8::Value* value) {
6888 #ifdef V8_ENABLE_CHECKS
6891 return static_cast<Name*>(value);
6895 Symbol* Symbol::Cast(v8::Value* value) {
6896 #ifdef V8_ENABLE_CHECKS
6899 return static_cast<Symbol*>(value);
6903 Number* Number::Cast(v8::Value* value) {
6904 #ifdef V8_ENABLE_CHECKS
6907 return static_cast<Number*>(value);
6911 Integer* Integer::Cast(v8::Value* value) {
6912 #ifdef V8_ENABLE_CHECKS
6915 return static_cast<Integer*>(value);
6919 Date* Date::Cast(v8::Value* value) {
6920 #ifdef V8_ENABLE_CHECKS
6923 return static_cast<Date*>(value);
6927 StringObject* StringObject::Cast(v8::Value* value) {
6928 #ifdef V8_ENABLE_CHECKS
6931 return static_cast<StringObject*>(value);
6935 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6936 #ifdef V8_ENABLE_CHECKS
6939 return static_cast<SymbolObject*>(value);
6943 NumberObject* NumberObject::Cast(v8::Value* value) {
6944 #ifdef V8_ENABLE_CHECKS
6947 return static_cast<NumberObject*>(value);
6951 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6952 #ifdef V8_ENABLE_CHECKS
6955 return static_cast<BooleanObject*>(value);
6959 RegExp* RegExp::Cast(v8::Value* value) {
6960 #ifdef V8_ENABLE_CHECKS
6963 return static_cast<RegExp*>(value);
6967 Object* Object::Cast(v8::Value* value) {
6968 #ifdef V8_ENABLE_CHECKS
6971 return static_cast<Object*>(value);
6975 Array* Array::Cast(v8::Value* value) {
6976 #ifdef V8_ENABLE_CHECKS
6979 return static_cast<Array*>(value);
6983 Promise* Promise::Cast(v8::Value* value) {
6984 #ifdef V8_ENABLE_CHECKS
6987 return static_cast<Promise*>(value);
6991 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6992 #ifdef V8_ENABLE_CHECKS
6995 return static_cast<Promise::Resolver*>(value);
6999 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7000 #ifdef V8_ENABLE_CHECKS
7003 return static_cast<ArrayBuffer*>(value);
7007 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7008 #ifdef V8_ENABLE_CHECKS
7011 return static_cast<ArrayBufferView*>(value);
7015 TypedArray* TypedArray::Cast(v8::Value* value) {
7016 #ifdef V8_ENABLE_CHECKS
7019 return static_cast<TypedArray*>(value);
7023 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7024 #ifdef V8_ENABLE_CHECKS
7027 return static_cast<Uint8Array*>(value);
7031 Int8Array* Int8Array::Cast(v8::Value* value) {
7032 #ifdef V8_ENABLE_CHECKS
7035 return static_cast<Int8Array*>(value);
7039 Uint16Array* Uint16Array::Cast(v8::Value* value) {
7040 #ifdef V8_ENABLE_CHECKS
7043 return static_cast<Uint16Array*>(value);
7047 Int16Array* Int16Array::Cast(v8::Value* value) {
7048 #ifdef V8_ENABLE_CHECKS
7051 return static_cast<Int16Array*>(value);
7055 Uint32Array* Uint32Array::Cast(v8::Value* value) {
7056 #ifdef V8_ENABLE_CHECKS
7059 return static_cast<Uint32Array*>(value);
7063 Int32Array* Int32Array::Cast(v8::Value* value) {
7064 #ifdef V8_ENABLE_CHECKS
7067 return static_cast<Int32Array*>(value);
7071 Float32Array* Float32Array::Cast(v8::Value* value) {
7072 #ifdef V8_ENABLE_CHECKS
7075 return static_cast<Float32Array*>(value);
7079 Float64Array* Float64Array::Cast(v8::Value* value) {
7080 #ifdef V8_ENABLE_CHECKS
7083 return static_cast<Float64Array*>(value);
7087 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
7088 #ifdef V8_ENABLE_CHECKS
7091 return static_cast<Uint8ClampedArray*>(value);
7095 DataView* DataView::Cast(v8::Value* value) {
7096 #ifdef V8_ENABLE_CHECKS
7099 return static_cast<DataView*>(value);
7103 Function* Function::Cast(v8::Value* value) {
7104 #ifdef V8_ENABLE_CHECKS
7107 return static_cast<Function*>(value);
7111 External* External::Cast(v8::Value* value) {
7112 #ifdef V8_ENABLE_CHECKS
7115 return static_cast<External*>(value);
7119 template<typename T>
7120 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
7121 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
7125 template<typename T>
7126 Local<Value> PropertyCallbackInfo<T>::Data() const {
7127 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
7131 template<typename T>
7132 Local<Object> PropertyCallbackInfo<T>::This() const {
7133 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
7137 template<typename T>
7138 Local<Object> PropertyCallbackInfo<T>::Holder() const {
7139 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
7143 template<typename T>
7144 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
7145 return ReturnValue<T>(&args_[kReturnValueIndex]);
7149 Handle<Primitive> Undefined(Isolate* isolate) {
7150 typedef internal::Object* S;
7151 typedef internal::Internals I;
7152 I::CheckInitialized(isolate);
7153 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
7154 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
7158 Handle<Primitive> Null(Isolate* isolate) {
7159 typedef internal::Object* S;
7160 typedef internal::Internals I;
7161 I::CheckInitialized(isolate);
7162 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
7163 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
7167 Handle<Boolean> True(Isolate* isolate) {
7168 typedef internal::Object* S;
7169 typedef internal::Internals I;
7170 I::CheckInitialized(isolate);
7171 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
7172 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
7176 Handle<Boolean> False(Isolate* isolate) {
7177 typedef internal::Object* S;
7178 typedef internal::Internals I;
7179 I::CheckInitialized(isolate);
7180 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
7181 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
7185 void Isolate::SetData(uint32_t slot, void* data) {
7186 typedef internal::Internals I;
7187 I::SetEmbedderData(this, slot, data);
7191 void* Isolate::GetData(uint32_t slot) {
7192 typedef internal::Internals I;
7193 return I::GetEmbedderData(this, slot);
7197 uint32_t Isolate::GetNumberOfDataSlots() {
7198 typedef internal::Internals I;
7199 return I::kNumIsolateDataSlots;
7203 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
7204 int64_t change_in_bytes) {
7205 typedef internal::Internals I;
7206 int64_t* amount_of_external_allocated_memory =
7207 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
7208 I::kAmountOfExternalAllocatedMemoryOffset);
7209 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
7210 reinterpret_cast<int64_t*>(
7211 reinterpret_cast<uint8_t*>(this) +
7212 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
7213 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
7214 if (change_in_bytes > 0 &&
7215 amount - *amount_of_external_allocated_memory_at_last_global_gc >
7216 I::kExternalAllocationLimit) {
7217 CollectAllGarbage("external memory allocation limit reached.");
7219 *amount_of_external_allocated_memory = amount;
7221 return *amount_of_external_allocated_memory;
7225 template<typename T>
7226 void Isolate::SetObjectGroupId(const Persistent<T>& object,
7228 TYPE_CHECK(Value, T);
7229 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
7233 template<typename T>
7234 void Isolate::SetReferenceFromGroup(UniqueId id,
7235 const Persistent<T>& object) {
7236 TYPE_CHECK(Value, T);
7237 SetReferenceFromGroup(id,
7238 reinterpret_cast<v8::internal::Object**>(object.val_));
7242 template<typename T, typename S>
7243 void Isolate::SetReference(const Persistent<T>& parent,
7244 const Persistent<S>& child) {
7245 TYPE_CHECK(Object, T);
7246 TYPE_CHECK(Value, S);
7247 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
7248 reinterpret_cast<v8::internal::Object**>(child.val_));
7252 Local<Value> Context::GetEmbedderData(int index) {
7253 #ifndef V8_ENABLE_CHECKS
7254 typedef internal::Object O;
7255 typedef internal::HeapObject HO;
7256 typedef internal::Internals I;
7257 HO* context = *reinterpret_cast<HO**>(this);
7259 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
7260 return Local<Value>(reinterpret_cast<Value*>(result));
7262 return SlowGetEmbedderData(index);
7267 void* Context::GetAlignedPointerFromEmbedderData(int index) {
7268 #ifndef V8_ENABLE_CHECKS
7269 typedef internal::Internals I;
7270 return I::ReadEmbedderData<void*>(this, index);
7272 return SlowGetAlignedPointerFromEmbedderData(index);
7277 void V8::SetAllowCodeGenerationFromStringsCallback(
7278 AllowCodeGenerationFromStringsCallback callback) {
7279 Isolate* isolate = Isolate::GetCurrent();
7280 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
7285 Isolate* isolate = Isolate::GetCurrent();
7286 return isolate->IsDead();
7290 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
7291 Isolate* isolate = Isolate::GetCurrent();
7292 return isolate->AddMessageListener(that, data);
7296 void V8::RemoveMessageListeners(MessageCallback that) {
7297 Isolate* isolate = Isolate::GetCurrent();
7298 isolate->RemoveMessageListeners(that);
7302 void V8::SetFailedAccessCheckCallbackFunction(
7303 FailedAccessCheckCallback callback) {
7304 Isolate* isolate = Isolate::GetCurrent();
7305 isolate->SetFailedAccessCheckCallbackFunction(callback);
7309 void V8::SetCaptureStackTraceForUncaughtExceptions(
7310 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7311 Isolate* isolate = Isolate::GetCurrent();
7312 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7317 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
7318 Isolate* isolate = Isolate::GetCurrent();
7319 isolate->SetFatalErrorHandler(callback);
7323 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
7324 Isolate* isolate = Isolate::GetCurrent();
7325 isolate->RemoveGCPrologueCallback(
7326 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
7330 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7331 Isolate* isolate = Isolate::GetCurrent();
7332 isolate->RemoveGCEpilogueCallback(
7333 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
7337 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
7339 AllocationAction action) {
7340 Isolate* isolate = Isolate::GetCurrent();
7341 isolate->AddMemoryAllocationCallback(callback, space, action);
7345 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
7346 Isolate* isolate = Isolate::GetCurrent();
7347 isolate->RemoveMemoryAllocationCallback(callback);
7351 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
7354 bool V8::IsExecutionTerminating(Isolate* isolate) {
7355 if (isolate == NULL) {
7356 isolate = Isolate::GetCurrent();
7358 return isolate->IsExecutionTerminating();
7362 void V8::CancelTerminateExecution(Isolate* isolate) {
7363 isolate->CancelTerminateExecution();
7367 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
7368 Isolate* isolate = Isolate::GetCurrent();
7369 isolate->VisitExternalResources(visitor);
7373 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
7374 Isolate* isolate = Isolate::GetCurrent();
7375 isolate->VisitHandlesWithClassIds(visitor);
7379 void V8::VisitHandlesWithClassIds(Isolate* isolate,
7380 PersistentHandleVisitor* visitor) {
7381 isolate->VisitHandlesWithClassIds(visitor);
7385 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
7386 PersistentHandleVisitor* visitor) {
7387 isolate->VisitHandlesForPartialDependence(visitor);
7392 * A simple shell that takes a list of expressions on the
7393 * command-line and executes them.
7398 * \example process.cc