1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /** \mainpage V8 API Reference Guide
7 * V8 is Google's open source JavaScript engine.
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
12 * For other documentation see http://code.google.com/apis/v8/
22 #include "v8-version.h"
25 // We reserve the V8_* prefix for macros defined in V8 public API and
26 // assume there are no name conflicts with the embedder's code.
30 // Setup for Windows DLL export/import. When building the V8 DLL the
31 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
32 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
33 // static library or building a program which uses the V8 static library neither
34 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
35 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
36 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
37 build configuration to ensure that at most one of these is set
40 #ifdef BUILDING_V8_SHARED
41 # define V8_EXPORT __declspec(dllexport)
43 # define V8_EXPORT __declspec(dllimport)
46 #endif // BUILDING_V8_SHARED
50 // Setup for Linux shared library export.
51 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
52 # ifdef BUILDING_V8_SHARED
53 # define V8_EXPORT __attribute__ ((visibility("default")))
64 * The v8 JavaScript engine.
68 class AccessorSignature;
78 class FunctionTemplate;
80 class ImplementationUtilities;
90 class ObjectOperationDescriptor;
95 class RawOperationDescriptor;
109 template <class T> class Handle;
110 template <class T> class Local;
113 template <class T> class Eternal;
114 template<class T> class NonCopyablePersistentTraits;
115 template<class T> class PersistentBase;
117 class M = NonCopyablePersistentTraits<T> > class Persistent;
120 template<class K, class V, class T> class PersistentValueMap;
121 template <class K, class V, class T>
122 class PersistentValueMapBase;
123 template <class K, class V, class T>
124 class GlobalValueMap;
125 template<class V, class T> class PersistentValueVector;
126 template<class T, class P> class WeakCallbackObject;
127 class FunctionTemplate;
128 class ObjectTemplate;
130 template<typename T> class FunctionCallbackInfo;
131 template<typename T> class PropertyCallbackInfo;
135 class CallHandlerHelper;
136 class EscapableHandleScope;
137 template<typename T> class ReturnValue;
145 struct StreamedSource;
146 template<typename T> class CustomArguments;
147 class PropertyCallbackArguments;
148 class FunctionCallbackArguments;
154 * General purpose unique identifier.
158 explicit UniqueId(intptr_t data)
161 bool operator==(const UniqueId& other) const {
162 return data_ == other.data_;
165 bool operator!=(const UniqueId& other) const {
166 return data_ != other.data_;
169 bool operator<(const UniqueId& other) const {
170 return data_ < other.data_;
179 #define TYPE_CHECK(T, S) \
181 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
186 * An object reference managed by the v8 garbage collector.
188 * All objects returned from v8 have to be tracked by the garbage
189 * collector so that it knows that the objects are still alive. Also,
190 * because the garbage collector may move objects, it is unsafe to
191 * point directly to an object. Instead, all objects are stored in
192 * handles which are known by the garbage collector and updated
193 * whenever an object moves. Handles should always be passed by value
194 * (except in cases like out-parameters) and they should never be
195 * allocated on the heap.
197 * There are two types of handles: local and persistent handles.
198 * Local handles are light-weight and transient and typically used in
199 * local operations. They are managed by HandleScopes. Persistent
200 * handles can be used when storing objects across several independent
201 * operations and have to be explicitly deallocated when they're no
204 * It is safe to extract the object stored in the handle by
205 * dereferencing the handle (for instance, to extract the Object* from
206 * a Handle<Object>); the value will still be governed by a handle
207 * behind the scenes and the same rules apply to these values as to
210 template <class T> class Handle {
213 * Creates an empty handle.
215 V8_INLINE Handle() : val_(0) {}
218 * Creates a handle for the contents of the specified handle. This
219 * constructor allows you to pass handles as arguments by value and
220 * to assign between handles. However, if you try to assign between
221 * incompatible handles, for instance from a Handle<String> to a
222 * Handle<Number> it will cause a compile-time error. Assigning
223 * between compatible handles, for instance assigning a
224 * Handle<String> to a variable declared as Handle<Value>, is legal
225 * because String is a subclass of Value.
227 template <class S> V8_INLINE Handle(Handle<S> that)
228 : val_(reinterpret_cast<T*>(*that)) {
230 * This check fails when trying to convert between incompatible
231 * handles. For example, converting from a Handle<String> to a
238 * Returns true if the handle is empty.
240 V8_INLINE bool IsEmpty() const { return val_ == 0; }
243 * Sets the handle to be empty. IsEmpty() will then return true.
245 V8_INLINE void Clear() { val_ = 0; }
247 V8_INLINE T* operator->() const { return val_; }
249 V8_INLINE T* operator*() const { return val_; }
252 * Checks whether two handles are the same.
253 * Returns true if both are empty, or if the objects
254 * to which they refer are identical.
255 * The handles' references are not checked.
257 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
258 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
259 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
260 if (a == 0) return b == 0;
261 if (b == 0) return false;
265 template <class S> V8_INLINE bool operator==(
266 const PersistentBase<S>& that) const {
267 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
268 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
269 if (a == 0) return b == 0;
270 if (b == 0) return false;
275 * Checks whether two handles are different.
276 * Returns true if only one of the handles is empty, or if
277 * the objects to which they refer are different.
278 * The handles' references are not checked.
280 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
281 return !operator==(that);
284 template <class S> V8_INLINE bool operator!=(
285 const Persistent<S>& that) const {
286 return !operator==(that);
289 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
290 #ifdef V8_ENABLE_CHECKS
291 // If we're going to perform the type check then we have to check
292 // that the handle isn't empty before doing the checked cast.
293 if (that.IsEmpty()) return Handle<T>();
295 return Handle<T>(T::Cast(*that));
298 template <class S> V8_INLINE Handle<S> As() {
299 return Handle<S>::Cast(*this);
302 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
303 return New(isolate, that.val_);
305 V8_INLINE static Handle<T> New(Isolate* isolate,
306 const PersistentBase<T>& that) {
307 return New(isolate, that.val_);
312 template<class F, class M> friend class Persistent;
313 template<class F> friend class PersistentBase;
314 template<class F> friend class Handle;
315 template<class F> friend class Local;
317 friend class MaybeLocal;
318 template<class F> friend class FunctionCallbackInfo;
319 template<class F> friend class PropertyCallbackInfo;
320 template<class F> friend class internal::CustomArguments;
321 friend Handle<Primitive> Undefined(Isolate* isolate);
322 friend Handle<Primitive> Null(Isolate* isolate);
323 friend Handle<Boolean> True(Isolate* isolate);
324 friend Handle<Boolean> False(Isolate* isolate);
325 friend class Context;
326 friend class HandleScope;
328 friend class Private;
331 * Creates a new handle for the specified value.
333 V8_INLINE explicit Handle(T* val) : val_(val) {}
335 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
342 * A light-weight stack-allocated object handle. All operations
343 * that return objects from within v8 return them in local handles. They
344 * are created within HandleScopes, and all local handles allocated within a
345 * handle scope are destroyed when the handle scope is destroyed. Hence it
346 * is not necessary to explicitly deallocate local handles.
348 template <class T> class Local : public Handle<T> {
351 template <class S> V8_INLINE Local(Local<S> that)
352 : Handle<T>(reinterpret_cast<T*>(*that)) {
354 * This check fails when trying to convert between incompatible
355 * handles. For example, converting from a Handle<String> to a
362 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
363 #ifdef V8_ENABLE_CHECKS
364 // If we're going to perform the type check then we have to check
365 // that the handle isn't empty before doing the checked cast.
366 if (that.IsEmpty()) return Local<T>();
368 return Local<T>(T::Cast(*that));
370 template <class S> V8_INLINE Local(Handle<S> that)
371 : Handle<T>(reinterpret_cast<T*>(*that)) {
375 template <class S> V8_INLINE Local<S> As() {
376 return Local<S>::Cast(*this);
380 * Create a local handle for the content of another handle.
381 * The referee is kept alive by the local handle even when
382 * the original handle is destroyed/disposed.
384 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
385 V8_INLINE static Local<T> New(Isolate* isolate,
386 const PersistentBase<T>& that);
390 template<class F> friend class Eternal;
391 template<class F> friend class PersistentBase;
392 template<class F, class M> friend class Persistent;
393 template<class F> friend class Handle;
394 template<class F> friend class Local;
396 friend class MaybeLocal;
397 template<class F> friend class FunctionCallbackInfo;
398 template<class F> friend class PropertyCallbackInfo;
401 friend class Context;
402 template<class F> friend class internal::CustomArguments;
403 friend class HandleScope;
404 friend class EscapableHandleScope;
405 template <class F1, class F2, class F3>
406 friend class PersistentValueMapBase;
407 template<class F1, class F2> friend class PersistentValueVector;
409 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
410 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
415 * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
416 * the Local<> is empty before it can be used.
418 * If an API method returns a MaybeLocal<>, the API method can potentially fail
419 * either because an exception is thrown, or because an exception is pending,
420 * e.g. because a previous API call threw an exception that hasn't been caught
421 * yet, or because a TerminateExecution exception was thrown. In that case, an
422 * empty MaybeLocal is returned.
427 V8_INLINE MaybeLocal() : val_(nullptr) {}
429 V8_INLINE MaybeLocal(Local<S> that)
430 : val_(reinterpret_cast<T*>(*that)) {
434 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
437 V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
438 out->val_ = IsEmpty() ? nullptr : this->val_;
442 // Will crash when checks are enabled if the MaybeLocal<> is empty.
443 V8_INLINE Local<T> ToLocalChecked();
446 V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
447 return IsEmpty() ? default_value : Local<S>(val_);
455 // Eternal handles are set-once handles that live for the life of the isolate.
456 template <class T> class Eternal {
458 V8_INLINE Eternal() : index_(kInitialValue) { }
460 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
461 Set(isolate, handle);
463 // Can only be safely called if already set.
464 V8_INLINE Local<T> Get(Isolate* isolate);
465 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
466 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
469 static const int kInitialValue = -1;
474 static const int kInternalFieldsInWeakCallback = 2;
477 template <typename T>
478 class WeakCallbackInfo {
480 typedef void (*Callback)(const WeakCallbackInfo<T>& data);
482 WeakCallbackInfo(Isolate* isolate, T* parameter,
483 void* internal_fields[kInternalFieldsInWeakCallback],
485 : isolate_(isolate), parameter_(parameter), callback_(callback) {
486 for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) {
487 internal_fields_[i] = internal_fields[i];
491 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
492 V8_INLINE T* GetParameter() const { return parameter_; }
493 V8_INLINE void* GetInternalField(int index) const;
495 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
496 void* GetInternalField1()) const {
497 return internal_fields_[0];
499 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
500 void* GetInternalField2()) const {
501 return internal_fields_[1];
504 bool IsFirstPass() const { return callback_ != nullptr; }
506 // When first called, the embedder MUST Reset() the Global which triggered the
507 // callback. The Global itself is unusable for anything else. No v8 other api
508 // calls may be called in the first callback. Should additional work be
509 // required, the embedder must set a second pass callback, which will be
510 // called after all the initial callbacks are processed.
511 // Calling SetSecondPassCallback on the second pass will immediately crash.
512 void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
518 void* internal_fields_[kInternalFieldsInWeakCallback];
522 template <class T, class P>
523 class WeakCallbackData {
525 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
527 WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
528 : isolate_(isolate), parameter_(parameter), handle_(handle) {}
530 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
531 V8_INLINE P* GetParameter() const { return parameter_; }
532 V8_INLINE Local<T> GetValue() const { return handle_; }
541 // TODO(dcarney): delete this with WeakCallbackData
543 using PhantomCallbackData = WeakCallbackInfo<T>;
546 enum class WeakCallbackType { kParameter, kInternalFields };
550 * An object reference that is independent of any handle scope. Where
551 * a Local handle only lives as long as the HandleScope in which it was
552 * allocated, a PersistentBase handle remains valid until it is explicitly
555 * A persistent handle contains a reference to a storage cell within
556 * the v8 engine which holds an object value and which is updated by
557 * the garbage collector whenever the object is moved. A new storage
558 * cell can be created using the constructor or PersistentBase::Reset and
559 * existing handles can be disposed using PersistentBase::Reset.
562 template <class T> class PersistentBase {
565 * If non-empty, destroy the underlying storage cell
566 * IsEmpty() will return true after this call.
568 V8_INLINE void Reset();
570 * If non-empty, destroy the underlying storage cell
571 * and create a new one with the contents of other if other is non empty
574 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
577 * If non-empty, destroy the underlying storage cell
578 * and create a new one with the contents of other if other is non empty
581 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
583 V8_INLINE bool IsEmpty() const { return val_ == NULL; }
584 V8_INLINE void Empty() { val_ = 0; }
587 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
588 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
589 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
590 if (a == NULL) return b == NULL;
591 if (b == NULL) return false;
595 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
596 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
597 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
598 if (a == NULL) return b == NULL;
599 if (b == NULL) return false;
604 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
605 return !operator==(that);
608 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
609 return !operator==(that);
613 * Install a finalization callback on this object.
614 * NOTE: There is no guarantee as to *when* or even *if* the callback is
615 * invoked. The invocation is performed solely on a best effort basis.
616 * As always, GC-based finalization should *not* be relied upon for any
617 * critical form of resource management!
619 template <typename P>
620 V8_INLINE V8_DEPRECATE_SOON(
621 "use WeakCallbackInfo version",
622 void SetWeak(P* parameter,
623 typename WeakCallbackData<T, P>::Callback callback));
625 template <typename S, typename P>
626 V8_INLINE V8_DEPRECATE_SOON(
627 "use WeakCallbackInfo version",
628 void SetWeak(P* parameter,
629 typename WeakCallbackData<S, P>::Callback callback));
631 // Phantom persistents work like weak persistents, except that the pointer to
632 // the object being collected is not available in the finalization callback.
633 // This enables the garbage collector to collect the object and any objects
634 // it references transitively in one GC cycle. At the moment you can either
635 // specify a parameter for the callback or the location of two internal
636 // fields in the dying object.
637 template <typename P>
638 V8_INLINE V8_DEPRECATE_SOON(
640 void SetPhantom(P* parameter,
641 typename WeakCallbackInfo<P>::Callback callback,
642 int internal_field_index1 = -1,
643 int internal_field_index2 = -1));
645 template <typename P>
646 V8_INLINE void SetWeak(P* parameter,
647 typename WeakCallbackInfo<P>::Callback callback,
648 WeakCallbackType type);
651 V8_INLINE P* ClearWeak();
653 // TODO(dcarney): remove this.
654 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
657 * Marks the reference to this object independent. Garbage collector is free
658 * to ignore any object groups containing this object. Weak callback for an
659 * independent handle should not assume that it will be preceded by a global
660 * GC prologue callback or followed by a global GC epilogue callback.
662 V8_INLINE void MarkIndependent();
665 * Marks the reference to this object partially dependent. Partially dependent
666 * handles only depend on other partially dependent handles and these
667 * dependencies are provided through object groups. It provides a way to build
668 * smaller object groups for young objects that represent only a subset of all
669 * external dependencies. This mark is automatically cleared after each
670 * garbage collection.
672 V8_INLINE void MarkPartiallyDependent();
674 V8_INLINE bool IsIndependent() const;
676 /** Checks if the handle holds the only reference to an object. */
677 V8_INLINE bool IsNearDeath() const;
679 /** Returns true if the handle's reference is weak. */
680 V8_INLINE bool IsWeak() const;
683 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
684 * description in v8-profiler.h for details.
686 V8_INLINE void SetWrapperClassId(uint16_t class_id);
689 * Returns the class ID previously assigned to this handle or 0 if no class ID
690 * was previously assigned.
692 V8_INLINE uint16_t WrapperClassId() const;
695 friend class Isolate;
697 template<class F> friend class Handle;
698 template<class F> friend class Local;
699 template<class F1, class F2> friend class Persistent;
702 template<class F> friend class PersistentBase;
703 template<class F> friend class ReturnValue;
704 template <class F1, class F2, class F3>
705 friend class PersistentValueMapBase;
706 template<class F1, class F2> friend class PersistentValueVector;
709 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
710 PersistentBase(PersistentBase& other) = delete; // NOLINT
711 void operator=(PersistentBase&) = delete;
712 V8_INLINE static T* New(Isolate* isolate, T* that);
719 * Default traits for Persistent. This class does not allow
720 * use of the copy constructor or assignment operator.
721 * At present kResetInDestructor is not set, but that will change in a future
725 class NonCopyablePersistentTraits {
727 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
728 static const bool kResetInDestructor = false;
729 template<class S, class M>
730 V8_INLINE static void Copy(const Persistent<S, M>& source,
731 NonCopyablePersistent* dest) {
732 Uncompilable<Object>();
734 // TODO(dcarney): come up with a good compile error here.
735 template<class O> V8_INLINE static void Uncompilable() {
736 TYPE_CHECK(O, Primitive);
742 * Helper class traits to allow copying and assignment of Persistent.
743 * This will clone the contents of storage cell, but not any of the flags, etc.
746 struct CopyablePersistentTraits {
747 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
748 static const bool kResetInDestructor = true;
749 template<class S, class M>
750 static V8_INLINE void Copy(const Persistent<S, M>& source,
751 CopyablePersistent* dest) {
752 // do nothing, just allow copy
758 * A PersistentBase which allows copy and assignment.
760 * Copy, assignment and destructor bevavior is controlled by the traits
763 * Note: Persistent class hierarchy is subject to future changes.
765 template <class T, class M> class Persistent : public PersistentBase<T> {
768 * A Persistent with no storage cell.
770 V8_INLINE Persistent() : PersistentBase<T>(0) { }
772 * Construct a Persistent from a Handle.
773 * When the Handle is non-empty, a new storage cell is created
774 * pointing to the same object, and no flags are set.
776 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
777 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
781 * Construct a Persistent from a Persistent.
782 * When the Persistent is non-empty, a new storage cell is created
783 * pointing to the same object, and no flags are set.
785 template <class S, class M2>
786 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
787 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
791 * The copy constructors and assignment operator create a Persistent
792 * exactly as the Persistent constructor, but the Copy function from the
793 * traits class is called, allowing the setting of flags based on the
796 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
799 template <class S, class M2>
800 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
803 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
807 template <class S, class M2>
808 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
813 * The destructor will dispose the Persistent based on the
814 * kResetInDestructor flags in the traits class. Since not calling dispose
815 * can result in a memory leak, it is recommended to always set this flag.
817 V8_INLINE ~Persistent() {
818 if (M::kResetInDestructor) this->Reset();
821 // TODO(dcarney): this is pretty useless, fix or remove
823 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
824 #ifdef V8_ENABLE_CHECKS
825 // If we're going to perform the type check then we have to check
826 // that the handle isn't empty before doing the checked cast.
827 if (!that.IsEmpty()) T::Cast(*that);
829 return reinterpret_cast<Persistent<T>&>(that);
832 // TODO(dcarney): this is pretty useless, fix or remove
833 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
834 return Persistent<S>::Cast(*this);
838 friend class Isolate;
840 template<class F> friend class Handle;
841 template<class F> friend class Local;
842 template<class F1, class F2> friend class Persistent;
843 template<class F> friend class ReturnValue;
845 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
846 V8_INLINE T* operator*() const { return this->val_; }
847 template<class S, class M2>
848 V8_INLINE void Copy(const Persistent<S, M2>& that);
853 * A PersistentBase which has move semantics.
855 * Note: Persistent class hierarchy is subject to future changes.
858 class Global : public PersistentBase<T> {
861 * A Global with no storage cell.
863 V8_INLINE Global() : PersistentBase<T>(nullptr) {}
865 * Construct a Global from a Handle.
866 * When the Handle is non-empty, a new storage cell is created
867 * pointing to the same object, and no flags are set.
870 V8_INLINE Global(Isolate* isolate, Handle<S> that)
871 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
875 * Construct a Global from a PersistentBase.
876 * When the Persistent is non-empty, a new storage cell is created
877 * pointing to the same object, and no flags are set.
880 V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
881 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
887 V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) {
888 other.val_ = nullptr;
890 V8_INLINE ~Global() { this->Reset(); }
892 * Move via assignment.
895 V8_INLINE Global& operator=(Global<S>&& rhs) {
899 this->val_ = rhs.val_;
905 * Pass allows returning uniques from functions, etc.
907 Global Pass() { return static_cast<Global&&>(*this); }
910 * For compatibility with Chromium's base::Bind (base::Passed).
912 typedef void MoveOnlyTypeForCPP03;
915 Global(Global&) = delete;
916 void operator=(Global&) = delete;
920 // UniquePersistent is an alias for Global for historical reason.
922 using UniquePersistent = Global<T>;
926 * A stack-allocated class that governs a number of local handles.
927 * After a handle scope has been created, all local handles will be
928 * allocated within that handle scope until either the handle scope is
929 * deleted or another handle scope is created. If there is already a
930 * handle scope and a new one is created, all allocations will take
931 * place in the new handle scope until it is deleted. After that,
932 * new handles will again be allocated in the original handle scope.
934 * After the handle scope of a local handle has been deleted the
935 * garbage collector will no longer track the object stored in the
936 * handle and may deallocate it. The behavior of accessing a handle
937 * for which the handle scope has been deleted is undefined.
939 class V8_EXPORT HandleScope {
941 HandleScope(Isolate* isolate);
946 * Counts the number of allocated handles.
948 static int NumberOfHandles(Isolate* isolate);
950 V8_INLINE Isolate* GetIsolate() const {
951 return reinterpret_cast<Isolate*>(isolate_);
955 V8_INLINE HandleScope() {}
957 void Initialize(Isolate* isolate);
959 static internal::Object** CreateHandle(internal::Isolate* isolate,
960 internal::Object* value);
963 // Uses heap_object to obtain the current Isolate.
964 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
965 internal::Object* value);
967 // Make it hard to create heap-allocated or illegal handle scopes by
968 // disallowing certain operations.
969 HandleScope(const HandleScope&);
970 void operator=(const HandleScope&);
971 void* operator new(size_t size);
972 void operator delete(void*, size_t);
974 internal::Isolate* isolate_;
975 internal::Object** prev_next_;
976 internal::Object** prev_limit_;
978 // Local::New uses CreateHandle with an Isolate* parameter.
979 template<class F> friend class Local;
981 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
982 // a HeapObject* in their shortcuts.
984 friend class Context;
989 * A HandleScope which first allocates a handle in the current scope
990 * which will be later filled with the escape value.
992 class V8_EXPORT EscapableHandleScope : public HandleScope {
994 EscapableHandleScope(Isolate* isolate);
995 V8_INLINE ~EscapableHandleScope() {}
998 * Pushes the value into the previous scope and returns a handle to it.
999 * Cannot be called twice.
1002 V8_INLINE Local<T> Escape(Local<T> value) {
1003 internal::Object** slot =
1004 Escape(reinterpret_cast<internal::Object**>(*value));
1005 return Local<T>(reinterpret_cast<T*>(slot));
1009 internal::Object** Escape(internal::Object** escape_value);
1011 // Make it hard to create heap-allocated or illegal handle scopes by
1012 // disallowing certain operations.
1013 EscapableHandleScope(const EscapableHandleScope&);
1014 void operator=(const EscapableHandleScope&);
1015 void* operator new(size_t size);
1016 void operator delete(void*, size_t);
1018 internal::Object** escape_slot_;
1021 class V8_EXPORT SealHandleScope {
1023 SealHandleScope(Isolate* isolate);
1027 // Make it hard to create heap-allocated or illegal handle scopes by
1028 // disallowing certain operations.
1029 SealHandleScope(const SealHandleScope&);
1030 void operator=(const SealHandleScope&);
1031 void* operator new(size_t size);
1032 void operator delete(void*, size_t);
1034 internal::Isolate* isolate_;
1036 internal::Object** prev_limit_;
1040 // --- Special objects ---
1044 * The superclass of values and API object templates.
1046 class V8_EXPORT Data {
1053 * The origin, within a file, of a script.
1055 class ScriptOrigin {
1057 V8_INLINE ScriptOrigin(
1058 Handle<Value> resource_name,
1059 Handle<Integer> resource_line_offset = Handle<Integer>(),
1060 Handle<Integer> resource_column_offset = Handle<Integer>(),
1061 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
1062 Handle<Integer> script_id = Handle<Integer>(),
1063 Handle<Boolean> resource_is_embedder_debug_script = Handle<Boolean>(),
1064 Handle<Value> source_map_url = Handle<Value>())
1065 : resource_name_(resource_name),
1066 resource_line_offset_(resource_line_offset),
1067 resource_column_offset_(resource_column_offset),
1068 resource_is_embedder_debug_script_(resource_is_embedder_debug_script),
1069 resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
1070 script_id_(script_id),
1071 source_map_url_(source_map_url) {}
1072 V8_INLINE Handle<Value> ResourceName() const;
1073 V8_INLINE Handle<Integer> ResourceLineOffset() const;
1074 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
1076 * Returns true for embedder's debugger scripts
1078 V8_INLINE Handle<Boolean> ResourceIsEmbedderDebugScript() const;
1079 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
1080 V8_INLINE Handle<Integer> ScriptID() const;
1081 V8_INLINE Handle<Value> SourceMapUrl() const;
1084 Handle<Value> resource_name_;
1085 Handle<Integer> resource_line_offset_;
1086 Handle<Integer> resource_column_offset_;
1087 Handle<Boolean> resource_is_embedder_debug_script_;
1088 Handle<Boolean> resource_is_shared_cross_origin_;
1089 Handle<Integer> script_id_;
1090 Handle<Value> source_map_url_;
1095 * A compiled JavaScript script, not yet tied to a Context.
1097 class V8_EXPORT UnboundScript {
1100 * Binds the script to the currently entered context.
1102 Local<Script> BindToCurrentContext();
1105 Handle<Value> GetScriptName();
1108 * Data read from magic sourceURL comments.
1110 Handle<Value> GetSourceURL();
1112 * Data read from magic sourceMappingURL comments.
1114 Handle<Value> GetSourceMappingURL();
1117 * Returns zero based line number of the code_pos location in the script.
1118 * -1 will be returned if no information available.
1120 int GetLineNumber(int code_pos);
1122 static const int kNoScriptId = 0;
1127 * A compiled JavaScript script, tied to a Context which was active when the
1128 * script was compiled.
1130 class V8_EXPORT Script {
1133 * A shorthand for ScriptCompiler::Compile().
1135 static V8_DEPRECATE_SOON(
1136 "Use maybe version",
1137 Local<Script> Compile(Handle<String> source,
1138 ScriptOrigin* origin = nullptr));
1139 static MaybeLocal<Script> Compile(Local<Context> context,
1140 Handle<String> source,
1141 ScriptOrigin* origin = nullptr);
1143 static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1144 Compile(Handle<String> source,
1145 Handle<String> file_name));
1148 * Runs the script returning the resulting value. It will be run in the
1149 * context in which it was created (ScriptCompiler::CompileBound or
1150 * UnboundScript::BindToCurrentContext()).
1152 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1153 MaybeLocal<Value> Run(Local<Context> context);
1156 * Returns the corresponding context-unbound script.
1158 Local<UnboundScript> GetUnboundScript();
1160 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1162 return GetUnboundScript()->GetId();
1168 * For compiling scripts.
1170 class V8_EXPORT ScriptCompiler {
1173 * Compilation data that the embedder can cache and pass back to speed up
1174 * future compilations. The data is produced if the CompilerOptions passed to
1175 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1176 * = true. The data to cache can then can be retrieved from
1179 struct V8_EXPORT CachedData {
1189 buffer_policy(BufferNotOwned) {}
1191 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1192 // data and guarantees that it stays alive until the CachedData object is
1193 // destroyed. If the policy is BufferOwned, the given data will be deleted
1194 // (with delete[]) when the CachedData object is destroyed.
1195 CachedData(const uint8_t* data, int length,
1196 BufferPolicy buffer_policy = BufferNotOwned);
1198 // TODO(marja): Async compilation; add constructors which take a callback
1199 // which will be called when V8 no longer needs the data.
1200 const uint8_t* data;
1203 BufferPolicy buffer_policy;
1206 // Prevent copying. Not implemented.
1207 CachedData(const CachedData&);
1208 CachedData& operator=(const CachedData&);
1212 * Source code which can be then compiled to a UnboundScript or Script.
1216 // Source takes ownership of CachedData.
1217 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1218 CachedData* cached_data = NULL);
1219 V8_INLINE Source(Local<String> source_string,
1220 CachedData* cached_data = NULL);
1221 V8_INLINE ~Source();
1223 // Ownership of the CachedData or its buffers is *not* transferred to the
1224 // caller. The CachedData object is alive as long as the Source object is
1226 V8_INLINE const CachedData* GetCachedData() const;
1229 friend class ScriptCompiler;
1230 // Prevent copying. Not implemented.
1231 Source(const Source&);
1232 Source& operator=(const Source&);
1234 Local<String> source_string;
1236 // Origin information
1237 Handle<Value> resource_name;
1238 Handle<Integer> resource_line_offset;
1239 Handle<Integer> resource_column_offset;
1240 Handle<Boolean> resource_is_embedder_debug_script;
1241 Handle<Boolean> resource_is_shared_cross_origin;
1242 Handle<Value> source_map_url;
1244 // Cached data from previous compilation (if a kConsume*Cache flag is
1245 // set), or hold newly generated cache data (kProduce*Cache flags) are
1246 // set when calling a compile method.
1247 CachedData* cached_data;
1251 * For streaming incomplete script data to V8. The embedder should implement a
1252 * subclass of this class.
1254 class ExternalSourceStream {
1256 virtual ~ExternalSourceStream() {}
1259 * V8 calls this to request the next chunk of data from the embedder. This
1260 * function will be called on a background thread, so it's OK to block and
1261 * wait for the data, if the embedder doesn't have data yet. Returns the
1262 * length of the data returned. When the data ends, GetMoreData should
1263 * return 0. Caller takes ownership of the data.
1265 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1266 * two data chunks, but doesn't handle multi-byte characters split between
1267 * more than two data chunks. The embedder can avoid this problem by always
1268 * returning at least 2 bytes of data.
1270 * If the embedder wants to cancel the streaming, they should make the next
1271 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1272 * probably, parsing will fail). The streaming task will return as soon as
1273 * V8 has parsed the data it received so far.
1275 virtual size_t GetMoreData(const uint8_t** src) = 0;
1280 * Source code which can be streamed into V8 in pieces. It will be parsed
1281 * while streaming. It can be compiled after the streaming is complete.
1282 * StreamedSource must be kept alive while the streaming task is ran (see
1283 * ScriptStreamingTask below).
1285 class V8_EXPORT StreamedSource {
1287 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1289 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1292 // Ownership of the CachedData or its buffers is *not* transferred to the
1293 // caller. The CachedData object is alive as long as the StreamedSource
1295 const CachedData* GetCachedData() const;
1297 internal::StreamedSource* impl() const { return impl_; }
1300 // Prevent copying. Not implemented.
1301 StreamedSource(const StreamedSource&);
1302 StreamedSource& operator=(const StreamedSource&);
1304 internal::StreamedSource* impl_;
1308 * A streaming task which the embedder must run on a background thread to
1309 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1311 class ScriptStreamingTask {
1313 virtual ~ScriptStreamingTask() {}
1314 virtual void Run() = 0;
1317 enum CompileOptions {
1318 kNoCompileOptions = 0,
1319 kProduceParserCache,
1320 kConsumeParserCache,
1324 // Support the previous API for a transition period.
1329 * Compiles the specified script (context-independent).
1330 * Cached data as part of the source object can be optionally produced to be
1331 * consumed later to speed up compilation of identical source scripts.
1333 * Note that when producing cached data, the source must point to NULL for
1334 * cached data. When consuming cached data, the cached data must have been
1335 * produced by the same version of V8.
1337 * \param source Script source code.
1338 * \return Compiled script object (context independent; for running it must be
1339 * bound to a context).
1341 static V8_DEPRECATE_SOON("Use maybe version",
1342 Local<UnboundScript> CompileUnbound(
1343 Isolate* isolate, Source* source,
1344 CompileOptions options = kNoCompileOptions));
1345 static MaybeLocal<UnboundScript> CompileUnboundScript(
1346 Isolate* isolate, Source* source,
1347 CompileOptions options = kNoCompileOptions);
1350 * Compiles the specified script (bound to current context).
1352 * \param source Script source code.
1353 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1354 * using pre_data speeds compilation if it's done multiple times.
1355 * Owned by caller, no references are kept when this function returns.
1356 * \return Compiled script object, bound to the context that was active
1357 * when this function was called. When run it will always use this
1360 static V8_DEPRECATE_SOON(
1361 "Use maybe version",
1362 Local<Script> Compile(Isolate* isolate, Source* source,
1363 CompileOptions options = kNoCompileOptions));
1364 static MaybeLocal<Script> Compile(Local<Context> context, Source* source,
1365 CompileOptions options = kNoCompileOptions);
1368 * Returns a task which streams script data into V8, or NULL if the script
1369 * cannot be streamed. The user is responsible for running the task on a
1370 * background thread and deleting it. When ran, the task starts parsing the
1371 * script, and it will request data from the StreamedSource as needed. When
1372 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1373 * can be compiled (see Compile below).
1375 * This API allows to start the streaming with as little data as possible, and
1376 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1378 static ScriptStreamingTask* StartStreamingScript(
1379 Isolate* isolate, StreamedSource* source,
1380 CompileOptions options = kNoCompileOptions);
1383 * Compiles a streamed script (bound to current context).
1385 * This can only be called after the streaming has finished
1386 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1387 * during streaming, so the embedder needs to pass the full source here.
1389 static V8_DEPRECATE_SOON(
1390 "Use maybe version",
1391 Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1392 Handle<String> full_source_string,
1393 const ScriptOrigin& origin));
1394 static MaybeLocal<Script> Compile(Local<Context> context,
1395 StreamedSource* source,
1396 Handle<String> full_source_string,
1397 const ScriptOrigin& origin);
1400 * Return a version tag for CachedData for the current V8 version & flags.
1402 * This value is meant only for determining whether a previously generated
1403 * CachedData instance is still valid; the tag has no other meaing.
1405 * Background: The data carried by CachedData may depend on the exact
1406 * V8 version number or currently compiler flags. This means when
1407 * persisting CachedData, the embedder must take care to not pass in
1408 * data from another V8 version, or the same version with different
1411 * The easiest way to do so is to clear the embedder's cache on any
1414 * Alternatively, this tag can be stored alongside the cached data and
1415 * compared when it is being used.
1417 static uint32_t CachedDataVersionTag();
1420 * Compile an ES6 module.
1422 * This is an experimental feature.
1424 * TODO(adamk): Script is likely the wrong return value for this;
1425 * should return some new Module type.
1427 static V8_DEPRECATE_SOON(
1428 "Use maybe version",
1429 Local<Script> CompileModule(Isolate* isolate, Source* source,
1430 CompileOptions options = kNoCompileOptions));
1431 static MaybeLocal<Script> CompileModule(
1432 Local<Context> context, Source* source,
1433 CompileOptions options = kNoCompileOptions);
1436 * Compile a function for a given context. This is equivalent to running
1439 * return function(args) { ... }
1442 * It is possible to specify multiple context extensions (obj in the above
1445 static V8_DEPRECATE_SOON("Use maybe version",
1446 Local<Function> CompileFunctionInContext(
1447 Isolate* isolate, Source* source,
1448 Local<Context> context, size_t arguments_count,
1449 Local<String> arguments[],
1450 size_t context_extension_count,
1451 Local<Object> context_extensions[]));
1452 static MaybeLocal<Function> CompileFunctionInContext(
1453 Local<Context> context, Source* source, size_t arguments_count,
1454 Local<String> arguments[], size_t context_extension_count,
1455 Local<Object> context_extensions[]);
1458 static MaybeLocal<UnboundScript> CompileUnboundInternal(
1459 Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1466 class V8_EXPORT Message {
1468 Local<String> Get() const;
1470 V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine()) const;
1471 MaybeLocal<String> GetSourceLine(Local<Context> context) const;
1474 * Returns the origin for the script from where the function causing the
1477 ScriptOrigin GetScriptOrigin() const;
1480 * Returns the resource name for the script from where the function causing
1481 * the error originates.
1483 Handle<Value> GetScriptResourceName() const;
1486 * Exception stack trace. By default stack traces are not captured for
1487 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1488 * to change this option.
1490 Handle<StackTrace> GetStackTrace() const;
1493 * Returns the number, 1-based, of the line where the error occurred.
1495 V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber()) const;
1496 Maybe<int> GetLineNumber(Local<Context> context) const;
1499 * Returns the index within the script of the first character where
1500 * the error occurred.
1502 int GetStartPosition() const;
1505 * Returns the index within the script of the last character where
1506 * the error occurred.
1508 int GetEndPosition() const;
1511 * Returns the index within the line of the first character where
1512 * the error occurred.
1514 V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn()) const;
1515 Maybe<int> GetStartColumn(Local<Context> context) const;
1518 * Returns the index within the line of the last character where
1519 * the error occurred.
1521 V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn()) const;
1522 Maybe<int> GetEndColumn(Local<Context> context) const;
1525 * Passes on the value set by the embedder when it fed the script from which
1526 * this Message was generated to V8.
1528 bool IsSharedCrossOrigin() const;
1530 // TODO(1245381): Print to a string instead of on a FILE.
1531 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1533 static const int kNoLineNumberInfo = 0;
1534 static const int kNoColumnInfo = 0;
1535 static const int kNoScriptIdInfo = 0;
1540 * Representation of a JavaScript stack trace. The information collected is a
1541 * snapshot of the execution stack and the information remains valid after
1542 * execution continues.
1544 class V8_EXPORT StackTrace {
1547 * Flags that determine what information is placed captured for each
1548 * StackFrame when grabbing the current stack trace.
1550 enum StackTraceOptions {
1552 kColumnOffset = 1 << 1 | kLineNumber,
1553 kScriptName = 1 << 2,
1554 kFunctionName = 1 << 3,
1556 kIsConstructor = 1 << 5,
1557 kScriptNameOrSourceURL = 1 << 6,
1559 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1560 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1561 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1565 * Returns a StackFrame at a particular index.
1567 Local<StackFrame> GetFrame(uint32_t index) const;
1570 * Returns the number of StackFrames.
1572 int GetFrameCount() const;
1575 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1577 Local<Array> AsArray();
1580 * Grab a snapshot of the current JavaScript execution stack.
1582 * \param frame_limit The maximum number of stack frames we want to capture.
1583 * \param options Enumerates the set of things we will capture for each
1586 static Local<StackTrace> CurrentStackTrace(
1589 StackTraceOptions options = kOverview);
1594 * A single JavaScript stack frame.
1596 class V8_EXPORT StackFrame {
1599 * Returns the number, 1-based, of the line for the associate function call.
1600 * This method will return Message::kNoLineNumberInfo if it is unable to
1601 * retrieve the line number, or if kLineNumber was not passed as an option
1602 * when capturing the StackTrace.
1604 int GetLineNumber() const;
1607 * Returns the 1-based column offset on the line for the associated function
1609 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1610 * the column number, or if kColumnOffset was not passed as an option when
1611 * capturing the StackTrace.
1613 int GetColumn() const;
1616 * Returns the id of the script for the function for this StackFrame.
1617 * This method will return Message::kNoScriptIdInfo if it is unable to
1618 * retrieve the script id, or if kScriptId was not passed as an option when
1619 * capturing the StackTrace.
1621 int GetScriptId() const;
1624 * Returns the name of the resource that contains the script for the
1625 * function for this StackFrame.
1627 Local<String> GetScriptName() const;
1630 * Returns the name of the resource that contains the script for the
1631 * function for this StackFrame or sourceURL value if the script name
1632 * is undefined and its source ends with //# sourceURL=... string or
1633 * deprecated //@ sourceURL=... string.
1635 Local<String> GetScriptNameOrSourceURL() const;
1638 * Returns the name of the function associated with this stack frame.
1640 Local<String> GetFunctionName() const;
1643 * Returns whether or not the associated function is compiled via a call to
1646 bool IsEval() const;
1649 * Returns whether or not the associated function is called as a
1650 * constructor via "new".
1652 bool IsConstructor() const;
1656 // A StateTag represents a possible state of the VM.
1657 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1660 // A RegisterState represents the current state of registers used
1661 // by the sampling profiler API.
1662 struct RegisterState {
1663 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1664 void* pc; // Instruction pointer.
1665 void* sp; // Stack pointer.
1666 void* fp; // Frame pointer.
1670 // The output structure filled up by GetStackSample API function.
1672 size_t frames_count;
1680 class V8_EXPORT JSON {
1683 * Tries to parse the string |json_string| and returns it as value if
1686 * \param json_string The string to parse.
1687 * \return The corresponding value if successfully parsed.
1689 static V8_DEPRECATE_SOON("Use maybe version",
1690 Local<Value> Parse(Local<String> json_string));
1691 static MaybeLocal<Value> Parse(Isolate* isolate, Local<String> json_string);
1696 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1697 * but can be created without entering a v8::Context and hence shouldn't
1698 * escape to JavaScript.
1700 class V8_EXPORT NativeWeakMap : public Data {
1702 static Local<NativeWeakMap> New(Isolate* isolate);
1703 void Set(Handle<Value> key, Handle<Value> value);
1704 Local<Value> Get(Handle<Value> key);
1705 bool Has(Handle<Value> key);
1706 bool Delete(Handle<Value> key);
1714 * The superclass of all JavaScript values and objects.
1716 class V8_EXPORT Value : public Data {
1719 * Returns true if this value is the undefined value. See ECMA-262
1722 V8_INLINE bool IsUndefined() const;
1725 * Returns true if this value is the null value. See ECMA-262
1728 V8_INLINE bool IsNull() const;
1731 * Returns true if this value is true.
1733 bool IsTrue() const;
1736 * Returns true if this value is false.
1738 bool IsFalse() const;
1741 * Returns true if this value is a symbol or a string.
1742 * This is an experimental feature.
1744 bool IsName() const;
1747 * Returns true if this value is an instance of the String type.
1750 V8_INLINE bool IsString() const;
1753 * Returns true if this value is a symbol.
1754 * This is an experimental feature.
1756 bool IsSymbol() const;
1759 * Returns true if this value is a function.
1761 bool IsFunction() const;
1764 * Returns true if this value is an array.
1766 bool IsArray() const;
1769 * Returns true if this value is an object.
1771 bool IsObject() const;
1774 * Returns true if this value is boolean.
1776 bool IsBoolean() const;
1779 * Returns true if this value is a number.
1781 bool IsNumber() const;
1784 * Returns true if this value is external.
1786 bool IsExternal() const;
1789 * Returns true if this value is a 32-bit signed integer.
1791 bool IsInt32() const;
1794 * Returns true if this value is a 32-bit unsigned integer.
1796 bool IsUint32() const;
1799 * Returns true if this value is a Date.
1801 bool IsDate() const;
1804 * Returns true if this value is an Arguments object.
1806 bool IsArgumentsObject() const;
1809 * Returns true if this value is a Boolean object.
1811 bool IsBooleanObject() const;
1814 * Returns true if this value is a Number object.
1816 bool IsNumberObject() const;
1819 * Returns true if this value is a String object.
1821 bool IsStringObject() const;
1824 * Returns true if this value is a Symbol object.
1825 * This is an experimental feature.
1827 bool IsSymbolObject() const;
1830 * Returns true if this value is a NativeError.
1832 bool IsNativeError() const;
1835 * Returns true if this value is a RegExp.
1837 bool IsRegExp() const;
1840 * Returns true if this value is a Generator function.
1841 * This is an experimental feature.
1843 bool IsGeneratorFunction() const;
1846 * Returns true if this value is a Generator object (iterator).
1847 * This is an experimental feature.
1849 bool IsGeneratorObject() const;
1852 * Returns true if this value is a Promise.
1853 * This is an experimental feature.
1855 bool IsPromise() const;
1858 * Returns true if this value is a Map.
1859 * This is an experimental feature.
1864 * Returns true if this value is a Set.
1865 * This is an experimental feature.
1870 * Returns true if this value is a Map Iterator.
1871 * This is an experimental feature.
1873 bool IsMapIterator() const;
1876 * Returns true if this value is a Set Iterator.
1877 * This is an experimental feature.
1879 bool IsSetIterator() const;
1882 * Returns true if this value is a WeakMap.
1883 * This is an experimental feature.
1885 bool IsWeakMap() const;
1888 * Returns true if this value is a WeakSet.
1889 * This is an experimental feature.
1891 bool IsWeakSet() const;
1894 * Returns true if this value is an ArrayBuffer.
1895 * This is an experimental feature.
1897 bool IsArrayBuffer() const;
1900 * Returns true if this value is an ArrayBufferView.
1901 * This is an experimental feature.
1903 bool IsArrayBufferView() const;
1906 * Returns true if this value is one of TypedArrays.
1907 * This is an experimental feature.
1909 bool IsTypedArray() const;
1912 * Returns true if this value is an Uint8Array.
1913 * This is an experimental feature.
1915 bool IsUint8Array() const;
1918 * Returns true if this value is an Uint8ClampedArray.
1919 * This is an experimental feature.
1921 bool IsUint8ClampedArray() const;
1924 * Returns true if this value is an Int8Array.
1925 * This is an experimental feature.
1927 bool IsInt8Array() const;
1930 * Returns true if this value is an Uint16Array.
1931 * This is an experimental feature.
1933 bool IsUint16Array() const;
1936 * Returns true if this value is an Int16Array.
1937 * This is an experimental feature.
1939 bool IsInt16Array() const;
1942 * Returns true if this value is an Uint32Array.
1943 * This is an experimental feature.
1945 bool IsUint32Array() const;
1948 * Returns true if this value is an Int32Array.
1949 * This is an experimental feature.
1951 bool IsInt32Array() const;
1954 * Returns true if this value is a Float32Array.
1955 * This is an experimental feature.
1957 bool IsFloat32Array() const;
1960 * Returns true if this value is a Float64Array.
1961 * This is an experimental feature.
1963 bool IsFloat64Array() const;
1966 * Returns true if this value is a DataView.
1967 * This is an experimental feature.
1969 bool IsDataView() const;
1971 MaybeLocal<Boolean> ToBoolean(Local<Context> context) const;
1972 MaybeLocal<Number> ToNumber(Local<Context> context) const;
1973 MaybeLocal<String> ToString(Local<Context> context) const;
1974 MaybeLocal<String> ToDetailString(Local<Context> context) const;
1975 MaybeLocal<Object> ToObject(Local<Context> context) const;
1976 MaybeLocal<Integer> ToInteger(Local<Context> context) const;
1977 MaybeLocal<Uint32> ToUint32(Local<Context> context) const;
1978 MaybeLocal<Int32> ToInt32(Local<Context> context) const;
1980 V8_DEPRECATE_SOON("Use maybe version",
1981 Local<Boolean> ToBoolean(Isolate* isolate)) const;
1982 V8_DEPRECATE_SOON("Use maybe version",
1983 Local<Number> ToNumber(Isolate* isolate)) const;
1984 V8_DEPRECATE_SOON("Use maybe version",
1985 Local<String> ToString(Isolate* isolate)) const;
1986 V8_DEPRECATE_SOON("Use maybe version",
1987 Local<String> ToDetailString(Isolate* isolate)) const;
1988 V8_DEPRECATE_SOON("Use maybe version",
1989 Local<Object> ToObject(Isolate* isolate)) const;
1990 V8_DEPRECATE_SOON("Use maybe version",
1991 Local<Integer> ToInteger(Isolate* isolate)) const;
1992 V8_DEPRECATE_SOON("Use maybe version",
1993 Local<Uint32> ToUint32(Isolate* isolate)) const;
1994 V8_DEPRECATE_SOON("Use maybe version",
1995 Local<Int32> ToInt32(Isolate* isolate)) const;
1997 inline V8_DEPRECATE_SOON("Use maybe version",
1998 Local<Boolean> ToBoolean()) const;
1999 inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber()) const;
2000 inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString()) const;
2001 inline V8_DEPRECATE_SOON("Use maybe version",
2002 Local<String> ToDetailString()) const;
2003 inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject()) const;
2004 inline V8_DEPRECATE_SOON("Use maybe version",
2005 Local<Integer> ToInteger()) const;
2006 inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32()) const;
2007 inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32()) const;
2010 * Attempts to convert a string to an array index.
2011 * Returns an empty handle if the conversion fails.
2013 V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex()) const;
2014 MaybeLocal<Uint32> ToArrayIndex(Local<Context> context) const;
2016 Maybe<bool> BooleanValue(Local<Context> context) const;
2017 Maybe<double> NumberValue(Local<Context> context) const;
2018 Maybe<int64_t> IntegerValue(Local<Context> context) const;
2019 Maybe<uint32_t> Uint32Value(Local<Context> context) const;
2020 Maybe<int32_t> Int32Value(Local<Context> context) const;
2022 V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue()) const;
2023 V8_DEPRECATE_SOON("Use maybe version", double NumberValue()) const;
2024 V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue()) const;
2025 V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value()) const;
2026 V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value()) const;
2029 V8_DEPRECATE_SOON("Use maybe version", bool Equals(Handle<Value> that)) const;
2030 Maybe<bool> Equals(Local<Context> context, Handle<Value> that) const;
2031 bool StrictEquals(Handle<Value> that) const;
2032 bool SameValue(Handle<Value> that) const;
2034 template <class T> V8_INLINE static Value* Cast(T* value);
2037 V8_INLINE bool QuickIsUndefined() const;
2038 V8_INLINE bool QuickIsNull() const;
2039 V8_INLINE bool QuickIsString() const;
2040 bool FullIsUndefined() const;
2041 bool FullIsNull() const;
2042 bool FullIsString() const;
2047 * The superclass of primitive values. See ECMA-262 4.3.2.
2049 class V8_EXPORT Primitive : public Value { };
2053 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2056 class V8_EXPORT Boolean : public Primitive {
2059 V8_INLINE static Boolean* Cast(v8::Value* obj);
2060 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
2062 static void CheckCast(v8::Value* obj);
2067 * A superclass for symbols and strings.
2069 class V8_EXPORT Name : public Primitive {
2072 * Returns the identity hash for this object. The current implementation
2073 * uses an inline property on the object to store the identity hash.
2075 * The return value will never be 0. Also, it is not guaranteed to be
2078 int GetIdentityHash();
2080 V8_INLINE static Name* Cast(v8::Value* obj);
2082 static void CheckCast(v8::Value* obj);
2086 enum class NewStringType { kNormal, kInternalized };
2090 * A JavaScript string value (ECMA-262, 4.3.17).
2092 class V8_EXPORT String : public Name {
2094 static const int kMaxLength = (1 << 28) - 16;
2097 UNKNOWN_ENCODING = 0x1,
2098 TWO_BYTE_ENCODING = 0x0,
2099 ONE_BYTE_ENCODING = 0x4
2102 * Returns the number of characters in this string.
2107 * Returns the number of bytes in the UTF-8 encoded
2108 * representation of this string.
2110 int Utf8Length() const;
2113 * Returns whether this string is known to contain only one byte data.
2114 * Does not read the string.
2115 * False negatives are possible.
2117 bool IsOneByte() const;
2120 * Returns whether this string contain only one byte data.
2121 * Will read the entire string in some cases.
2123 bool ContainsOnlyOneByte() const;
2126 * Write the contents of the string to an external buffer.
2127 * If no arguments are given, expects the buffer to be large
2128 * enough to hold the entire string and NULL terminator. Copies
2129 * the contents of the string and the NULL terminator into the
2132 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2133 * before the end of the buffer.
2135 * Copies up to length characters into the output buffer.
2136 * Only null-terminates if there is enough space in the buffer.
2138 * \param buffer The buffer into which the string will be copied.
2139 * \param start The starting position within the string at which
2141 * \param length The number of characters to copy from the string. For
2142 * WriteUtf8 the number of bytes in the buffer.
2143 * \param nchars_ref The number of characters written, can be NULL.
2144 * \param options Various options that might affect performance of this or
2145 * subsequent operations.
2146 * \return The number of characters copied to the buffer excluding the null
2147 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2148 * including the null terminator (if written).
2152 HINT_MANY_WRITES_EXPECTED = 1,
2153 NO_NULL_TERMINATION = 2,
2154 PRESERVE_ONE_BYTE_NULL = 4,
2155 // Used by WriteUtf8 to replace orphan surrogate code units with the
2156 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2158 REPLACE_INVALID_UTF8 = 8
2161 // 16-bit character codes.
2162 int Write(uint16_t* buffer,
2165 int options = NO_OPTIONS) const;
2166 // One byte characters.
2167 int WriteOneByte(uint8_t* buffer,
2170 int options = NO_OPTIONS) const;
2171 // UTF-8 encoded characters.
2172 int WriteUtf8(char* buffer,
2174 int* nchars_ref = NULL,
2175 int options = NO_OPTIONS) const;
2178 * A zero length string.
2180 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2183 * Returns true if the string is external
2185 bool IsExternal() const;
2188 * Returns true if the string is both external and one-byte.
2190 bool IsExternalOneByte() const;
2192 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2194 virtual ~ExternalStringResourceBase() {}
2197 ExternalStringResourceBase() {}
2200 * Internally V8 will call this Dispose method when the external string
2201 * resource is no longer needed. The default implementation will use the
2202 * delete operator. This method can be overridden in subclasses to
2203 * control how allocated external string resources are disposed.
2205 virtual void Dispose() { delete this; }
2208 // Disallow copying and assigning.
2209 ExternalStringResourceBase(const ExternalStringResourceBase&);
2210 void operator=(const ExternalStringResourceBase&);
2212 friend class v8::internal::Heap;
2216 * An ExternalStringResource is a wrapper around a two-byte string
2217 * buffer that resides outside V8's heap. Implement an
2218 * ExternalStringResource to manage the life cycle of the underlying
2219 * buffer. Note that the string data must be immutable.
2221 class V8_EXPORT ExternalStringResource
2222 : public ExternalStringResourceBase {
2225 * Override the destructor to manage the life cycle of the underlying
2228 virtual ~ExternalStringResource() {}
2231 * The string data from the underlying buffer.
2233 virtual const uint16_t* data() const = 0;
2236 * The length of the string. That is, the number of two-byte characters.
2238 virtual size_t length() const = 0;
2241 ExternalStringResource() {}
2245 * An ExternalOneByteStringResource is a wrapper around an one-byte
2246 * string buffer that resides outside V8's heap. Implement an
2247 * ExternalOneByteStringResource to manage the life cycle of the
2248 * underlying buffer. Note that the string data must be immutable
2249 * and that the data must be Latin-1 and not UTF-8, which would require
2250 * special treatment internally in the engine and do not allow efficient
2251 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2254 class V8_EXPORT ExternalOneByteStringResource
2255 : public ExternalStringResourceBase {
2258 * Override the destructor to manage the life cycle of the underlying
2261 virtual ~ExternalOneByteStringResource() {}
2262 /** The string data from the underlying buffer.*/
2263 virtual const char* data() const = 0;
2264 /** The number of Latin-1 characters in the string.*/
2265 virtual size_t length() const = 0;
2267 ExternalOneByteStringResource() {}
2271 * If the string is an external string, return the ExternalStringResourceBase
2272 * regardless of the encoding, otherwise return NULL. The encoding of the
2273 * string is returned in encoding_out.
2275 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2276 Encoding* encoding_out) const;
2279 * Get the ExternalStringResource for an external string. Returns
2280 * NULL if IsExternal() doesn't return true.
2282 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2285 * Get the ExternalOneByteStringResource for an external one-byte string.
2286 * Returns NULL if IsExternalOneByte() doesn't return true.
2288 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2290 V8_INLINE static String* Cast(v8::Value* obj);
2292 // TODO(dcarney): remove with deprecation of New functions.
2293 enum NewStringType {
2294 kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2295 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2298 /** Allocates a new string from UTF-8 data.*/
2299 static V8_DEPRECATE_SOON(
2300 "Use maybe version",
2301 Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2302 NewStringType type = kNormalString,
2305 /** Allocates a new string from UTF-8 data. Only returns an empty value when
2306 * length > kMaxLength. **/
2307 static MaybeLocal<String> NewFromUtf8(Isolate* isolate, const char* data,
2308 v8::NewStringType type,
2311 /** Allocates a new string from Latin-1 data.*/
2312 static V8_DEPRECATE_SOON(
2313 "Use maybe version",
2314 Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2315 NewStringType type = kNormalString,
2318 /** Allocates a new string from Latin-1 data. Only returns an empty value
2319 * when length > kMaxLength. **/
2320 static MaybeLocal<String> NewFromOneByte(Isolate* isolate,
2321 const uint8_t* data,
2322 v8::NewStringType type,
2325 /** Allocates a new string from UTF-16 data.*/
2326 static V8_DEPRECATE_SOON(
2327 "Use maybe version",
2328 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2329 NewStringType type = kNormalString,
2332 /** Allocates a new string from UTF-16 data. Only returns an empty value when
2333 * length > kMaxLength. **/
2334 static MaybeLocal<String> NewFromTwoByte(Isolate* isolate,
2335 const uint16_t* data,
2336 v8::NewStringType type,
2340 * Creates a new string by concatenating the left and the right strings
2341 * passed in as parameters.
2343 static Local<String> Concat(Handle<String> left, Handle<String> right);
2346 * Creates a new external string using the data defined in the given
2347 * resource. When the external string is no longer live on V8's heap the
2348 * resource will be disposed by calling its Dispose method. The caller of
2349 * this function should not otherwise delete or modify the resource. Neither
2350 * should the underlying buffer be deallocated or modified except through the
2351 * destructor of the external string resource.
2353 static V8_DEPRECATE_SOON(
2354 "Use maybe version",
2355 Local<String> NewExternal(Isolate* isolate,
2356 ExternalStringResource* resource));
2357 static MaybeLocal<String> NewExternalTwoByte(
2358 Isolate* isolate, ExternalStringResource* resource);
2361 * Associate an external string resource with this string by transforming it
2362 * in place so that existing references to this string in the JavaScript heap
2363 * will use the external string resource. The external string resource's
2364 * character contents need to be equivalent to this string.
2365 * Returns true if the string has been changed to be an external string.
2366 * The string is not modified if the operation fails. See NewExternal for
2367 * information on the lifetime of the resource.
2369 bool MakeExternal(ExternalStringResource* resource);
2372 * Creates a new external string using the one-byte data defined in the given
2373 * resource. When the external string is no longer live on V8's heap the
2374 * resource will be disposed by calling its Dispose method. The caller of
2375 * this function should not otherwise delete or modify the resource. Neither
2376 * should the underlying buffer be deallocated or modified except through the
2377 * destructor of the external string resource.
2379 static V8_DEPRECATE_SOON(
2380 "Use maybe version",
2381 Local<String> NewExternal(Isolate* isolate,
2382 ExternalOneByteStringResource* resource));
2383 static MaybeLocal<String> NewExternalOneByte(
2384 Isolate* isolate, ExternalOneByteStringResource* resource);
2387 * Associate an external string resource with this string by transforming it
2388 * in place so that existing references to this string in the JavaScript heap
2389 * will use the external string resource. The external string resource's
2390 * character contents need to be equivalent to this string.
2391 * Returns true if the string has been changed to be an external string.
2392 * The string is not modified if the operation fails. See NewExternal for
2393 * information on the lifetime of the resource.
2395 bool MakeExternal(ExternalOneByteStringResource* resource);
2398 * Returns true if this string can be made external.
2400 bool CanMakeExternal();
2403 * Converts an object to a UTF-8-encoded character array. Useful if
2404 * you want to print the object. If conversion to a string fails
2405 * (e.g. due to an exception in the toString() method of the object)
2406 * then the length() method returns 0 and the * operator returns
2409 class V8_EXPORT Utf8Value {
2411 explicit Utf8Value(Handle<v8::Value> obj);
2413 char* operator*() { return str_; }
2414 const char* operator*() const { return str_; }
2415 int length() const { return length_; }
2420 // Disallow copying and assigning.
2421 Utf8Value(const Utf8Value&);
2422 void operator=(const Utf8Value&);
2426 * Converts an object to a two-byte string.
2427 * If conversion to a string fails (eg. due to an exception in the toString()
2428 * method of the object) then the length() method returns 0 and the * operator
2431 class V8_EXPORT Value {
2433 explicit Value(Handle<v8::Value> obj);
2435 uint16_t* operator*() { return str_; }
2436 const uint16_t* operator*() const { return str_; }
2437 int length() const { return length_; }
2442 // Disallow copying and assigning.
2443 Value(const Value&);
2444 void operator=(const Value&);
2448 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2449 Encoding encoding) const;
2450 void VerifyExternalStringResource(ExternalStringResource* val) const;
2451 static void CheckCast(v8::Value* obj);
2456 * A JavaScript symbol (ECMA-262 edition 6)
2458 * This is an experimental feature. Use at your own risk.
2460 class V8_EXPORT Symbol : public Name {
2462 // Returns the print name string of the symbol, or undefined if none.
2463 Local<Value> Name() const;
2465 // Create a symbol. If name is not empty, it will be used as the description.
2466 static Local<Symbol> New(
2467 Isolate *isolate, Local<String> name = Local<String>());
2469 // Access global symbol registry.
2470 // Note that symbols created this way are never collected, so
2471 // they should only be used for statically fixed properties.
2472 // Also, there is only one global name space for the names used as keys.
2473 // To minimize the potential for clashes, use qualified names as keys.
2474 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2476 // Retrieve a global symbol. Similar to |For|, but using a separate
2477 // registry that is not accessible by (and cannot clash with) JavaScript code.
2478 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2480 // Well-known symbols
2481 static Local<Symbol> GetIterator(Isolate* isolate);
2482 static Local<Symbol> GetUnscopables(Isolate* isolate);
2483 static Local<Symbol> GetToStringTag(Isolate* isolate);
2485 V8_INLINE static Symbol* Cast(v8::Value* obj);
2489 static void CheckCast(v8::Value* obj);
2496 * This is an experimental feature. Use at your own risk.
2498 class V8_EXPORT Private : public Data {
2500 // Returns the print name string of the private symbol, or undefined if none.
2501 Local<Value> Name() const;
2503 // Create a private symbol. If name is not empty, it will be the description.
2504 static Local<Private> New(
2505 Isolate *isolate, Local<String> name = Local<String>());
2507 // Retrieve a global private symbol. If a symbol with this name has not
2508 // been retrieved in the same isolate before, it is created.
2509 // Note that private symbols created this way are never collected, so
2510 // they should only be used for statically fixed properties.
2511 // Also, there is only one global name space for the names used as keys.
2512 // To minimize the potential for clashes, use qualified names as keys,
2513 // e.g., "Class#property".
2514 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2522 * A JavaScript number value (ECMA-262, 4.3.20)
2524 class V8_EXPORT Number : public Primitive {
2526 double Value() const;
2527 static Local<Number> New(Isolate* isolate, double value);
2528 V8_INLINE static Number* Cast(v8::Value* obj);
2531 static void CheckCast(v8::Value* obj);
2536 * A JavaScript value representing a signed integer.
2538 class V8_EXPORT Integer : public Number {
2540 static Local<Integer> New(Isolate* isolate, int32_t value);
2541 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2542 int64_t Value() const;
2543 V8_INLINE static Integer* Cast(v8::Value* obj);
2546 static void CheckCast(v8::Value* obj);
2551 * A JavaScript value representing a 32-bit signed integer.
2553 class V8_EXPORT Int32 : public Integer {
2555 int32_t Value() const;
2556 V8_INLINE static Int32* Cast(v8::Value* obj);
2560 static void CheckCast(v8::Value* obj);
2565 * A JavaScript value representing a 32-bit unsigned integer.
2567 class V8_EXPORT Uint32 : public Integer {
2569 uint32_t Value() const;
2570 V8_INLINE static Uint32* Cast(v8::Value* obj);
2574 static void CheckCast(v8::Value* obj);
2578 enum PropertyAttribute {
2585 enum ExternalArrayType {
2586 kExternalInt8Array = 1,
2587 kExternalUint8Array,
2588 kExternalInt16Array,
2589 kExternalUint16Array,
2590 kExternalInt32Array,
2591 kExternalUint32Array,
2592 kExternalFloat32Array,
2593 kExternalFloat64Array,
2594 kExternalUint8ClampedArray,
2596 // Legacy constant names
2597 kExternalByteArray = kExternalInt8Array,
2598 kExternalUnsignedByteArray = kExternalUint8Array,
2599 kExternalShortArray = kExternalInt16Array,
2600 kExternalUnsignedShortArray = kExternalUint16Array,
2601 kExternalIntArray = kExternalInt32Array,
2602 kExternalUnsignedIntArray = kExternalUint32Array,
2603 kExternalFloatArray = kExternalFloat32Array,
2604 kExternalDoubleArray = kExternalFloat64Array,
2605 kExternalPixelArray = kExternalUint8ClampedArray
2609 * Accessor[Getter|Setter] are used as callback functions when
2610 * setting|getting a particular property. See Object and ObjectTemplate's
2611 * method SetAccessor.
2613 typedef void (*AccessorGetterCallback)(
2614 Local<String> property,
2615 const PropertyCallbackInfo<Value>& info);
2616 typedef void (*AccessorNameGetterCallback)(
2617 Local<Name> property,
2618 const PropertyCallbackInfo<Value>& info);
2621 typedef void (*AccessorSetterCallback)(
2622 Local<String> property,
2624 const PropertyCallbackInfo<void>& info);
2625 typedef void (*AccessorNameSetterCallback)(
2626 Local<Name> property,
2628 const PropertyCallbackInfo<void>& info);
2632 * Access control specifications.
2634 * Some accessors should be accessible across contexts. These
2635 * accessors have an explicit access control parameter which specifies
2636 * the kind of cross-context access that should be allowed.
2638 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2640 enum AccessControl {
2643 ALL_CAN_WRITE = 1 << 1,
2644 PROHIBITS_OVERWRITING = 1 << 2
2649 * A JavaScript object (ECMA-262, 4.3.3)
2651 class V8_EXPORT Object : public Value {
2653 V8_DEPRECATE_SOON("Use maybe version",
2654 bool Set(Handle<Value> key, Handle<Value> value));
2655 Maybe<bool> Set(Local<Context> context, Local<Value> key, Local<Value> value);
2657 V8_DEPRECATE_SOON("Use maybe version",
2658 bool Set(uint32_t index, Handle<Value> value));
2659 Maybe<bool> Set(Local<Context> context, uint32_t index, Local<Value> value);
2661 // Sets an own property on this object bypassing interceptors and
2662 // overriding accessors or read-only properties.
2664 // Note that if the object has an interceptor the property will be set
2665 // locally, but since the interceptor takes precedence the local property
2666 // will only be returned if the interceptor doesn't return a value.
2668 // Note also that this only works for named properties.
2669 V8_DEPRECATE_SOON("Use maybe version",
2670 bool ForceSet(Handle<Value> key, Handle<Value> value,
2671 PropertyAttribute attribs = None));
2672 Maybe<bool> ForceSet(Local<Context> context, Local<Value> key,
2673 Local<Value> value, PropertyAttribute attribs = None);
2675 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Handle<Value> key));
2676 MaybeLocal<Value> Get(Local<Context> context, Local<Value> key);
2678 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2679 MaybeLocal<Value> Get(Local<Context> context, uint32_t index);
2682 * Gets the property attributes of a property which can be None or
2683 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2684 * None when the property doesn't exist.
2686 V8_DEPRECATE_SOON("Use maybe version",
2687 PropertyAttribute GetPropertyAttributes(Handle<Value> key));
2688 Maybe<PropertyAttribute> GetPropertyAttributes(Local<Context> context,
2692 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2694 V8_DEPRECATE_SOON("Use maybe version",
2695 Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2696 MaybeLocal<Value> GetOwnPropertyDescriptor(Local<Context> context,
2699 V8_DEPRECATE_SOON("Use maybe version", bool Has(Handle<Value> key));
2700 Maybe<bool> Has(Local<Context> context, Local<Value> key);
2702 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Handle<Value> key));
2703 Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2705 V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2706 Maybe<bool> Has(Local<Context> context, uint32_t index);
2708 V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2709 Maybe<bool> Delete(Local<Context> context, uint32_t index);
2711 V8_DEPRECATE_SOON("Use maybe version",
2712 bool SetAccessor(Handle<String> name,
2713 AccessorGetterCallback getter,
2714 AccessorSetterCallback setter = 0,
2715 Handle<Value> data = Handle<Value>(),
2716 AccessControl settings = DEFAULT,
2717 PropertyAttribute attribute = None));
2718 V8_DEPRECATE_SOON("Use maybe version",
2719 bool SetAccessor(Handle<Name> name,
2720 AccessorNameGetterCallback getter,
2721 AccessorNameSetterCallback setter = 0,
2722 Handle<Value> data = Handle<Value>(),
2723 AccessControl settings = DEFAULT,
2724 PropertyAttribute attribute = None));
2725 Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2726 AccessorNameGetterCallback getter,
2727 AccessorNameSetterCallback setter = 0,
2728 MaybeLocal<Value> data = MaybeLocal<Value>(),
2729 AccessControl settings = DEFAULT,
2730 PropertyAttribute attribute = None);
2732 void SetAccessorProperty(Local<Name> name,
2733 Local<Function> getter,
2734 Handle<Function> setter = Handle<Function>(),
2735 PropertyAttribute attribute = None,
2736 AccessControl settings = DEFAULT);
2739 * Functionality for private properties.
2740 * This is an experimental feature, use at your own risk.
2741 * Note: Private properties are inherited. Do not rely on this, since it may
2744 // TODO(dcarney): convert these or remove?
2745 bool HasPrivate(Handle<Private> key);
2746 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2747 bool DeletePrivate(Handle<Private> key);
2748 Local<Value> GetPrivate(Handle<Private> key);
2751 * Returns an array containing the names of the enumerable properties
2752 * of this object, including properties from prototype objects. The
2753 * array returned by this method contains the same values as would
2754 * be enumerated by a for-in statement over this object.
2756 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2757 MaybeLocal<Array> GetPropertyNames(Local<Context> context);
2760 * This function has the same functionality as GetPropertyNames but
2761 * the returned array doesn't contain the names of properties from
2762 * prototype objects.
2764 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2765 MaybeLocal<Array> GetOwnPropertyNames(Local<Context> context);
2768 * Get the prototype object. This does not skip objects marked to
2769 * be skipped by __proto__ and it does not consult the security
2772 Local<Value> GetPrototype();
2775 * Set the prototype object. This does not skip objects marked to
2776 * be skipped by __proto__ and it does not consult the security
2779 V8_DEPRECATE_SOON("Use maybe version",
2780 bool SetPrototype(Handle<Value> prototype));
2781 Maybe<bool> SetPrototype(Local<Context> context, Local<Value> prototype);
2784 * Finds an instance of the given function template in the prototype
2787 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2790 * Call builtin Object.prototype.toString on this object.
2791 * This is different from Value::ToString() that may call
2792 * user-defined toString function. This one does not.
2794 V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2795 MaybeLocal<String> ObjectProtoToString(Local<Context> context);
2798 * Returns the name of the function invoked as a constructor for this object.
2800 Local<String> GetConstructorName();
2802 /** Gets the number of internal fields for this Object. */
2803 int InternalFieldCount();
2805 /** Same as above, but works for Persistents */
2806 V8_INLINE static int InternalFieldCount(
2807 const PersistentBase<Object>& object) {
2808 return object.val_->InternalFieldCount();
2811 /** Gets the value from an internal field. */
2812 V8_INLINE Local<Value> GetInternalField(int index);
2814 /** Sets the value in an internal field. */
2815 void SetInternalField(int index, Handle<Value> value);
2818 * Gets a 2-byte-aligned native pointer from an internal field. This field
2819 * must have been set by SetAlignedPointerInInternalField, everything else
2820 * leads to undefined behavior.
2822 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2824 /** Same as above, but works for Persistents */
2825 V8_INLINE static void* GetAlignedPointerFromInternalField(
2826 const PersistentBase<Object>& object, int index) {
2827 return object.val_->GetAlignedPointerFromInternalField(index);
2831 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2832 * a field, GetAlignedPointerFromInternalField must be used, everything else
2833 * leads to undefined behavior.
2835 void SetAlignedPointerInInternalField(int index, void* value);
2837 // Testers for local properties.
2838 V8_DEPRECATE_SOON("Use maybe version",
2839 bool HasOwnProperty(Handle<String> key));
2840 Maybe<bool> HasOwnProperty(Local<Context> context, Local<Name> key);
2841 V8_DEPRECATE_SOON("Use maybe version",
2842 bool HasRealNamedProperty(Handle<String> key));
2843 Maybe<bool> HasRealNamedProperty(Local<Context> context, Local<Name> key);
2844 V8_DEPRECATE_SOON("Use maybe version",
2845 bool HasRealIndexedProperty(uint32_t index));
2846 Maybe<bool> HasRealIndexedProperty(Local<Context> context, uint32_t index);
2847 V8_DEPRECATE_SOON("Use maybe version",
2848 bool HasRealNamedCallbackProperty(Handle<String> key));
2849 Maybe<bool> HasRealNamedCallbackProperty(Local<Context> context,
2853 * If result.IsEmpty() no real property was located in the prototype chain.
2854 * This means interceptors in the prototype chain are not called.
2857 "Use maybe version",
2858 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key));
2859 MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(Local<Context> context,
2863 * Gets the property attributes of a real property in the prototype chain,
2864 * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2865 * Interceptors in the prototype chain are not called.
2868 "Use maybe version",
2869 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2870 Handle<String> key));
2871 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2872 Local<Context> context, Local<Name> key);
2875 * If result.IsEmpty() no real property was located on the object or
2876 * in the prototype chain.
2877 * This means interceptors in the prototype chain are not called.
2879 V8_DEPRECATE_SOON("Use maybe version",
2880 Local<Value> GetRealNamedProperty(Handle<String> key));
2881 MaybeLocal<Value> GetRealNamedProperty(Local<Context> context,
2885 * Gets the property attributes of a real property which can be
2886 * None or any combination of ReadOnly, DontEnum and DontDelete.
2887 * Interceptors in the prototype chain are not called.
2889 V8_DEPRECATE_SOON("Use maybe version",
2890 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2891 Handle<String> key));
2892 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2893 Local<Context> context, Local<Name> key);
2895 /** Tests for a named lookup interceptor.*/
2896 bool HasNamedLookupInterceptor();
2898 /** Tests for an index lookup interceptor.*/
2899 bool HasIndexedLookupInterceptor();
2902 * Turns on access check on the object if the object is an instance of
2903 * a template that has access check callbacks. If an object has no
2904 * access check info, the object cannot be accessed by anyone.
2906 V8_DEPRECATE_SOON("No alternative", void TurnOnAccessCheck());
2909 * Returns the identity hash for this object. The current implementation
2910 * uses a hidden property on the object to store the identity hash.
2912 * The return value will never be 0. Also, it is not guaranteed to be
2915 int GetIdentityHash();
2918 * Access hidden properties on JavaScript objects. These properties are
2919 * hidden from the executing JavaScript and only accessible through the V8
2920 * C++ API. Hidden properties introduced by V8 internally (for example the
2921 * identity hash) are prefixed with "v8::".
2923 // TODO(dcarney): convert these to take a isolate and optionally bailout?
2924 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2925 Local<Value> GetHiddenValue(Handle<String> key);
2926 bool DeleteHiddenValue(Handle<String> key);
2929 * Clone this object with a fast but shallow copy. Values will point
2930 * to the same values as the original object.
2932 // TODO(dcarney): take an isolate and optionally bail out?
2933 Local<Object> Clone();
2936 * Returns the context in which the object was created.
2938 Local<Context> CreationContext();
2941 * Set the backing store of the indexed properties to be managed by the
2942 * embedding layer. Access to the indexed properties will follow the rules
2943 * spelled out in CanvasPixelArray.
2944 * Note: The embedding program still owns the data and needs to ensure that
2945 * the backing store is preserved while V8 has a reference.
2947 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2948 bool HasIndexedPropertiesInPixelData();
2949 uint8_t* GetIndexedPropertiesPixelData();
2950 int GetIndexedPropertiesPixelDataLength();
2953 * Set the backing store of the indexed properties to be managed by the
2954 * embedding layer. Access to the indexed properties will follow the rules
2955 * spelled out for the CanvasArray subtypes in the WebGL specification.
2956 * Note: The embedding program still owns the data and needs to ensure that
2957 * the backing store is preserved while V8 has a reference.
2959 void SetIndexedPropertiesToExternalArrayData(void* data,
2960 ExternalArrayType array_type,
2961 int number_of_elements);
2962 bool HasIndexedPropertiesInExternalArrayData();
2963 void* GetIndexedPropertiesExternalArrayData();
2964 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2965 int GetIndexedPropertiesExternalArrayDataLength();
2968 * Checks whether a callback is set by the
2969 * ObjectTemplate::SetCallAsFunctionHandler method.
2970 * When an Object is callable this method returns true.
2975 * Call an Object as a function if a callback is set by the
2976 * ObjectTemplate::SetCallAsFunctionHandler method.
2978 V8_DEPRECATE_SOON("Use maybe version",
2979 Local<Value> CallAsFunction(Handle<Value> recv, int argc,
2980 Handle<Value> argv[]));
2981 MaybeLocal<Value> CallAsFunction(Local<Context> context, Handle<Value> recv,
2982 int argc, Handle<Value> argv[]);
2985 * Call an Object as a constructor if a callback is set by the
2986 * ObjectTemplate::SetCallAsFunctionHandler method.
2987 * Note: This method behaves like the Function::NewInstance method.
2989 V8_DEPRECATE_SOON("Use maybe version",
2990 Local<Value> CallAsConstructor(int argc,
2991 Handle<Value> argv[]));
2992 MaybeLocal<Value> CallAsConstructor(Local<Context> context, int argc,
2993 Local<Value> argv[]);
2996 * Return the isolate to which the Object belongs to.
2998 V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
3000 static Local<Object> New(Isolate* isolate);
3002 V8_INLINE static Object* Cast(Value* obj);
3006 static void CheckCast(Value* obj);
3007 Local<Value> SlowGetInternalField(int index);
3008 void* SlowGetAlignedPointerFromInternalField(int index);
3013 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
3015 class V8_EXPORT Array : public Object {
3017 uint32_t Length() const;
3020 * Clones an element at index |index|. Returns an empty
3021 * handle if cloning fails (for any reason).
3023 V8_DEPRECATE_SOON("Use maybe version",
3024 Local<Object> CloneElementAt(uint32_t index));
3025 MaybeLocal<Object> CloneElementAt(Local<Context> context, uint32_t index);
3028 * Creates a JavaScript array with the given length. If the length
3029 * is negative the returned array will have length 0.
3031 static Local<Array> New(Isolate* isolate, int length = 0);
3033 V8_INLINE static Array* Cast(Value* obj);
3036 static void CheckCast(Value* obj);
3040 template<typename T>
3043 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3044 : value_(that.value_) {
3048 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
3049 template <typename S> V8_INLINE void Set(const Handle<S> handle);
3050 // Fast primitive setters
3051 V8_INLINE void Set(bool value);
3052 V8_INLINE void Set(double i);
3053 V8_INLINE void Set(int32_t i);
3054 V8_INLINE void Set(uint32_t i);
3055 // Fast JS primitive setters
3056 V8_INLINE void SetNull();
3057 V8_INLINE void SetUndefined();
3058 V8_INLINE void SetEmptyString();
3059 // Convenience getter for Isolate
3060 V8_INLINE Isolate* GetIsolate();
3062 // Pointer setter: Uncompilable to prevent inadvertent misuse.
3063 template <typename S>
3064 V8_INLINE void Set(S* whatever);
3067 template<class F> friend class ReturnValue;
3068 template<class F> friend class FunctionCallbackInfo;
3069 template<class F> friend class PropertyCallbackInfo;
3070 template <class F, class G, class H>
3071 friend class PersistentValueMapBase;
3072 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3073 V8_INLINE internal::Object* GetDefaultValue();
3074 V8_INLINE explicit ReturnValue(internal::Object** slot);
3075 internal::Object** value_;
3080 * The argument information given to function call callbacks. This
3081 * class provides access to information about the context of the call,
3082 * including the receiver, the number and values of arguments, and
3083 * the holder of the function.
3085 template<typename T>
3086 class FunctionCallbackInfo {
3088 V8_INLINE int Length() const;
3089 V8_INLINE Local<Value> operator[](int i) const;
3090 V8_INLINE Local<Function> Callee() const;
3091 V8_INLINE Local<Object> This() const;
3092 V8_INLINE Local<Object> Holder() const;
3093 V8_INLINE bool IsConstructCall() const;
3094 V8_INLINE Local<Value> Data() const;
3095 V8_INLINE Isolate* GetIsolate() const;
3096 V8_INLINE ReturnValue<T> GetReturnValue() const;
3097 // This shouldn't be public, but the arm compiler needs it.
3098 static const int kArgsLength = 7;
3101 friend class internal::FunctionCallbackArguments;
3102 friend class internal::CustomArguments<FunctionCallbackInfo>;
3103 static const int kHolderIndex = 0;
3104 static const int kIsolateIndex = 1;
3105 static const int kReturnValueDefaultValueIndex = 2;
3106 static const int kReturnValueIndex = 3;
3107 static const int kDataIndex = 4;
3108 static const int kCalleeIndex = 5;
3109 static const int kContextSaveIndex = 6;
3111 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3112 internal::Object** values,
3114 bool is_construct_call);
3115 internal::Object** implicit_args_;
3116 internal::Object** values_;
3118 int is_construct_call_;
3123 * The information passed to a property callback about the context
3124 * of the property access.
3126 template<typename T>
3127 class PropertyCallbackInfo {
3129 V8_INLINE Isolate* GetIsolate() const;
3130 V8_INLINE Local<Value> Data() const;
3131 V8_INLINE Local<Object> This() const;
3132 V8_INLINE Local<Object> Holder() const;
3133 V8_INLINE ReturnValue<T> GetReturnValue() const;
3134 // This shouldn't be public, but the arm compiler needs it.
3135 static const int kArgsLength = 6;
3138 friend class MacroAssembler;
3139 friend class internal::PropertyCallbackArguments;
3140 friend class internal::CustomArguments<PropertyCallbackInfo>;
3141 static const int kHolderIndex = 0;
3142 static const int kIsolateIndex = 1;
3143 static const int kReturnValueDefaultValueIndex = 2;
3144 static const int kReturnValueIndex = 3;
3145 static const int kDataIndex = 4;
3146 static const int kThisIndex = 5;
3148 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3149 internal::Object** args_;
3153 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3157 * A JavaScript function object (ECMA-262, 15.3).
3159 class V8_EXPORT Function : public Object {
3162 * Create a function in the current execution context
3163 * for a given FunctionCallback.
3165 static Local<Function> New(Isolate* isolate,
3166 FunctionCallback callback,
3167 Local<Value> data = Local<Value>(),
3170 V8_DEPRECATE_SOON("Use maybe version",
3171 Local<Object> NewInstance(int argc,
3172 Handle<Value> argv[])) const;
3173 MaybeLocal<Object> NewInstance(Local<Context> context, int argc,
3174 Handle<Value> argv[]) const;
3176 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance()) const;
3177 MaybeLocal<Object> NewInstance(Local<Context> context) const {
3178 return NewInstance(context, 0, nullptr);
3181 V8_DEPRECATE_SOON("Use maybe version",
3182 Local<Value> Call(Handle<Value> recv, int argc,
3183 Handle<Value> argv[]));
3184 MaybeLocal<Value> Call(Local<Context> context, Handle<Value> recv, int argc,
3185 Handle<Value> argv[]);
3187 void SetName(Handle<String> name);
3188 Handle<Value> GetName() const;
3191 * Name inferred from variable or property assignment of this function.
3192 * Used to facilitate debugging and profiling of JavaScript code written
3193 * in an OO style, where many functions are anonymous but are assigned
3194 * to object properties.
3196 Handle<Value> GetInferredName() const;
3199 * User-defined name assigned to the "displayName" property of this function.
3200 * Used to facilitate debugging and profiling of JavaScript code.
3202 Handle<Value> GetDisplayName() const;
3205 * Returns zero based line number of function body and
3206 * kLineOffsetNotFound if no information available.
3208 int GetScriptLineNumber() const;
3210 * Returns zero based column number of function body and
3211 * kLineOffsetNotFound if no information available.
3213 int GetScriptColumnNumber() const;
3216 * Tells whether this function is builtin.
3218 bool IsBuiltin() const;
3223 int ScriptId() const;
3226 * Returns the original function if this function is bound, else returns
3229 Local<Value> GetBoundFunction() const;
3231 ScriptOrigin GetScriptOrigin() const;
3232 V8_INLINE static Function* Cast(Value* obj);
3233 static const int kLineOffsetNotFound;
3237 static void CheckCast(Value* obj);
3242 * An instance of the built-in Promise constructor (ES6 draft).
3243 * This API is experimental. Only works with --harmony flag.
3245 class V8_EXPORT Promise : public Object {
3247 class V8_EXPORT Resolver : public Object {
3250 * Create a new resolver, along with an associated promise in pending state.
3252 static V8_DEPRECATE_SOON("Use maybe version",
3253 Local<Resolver> New(Isolate* isolate));
3254 static MaybeLocal<Resolver> New(Local<Context> context);
3257 * Extract the associated promise.
3259 Local<Promise> GetPromise();
3262 * Resolve/reject the associated promise with a given value.
3263 * Ignored if the promise is no longer pending.
3265 V8_DEPRECATE_SOON("Use maybe version", void Resolve(Handle<Value> value));
3266 Maybe<bool> Resolve(Local<Context> context, Handle<Value> value);
3268 V8_DEPRECATE_SOON("Use maybe version", void Reject(Handle<Value> value));
3269 Maybe<bool> Reject(Local<Context> context, Handle<Value> value);
3271 V8_INLINE static Resolver* Cast(Value* obj);
3275 static void CheckCast(Value* obj);
3279 * Register a resolution/rejection handler with a promise.
3280 * The handler is given the respective resolution/rejection value as
3281 * an argument. If the promise is already resolved/rejected, the handler is
3282 * invoked at the end of turn.
3284 V8_DEPRECATE_SOON("Use maybe version",
3285 Local<Promise> Chain(Handle<Function> handler));
3286 MaybeLocal<Promise> Chain(Local<Context> context, Handle<Function> handler);
3288 V8_DEPRECATE_SOON("Use maybe version",
3289 Local<Promise> Catch(Handle<Function> handler));
3290 MaybeLocal<Promise> Catch(Local<Context> context, Handle<Function> handler);
3292 V8_DEPRECATE_SOON("Use maybe version",
3293 Local<Promise> Then(Handle<Function> handler));
3294 MaybeLocal<Promise> Then(Local<Context> context, Handle<Function> handler);
3297 * Returns true if the promise has at least one derived promise, and
3298 * therefore resolve/reject handlers (including default handler).
3302 V8_INLINE static Promise* Cast(Value* obj);
3306 static void CheckCast(Value* obj);
3310 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3311 // The number of required internal fields can be defined by embedder.
3312 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3316 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
3320 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3321 * This API is experimental and may change significantly.
3323 class V8_EXPORT ArrayBuffer : public Object {
3326 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3327 * The allocator is a global V8 setting. It should be set with
3328 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
3330 * This API is experimental and may change significantly.
3332 class V8_EXPORT Allocator { // NOLINT
3334 virtual ~Allocator() {}
3337 * Allocate |length| bytes. Return NULL if allocation is not successful.
3338 * Memory should be initialized to zeroes.
3340 virtual void* Allocate(size_t length) = 0;
3343 * Allocate |length| bytes. Return NULL if allocation is not successful.
3344 * Memory does not have to be initialized.
3346 virtual void* AllocateUninitialized(size_t length) = 0;
3348 * Free the memory block of size |length|, pointed to by |data|.
3349 * That memory is guaranteed to be previously allocated by |Allocate|.
3351 virtual void Free(void* data, size_t length) = 0;
3355 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3356 * returns an instance of this class, populated, with a pointer to data
3359 * The Data pointer of ArrayBuffer::Contents is always allocated with
3360 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
3362 * This API is experimental and may change significantly.
3364 class V8_EXPORT Contents { // NOLINT
3366 Contents() : data_(NULL), byte_length_(0) {}
3368 void* Data() const { return data_; }
3369 size_t ByteLength() const { return byte_length_; }
3373 size_t byte_length_;
3375 friend class ArrayBuffer;
3380 * Data length in bytes.
3382 size_t ByteLength() const;
3385 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3386 * Allocated memory will be owned by a created ArrayBuffer and
3387 * will be deallocated when it is garbage-collected,
3388 * unless the object is externalized.
3390 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3393 * Create a new ArrayBuffer over an existing memory block.
3394 * The created array buffer is by default immediately in externalized state.
3395 * The memory block will not be reclaimed when a created ArrayBuffer
3396 * is garbage-collected.
3398 static Local<ArrayBuffer> New(
3399 Isolate* isolate, void* data, size_t byte_length,
3400 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3403 * Returns true if ArrayBuffer is extrenalized, that is, does not
3404 * own its memory block.
3406 bool IsExternal() const;
3409 * Returns true if this ArrayBuffer may be neutered.
3411 bool IsNeuterable() const;
3414 * Neuters this ArrayBuffer and all its views (typed arrays).
3415 * Neutering sets the byte length of the buffer and all typed arrays to zero,
3416 * preventing JavaScript from ever accessing underlying backing store.
3417 * ArrayBuffer should have been externalized and must be neuterable.
3422 * Make this ArrayBuffer external. The pointer to underlying memory block
3423 * and byte length are returned as |Contents| structure. After ArrayBuffer
3424 * had been etxrenalized, it does no longer owns the memory block. The caller
3425 * should take steps to free memory when it is no longer needed.
3427 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3428 * that has been set with V8::SetArrayBufferAllocator.
3430 Contents Externalize();
3433 * Get a pointer to the ArrayBuffer's underlying memory block without
3434 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3435 * will become invalid as soon as the ArrayBuffer became garbage collected.
3437 * The embedder should make sure to hold a strong reference to the
3438 * ArrayBuffer while accessing this pointer.
3440 * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3442 Contents GetContents();
3444 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3446 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3450 static void CheckCast(Value* obj);
3454 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3455 // The number of required internal fields can be defined by embedder.
3456 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3461 * A base class for an instance of one of "views" over ArrayBuffer,
3462 * including TypedArrays and DataView (ES6 draft 15.13).
3464 * This API is experimental and may change significantly.
3466 class V8_EXPORT ArrayBufferView : public Object {
3469 * Returns underlying ArrayBuffer.
3471 Local<ArrayBuffer> Buffer();
3473 * Byte offset in |Buffer|.
3475 size_t ByteOffset();
3477 * Size of a view in bytes.
3479 size_t ByteLength();
3482 * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3483 * memory without additional overhead that calling ArrayBufferView::Buffer
3486 * Will write at most min(|byte_length|, ByteLength) bytes starting at
3487 * ByteOffset of the underling buffer to the memory starting at |dest|.
3488 * Returns the number of bytes actually written.
3490 size_t CopyContents(void* dest, size_t byte_length);
3493 * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3496 bool HasBuffer() const;
3498 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3500 static const int kInternalFieldCount =
3501 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3505 static void CheckCast(Value* obj);
3510 * A base class for an instance of TypedArray series of constructors
3511 * (ES6 draft 15.13.6).
3512 * This API is experimental and may change significantly.
3514 class V8_EXPORT TypedArray : public ArrayBufferView {
3517 * Number of elements in this typed array
3518 * (e.g. for Int16Array, |ByteLength|/2).
3522 V8_INLINE static TypedArray* Cast(Value* obj);
3526 static void CheckCast(Value* obj);
3531 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3532 * This API is experimental and may change significantly.
3534 class V8_EXPORT Uint8Array : public TypedArray {
3536 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
3537 size_t byte_offset, size_t length);
3538 V8_INLINE static Uint8Array* Cast(Value* obj);
3542 static void CheckCast(Value* obj);
3547 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3548 * This API is experimental and may change significantly.
3550 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3552 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
3553 size_t byte_offset, size_t length);
3554 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3557 Uint8ClampedArray();
3558 static void CheckCast(Value* obj);
3562 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3563 * This API is experimental and may change significantly.
3565 class V8_EXPORT Int8Array : public TypedArray {
3567 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
3568 size_t byte_offset, size_t length);
3569 V8_INLINE static Int8Array* Cast(Value* obj);
3573 static void CheckCast(Value* obj);
3578 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3579 * This API is experimental and may change significantly.
3581 class V8_EXPORT Uint16Array : public TypedArray {
3583 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
3584 size_t byte_offset, size_t length);
3585 V8_INLINE static Uint16Array* Cast(Value* obj);
3589 static void CheckCast(Value* obj);
3594 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3595 * This API is experimental and may change significantly.
3597 class V8_EXPORT Int16Array : public TypedArray {
3599 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
3600 size_t byte_offset, size_t length);
3601 V8_INLINE static Int16Array* Cast(Value* obj);
3605 static void CheckCast(Value* obj);
3610 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3611 * This API is experimental and may change significantly.
3613 class V8_EXPORT Uint32Array : public TypedArray {
3615 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
3616 size_t byte_offset, size_t length);
3617 V8_INLINE static Uint32Array* Cast(Value* obj);
3621 static void CheckCast(Value* obj);
3626 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3627 * This API is experimental and may change significantly.
3629 class V8_EXPORT Int32Array : public TypedArray {
3631 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
3632 size_t byte_offset, size_t length);
3633 V8_INLINE static Int32Array* Cast(Value* obj);
3637 static void CheckCast(Value* obj);
3642 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3643 * This API is experimental and may change significantly.
3645 class V8_EXPORT Float32Array : public TypedArray {
3647 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
3648 size_t byte_offset, size_t length);
3649 V8_INLINE static Float32Array* Cast(Value* obj);
3653 static void CheckCast(Value* obj);
3658 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3659 * This API is experimental and may change significantly.
3661 class V8_EXPORT Float64Array : public TypedArray {
3663 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3664 size_t byte_offset, size_t length);
3665 V8_INLINE static Float64Array* Cast(Value* obj);
3669 static void CheckCast(Value* obj);
3674 * An instance of DataView constructor (ES6 draft 15.13.7).
3675 * This API is experimental and may change significantly.
3677 class V8_EXPORT DataView : public ArrayBufferView {
3679 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3680 size_t byte_offset, size_t length);
3681 V8_INLINE static DataView* Cast(Value* obj);
3685 static void CheckCast(Value* obj);
3690 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3692 class V8_EXPORT Date : public Object {
3694 static V8_DEPRECATE_SOON("Use maybe version.",
3695 Local<Value> New(Isolate* isolate, double time));
3696 static MaybeLocal<Value> New(Local<Context> context, double time);
3699 * A specialization of Value::NumberValue that is more efficient
3700 * because we know the structure of this object.
3702 double ValueOf() const;
3704 V8_INLINE static Date* Cast(v8::Value* obj);
3707 * Notification that the embedder has changed the time zone,
3708 * daylight savings time, or other date / time configuration
3709 * parameters. V8 keeps a cache of various values used for
3710 * date / time computation. This notification will reset
3711 * those cached values for the current context so that date /
3712 * time configuration changes would be reflected in the Date
3715 * This API should not be called more than needed as it will
3716 * negatively impact the performance of date operations.
3718 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3721 static void CheckCast(v8::Value* obj);
3726 * A Number object (ECMA-262, 4.3.21).
3728 class V8_EXPORT NumberObject : public Object {
3730 static Local<Value> New(Isolate* isolate, double value);
3732 double ValueOf() const;
3734 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3737 static void CheckCast(v8::Value* obj);
3742 * A Boolean object (ECMA-262, 4.3.15).
3744 class V8_EXPORT BooleanObject : public Object {
3746 static Local<Value> New(bool value);
3748 bool ValueOf() const;
3750 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3753 static void CheckCast(v8::Value* obj);
3758 * A String object (ECMA-262, 4.3.18).
3760 class V8_EXPORT StringObject : public Object {
3762 static Local<Value> New(Handle<String> value);
3764 Local<String> ValueOf() const;
3766 V8_INLINE static StringObject* Cast(v8::Value* obj);
3769 static void CheckCast(v8::Value* obj);
3774 * A Symbol object (ECMA-262 edition 6).
3776 * This is an experimental feature. Use at your own risk.
3778 class V8_EXPORT SymbolObject : public Object {
3780 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3782 Local<Symbol> ValueOf() const;
3784 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3787 static void CheckCast(v8::Value* obj);
3792 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3794 class V8_EXPORT RegExp : public Object {
3797 * Regular expression flag bits. They can be or'ed to enable a set
3808 * Creates a regular expression from the given pattern string and
3809 * the flags bit field. May throw a JavaScript exception as
3810 * described in ECMA-262, 15.10.4.1.
3813 * RegExp::New(v8::String::New("foo"),
3814 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3815 * is equivalent to evaluating "/foo/gm".
3817 static V8_DEPRECATE_SOON("Use maybe version",
3818 Local<RegExp> New(Handle<String> pattern,
3820 static MaybeLocal<RegExp> New(Local<Context> context, Handle<String> pattern,
3824 * Returns the value of the source property: a string representing
3825 * the regular expression.
3827 Local<String> GetSource() const;
3830 * Returns the flags bit field.
3832 Flags GetFlags() const;
3834 V8_INLINE static RegExp* Cast(v8::Value* obj);
3837 static void CheckCast(v8::Value* obj);
3842 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3843 * to associate C++ data structures with JavaScript objects.
3845 class V8_EXPORT External : public Value {
3847 static Local<External> New(Isolate* isolate, void* value);
3848 V8_INLINE static External* Cast(Value* obj);
3849 void* Value() const;
3851 static void CheckCast(v8::Value* obj);
3855 // --- Templates ---
3859 * The superclass of object and function templates.
3861 class V8_EXPORT Template : public Data {
3863 /** Adds a property to each instance created by this template.*/
3864 void Set(Handle<Name> name, Handle<Data> value,
3865 PropertyAttribute attributes = None);
3866 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3868 void SetAccessorProperty(
3870 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3871 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3872 PropertyAttribute attribute = None,
3873 AccessControl settings = DEFAULT);
3876 * Whenever the property with the given name is accessed on objects
3877 * created from this Template the getter and setter callbacks
3878 * are called instead of getting and setting the property directly
3879 * on the JavaScript object.
3881 * \param name The name of the property for which an accessor is added.
3882 * \param getter The callback to invoke when getting the property.
3883 * \param setter The callback to invoke when setting the property.
3884 * \param data A piece of data that will be passed to the getter and setter
3885 * callbacks whenever they are invoked.
3886 * \param settings Access control settings for the accessor. This is a bit
3887 * field consisting of one of more of
3888 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3889 * The default is to not allow cross-context access.
3890 * ALL_CAN_READ means that all cross-context reads are allowed.
3891 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3892 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3893 * cross-context access.
3894 * \param attribute The attributes of the property for which an accessor
3896 * \param signature The signature describes valid receivers for the accessor
3897 * and is used to perform implicit instance checks against them. If the
3898 * receiver is incompatible (i.e. is not an instance of the constructor as
3899 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3900 * thrown and no callback is invoked.
3902 void SetNativeDataProperty(Local<String> name,
3903 AccessorGetterCallback getter,
3904 AccessorSetterCallback setter = 0,
3905 // TODO(dcarney): gcc can't handle Local below
3906 Handle<Value> data = Handle<Value>(),
3907 PropertyAttribute attribute = None,
3908 Local<AccessorSignature> signature =
3909 Local<AccessorSignature>(),
3910 AccessControl settings = DEFAULT);
3911 void SetNativeDataProperty(Local<Name> name,
3912 AccessorNameGetterCallback getter,
3913 AccessorNameSetterCallback setter = 0,
3914 // TODO(dcarney): gcc can't handle Local below
3915 Handle<Value> data = Handle<Value>(),
3916 PropertyAttribute attribute = None,
3917 Local<AccessorSignature> signature =
3918 Local<AccessorSignature>(),
3919 AccessControl settings = DEFAULT);
3924 friend class ObjectTemplate;
3925 friend class FunctionTemplate;
3930 * NamedProperty[Getter|Setter] are used as interceptors on object.
3931 * See ObjectTemplate::SetNamedPropertyHandler.
3933 typedef void (*NamedPropertyGetterCallback)(
3934 Local<String> property,
3935 const PropertyCallbackInfo<Value>& info);
3939 * Returns the value if the setter intercepts the request.
3940 * Otherwise, returns an empty handle.
3942 typedef void (*NamedPropertySetterCallback)(
3943 Local<String> property,
3945 const PropertyCallbackInfo<Value>& info);
3949 * Returns a non-empty handle if the interceptor intercepts the request.
3950 * The result is an integer encoding property attributes (like v8::None,
3951 * v8::DontEnum, etc.)
3953 typedef void (*NamedPropertyQueryCallback)(
3954 Local<String> property,
3955 const PropertyCallbackInfo<Integer>& info);
3959 * Returns a non-empty handle if the deleter intercepts the request.
3960 * The return value is true if the property could be deleted and false
3963 typedef void (*NamedPropertyDeleterCallback)(
3964 Local<String> property,
3965 const PropertyCallbackInfo<Boolean>& info);
3969 * Returns an array containing the names of the properties the named
3970 * property getter intercepts.
3972 typedef void (*NamedPropertyEnumeratorCallback)(
3973 const PropertyCallbackInfo<Array>& info);
3976 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
3977 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
3979 * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
3980 * See ObjectTemplate::SetNamedPropertyHandler.
3982 typedef void (*GenericNamedPropertyGetterCallback)(
3983 Local<Name> property, const PropertyCallbackInfo<Value>& info);
3987 * Returns the value if the setter intercepts the request.
3988 * Otherwise, returns an empty handle.
3990 typedef void (*GenericNamedPropertySetterCallback)(
3991 Local<Name> property, Local<Value> value,
3992 const PropertyCallbackInfo<Value>& info);
3996 * Returns a non-empty handle if the interceptor intercepts the request.
3997 * The result is an integer encoding property attributes (like v8::None,
3998 * v8::DontEnum, etc.)
4000 typedef void (*GenericNamedPropertyQueryCallback)(
4001 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4005 * Returns a non-empty handle if the deleter intercepts the request.
4006 * The return value is true if the property could be deleted and false
4009 typedef void (*GenericNamedPropertyDeleterCallback)(
4010 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4014 * Returns an array containing the names of the properties the named
4015 * property getter intercepts.
4017 typedef void (*GenericNamedPropertyEnumeratorCallback)(
4018 const PropertyCallbackInfo<Array>& info);
4022 * Returns the value of the property if the getter intercepts the
4023 * request. Otherwise, returns an empty handle.
4025 typedef void (*IndexedPropertyGetterCallback)(
4027 const PropertyCallbackInfo<Value>& info);
4031 * Returns the value if the setter intercepts the request.
4032 * Otherwise, returns an empty handle.
4034 typedef void (*IndexedPropertySetterCallback)(
4037 const PropertyCallbackInfo<Value>& info);
4041 * Returns a non-empty handle if the interceptor intercepts the request.
4042 * The result is an integer encoding property attributes.
4044 typedef void (*IndexedPropertyQueryCallback)(
4046 const PropertyCallbackInfo<Integer>& info);
4050 * Returns a non-empty handle if the deleter intercepts the request.
4051 * The return value is true if the property could be deleted and false
4054 typedef void (*IndexedPropertyDeleterCallback)(
4056 const PropertyCallbackInfo<Boolean>& info);
4060 * Returns an array containing the indices of the properties the
4061 * indexed property getter intercepts.
4063 typedef void (*IndexedPropertyEnumeratorCallback)(
4064 const PropertyCallbackInfo<Array>& info);
4068 * Access type specification.
4080 * Returns true if cross-context access should be allowed to the named
4081 * property with the given key on the host object.
4083 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4090 * Returns true if cross-context access should be allowed to the indexed
4091 * property with the given index on the host object.
4093 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4100 * A FunctionTemplate is used to create functions at runtime. There
4101 * can only be one function created from a FunctionTemplate in a
4102 * context. The lifetime of the created function is equal to the
4103 * lifetime of the context. So in case the embedder needs to create
4104 * temporary functions that can be collected using Scripts is
4107 * Any modification of a FunctionTemplate after first instantiation will trigger
4110 * A FunctionTemplate can have properties, these properties are added to the
4111 * function object when it is created.
4113 * A FunctionTemplate has a corresponding instance template which is
4114 * used to create object instances when the function is used as a
4115 * constructor. Properties added to the instance template are added to
4116 * each object instance.
4118 * A FunctionTemplate can have a prototype template. The prototype template
4119 * is used to create the prototype object of the function.
4121 * The following example shows how to use a FunctionTemplate:
4124 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4125 * t->Set("func_property", v8::Number::New(1));
4127 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4128 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4129 * proto_t->Set("proto_const", v8::Number::New(2));
4131 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4132 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4133 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4134 * instance_t->Set("instance_property", Number::New(3));
4136 * v8::Local<v8::Function> function = t->GetFunction();
4137 * v8::Local<v8::Object> instance = function->NewInstance();
4140 * Let's use "function" as the JS variable name of the function object
4141 * and "instance" for the instance object created above. The function
4142 * and the instance will have the following properties:
4145 * func_property in function == true;
4146 * function.func_property == 1;
4148 * function.prototype.proto_method() invokes 'InvokeCallback'
4149 * function.prototype.proto_const == 2;
4151 * instance instanceof function == true;
4152 * instance.instance_accessor calls 'InstanceAccessorCallback'
4153 * instance.instance_property == 3;
4156 * A FunctionTemplate can inherit from another one by calling the
4157 * FunctionTemplate::Inherit method. The following graph illustrates
4158 * the semantics of inheritance:
4161 * FunctionTemplate Parent -> Parent() . prototype -> { }
4163 * | Inherit(Parent) | .__proto__
4165 * FunctionTemplate Child -> Child() . prototype -> { }
4168 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4169 * object of the Child() function has __proto__ pointing to the
4170 * Parent() function's prototype object. An instance of the Child
4171 * function has all properties on Parent's instance templates.
4173 * Let Parent be the FunctionTemplate initialized in the previous
4174 * section and create a Child FunctionTemplate by:
4177 * Local<FunctionTemplate> parent = t;
4178 * Local<FunctionTemplate> child = FunctionTemplate::New();
4179 * child->Inherit(parent);
4181 * Local<Function> child_function = child->GetFunction();
4182 * Local<Object> child_instance = child_function->NewInstance();
4185 * The Child function and Child instance will have the following
4189 * child_func.prototype.__proto__ == function.prototype;
4190 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
4191 * child_instance.instance_property == 3;
4194 class V8_EXPORT FunctionTemplate : public Template {
4196 /** Creates a function template.*/
4197 static Local<FunctionTemplate> New(
4199 FunctionCallback callback = 0,
4200 Handle<Value> data = Handle<Value>(),
4201 Handle<Signature> signature = Handle<Signature>(),
4204 /** Returns the unique function instance in the current execution context.*/
4205 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4206 MaybeLocal<Function> GetFunction(Local<Context> context);
4209 * Set the call-handler callback for a FunctionTemplate. This
4210 * callback is called whenever the function created from this
4211 * FunctionTemplate is called.
4213 void SetCallHandler(FunctionCallback callback,
4214 Handle<Value> data = Handle<Value>());
4216 /** Set the predefined length property for the FunctionTemplate. */
4217 void SetLength(int length);
4219 /** Get the InstanceTemplate. */
4220 Local<ObjectTemplate> InstanceTemplate();
4222 /** Causes the function template to inherit from a parent function template.*/
4223 void Inherit(Handle<FunctionTemplate> parent);
4226 * A PrototypeTemplate is the template used to create the prototype object
4227 * of the function created by this template.
4229 Local<ObjectTemplate> PrototypeTemplate();
4232 * Set the class name of the FunctionTemplate. This is used for
4233 * printing objects created with the function created from the
4234 * FunctionTemplate as its constructor.
4236 void SetClassName(Handle<String> name);
4240 * When set to true, no access check will be performed on the receiver of a
4241 * function call. Currently defaults to true, but this is subject to change.
4243 void SetAcceptAnyReceiver(bool value);
4246 * Determines whether the __proto__ accessor ignores instances of
4247 * the function template. If instances of the function template are
4248 * ignored, __proto__ skips all instances and instead returns the
4249 * next object in the prototype chain.
4251 * Call with a value of true to make the __proto__ accessor ignore
4252 * instances of the function template. Call with a value of false
4253 * to make the __proto__ accessor not ignore instances of the
4254 * function template. By default, instances of a function template
4257 void SetHiddenPrototype(bool value);
4260 * Sets the ReadOnly flag in the attributes of the 'prototype' property
4261 * of functions created from this FunctionTemplate to true.
4263 void ReadOnlyPrototype();
4266 * Removes the prototype property from functions created from this
4269 void RemovePrototype();
4272 * Returns true if the given object is an instance of this function
4275 bool HasInstance(Handle<Value> object);
4279 friend class Context;
4280 friend class ObjectTemplate;
4284 enum class PropertyHandlerFlags {
4286 // See ALL_CAN_READ above.
4288 // Will not call into interceptor for properties on the receiver or prototype
4289 // chain. Currently only valid for named interceptors.
4290 kNonMasking = 1 << 1,
4291 // Will not call into interceptor for symbol lookup. Only meaningful for
4292 // named interceptors.
4293 kOnlyInterceptStrings = 1 << 2,
4297 struct NamedPropertyHandlerConfiguration {
4298 NamedPropertyHandlerConfiguration(
4299 /** Note: getter is required **/
4300 GenericNamedPropertyGetterCallback getter = 0,
4301 GenericNamedPropertySetterCallback setter = 0,
4302 GenericNamedPropertyQueryCallback query = 0,
4303 GenericNamedPropertyDeleterCallback deleter = 0,
4304 GenericNamedPropertyEnumeratorCallback enumerator = 0,
4305 Handle<Value> data = Handle<Value>(),
4306 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4311 enumerator(enumerator),
4315 GenericNamedPropertyGetterCallback getter;
4316 GenericNamedPropertySetterCallback setter;
4317 GenericNamedPropertyQueryCallback query;
4318 GenericNamedPropertyDeleterCallback deleter;
4319 GenericNamedPropertyEnumeratorCallback enumerator;
4321 PropertyHandlerFlags flags;
4325 struct IndexedPropertyHandlerConfiguration {
4326 IndexedPropertyHandlerConfiguration(
4327 /** Note: getter is required **/
4328 IndexedPropertyGetterCallback getter = 0,
4329 IndexedPropertySetterCallback setter = 0,
4330 IndexedPropertyQueryCallback query = 0,
4331 IndexedPropertyDeleterCallback deleter = 0,
4332 IndexedPropertyEnumeratorCallback enumerator = 0,
4333 Handle<Value> data = Handle<Value>(),
4334 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4339 enumerator(enumerator),
4343 IndexedPropertyGetterCallback getter;
4344 IndexedPropertySetterCallback setter;
4345 IndexedPropertyQueryCallback query;
4346 IndexedPropertyDeleterCallback deleter;
4347 IndexedPropertyEnumeratorCallback enumerator;
4349 PropertyHandlerFlags flags;
4354 * An ObjectTemplate is used to create objects at runtime.
4356 * Properties added to an ObjectTemplate are added to each object
4357 * created from the ObjectTemplate.
4359 class V8_EXPORT ObjectTemplate : public Template {
4361 /** Creates an ObjectTemplate. */
4362 static Local<ObjectTemplate> New(Isolate* isolate);
4363 static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4365 /** Creates a new instance of this template.*/
4366 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4367 MaybeLocal<Object> NewInstance(Local<Context> context);
4370 * Sets an accessor on the object template.
4372 * Whenever the property with the given name is accessed on objects
4373 * created from this ObjectTemplate the getter and setter callbacks
4374 * are called instead of getting and setting the property directly
4375 * on the JavaScript object.
4377 * \param name The name of the property for which an accessor is added.
4378 * \param getter The callback to invoke when getting the property.
4379 * \param setter The callback to invoke when setting the property.
4380 * \param data A piece of data that will be passed to the getter and setter
4381 * callbacks whenever they are invoked.
4382 * \param settings Access control settings for the accessor. This is a bit
4383 * field consisting of one of more of
4384 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4385 * The default is to not allow cross-context access.
4386 * ALL_CAN_READ means that all cross-context reads are allowed.
4387 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4388 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4389 * cross-context access.
4390 * \param attribute The attributes of the property for which an accessor
4392 * \param signature The signature describes valid receivers for the accessor
4393 * and is used to perform implicit instance checks against them. If the
4394 * receiver is incompatible (i.e. is not an instance of the constructor as
4395 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4396 * thrown and no callback is invoked.
4398 void SetAccessor(Handle<String> name,
4399 AccessorGetterCallback getter,
4400 AccessorSetterCallback setter = 0,
4401 Handle<Value> data = Handle<Value>(),
4402 AccessControl settings = DEFAULT,
4403 PropertyAttribute attribute = None,
4404 Handle<AccessorSignature> signature =
4405 Handle<AccessorSignature>());
4406 void SetAccessor(Handle<Name> name,
4407 AccessorNameGetterCallback getter,
4408 AccessorNameSetterCallback setter = 0,
4409 Handle<Value> data = Handle<Value>(),
4410 AccessControl settings = DEFAULT,
4411 PropertyAttribute attribute = None,
4412 Handle<AccessorSignature> signature =
4413 Handle<AccessorSignature>());
4416 * Sets a named property handler on the object template.
4418 * Whenever a property whose name is a string is accessed on objects created
4419 * from this object template, the provided callback is invoked instead of
4420 * accessing the property directly on the JavaScript object.
4422 * Note that new code should use the second version that can intercept
4423 * symbol-named properties as well as string-named properties.
4425 * \param getter The callback to invoke when getting a property.
4426 * \param setter The callback to invoke when setting a property.
4427 * \param query The callback to invoke to check if a property is present,
4428 * and if present, get its attributes.
4429 * \param deleter The callback to invoke when deleting a property.
4430 * \param enumerator The callback to invoke to enumerate all the named
4431 * properties of an object.
4432 * \param data A piece of data that will be passed to the callbacks
4433 * whenever they are invoked.
4435 // TODO(dcarney): deprecate
4436 void SetNamedPropertyHandler(
4437 NamedPropertyGetterCallback getter,
4438 NamedPropertySetterCallback setter = 0,
4439 NamedPropertyQueryCallback query = 0,
4440 NamedPropertyDeleterCallback deleter = 0,
4441 NamedPropertyEnumeratorCallback enumerator = 0,
4442 Handle<Value> data = Handle<Value>());
4443 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4446 * Sets an indexed property handler on the object template.
4448 * Whenever an indexed property is accessed on objects created from
4449 * this object template, the provided callback is invoked instead of
4450 * accessing the property directly on the JavaScript object.
4452 * \param getter The callback to invoke when getting a property.
4453 * \param setter The callback to invoke when setting a property.
4454 * \param query The callback to invoke to check if an object has a property.
4455 * \param deleter The callback to invoke when deleting a property.
4456 * \param enumerator The callback to invoke to enumerate all the indexed
4457 * properties of an object.
4458 * \param data A piece of data that will be passed to the callbacks
4459 * whenever they are invoked.
4461 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4462 // TODO(dcarney): deprecate
4463 void SetIndexedPropertyHandler(
4464 IndexedPropertyGetterCallback getter,
4465 IndexedPropertySetterCallback setter = 0,
4466 IndexedPropertyQueryCallback query = 0,
4467 IndexedPropertyDeleterCallback deleter = 0,
4468 IndexedPropertyEnumeratorCallback enumerator = 0,
4469 Handle<Value> data = Handle<Value>()) {
4470 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4471 deleter, enumerator, data));
4474 * Sets the callback to be used when calling instances created from
4475 * this template as a function. If no callback is set, instances
4476 * behave like normal JavaScript objects that cannot be called as a
4479 void SetCallAsFunctionHandler(FunctionCallback callback,
4480 Handle<Value> data = Handle<Value>());
4483 * Mark object instances of the template as undetectable.
4485 * In many ways, undetectable objects behave as though they are not
4486 * there. They behave like 'undefined' in conditionals and when
4487 * printed. However, properties can be accessed and called as on
4490 void MarkAsUndetectable();
4493 * Sets access check callbacks on the object template.
4495 * When accessing properties on instances of this object template,
4496 * the access check callback will be called to determine whether or
4497 * not to allow cross-context access to the properties.
4498 * The last parameter specifies whether access checks are turned
4499 * on by default on instances. If access checks are off by default,
4500 * they can be turned on on individual instances by calling
4501 * Object::TurnOnAccessCheck().
4503 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4504 IndexedSecurityCallback indexed_handler,
4505 Handle<Value> data = Handle<Value>(),
4506 bool turned_on_by_default = true);
4509 * Gets the number of internal fields for objects generated from
4512 int InternalFieldCount();
4515 * Sets the number of internal fields for objects generated from
4518 void SetInternalFieldCount(int value);
4522 static Local<ObjectTemplate> New(internal::Isolate* isolate,
4523 Handle<FunctionTemplate> constructor);
4524 friend class FunctionTemplate;
4529 * A Signature specifies which receiver is valid for a function.
4531 class V8_EXPORT Signature : public Data {
4533 static Local<Signature> New(
4535 Handle<FunctionTemplate> receiver = Handle<FunctionTemplate>());
4543 * An AccessorSignature specifies which receivers are valid parameters
4544 * to an accessor callback.
4546 class V8_EXPORT AccessorSignature : public Data {
4548 static Local<AccessorSignature> New(Isolate* isolate,
4549 Handle<FunctionTemplate> receiver =
4550 Handle<FunctionTemplate>());
4553 AccessorSignature();
4558 * A utility for determining the type of objects based on the template
4559 * they were constructed from.
4561 class V8_EXPORT TypeSwitch : public Data {
4563 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
4564 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
4565 int match(Handle<Value> value);
4571 // --- Extensions ---
4573 class V8_EXPORT ExternalOneByteStringResourceImpl
4574 : public String::ExternalOneByteStringResource {
4576 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4577 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4578 : data_(data), length_(length) {}
4579 const char* data() const { return data_; }
4580 size_t length() const { return length_; }
4590 class V8_EXPORT Extension { // NOLINT
4592 // Note that the strings passed into this constructor must live as long
4593 // as the Extension itself.
4594 Extension(const char* name,
4595 const char* source = 0,
4597 const char** deps = 0,
4598 int source_length = -1);
4599 virtual ~Extension() { }
4600 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
4601 v8::Isolate* isolate, v8::Handle<v8::String> name) {
4602 return v8::Handle<v8::FunctionTemplate>();
4605 const char* name() const { return name_; }
4606 size_t source_length() const { return source_length_; }
4607 const String::ExternalOneByteStringResource* source() const {
4609 int dependency_count() { return dep_count_; }
4610 const char** dependencies() { return deps_; }
4611 void set_auto_enable(bool value) { auto_enable_ = value; }
4612 bool auto_enable() { return auto_enable_; }
4616 size_t source_length_; // expected to initialize before source_
4617 ExternalOneByteStringResourceImpl source_;
4622 // Disallow copying and assigning.
4623 Extension(const Extension&);
4624 void operator=(const Extension&);
4628 void V8_EXPORT RegisterExtension(Extension* extension);
4633 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
4634 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
4635 V8_INLINE Handle<Boolean> True(Isolate* isolate);
4636 V8_INLINE Handle<Boolean> False(Isolate* isolate);
4640 * A set of constraints that specifies the limits of the runtime's memory use.
4641 * You must set the heap size before initializing the VM - the size cannot be
4642 * adjusted after the VM is initialized.
4644 * If you are using threads then you should hold the V8::Locker lock while
4645 * setting the stack limit and you must set a non-default stack limit separately
4648 class V8_EXPORT ResourceConstraints {
4650 ResourceConstraints();
4653 * Configures the constraints with reasonable default values based on the
4654 * capabilities of the current device the VM is running on.
4656 * \param physical_memory The total amount of physical memory on the current
4658 * \param virtual_memory_limit The amount of virtual memory on the current
4659 * device, in bytes, or zero, if there is no limit.
4660 * \param number_of_processors The number of CPUs available on the current
4663 void ConfigureDefaults(uint64_t physical_memory,
4664 uint64_t virtual_memory_limit,
4665 uint32_t number_of_processors);
4667 int max_semi_space_size() const { return max_semi_space_size_; }
4668 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4669 int max_old_space_size() const { return max_old_space_size_; }
4670 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4671 int max_executable_size() const { return max_executable_size_; }
4672 void set_max_executable_size(int value) { max_executable_size_ = value; }
4673 uint32_t* stack_limit() const { return stack_limit_; }
4674 // Sets an address beyond which the VM's stack may not grow.
4675 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4676 int max_available_threads() const { return max_available_threads_; }
4677 // Set the number of threads available to V8, assuming at least 1.
4678 void set_max_available_threads(int value) {
4679 max_available_threads_ = value;
4681 size_t code_range_size() const { return code_range_size_; }
4682 void set_code_range_size(size_t value) {
4683 code_range_size_ = value;
4687 int max_semi_space_size_;
4688 int max_old_space_size_;
4689 int max_executable_size_;
4690 uint32_t* stack_limit_;
4691 int max_available_threads_;
4692 size_t code_range_size_;
4696 // --- Exceptions ---
4699 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4702 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
4706 typedef void (*LogEventCallback)(const char* name, int event);
4709 * Create new error objects by calling the corresponding error object
4710 * constructor with the message.
4712 class V8_EXPORT Exception {
4714 static Local<Value> RangeError(Handle<String> message);
4715 static Local<Value> ReferenceError(Handle<String> message);
4716 static Local<Value> SyntaxError(Handle<String> message);
4717 static Local<Value> TypeError(Handle<String> message);
4718 static Local<Value> Error(Handle<String> message);
4721 * Creates an error message for the given exception.
4722 * Will try to reconstruct the original stack trace from the exception value,
4723 * or capture the current stack trace if not available.
4725 static Local<Message> CreateMessage(Handle<Value> exception);
4728 * Returns the original stack trace that was captured at the creation time
4729 * of a given exception, or an empty handle if not available.
4731 static Local<StackTrace> GetStackTrace(Handle<Value> exception);
4735 // --- Counters Callbacks ---
4737 typedef int* (*CounterLookupCallback)(const char* name);
4739 typedef void* (*CreateHistogramCallback)(const char* name,
4744 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4746 // --- Memory Allocation Callback ---
4748 kObjectSpaceNewSpace = 1 << 0,
4749 kObjectSpaceOldPointerSpace = 1 << 1,
4750 kObjectSpaceOldDataSpace = 1 << 2,
4751 kObjectSpaceCodeSpace = 1 << 3,
4752 kObjectSpaceMapSpace = 1 << 4,
4753 kObjectSpaceCellSpace = 1 << 5,
4754 kObjectSpaceLoSpace = 1 << 6,
4755 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4756 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace |
4757 kObjectSpaceMapSpace | kObjectSpaceLoSpace
4760 enum AllocationAction {
4761 kAllocationActionAllocate = 1 << 0,
4762 kAllocationActionFree = 1 << 1,
4763 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4766 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4767 AllocationAction action,
4770 // --- Leave Script Callback ---
4771 typedef void (*CallCompletedCallback)();
4773 // --- Promise Reject Callback ---
4774 enum PromiseRejectEvent {
4775 kPromiseRejectWithNoHandler = 0,
4776 kPromiseHandlerAddedAfterReject = 1
4779 class PromiseRejectMessage {
4781 PromiseRejectMessage(Handle<Promise> promise, PromiseRejectEvent event,
4782 Handle<Value> value, Handle<StackTrace> stack_trace)
4783 : promise_(promise),
4786 stack_trace_(stack_trace) {}
4788 V8_INLINE Handle<Promise> GetPromise() const { return promise_; }
4789 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4790 V8_INLINE Handle<Value> GetValue() const { return value_; }
4792 // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4793 V8_INLINE Handle<StackTrace> GetStackTrace() const { return stack_trace_; }
4796 Handle<Promise> promise_;
4797 PromiseRejectEvent event_;
4798 Handle<Value> value_;
4799 Handle<StackTrace> stack_trace_;
4802 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4804 // --- Microtask Callback ---
4805 typedef void (*MicrotaskCallback)(void* data);
4807 // --- Failed Access Check Callback ---
4808 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4812 // --- AllowCodeGenerationFromStrings callbacks ---
4815 * Callback to check if code generation from strings is allowed. See
4816 * Context::AllowCodeGenerationFromStrings.
4818 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4820 // --- Garbage Collection Callbacks ---
4823 * Applications can register callback functions which will be called
4824 * before and after a garbage collection. Allocations are not
4825 * allowed in the callback functions, you therefore cannot manipulate
4826 * objects (set or delete properties for example) since it is possible
4827 * such operations will result in the allocation of objects.
4830 kGCTypeScavenge = 1 << 0,
4831 kGCTypeMarkSweepCompact = 1 << 1,
4832 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4835 enum GCCallbackFlags {
4836 kNoGCCallbackFlags = 0,
4837 kGCCallbackFlagCompacted = 1 << 0,
4838 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4839 kGCCallbackFlagForced = 1 << 2
4842 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4843 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4845 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4849 * Collection of V8 heap information.
4851 * Instances of this class can be passed to v8::V8::HeapStatistics to
4852 * get heap statistics from V8.
4854 class V8_EXPORT HeapStatistics {
4857 size_t total_heap_size() { return total_heap_size_; }
4858 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4859 size_t total_physical_size() { return total_physical_size_; }
4860 size_t used_heap_size() { return used_heap_size_; }
4861 size_t heap_size_limit() { return heap_size_limit_; }
4864 size_t total_heap_size_;
4865 size_t total_heap_size_executable_;
4866 size_t total_physical_size_;
4867 size_t used_heap_size_;
4868 size_t heap_size_limit_;
4871 friend class Isolate;
4875 class RetainedObjectInfo;
4879 * FunctionEntryHook is the type of the profile entry hook called at entry to
4880 * any generated function when function-level profiling is enabled.
4882 * \param function the address of the function that's being entered.
4883 * \param return_addr_location points to a location on stack where the machine
4884 * return address resides. This can be used to identify the caller of
4885 * \p function, and/or modified to divert execution when \p function exits.
4887 * \note the entry hook must not cause garbage collection.
4889 typedef void (*FunctionEntryHook)(uintptr_t function,
4890 uintptr_t return_addr_location);
4893 * A JIT code event is issued each time code is added, moved or removed.
4895 * \note removal events are not currently issued.
4897 struct JitCodeEvent {
4902 CODE_ADD_LINE_POS_INFO,
4903 CODE_START_LINE_INFO_RECORDING,
4904 CODE_END_LINE_INFO_RECORDING
4906 // Definition of the code position type. The "POSITION" type means the place
4907 // in the source code which are of interest when making stack traces to
4908 // pin-point the source location of a stack frame as close as possible.
4909 // The "STATEMENT_POSITION" means the place at the beginning of each
4910 // statement, and is used to indicate possible break locations.
4911 enum PositionType { POSITION, STATEMENT_POSITION };
4915 // Start of the instructions.
4917 // Size of the instructions.
4919 // Script info for CODE_ADDED event.
4920 Handle<UnboundScript> script;
4921 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4922 // code line information which is returned from the
4923 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4924 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4928 // Name of the object associated with the code, note that the string is not
4931 // Number of chars in str.
4935 struct line_info_t {
4940 // The position type.
4941 PositionType position_type;
4945 // Only valid for CODE_ADDED.
4948 // Only valid for CODE_ADD_LINE_POS_INFO
4949 struct line_info_t line_info;
4951 // New location of instructions. Only valid for CODE_MOVED.
4952 void* new_code_start;
4957 * Option flags passed to the SetJitCodeEventHandler function.
4959 enum JitCodeEventOptions {
4960 kJitCodeEventDefault = 0,
4961 // Generate callbacks for already existent code.
4962 kJitCodeEventEnumExisting = 1
4967 * Callback function passed to SetJitCodeEventHandler.
4969 * \param event code add, move or removal event.
4971 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4975 * Interface for iterating through all external resources in the heap.
4977 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4979 virtual ~ExternalResourceVisitor() {}
4980 virtual void VisitExternalString(Handle<String> string) {}
4985 * Interface for iterating through all the persistent handles in the heap.
4987 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4989 virtual ~PersistentHandleVisitor() {}
4990 virtual void VisitPersistentHandle(Persistent<Value>* value,
4991 uint16_t class_id) {}
4996 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
4997 * completely separate states. Objects from one isolate must not be used in
4998 * other isolates. The embedder can create multiple isolates and use them in
4999 * parallel in multiple threads. An isolate can be entered by at most one
5000 * thread at any given time. The Locker/Unlocker API must be used to
5003 class V8_EXPORT Isolate {
5006 * Initial configuration parameters for a new Isolate.
5008 struct CreateParams {
5011 code_event_handler(NULL),
5012 snapshot_blob(NULL),
5013 counter_lookup_callback(NULL),
5014 create_histogram_callback(NULL),
5015 add_histogram_sample_callback(NULL) {}
5018 * The optional entry_hook allows the host application to provide the
5019 * address of a function that's invoked on entry to every V8-generated
5020 * function. Note that entry_hook is invoked at the very start of each
5021 * generated function. Furthermore, if an entry_hook is given, V8 will
5022 * always run without a context snapshot.
5024 FunctionEntryHook entry_hook;
5027 * Allows the host application to provide the address of a function that is
5028 * notified each time code is added, moved or removed.
5030 JitCodeEventHandler code_event_handler;
5033 * ResourceConstraints to use for the new Isolate.
5035 ResourceConstraints constraints;
5038 * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5040 StartupData* snapshot_blob;
5044 * Enables the host application to provide a mechanism for recording
5045 * statistics counters.
5047 CounterLookupCallback counter_lookup_callback;
5050 * Enables the host application to provide a mechanism for recording
5051 * histograms. The CreateHistogram function returns a
5052 * histogram which will later be passed to the AddHistogramSample
5055 CreateHistogramCallback create_histogram_callback;
5056 AddHistogramSampleCallback add_histogram_sample_callback;
5061 * Stack-allocated class which sets the isolate for all operations
5062 * executed within a local scope.
5064 class V8_EXPORT Scope {
5066 explicit Scope(Isolate* isolate) : isolate_(isolate) {
5070 ~Scope() { isolate_->Exit(); }
5073 Isolate* const isolate_;
5075 // Prevent copying of Scope objects.
5076 Scope(const Scope&);
5077 Scope& operator=(const Scope&);
5082 * Assert that no Javascript code is invoked.
5084 class V8_EXPORT DisallowJavascriptExecutionScope {
5086 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
5088 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
5089 ~DisallowJavascriptExecutionScope();
5095 // Prevent copying of Scope objects.
5096 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5097 DisallowJavascriptExecutionScope& operator=(
5098 const DisallowJavascriptExecutionScope&);
5103 * Introduce exception to DisallowJavascriptExecutionScope.
5105 class V8_EXPORT AllowJavascriptExecutionScope {
5107 explicit AllowJavascriptExecutionScope(Isolate* isolate);
5108 ~AllowJavascriptExecutionScope();
5111 void* internal_throws_;
5112 void* internal_assert_;
5114 // Prevent copying of Scope objects.
5115 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5116 AllowJavascriptExecutionScope& operator=(
5117 const AllowJavascriptExecutionScope&);
5121 * Do not run microtasks while this scope is active, even if microtasks are
5122 * automatically executed otherwise.
5124 class V8_EXPORT SuppressMicrotaskExecutionScope {
5126 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
5127 ~SuppressMicrotaskExecutionScope();
5130 internal::Isolate* isolate_;
5132 // Prevent copying of Scope objects.
5133 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5134 SuppressMicrotaskExecutionScope& operator=(
5135 const SuppressMicrotaskExecutionScope&);
5139 * Types of garbage collections that can be requested via
5140 * RequestGarbageCollectionForTesting.
5142 enum GarbageCollectionType {
5143 kFullGarbageCollection,
5144 kMinorGarbageCollection
5148 * Features reported via the SetUseCounterCallback callback. Do not chang
5149 * assigned numbers of existing items; add new features to the end of this
5152 enum UseCounterFeature {
5156 kUseCounterFeatureCount // This enum value must be last.
5159 typedef void (*UseCounterCallback)(Isolate* isolate,
5160 UseCounterFeature feature);
5164 * Creates a new isolate. Does not change the currently entered
5167 * When an isolate is no longer used its resources should be freed
5168 * by calling Dispose(). Using the delete operator is not allowed.
5170 * V8::Initialize() must have run prior to this.
5172 static Isolate* New(const CreateParams& params = CreateParams());
5175 * Returns the entered isolate for the current thread or NULL in
5176 * case there is no current isolate.
5178 * This method must not be invoked before V8::Initialize() was invoked.
5180 static Isolate* GetCurrent();
5183 * Methods below this point require holding a lock (using Locker) in
5184 * a multi-threaded environment.
5188 * Sets this isolate as the entered one for the current thread.
5189 * Saves the previously entered one (if any), so that it can be
5190 * restored when exiting. Re-entering an isolate is allowed.
5195 * Exits this isolate by restoring the previously entered one in the
5196 * current thread. The isolate may still stay the same, if it was
5197 * entered more than once.
5199 * Requires: this == Isolate::GetCurrent().
5204 * Disposes the isolate. The isolate must not be entered by any
5205 * thread to be disposable.
5210 * Associate embedder-specific data with the isolate. |slot| has to be
5211 * between 0 and GetNumberOfDataSlots() - 1.
5213 V8_INLINE void SetData(uint32_t slot, void* data);
5216 * Retrieve embedder-specific data from the isolate.
5217 * Returns NULL if SetData has never been called for the given |slot|.
5219 V8_INLINE void* GetData(uint32_t slot);
5222 * Returns the maximum number of available embedder data slots. Valid slots
5223 * are in the range of 0 - GetNumberOfDataSlots() - 1.
5225 V8_INLINE static uint32_t GetNumberOfDataSlots();
5228 * Get statistics about the heap memory usage.
5230 void GetHeapStatistics(HeapStatistics* heap_statistics);
5233 * Get a call stack sample from the isolate.
5234 * \param state Execution state.
5235 * \param frames Caller allocated buffer to store stack frames.
5236 * \param frames_limit Maximum number of frames to capture. The buffer must
5237 * be large enough to hold the number of frames.
5238 * \param sample_info The sample info is filled up by the function
5239 * provides number of actual captured stack frames and
5240 * the current VM state.
5241 * \note GetStackSample should only be called when the JS thread is paused or
5242 * interrupted. Otherwise the behavior is undefined.
5244 void GetStackSample(const RegisterState& state, void** frames,
5245 size_t frames_limit, SampleInfo* sample_info);
5248 * Adjusts the amount of registered external memory. Used to give V8 an
5249 * indication of the amount of externally allocated memory that is kept alive
5250 * by JavaScript objects. V8 uses this to decide when to perform global
5251 * garbage collections. Registering externally allocated memory will trigger
5252 * global garbage collections more often than it would otherwise in an attempt
5253 * to garbage collect the JavaScript objects that keep the externally
5254 * allocated memory alive.
5256 * \param change_in_bytes the change in externally allocated memory that is
5257 * kept alive by JavaScript objects.
5258 * \returns the adjusted value.
5261 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5264 * Returns heap profiler for this isolate. Will return NULL until the isolate
5267 HeapProfiler* GetHeapProfiler();
5270 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5271 * is initialized. It is the embedder's responsibility to stop all CPU
5272 * profiling activities if it has started any.
5274 CpuProfiler* GetCpuProfiler();
5276 /** Returns true if this isolate has a current context. */
5279 /** Returns the context that is on the top of the stack. */
5280 Local<Context> GetCurrentContext();
5283 * Returns the context of the calling JavaScript code. That is the
5284 * context of the top-most JavaScript frame. If there are no
5285 * JavaScript frames an empty handle is returned.
5287 Local<Context> GetCallingContext();
5289 /** Returns the last entered context. */
5290 Local<Context> GetEnteredContext();
5293 * Schedules an exception to be thrown when returning to JavaScript. When an
5294 * exception has been scheduled it is illegal to invoke any JavaScript
5295 * operation; the caller must return immediately and only after the exception
5296 * has been handled does it become legal to invoke JavaScript operations.
5298 Local<Value> ThrowException(Local<Value> exception);
5301 * Allows the host application to group objects together. If one
5302 * object in the group is alive, all objects in the group are alive.
5303 * After each garbage collection, object groups are removed. It is
5304 * intended to be used in the before-garbage-collection callback
5305 * function, for instance to simulate DOM tree connections among JS
5306 * wrapper objects. Object groups for all dependent handles need to
5307 * be provided for kGCTypeMarkSweepCompact collections, for all other
5308 * garbage collection types it is sufficient to provide object groups
5309 * for partially dependent handles only.
5311 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5315 * Allows the host application to declare implicit references from an object
5316 * group to an object. If the objects of the object group are alive, the child
5317 * object is alive too. After each garbage collection, all implicit references
5318 * are removed. It is intended to be used in the before-garbage-collection
5319 * callback function.
5321 template<typename T> void SetReferenceFromGroup(UniqueId id,
5322 const Persistent<T>& child);
5325 * Allows the host application to declare implicit references from an object
5326 * to another object. If the parent object is alive, the child object is alive
5327 * too. After each garbage collection, all implicit references are removed. It
5328 * is intended to be used in the before-garbage-collection callback function.
5330 template<typename T, typename S>
5331 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5333 typedef void (*GCPrologueCallback)(Isolate* isolate,
5335 GCCallbackFlags flags);
5336 typedef void (*GCEpilogueCallback)(Isolate* isolate,
5338 GCCallbackFlags flags);
5341 * Enables the host application to receive a notification before a
5342 * garbage collection. Allocations are allowed in the callback function,
5343 * but the callback is not re-entrant: if the allocation inside it will
5344 * trigger the garbage collection, the callback won't be called again.
5345 * It is possible to specify the GCType filter for your callback. But it is
5346 * not possible to register the same callback function two times with
5347 * different GCType filters.
5349 void AddGCPrologueCallback(
5350 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5353 * This function removes callback which was installed by
5354 * AddGCPrologueCallback function.
5356 void RemoveGCPrologueCallback(GCPrologueCallback callback);
5359 * Enables the host application to receive a notification after a
5360 * garbage collection. Allocations are allowed in the callback function,
5361 * but the callback is not re-entrant: if the allocation inside it will
5362 * trigger the garbage collection, the callback won't be called again.
5363 * It is possible to specify the GCType filter for your callback. But it is
5364 * not possible to register the same callback function two times with
5365 * different GCType filters.
5367 void AddGCEpilogueCallback(
5368 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5371 * This function removes callback which was installed by
5372 * AddGCEpilogueCallback function.
5374 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5378 * Forcefully terminate the current thread of JavaScript execution
5379 * in the given isolate.
5381 * This method can be used by any thread even if that thread has not
5382 * acquired the V8 lock with a Locker object.
5384 void TerminateExecution();
5387 * Is V8 terminating JavaScript execution.
5389 * Returns true if JavaScript execution is currently terminating
5390 * because of a call to TerminateExecution. In that case there are
5391 * still JavaScript frames on the stack and the termination
5392 * exception is still active.
5394 bool IsExecutionTerminating();
5397 * Resume execution capability in the given isolate, whose execution
5398 * was previously forcefully terminated using TerminateExecution().
5400 * When execution is forcefully terminated using TerminateExecution(),
5401 * the isolate can not resume execution until all JavaScript frames
5402 * have propagated the uncatchable exception which is generated. This
5403 * method allows the program embedding the engine to handle the
5404 * termination event and resume execution capability, even if
5405 * JavaScript frames remain on the stack.
5407 * This method can be used by any thread even if that thread has not
5408 * acquired the V8 lock with a Locker object.
5410 void CancelTerminateExecution();
5413 * Request V8 to interrupt long running JavaScript code and invoke
5414 * the given |callback| passing the given |data| to it. After |callback|
5415 * returns control will be returned to the JavaScript code.
5416 * There may be a number of interrupt requests in flight.
5417 * Can be called from another thread without acquiring a |Locker|.
5418 * Registered |callback| must not reenter interrupted Isolate.
5420 void RequestInterrupt(InterruptCallback callback, void* data);
5423 * Request garbage collection in this Isolate. It is only valid to call this
5424 * function if --expose_gc was specified.
5426 * This should only be used for testing purposes and not to enforce a garbage
5427 * collection schedule. It has strong negative impact on the garbage
5428 * collection performance. Use IdleNotification() or LowMemoryNotification()
5429 * instead to influence the garbage collection schedule.
5431 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5434 * Set the callback to invoke for logging event.
5436 void SetEventLogger(LogEventCallback that);
5439 * Adds a callback to notify the host application when a script finished
5440 * running. If a script re-enters the runtime during executing, the
5441 * CallCompletedCallback is only invoked when the outer-most script
5442 * execution ends. Executing scripts inside the callback do not trigger
5443 * further callbacks.
5445 void AddCallCompletedCallback(CallCompletedCallback callback);
5448 * Removes callback that was installed by AddCallCompletedCallback.
5450 void RemoveCallCompletedCallback(CallCompletedCallback callback);
5454 * Set callback to notify about promise reject with no handler, or
5455 * revocation of such a previous notification once the handler is added.
5457 void SetPromiseRejectCallback(PromiseRejectCallback callback);
5460 * Experimental: Runs the Microtask Work Queue until empty
5461 * Any exceptions thrown by microtask callbacks are swallowed.
5463 void RunMicrotasks();
5466 * Experimental: Enqueues the callback to the Microtask Work Queue
5468 void EnqueueMicrotask(Handle<Function> microtask);
5471 * Experimental: Enqueues the callback to the Microtask Work Queue
5473 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5476 * Experimental: Controls whether the Microtask Work Queue is automatically
5477 * run when the script call depth decrements to zero.
5479 void SetAutorunMicrotasks(bool autorun);
5482 * Experimental: Returns whether the Microtask Work Queue is automatically
5483 * run when the script call depth decrements to zero.
5485 bool WillAutorunMicrotasks() const;
5488 * Sets a callback for counting the number of times a feature of V8 is used.
5490 void SetUseCounterCallback(UseCounterCallback callback);
5493 * Enables the host application to provide a mechanism for recording
5494 * statistics counters.
5496 void SetCounterFunction(CounterLookupCallback);
5499 * Enables the host application to provide a mechanism for recording
5500 * histograms. The CreateHistogram function returns a
5501 * histogram which will later be passed to the AddHistogramSample
5504 void SetCreateHistogramFunction(CreateHistogramCallback);
5505 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5508 * Optional notification that the embedder is idle.
5509 * V8 uses the notification to perform garbage collection.
5510 * This call can be used repeatedly if the embedder remains idle.
5511 * Returns true if the embedder should stop calling IdleNotification
5512 * until real work has been done. This indicates that V8 has done
5513 * as much cleanup as it will be able to do.
5515 * The idle_time_in_ms argument specifies the time V8 has to perform
5516 * garbage collection. There is no guarantee that the actual work will be
5517 * done within the time limit. This variant is deprecated and will be removed
5520 * The deadline_in_seconds argument specifies the deadline V8 has to finish
5521 * garbage collection work. deadline_in_seconds is compared with
5522 * MonotonicallyIncreasingTime() and should be based on the same timebase as
5523 * that function. There is no guarantee that the actual work will be done
5524 * within the time limit.
5526 bool IdleNotification(int idle_time_in_ms);
5527 bool IdleNotificationDeadline(double deadline_in_seconds);
5530 * Optional notification that the system is running low on memory.
5531 * V8 uses these notifications to attempt to free memory.
5533 void LowMemoryNotification();
5536 * Optional notification that a context has been disposed. V8 uses
5537 * these notifications to guide the GC heuristic. Returns the number
5538 * of context disposals - including this one - since the last time
5539 * V8 had a chance to clean up.
5541 * The optional parameter |dependant_context| specifies whether the disposed
5542 * context was depending on state from other contexts or not.
5544 int ContextDisposedNotification(bool dependant_context = true);
5547 * Allows the host application to provide the address of a function that is
5548 * notified each time code is added, moved or removed.
5550 * \param options options for the JIT code event handler.
5551 * \param event_handler the JIT code event handler, which will be invoked
5552 * each time code is added, moved or removed.
5553 * \note \p event_handler won't get notified of existent code.
5554 * \note since code removal notifications are not currently issued, the
5555 * \p event_handler may get notifications of code that overlaps earlier
5556 * code notifications. This happens when code areas are reused, and the
5557 * earlier overlapping code areas should therefore be discarded.
5558 * \note the events passed to \p event_handler and the strings they point to
5559 * are not guaranteed to live past each call. The \p event_handler must
5560 * copy strings and other parameters it needs to keep around.
5561 * \note the set of events declared in JitCodeEvent::EventType is expected to
5562 * grow over time, and the JitCodeEvent structure is expected to accrue
5563 * new members. The \p event_handler function must ignore event codes
5564 * it does not recognize to maintain future compatibility.
5565 * \note Use Isolate::CreateParams to get events for code executed during
5568 void SetJitCodeEventHandler(JitCodeEventOptions options,
5569 JitCodeEventHandler event_handler);
5572 * Modifies the stack limit for this Isolate.
5574 * \param stack_limit An address beyond which the Vm's stack may not grow.
5576 * \note If you are using threads then you should hold the V8::Locker lock
5577 * while setting the stack limit and you must set a non-default stack
5578 * limit separately for each thread.
5580 void SetStackLimit(uintptr_t stack_limit);
5583 * Returns a memory range that can potentially contain jitted code.
5585 * On Win64, embedders are advised to install function table callbacks for
5586 * these ranges, as default SEH won't be able to unwind through jitted code.
5588 * The first page of the code range is reserved for the embedder and is
5589 * committed, writable, and executable.
5591 * Might be empty on other platforms.
5593 * https://code.google.com/p/v8/issues/detail?id=3598
5595 void GetCodeRange(void** start, size_t* length_in_bytes);
5597 /** Set the callback to invoke in case of fatal errors. */
5598 void SetFatalErrorHandler(FatalErrorCallback that);
5601 * Set the callback to invoke to check if code generation from
5602 * strings should be allowed.
5604 void SetAllowCodeGenerationFromStringsCallback(
5605 AllowCodeGenerationFromStringsCallback callback);
5608 * Check if V8 is dead and therefore unusable. This is the case after
5609 * fatal errors such as out-of-memory situations.
5614 * Adds a message listener.
5616 * The same message listener can be added more than once and in that
5617 * case it will be called more than once for each message.
5619 * If data is specified, it will be passed to the callback when it is called.
5620 * Otherwise, the exception object will be passed to the callback instead.
5622 bool AddMessageListener(MessageCallback that,
5623 Handle<Value> data = Handle<Value>());
5626 * Remove all message listeners from the specified callback function.
5628 void RemoveMessageListeners(MessageCallback that);
5630 /** Callback function for reporting failed access checks.*/
5631 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5634 * Tells V8 to capture current stack trace when uncaught exception occurs
5635 * and report it to the message listeners. The option is off by default.
5637 void SetCaptureStackTraceForUncaughtExceptions(
5638 bool capture, int frame_limit = 10,
5639 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5642 * Enables the host application to provide a mechanism to be notified
5643 * and perform custom logging when V8 Allocates Executable Memory.
5645 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5646 ObjectSpace space, AllocationAction action);
5649 * Removes callback that was installed by AddMemoryAllocationCallback.
5651 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5654 * Iterates through all external resources referenced from current isolate
5655 * heap. GC is not invoked prior to iterating, therefore there is no
5656 * guarantee that visited objects are still alive.
5658 void VisitExternalResources(ExternalResourceVisitor* visitor);
5661 * Iterates through all the persistent handles in the current isolate's heap
5662 * that have class_ids.
5664 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5667 * Iterates through all the persistent handles in the current isolate's heap
5668 * that have class_ids and are candidates to be marked as partially dependent
5669 * handles. This will visit handles to young objects created since the last
5670 * garbage collection but is free to visit an arbitrary superset of these
5673 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5676 template <class K, class V, class Traits>
5677 friend class PersistentValueMapBase;
5680 Isolate(const Isolate&);
5682 Isolate& operator=(const Isolate&);
5683 void* operator new(size_t size);
5684 void operator delete(void*, size_t);
5686 void SetObjectGroupId(internal::Object** object, UniqueId id);
5687 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5688 void SetReference(internal::Object** parent, internal::Object** child);
5689 void CollectAllGarbage(const char* gc_reason);
5692 class V8_EXPORT StartupData {
5700 * EntropySource is used as a callback function when v8 needs a source
5703 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5707 * ReturnAddressLocationResolver is used as a callback function when v8 is
5708 * resolving the location of a return address on the stack. Profilers that
5709 * change the return address on the stack can use this to resolve the stack
5710 * location to whereever the profiler stashed the original return address.
5712 * \param return_addr_location points to a location on stack where a machine
5713 * return address resides.
5714 * \returns either return_addr_location, or else a pointer to the profiler's
5715 * copy of the original return address.
5717 * \note the resolver function must not cause garbage collection.
5719 typedef uintptr_t (*ReturnAddressLocationResolver)(
5720 uintptr_t return_addr_location);
5724 * Container class for static utility functions.
5726 class V8_EXPORT V8 {
5728 /** Set the callback to invoke in case of fatal errors. */
5729 V8_INLINE static V8_DEPRECATE_SOON(
5730 "Use isolate version",
5731 void SetFatalErrorHandler(FatalErrorCallback that));
5734 * Set the callback to invoke to check if code generation from
5735 * strings should be allowed.
5737 V8_INLINE static V8_DEPRECATE_SOON(
5738 "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
5739 AllowCodeGenerationFromStringsCallback that));
5742 * Set allocator to use for ArrayBuffer memory.
5743 * The allocator should be set only once. The allocator should be set
5744 * before any code tha uses ArrayBuffers is executed.
5745 * This allocator is used in all isolates.
5747 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
5750 * Check if V8 is dead and therefore unusable. This is the case after
5751 * fatal errors such as out-of-memory situations.
5753 V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
5756 * Hand startup data to V8, in case the embedder has chosen to build
5757 * V8 with external startup data.
5760 * - By default the startup data is linked into the V8 library, in which
5761 * case this function is not meaningful.
5762 * - If this needs to be called, it needs to be called before V8
5763 * tries to make use of its built-ins.
5764 * - To avoid unnecessary copies of data, V8 will point directly into the
5765 * given data blob, so pretty please keep it around until V8 exit.
5766 * - Compression of the startup blob might be useful, but needs to
5767 * handled entirely on the embedders' side.
5768 * - The call will abort if the data is invalid.
5770 static void SetNativesDataBlob(StartupData* startup_blob);
5771 static void SetSnapshotDataBlob(StartupData* startup_blob);
5774 * Create a new isolate and context for the purpose of capturing a snapshot
5775 * Returns { NULL, 0 } on failure.
5776 * The caller owns the data array in the return value.
5778 static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
5781 * Adds a message listener.
5783 * The same message listener can be added more than once and in that
5784 * case it will be called more than once for each message.
5786 * If data is specified, it will be passed to the callback when it is called.
5787 * Otherwise, the exception object will be passed to the callback instead.
5789 V8_INLINE static V8_DEPRECATE_SOON(
5790 "Use isolate version",
5791 bool AddMessageListener(MessageCallback that,
5792 Handle<Value> data = Handle<Value>()));
5795 * Remove all message listeners from the specified callback function.
5797 V8_INLINE static V8_DEPRECATE_SOON(
5798 "Use isolate version", void RemoveMessageListeners(MessageCallback that));
5801 * Tells V8 to capture current stack trace when uncaught exception occurs
5802 * and report it to the message listeners. The option is off by default.
5804 V8_INLINE static V8_DEPRECATE_SOON(
5805 "Use isolate version",
5806 void SetCaptureStackTraceForUncaughtExceptions(
5807 bool capture, int frame_limit = 10,
5808 StackTrace::StackTraceOptions options = StackTrace::kOverview));
5811 * Sets V8 flags from a string.
5813 static void SetFlagsFromString(const char* str, int length);
5816 * Sets V8 flags from the command line.
5818 static void SetFlagsFromCommandLine(int* argc,
5822 /** Get the version string. */
5823 static const char* GetVersion();
5825 /** Callback function for reporting failed access checks.*/
5826 V8_INLINE static V8_DEPRECATE_SOON(
5827 "Use isolate version",
5828 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
5831 * Enables the host application to receive a notification before a
5832 * garbage collection. Allocations are not allowed in the
5833 * callback function, you therefore cannot manipulate objects (set
5834 * or delete properties for example) since it is possible such
5835 * operations will result in the allocation of objects. It is possible
5836 * to specify the GCType filter for your callback. But it is not possible to
5837 * register the same callback function two times with different
5840 static V8_DEPRECATE_SOON(
5841 "Use isolate version",
5842 void AddGCPrologueCallback(GCPrologueCallback callback,
5843 GCType gc_type_filter = kGCTypeAll));
5846 * This function removes callback which was installed by
5847 * AddGCPrologueCallback function.
5849 V8_INLINE static V8_DEPRECATE_SOON(
5850 "Use isolate version",
5851 void RemoveGCPrologueCallback(GCPrologueCallback callback));
5854 * Enables the host application to receive a notification after a
5855 * garbage collection. Allocations are not allowed in the
5856 * callback function, you therefore cannot manipulate objects (set
5857 * or delete properties for example) since it is possible such
5858 * operations will result in the allocation of objects. It is possible
5859 * to specify the GCType filter for your callback. But it is not possible to
5860 * register the same callback function two times with different
5863 static V8_DEPRECATE_SOON(
5864 "Use isolate version",
5865 void AddGCEpilogueCallback(GCEpilogueCallback callback,
5866 GCType gc_type_filter = kGCTypeAll));
5869 * This function removes callback which was installed by
5870 * AddGCEpilogueCallback function.
5872 V8_INLINE static V8_DEPRECATE_SOON(
5873 "Use isolate version",
5874 void RemoveGCEpilogueCallback(GCEpilogueCallback callback));
5877 * Enables the host application to provide a mechanism to be notified
5878 * and perform custom logging when V8 Allocates Executable Memory.
5880 V8_INLINE static V8_DEPRECATE_SOON(
5881 "Use isolate version",
5882 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5884 AllocationAction action));
5887 * Removes callback that was installed by AddMemoryAllocationCallback.
5889 V8_INLINE static V8_DEPRECATE_SOON(
5890 "Use isolate version",
5891 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
5894 * Initializes V8. This function needs to be called before the first Isolate
5895 * is created. It always returns true.
5897 static bool Initialize();
5900 * Allows the host application to provide a callback which can be used
5901 * as a source of entropy for random number generators.
5903 static void SetEntropySource(EntropySource source);
5906 * Allows the host application to provide a callback that allows v8 to
5907 * cooperate with a profiler that rewrites return addresses on stack.
5909 static void SetReturnAddressLocationResolver(
5910 ReturnAddressLocationResolver return_address_resolver);
5913 * Forcefully terminate the current thread of JavaScript execution
5914 * in the given isolate.
5916 * This method can be used by any thread even if that thread has not
5917 * acquired the V8 lock with a Locker object.
5919 * \param isolate The isolate in which to terminate the current JS execution.
5921 V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
5922 void TerminateExecution(Isolate* isolate));
5925 * Is V8 terminating JavaScript execution.
5927 * Returns true if JavaScript execution is currently terminating
5928 * because of a call to TerminateExecution. In that case there are
5929 * still JavaScript frames on the stack and the termination
5930 * exception is still active.
5932 * \param isolate The isolate in which to check.
5934 V8_INLINE static V8_DEPRECATE_SOON(
5935 "Use isolate version",
5936 bool IsExecutionTerminating(Isolate* isolate = NULL));
5939 * Resume execution capability in the given isolate, whose execution
5940 * was previously forcefully terminated using TerminateExecution().
5942 * When execution is forcefully terminated using TerminateExecution(),
5943 * the isolate can not resume execution until all JavaScript frames
5944 * have propagated the uncatchable exception which is generated. This
5945 * method allows the program embedding the engine to handle the
5946 * termination event and resume execution capability, even if
5947 * JavaScript frames remain on the stack.
5949 * This method can be used by any thread even if that thread has not
5950 * acquired the V8 lock with a Locker object.
5952 * \param isolate The isolate in which to resume execution capability.
5954 V8_INLINE static V8_DEPRECATE_SOON(
5955 "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
5958 * Releases any resources used by v8 and stops any utility threads
5959 * that may be running. Note that disposing v8 is permanent, it
5960 * cannot be reinitialized.
5962 * It should generally not be necessary to dispose v8 before exiting
5963 * a process, this should happen automatically. It is only necessary
5964 * to use if the process needs the resources taken up by v8.
5966 static bool Dispose();
5969 * Iterates through all external resources referenced from current isolate
5970 * heap. GC is not invoked prior to iterating, therefore there is no
5971 * guarantee that visited objects are still alive.
5973 V8_INLINE static V8_DEPRECATE_SOON(
5974 "Use isoalte version",
5975 void VisitExternalResources(ExternalResourceVisitor* visitor));
5978 * Iterates through all the persistent handles in the current isolate's heap
5979 * that have class_ids.
5981 V8_INLINE static V8_DEPRECATE_SOON(
5982 "Use isolate version",
5983 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
5986 * Iterates through all the persistent handles in isolate's heap that have
5989 V8_INLINE static V8_DEPRECATE_SOON(
5990 "Use isolate version",
5991 void VisitHandlesWithClassIds(Isolate* isolate,
5992 PersistentHandleVisitor* visitor));
5995 * Iterates through all the persistent handles in the current isolate's heap
5996 * that have class_ids and are candidates to be marked as partially dependent
5997 * handles. This will visit handles to young objects created since the last
5998 * garbage collection but is free to visit an arbitrary superset of these
6001 V8_INLINE static V8_DEPRECATE_SOON(
6002 "Use isolate version",
6003 void VisitHandlesForPartialDependence(Isolate* isolate,
6004 PersistentHandleVisitor* visitor));
6007 * Initialize the ICU library bundled with V8. The embedder should only
6008 * invoke this method when using the bundled ICU. Returns true on success.
6010 * If V8 was compiled with the ICU data in an external file, the location
6011 * of the data file has to be provided.
6013 static bool InitializeICU(const char* icu_data_file = NULL);
6016 * Sets the v8::Platform to use. This should be invoked before V8 is
6019 static void InitializePlatform(Platform* platform);
6022 * Clears all references to the v8::Platform. This should be invoked after
6025 static void ShutdownPlatform();
6030 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6031 internal::Object** handle);
6032 static internal::Object** CopyPersistent(internal::Object** handle);
6033 static void DisposeGlobal(internal::Object** global_handle);
6034 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6035 static void MakeWeak(internal::Object** global_handle, void* data,
6036 WeakCallback weak_callback);
6037 static void MakeWeak(internal::Object** global_handle, void* data,
6038 WeakCallbackInfo<void>::Callback weak_callback,
6039 WeakCallbackType type);
6040 static void MakeWeak(internal::Object** global_handle, void* data,
6042 int internal_field_index1,
6044 int internal_field_index2,
6045 WeakCallbackInfo<void>::Callback weak_callback);
6046 static void* ClearWeak(internal::Object** global_handle);
6047 static void Eternalize(Isolate* isolate,
6050 static Local<Value> GetEternal(Isolate* isolate, int index);
6052 static void CheckIsJust(bool is_just);
6053 static void ToLocalEmpty();
6054 static void InternalFieldOutOfBounds(int index);
6056 template <class T> friend class Handle;
6057 template <class T> friend class Local;
6059 friend class MaybeLocal;
6063 friend class WeakCallbackInfo;
6064 template <class T> friend class Eternal;
6065 template <class T> friend class PersistentBase;
6066 template <class T, class M> friend class Persistent;
6067 friend class Context;
6072 * A simple Maybe type, representing an object which may or may not have a
6073 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6075 * If an API method returns a Maybe<>, the API method can potentially fail
6076 * either because an exception is thrown, or because an exception is pending,
6077 * e.g. because a previous API call threw an exception that hasn't been caught
6078 * yet, or because a TerminateExecution exception was thrown. In that case, a
6079 * "Nothing" value is returned.
6084 V8_INLINE bool IsNothing() const { return !has_value; }
6085 V8_INLINE bool IsJust() const { return has_value; }
6087 // Will crash when checks are enabled if the Maybe<> is nothing.
6088 V8_INLINE T FromJust() const {
6089 #ifdef V8_ENABLE_CHECKS
6090 V8::CheckIsJust(IsJust());
6095 V8_INLINE T FromMaybe(const T& default_value) const {
6096 return has_value ? value : default_value;
6099 V8_INLINE bool operator==(const Maybe& other) const {
6100 return (IsJust() == other.IsJust()) &&
6101 (!IsJust() || FromJust() == other.FromJust());
6104 V8_INLINE bool operator!=(const Maybe& other) const {
6105 return !operator==(other);
6109 Maybe() : has_value(false) {}
6110 explicit Maybe(const T& t) : has_value(true), value(t) {}
6116 friend Maybe<U> Nothing();
6118 friend Maybe<U> Just(const U& u);
6123 inline Maybe<T> Nothing() {
6129 inline Maybe<T> Just(const T& t) {
6135 * An external exception handler.
6137 class V8_EXPORT TryCatch {
6140 * Creates a new try/catch block and registers it with v8. Note that
6141 * all TryCatch blocks should be stack allocated because the memory
6142 * location itself is compared against JavaScript try/catch blocks.
6144 V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6147 * Creates a new try/catch block and registers it with v8. Note that
6148 * all TryCatch blocks should be stack allocated because the memory
6149 * location itself is compared against JavaScript try/catch blocks.
6151 TryCatch(Isolate* isolate);
6154 * Unregisters and deletes this try/catch block.
6159 * Returns true if an exception has been caught by this try/catch block.
6161 bool HasCaught() const;
6164 * For certain types of exceptions, it makes no sense to continue execution.
6166 * If CanContinue returns false, the correct action is to perform any C++
6167 * cleanup needed and then return. If CanContinue returns false and
6168 * HasTerminated returns true, it is possible to call
6169 * CancelTerminateExecution in order to continue calling into the engine.
6171 bool CanContinue() const;
6174 * Returns true if an exception has been caught due to script execution
6177 * There is no JavaScript representation of an execution termination
6178 * exception. Such exceptions are thrown when the TerminateExecution
6179 * methods are called to terminate a long-running script.
6181 * If such an exception has been thrown, HasTerminated will return true,
6182 * indicating that it is possible to call CancelTerminateExecution in order
6183 * to continue calling into the engine.
6185 bool HasTerminated() const;
6188 * Throws the exception caught by this TryCatch in a way that avoids
6189 * it being caught again by this same TryCatch. As with ThrowException
6190 * it is illegal to execute any JavaScript operations after calling
6191 * ReThrow; the caller must return immediately to where the exception
6194 Handle<Value> ReThrow();
6197 * Returns the exception caught by this try/catch block. If no exception has
6198 * been caught an empty handle is returned.
6200 * The returned handle is valid until this TryCatch block has been destroyed.
6202 Local<Value> Exception() const;
6205 * Returns the .stack property of the thrown object. If no .stack
6206 * property is present an empty handle is returned.
6208 V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace()) const;
6209 MaybeLocal<Value> StackTrace(Local<Context> context) const;
6212 * Returns the message associated with this exception. If there is
6213 * no message associated an empty handle is returned.
6215 * The returned handle is valid until this TryCatch block has been
6218 Local<v8::Message> Message() const;
6221 * Clears any exceptions that may have been caught by this try/catch block.
6222 * After this method has been called, HasCaught() will return false. Cancels
6223 * the scheduled exception if it is caught and ReThrow() is not called before.
6225 * It is not necessary to clear a try/catch block before using it again; if
6226 * another exception is thrown the previously caught exception will just be
6227 * overwritten. However, it is often a good idea since it makes it easier
6228 * to determine which operation threw a given exception.
6233 * Set verbosity of the external exception handler.
6235 * By default, exceptions that are caught by an external exception
6236 * handler are not reported. Call SetVerbose with true on an
6237 * external exception handler to have exceptions caught by the
6238 * handler reported as if they were not caught.
6240 void SetVerbose(bool value);
6243 * Set whether or not this TryCatch should capture a Message object
6244 * which holds source information about where the exception
6245 * occurred. True by default.
6247 void SetCaptureMessage(bool value);
6250 * There are cases when the raw address of C++ TryCatch object cannot be
6251 * used for comparisons with addresses into the JS stack. The cases are:
6252 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6253 * 2) Address sanitizer allocates local C++ object in the heap when
6254 * UseAfterReturn mode is enabled.
6255 * This method returns address that can be used for comparisons with
6256 * addresses into the JS stack. When neither simulator nor ASAN's
6257 * UseAfterReturn is enabled, then the address returned will be the address
6258 * of the C++ try catch handler itself.
6260 static void* JSStackComparableAddress(v8::TryCatch* handler) {
6261 if (handler == NULL) return NULL;
6262 return handler->js_stack_comparable_address_;
6266 void ResetInternal();
6268 // Make it hard to create heap-allocated TryCatch blocks.
6269 TryCatch(const TryCatch&);
6270 void operator=(const TryCatch&);
6271 void* operator new(size_t size);
6272 void operator delete(void*, size_t);
6274 v8::internal::Isolate* isolate_;
6275 v8::TryCatch* next_;
6278 void* js_stack_comparable_address_;
6279 bool is_verbose_ : 1;
6280 bool can_continue_ : 1;
6281 bool capture_message_ : 1;
6283 bool has_terminated_ : 1;
6285 friend class v8::internal::Isolate;
6293 * A container for extension names.
6295 class V8_EXPORT ExtensionConfiguration {
6297 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6298 ExtensionConfiguration(int name_count, const char* names[])
6299 : name_count_(name_count), names_(names) { }
6301 const char** begin() const { return &names_[0]; }
6302 const char** end() const { return &names_[name_count_]; }
6305 const int name_count_;
6306 const char** names_;
6311 * A sandboxed execution context with its own set of built-in objects
6314 class V8_EXPORT Context {
6317 * Returns the global proxy object.
6319 * Global proxy object is a thin wrapper whose prototype points to actual
6320 * context's global object with the properties like Object, etc. This is done
6321 * that way for security reasons (for more details see
6322 * https://wiki.mozilla.org/Gecko:SplitWindow).
6324 * Please note that changes to global proxy object prototype most probably
6325 * would break VM---v8 expects only global object as a prototype of global
6328 Local<Object> Global();
6331 * Detaches the global object from its context before
6332 * the global object can be reused to create a new context.
6334 void DetachGlobal();
6337 * Creates a new context and returns a handle to the newly allocated
6340 * \param isolate The isolate in which to create the context.
6342 * \param extensions An optional extension configuration containing
6343 * the extensions to be installed in the newly created context.
6345 * \param global_template An optional object template from which the
6346 * global object for the newly created context will be created.
6348 * \param global_object An optional global object to be reused for
6349 * the newly created context. This global object must have been
6350 * created by a previous call to Context::New with the same global
6351 * template. The state of the global object will be completely reset
6352 * and only object identify will remain.
6354 static Local<Context> New(
6356 ExtensionConfiguration* extensions = NULL,
6357 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
6358 Handle<Value> global_object = Handle<Value>());
6361 * Sets the security token for the context. To access an object in
6362 * another context, the security tokens must match.
6364 void SetSecurityToken(Handle<Value> token);
6366 /** Restores the security token to the default value. */
6367 void UseDefaultSecurityToken();
6369 /** Returns the security token of this context.*/
6370 Handle<Value> GetSecurityToken();
6373 * Enter this context. After entering a context, all code compiled
6374 * and run is compiled and run in this context. If another context
6375 * is already entered, this old context is saved so it can be
6376 * restored when the new context is exited.
6381 * Exit this context. Exiting the current context restores the
6382 * context that was in place when entering the current context.
6386 /** Returns an isolate associated with a current context. */
6387 v8::Isolate* GetIsolate();
6390 * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6391 * The value is propagated to the scripts compiled in given Context and
6392 * can be used for filtering scripts.
6394 enum EmbedderDataFields { kDebugIdIndex = 0 };
6397 * Gets the embedder data with the given index, which must have been set by a
6398 * previous call to SetEmbedderData with the same index. Note that index 0
6399 * currently has a special meaning for Chrome's debugger.
6401 V8_INLINE Local<Value> GetEmbedderData(int index);
6404 * Sets the embedder data with the given index, growing the data as
6405 * needed. Note that index 0 currently has a special meaning for Chrome's
6408 void SetEmbedderData(int index, Handle<Value> value);
6411 * Gets a 2-byte-aligned native pointer from the embedder data with the given
6412 * index, which must have bees set by a previous call to
6413 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6414 * currently has a special meaning for Chrome's debugger.
6416 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
6419 * Sets a 2-byte-aligned native pointer in the embedder data with the given
6420 * index, growing the data as needed. Note that index 0 currently has a
6421 * special meaning for Chrome's debugger.
6423 void SetAlignedPointerInEmbedderData(int index, void* value);
6426 * Control whether code generation from strings is allowed. Calling
6427 * this method with false will disable 'eval' and the 'Function'
6428 * constructor for code running in this context. If 'eval' or the
6429 * 'Function' constructor are used an exception will be thrown.
6431 * If code generation from strings is not allowed the
6432 * V8::AllowCodeGenerationFromStrings callback will be invoked if
6433 * set before blocking the call to 'eval' or the 'Function'
6434 * constructor. If that callback returns true, the call will be
6435 * allowed, otherwise an exception will be thrown. If no callback is
6436 * set an exception will be thrown.
6438 void AllowCodeGenerationFromStrings(bool allow);
6441 * Returns true if code generation from strings is allowed for the context.
6442 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6444 bool IsCodeGenerationFromStringsAllowed();
6447 * Sets the error description for the exception that is thrown when
6448 * code generation from strings is not allowed and 'eval' or the 'Function'
6449 * constructor are called.
6451 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
6454 * Stack-allocated class which sets the execution context for all
6455 * operations executed within a local scope.
6459 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
6462 V8_INLINE ~Scope() { context_->Exit(); }
6465 Handle<Context> context_;
6470 friend class Script;
6471 friend class Object;
6472 friend class Function;
6474 Local<Value> SlowGetEmbedderData(int index);
6475 void* SlowGetAlignedPointerFromEmbedderData(int index);
6480 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6481 * to use any given V8 isolate, see the comments in the Isolate class. The
6482 * definition of 'using a V8 isolate' includes accessing handles or holding onto
6483 * object pointers obtained from V8 handles while in the particular V8 isolate.
6484 * It is up to the user of V8 to ensure, perhaps with locking, that this
6485 * constraint is not violated. In addition to any other synchronization
6486 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6487 * used to signal thead switches to V8.
6489 * v8::Locker is a scoped lock object. While it's active, i.e. between its
6490 * construction and destruction, the current thread is allowed to use the locked
6491 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6492 * any time. In other words, the scope of a v8::Locker is a critical section.
6498 * v8::Locker locker(isolate);
6499 * v8::Isolate::Scope isolate_scope(isolate);
6501 * // Code using V8 and isolate goes here.
6503 * } // Destructor called here
6506 * If you wish to stop using V8 in a thread A you can do this either by
6507 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6513 * v8::Unlocker unlocker(isolate);
6515 * // Code not using V8 goes here while V8 can run in another thread.
6517 * } // Destructor called here.
6521 * The Unlocker object is intended for use in a long-running callback from V8,
6522 * where you want to release the V8 lock for other threads to use.
6524 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6525 * given thread. This can be useful if you have code that can be called either
6526 * from code that holds the lock or from code that does not. The Unlocker is
6527 * not recursive so you can not have several Unlockers on the stack at once, and
6528 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6530 * An unlocker will unlock several lockers if it has to and reinstate the
6531 * correct depth of locking on its destruction, e.g.:
6536 * v8::Locker locker(isolate);
6537 * Isolate::Scope isolate_scope(isolate);
6540 * v8::Locker another_locker(isolate);
6541 * // V8 still locked (2 levels).
6544 * v8::Unlocker unlocker(isolate);
6548 * // V8 locked again (2 levels).
6550 * // V8 still locked (1 level).
6552 * // V8 Now no longer locked.
6555 class V8_EXPORT Unlocker {
6558 * Initialize Unlocker for a given Isolate.
6560 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6564 void Initialize(Isolate* isolate);
6566 internal::Isolate* isolate_;
6570 class V8_EXPORT Locker {
6573 * Initialize Locker for a given Isolate.
6575 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6580 * Returns whether or not the locker for a given isolate, is locked by the
6583 static bool IsLocked(Isolate* isolate);
6586 * Returns whether v8::Locker is being used by this V8 instance.
6588 static bool IsActive();
6591 void Initialize(Isolate* isolate);
6595 internal::Isolate* isolate_;
6597 // Disallow copying and assigning.
6598 Locker(const Locker&);
6599 void operator=(const Locker&);
6603 // --- Implementation ---
6606 namespace internal {
6608 const int kApiPointerSize = sizeof(void*); // NOLINT
6609 const int kApiIntSize = sizeof(int); // NOLINT
6610 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6612 // Tag information for HeapObject.
6613 const int kHeapObjectTag = 1;
6614 const int kHeapObjectTagSize = 2;
6615 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6617 // Tag information for Smi.
6618 const int kSmiTag = 0;
6619 const int kSmiTagSize = 1;
6620 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6622 template <size_t ptr_size> struct SmiTagging;
6624 template<int kSmiShiftSize>
6625 V8_INLINE internal::Object* IntToSmi(int value) {
6626 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6627 uintptr_t tagged_value =
6628 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6629 return reinterpret_cast<internal::Object*>(tagged_value);
6632 // Smi constants for 32-bit systems.
6633 template <> struct SmiTagging<4> {
6634 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6635 static int SmiShiftSize() { return kSmiShiftSize; }
6636 static int SmiValueSize() { return kSmiValueSize; }
6637 V8_INLINE static int SmiToInt(const internal::Object* value) {
6638 int shift_bits = kSmiTagSize + kSmiShiftSize;
6639 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6640 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6642 V8_INLINE static internal::Object* IntToSmi(int value) {
6643 return internal::IntToSmi<kSmiShiftSize>(value);
6645 V8_INLINE static bool IsValidSmi(intptr_t value) {
6646 // To be representable as an tagged small integer, the two
6647 // most-significant bits of 'value' must be either 00 or 11 due to
6648 // sign-extension. To check this we add 01 to the two
6649 // most-significant bits, and check if the most-significant bit is 0
6651 // CAUTION: The original code below:
6652 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6653 // may lead to incorrect results according to the C language spec, and
6654 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6655 // compiler may produce undefined results in case of signed integer
6656 // overflow. The computation must be done w/ unsigned ints.
6657 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6661 // Smi constants for 64-bit systems.
6662 template <> struct SmiTagging<8> {
6663 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6664 static int SmiShiftSize() { return kSmiShiftSize; }
6665 static int SmiValueSize() { return kSmiValueSize; }
6666 V8_INLINE static int SmiToInt(const internal::Object* value) {
6667 int shift_bits = kSmiTagSize + kSmiShiftSize;
6668 // Shift down and throw away top 32 bits.
6669 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6671 V8_INLINE static internal::Object* IntToSmi(int value) {
6672 return internal::IntToSmi<kSmiShiftSize>(value);
6674 V8_INLINE static bool IsValidSmi(intptr_t value) {
6675 // To be representable as a long smi, the value must be a 32-bit integer.
6676 return (value == static_cast<int32_t>(value));
6680 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6681 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6682 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6683 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6684 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6687 * This class exports constants and functionality from within v8 that
6688 * is necessary to implement inline functions in the v8 api. Don't
6689 * depend on functions and constants defined here.
6693 // These values match non-compiler-dependent values defined within
6694 // the implementation of v8.
6695 static const int kHeapObjectMapOffset = 0;
6696 static const int kMapInstanceTypeAndBitFieldOffset =
6697 1 * kApiPointerSize + kApiIntSize;
6698 static const int kStringResourceOffset = 3 * kApiPointerSize;
6700 static const int kOddballKindOffset = 3 * kApiPointerSize;
6701 static const int kForeignAddressOffset = kApiPointerSize;
6702 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6703 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6704 static const int kContextHeaderSize = 2 * kApiPointerSize;
6705 static const int kContextEmbedderDataIndex = 76;
6706 static const int kFullStringRepresentationMask = 0x07;
6707 static const int kStringEncodingMask = 0x4;
6708 static const int kExternalTwoByteRepresentationTag = 0x02;
6709 static const int kExternalOneByteRepresentationTag = 0x06;
6711 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6712 static const int kAmountOfExternalAllocatedMemoryOffset =
6713 4 * kApiPointerSize;
6714 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6715 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6716 static const int kIsolateRootsOffset =
6717 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6719 static const int kUndefinedValueRootIndex = 5;
6720 static const int kNullValueRootIndex = 7;
6721 static const int kTrueValueRootIndex = 8;
6722 static const int kFalseValueRootIndex = 9;
6723 static const int kEmptyStringRootIndex = 156;
6725 // The external allocation limit should be below 256 MB on all architectures
6726 // to avoid that resource-constrained embedders run low on memory.
6727 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6729 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6730 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6731 static const int kNodeStateMask = 0x7;
6732 static const int kNodeStateIsWeakValue = 2;
6733 static const int kNodeStateIsPendingValue = 3;
6734 static const int kNodeStateIsNearDeathValue = 4;
6735 static const int kNodeIsIndependentShift = 3;
6736 static const int kNodeIsPartiallyDependentShift = 4;
6738 static const int kJSObjectType = 0xbd;
6739 static const int kFirstNonstringType = 0x80;
6740 static const int kOddballType = 0x83;
6741 static const int kForeignType = 0x87;
6743 static const int kUndefinedOddballKind = 5;
6744 static const int kNullOddballKind = 3;
6746 static const uint32_t kNumIsolateDataSlots = 4;
6748 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
6749 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
6750 #ifdef V8_ENABLE_CHECKS
6751 CheckInitializedImpl(isolate);
6755 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
6756 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
6760 V8_INLINE static int SmiValue(const internal::Object* value) {
6761 return PlatformSmiTagging::SmiToInt(value);
6764 V8_INLINE static internal::Object* IntToSmi(int value) {
6765 return PlatformSmiTagging::IntToSmi(value);
6768 V8_INLINE static bool IsValidSmi(intptr_t value) {
6769 return PlatformSmiTagging::IsValidSmi(value);
6772 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
6773 typedef internal::Object O;
6774 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
6775 // Map::InstanceType is defined so that it will always be loaded into
6776 // the LS 8 bits of one 16-bit word, regardless of endianess.
6777 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
6780 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
6781 typedef internal::Object O;
6782 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
6785 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
6786 int representation = (instance_type & kFullStringRepresentationMask);
6787 return representation == kExternalTwoByteRepresentationTag;
6790 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
6791 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6792 return *addr & static_cast<uint8_t>(1U << shift);
6795 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
6796 bool value, int shift) {
6797 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6798 uint8_t mask = static_cast<uint8_t>(1U << shift);
6799 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
6802 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
6803 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6804 return *addr & kNodeStateMask;
6807 V8_INLINE static void UpdateNodeState(internal::Object** obj,
6809 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
6810 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
6813 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
6816 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
6817 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
6818 *reinterpret_cast<void**>(addr) = data;
6821 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
6823 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
6824 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
6825 return *reinterpret_cast<void* const*>(addr);
6828 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
6830 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
6831 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
6834 template <typename T>
6835 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
6836 const uint8_t* addr =
6837 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
6838 return *reinterpret_cast<const T*>(addr);
6841 template <typename T>
6842 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
6843 typedef internal::Object O;
6844 typedef internal::Internals I;
6845 O* ctx = *reinterpret_cast<O* const*>(context);
6846 int embedder_data_offset = I::kContextHeaderSize +
6847 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
6848 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
6850 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
6851 return I::ReadField<T>(embedder_data, value_offset);
6855 } // namespace internal
6859 Local<T>::Local() : Handle<T>() { }
6863 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
6864 return New(isolate, that.val_);
6868 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
6869 return New(isolate, that.val_);
6873 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
6874 if (that == NULL) return Handle<T>();
6876 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
6877 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
6878 reinterpret_cast<internal::Isolate*>(isolate), *p)));
6883 Local<T> Local<T>::New(Isolate* isolate, T* that) {
6884 if (that == NULL) return Local<T>();
6886 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
6887 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
6888 reinterpret_cast<internal::Isolate*>(isolate), *p)));
6894 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
6896 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
6901 Local<T> Eternal<T>::Get(Isolate* isolate) {
6902 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
6907 Local<T> MaybeLocal<T>::ToLocalChecked() {
6908 #ifdef V8_ENABLE_CHECKS
6909 if (val_ == nullptr) V8::ToLocalEmpty();
6911 return Local<T>(val_);
6916 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
6917 #ifdef V8_ENABLE_CHECKS
6918 if (index < 0 || index >= kInternalFieldsInWeakCallback) {
6919 V8::InternalFieldOutOfBounds(index);
6922 return internal_fields_[index];
6927 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
6928 if (that == NULL) return NULL;
6929 internal::Object** p = reinterpret_cast<internal::Object**>(that);
6930 return reinterpret_cast<T*>(
6931 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
6936 template <class T, class M>
6937 template <class S, class M2>
6938 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
6941 if (that.IsEmpty()) return;
6942 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
6943 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
6944 M::Copy(that, this);
6949 bool PersistentBase<T>::IsIndependent() const {
6950 typedef internal::Internals I;
6951 if (this->IsEmpty()) return false;
6952 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
6953 I::kNodeIsIndependentShift);
6958 bool PersistentBase<T>::IsNearDeath() const {
6959 typedef internal::Internals I;
6960 if (this->IsEmpty()) return false;
6961 uint8_t node_state =
6962 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
6963 return node_state == I::kNodeStateIsNearDeathValue ||
6964 node_state == I::kNodeStateIsPendingValue;
6969 bool PersistentBase<T>::IsWeak() const {
6970 typedef internal::Internals I;
6971 if (this->IsEmpty()) return false;
6972 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
6973 I::kNodeStateIsWeakValue;
6978 void PersistentBase<T>::Reset() {
6979 if (this->IsEmpty()) return;
6980 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
6987 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
6990 if (other.IsEmpty()) return;
6991 this->val_ = New(isolate, other.val_);
6997 void PersistentBase<T>::Reset(Isolate* isolate,
6998 const PersistentBase<S>& other) {
7001 if (other.IsEmpty()) return;
7002 this->val_ = New(isolate, other.val_);
7007 template <typename S, typename P>
7008 void PersistentBase<T>::SetWeak(
7010 typename WeakCallbackData<S, P>::Callback callback) {
7012 typedef typename WeakCallbackData<Value, void>::Callback Callback;
7013 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7014 reinterpret_cast<Callback>(callback));
7019 template <typename P>
7020 void PersistentBase<T>::SetWeak(
7022 typename WeakCallbackData<T, P>::Callback callback) {
7023 SetWeak<T, P>(parameter, callback);
7028 template <typename P>
7029 void PersistentBase<T>::SetPhantom(
7030 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7031 int internal_field_index1, int internal_field_index2) {
7032 typedef typename WeakCallbackInfo<void>::Callback Callback;
7033 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7034 internal_field_index1, internal_field_index2,
7035 reinterpret_cast<Callback>(callback));
7040 template <typename P>
7041 V8_INLINE void PersistentBase<T>::SetWeak(
7042 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7043 WeakCallbackType type) {
7044 typedef typename WeakCallbackInfo<void>::Callback Callback;
7045 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7046 reinterpret_cast<Callback>(callback), type);
7051 template <typename P>
7052 P* PersistentBase<T>::ClearWeak() {
7053 return reinterpret_cast<P*>(
7054 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7059 void PersistentBase<T>::MarkIndependent() {
7060 typedef internal::Internals I;
7061 if (this->IsEmpty()) return;
7062 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7064 I::kNodeIsIndependentShift);
7069 void PersistentBase<T>::MarkPartiallyDependent() {
7070 typedef internal::Internals I;
7071 if (this->IsEmpty()) return;
7072 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7074 I::kNodeIsPartiallyDependentShift);
7079 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7080 typedef internal::Internals I;
7081 if (this->IsEmpty()) return;
7082 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7083 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7084 *reinterpret_cast<uint16_t*>(addr) = class_id;
7089 uint16_t PersistentBase<T>::WrapperClassId() const {
7090 typedef internal::Internals I;
7091 if (this->IsEmpty()) return 0;
7092 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7093 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7094 return *reinterpret_cast<uint16_t*>(addr);
7098 template<typename T>
7099 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7101 template<typename T>
7102 template<typename S>
7103 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7105 if (V8_UNLIKELY(handle.IsEmpty())) {
7106 *value_ = GetDefaultValue();
7108 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7112 template<typename T>
7113 template<typename S>
7114 void ReturnValue<T>::Set(const Handle<S> handle) {
7116 if (V8_UNLIKELY(handle.IsEmpty())) {
7117 *value_ = GetDefaultValue();
7119 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7123 template<typename T>
7124 void ReturnValue<T>::Set(double i) {
7125 TYPE_CHECK(T, Number);
7126 Set(Number::New(GetIsolate(), i));
7129 template<typename T>
7130 void ReturnValue<T>::Set(int32_t i) {
7131 TYPE_CHECK(T, Integer);
7132 typedef internal::Internals I;
7133 if (V8_LIKELY(I::IsValidSmi(i))) {
7134 *value_ = I::IntToSmi(i);
7137 Set(Integer::New(GetIsolate(), i));
7140 template<typename T>
7141 void ReturnValue<T>::Set(uint32_t i) {
7142 TYPE_CHECK(T, Integer);
7143 // Can't simply use INT32_MAX here for whatever reason.
7144 bool fits_into_int32_t = (i & (1U << 31)) == 0;
7145 if (V8_LIKELY(fits_into_int32_t)) {
7146 Set(static_cast<int32_t>(i));
7149 Set(Integer::NewFromUnsigned(GetIsolate(), i));
7152 template<typename T>
7153 void ReturnValue<T>::Set(bool value) {
7154 TYPE_CHECK(T, Boolean);
7155 typedef internal::Internals I;
7158 root_index = I::kTrueValueRootIndex;
7160 root_index = I::kFalseValueRootIndex;
7162 *value_ = *I::GetRoot(GetIsolate(), root_index);
7165 template<typename T>
7166 void ReturnValue<T>::SetNull() {
7167 TYPE_CHECK(T, Primitive);
7168 typedef internal::Internals I;
7169 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
7172 template<typename T>
7173 void ReturnValue<T>::SetUndefined() {
7174 TYPE_CHECK(T, Primitive);
7175 typedef internal::Internals I;
7176 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
7179 template<typename T>
7180 void ReturnValue<T>::SetEmptyString() {
7181 TYPE_CHECK(T, String);
7182 typedef internal::Internals I;
7183 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
7186 template<typename T>
7187 Isolate* ReturnValue<T>::GetIsolate() {
7188 // Isolate is always the pointer below the default value on the stack.
7189 return *reinterpret_cast<Isolate**>(&value_[-2]);
7192 template<typename T>
7193 template<typename S>
7194 void ReturnValue<T>::Set(S* whatever) {
7195 // Uncompilable to prevent inadvertent misuse.
7196 TYPE_CHECK(S*, Primitive);
7199 template<typename T>
7200 internal::Object* ReturnValue<T>::GetDefaultValue() {
7201 // Default value is always the pointer below value_ on the stack.
7206 template<typename T>
7207 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
7208 internal::Object** values,
7210 bool is_construct_call)
7211 : implicit_args_(implicit_args),
7214 is_construct_call_(is_construct_call) { }
7217 template<typename T>
7218 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
7219 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7220 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7224 template<typename T>
7225 Local<Function> FunctionCallbackInfo<T>::Callee() const {
7226 return Local<Function>(reinterpret_cast<Function*>(
7227 &implicit_args_[kCalleeIndex]));
7231 template<typename T>
7232 Local<Object> FunctionCallbackInfo<T>::This() const {
7233 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7237 template<typename T>
7238 Local<Object> FunctionCallbackInfo<T>::Holder() const {
7239 return Local<Object>(reinterpret_cast<Object*>(
7240 &implicit_args_[kHolderIndex]));
7244 template<typename T>
7245 Local<Value> FunctionCallbackInfo<T>::Data() const {
7246 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7250 template<typename T>
7251 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
7252 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7256 template<typename T>
7257 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
7258 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
7262 template<typename T>
7263 bool FunctionCallbackInfo<T>::IsConstructCall() const {
7264 return is_construct_call_ & 0x1;
7268 template<typename T>
7269 int FunctionCallbackInfo<T>::Length() const {
7274 Handle<Value> ScriptOrigin::ResourceName() const {
7275 return resource_name_;
7279 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
7280 return resource_line_offset_;
7284 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
7285 return resource_column_offset_;
7289 Handle<Boolean> ScriptOrigin::ResourceIsEmbedderDebugScript() const {
7290 return resource_is_embedder_debug_script_;
7294 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
7295 return resource_is_shared_cross_origin_;
7299 Handle<Integer> ScriptOrigin::ScriptID() const {
7304 Handle<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7307 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
7309 : source_string(string),
7310 resource_name(origin.ResourceName()),
7311 resource_line_offset(origin.ResourceLineOffset()),
7312 resource_column_offset(origin.ResourceColumnOffset()),
7313 resource_is_embedder_debug_script(origin.ResourceIsEmbedderDebugScript()),
7314 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
7315 source_map_url(origin.SourceMapUrl()),
7316 cached_data(data) {}
7319 ScriptCompiler::Source::Source(Local<String> string,
7321 : source_string(string), cached_data(data) {}
7324 ScriptCompiler::Source::~Source() {
7329 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
7335 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
7336 return value ? True(isolate) : False(isolate);
7340 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
7341 Set(v8::String::NewFromUtf8(isolate, name), value);
7345 Local<Value> Object::GetInternalField(int index) {
7346 #ifndef V8_ENABLE_CHECKS
7347 typedef internal::Object O;
7348 typedef internal::HeapObject HO;
7349 typedef internal::Internals I;
7350 O* obj = *reinterpret_cast<O**>(this);
7351 // Fast path: If the object is a plain JSObject, which is the common case, we
7352 // know where to find the internal fields and can return the value directly.
7353 if (I::GetInstanceType(obj) == I::kJSObjectType) {
7354 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7355 O* value = I::ReadField<O*>(obj, offset);
7356 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7357 return Local<Value>(reinterpret_cast<Value*>(result));
7360 return SlowGetInternalField(index);
7364 void* Object::GetAlignedPointerFromInternalField(int index) {
7365 #ifndef V8_ENABLE_CHECKS
7366 typedef internal::Object O;
7367 typedef internal::Internals I;
7368 O* obj = *reinterpret_cast<O**>(this);
7369 // Fast path: If the object is a plain JSObject, which is the common case, we
7370 // know where to find the internal fields and can return the value directly.
7371 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
7372 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7373 return I::ReadField<void*>(obj, offset);
7376 return SlowGetAlignedPointerFromInternalField(index);
7380 String* String::Cast(v8::Value* value) {
7381 #ifdef V8_ENABLE_CHECKS
7384 return static_cast<String*>(value);
7388 Local<String> String::Empty(Isolate* isolate) {
7389 typedef internal::Object* S;
7390 typedef internal::Internals I;
7391 I::CheckInitialized(isolate);
7392 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7393 return Local<String>(reinterpret_cast<String*>(slot));
7397 String::ExternalStringResource* String::GetExternalStringResource() const {
7398 typedef internal::Object O;
7399 typedef internal::Internals I;
7400 O* obj = *reinterpret_cast<O* const*>(this);
7401 String::ExternalStringResource* result;
7402 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
7403 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7404 result = reinterpret_cast<String::ExternalStringResource*>(value);
7408 #ifdef V8_ENABLE_CHECKS
7409 VerifyExternalStringResource(result);
7415 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
7416 String::Encoding* encoding_out) const {
7417 typedef internal::Object O;
7418 typedef internal::Internals I;
7419 O* obj = *reinterpret_cast<O* const*>(this);
7420 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
7421 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7422 ExternalStringResourceBase* resource = NULL;
7423 if (type == I::kExternalOneByteRepresentationTag ||
7424 type == I::kExternalTwoByteRepresentationTag) {
7425 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7426 resource = static_cast<ExternalStringResourceBase*>(value);
7428 #ifdef V8_ENABLE_CHECKS
7429 VerifyExternalStringResourceBase(resource, *encoding_out);
7435 bool Value::IsUndefined() const {
7436 #ifdef V8_ENABLE_CHECKS
7437 return FullIsUndefined();
7439 return QuickIsUndefined();
7443 bool Value::QuickIsUndefined() const {
7444 typedef internal::Object O;
7445 typedef internal::Internals I;
7446 O* obj = *reinterpret_cast<O* const*>(this);
7447 if (!I::HasHeapObjectTag(obj)) return false;
7448 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7449 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
7453 bool Value::IsNull() const {
7454 #ifdef V8_ENABLE_CHECKS
7455 return FullIsNull();
7457 return QuickIsNull();
7461 bool Value::QuickIsNull() const {
7462 typedef internal::Object O;
7463 typedef internal::Internals I;
7464 O* obj = *reinterpret_cast<O* const*>(this);
7465 if (!I::HasHeapObjectTag(obj)) return false;
7466 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7467 return (I::GetOddballKind(obj) == I::kNullOddballKind);
7471 bool Value::IsString() const {
7472 #ifdef V8_ENABLE_CHECKS
7473 return FullIsString();
7475 return QuickIsString();
7479 bool Value::QuickIsString() const {
7480 typedef internal::Object O;
7481 typedef internal::Internals I;
7482 O* obj = *reinterpret_cast<O* const*>(this);
7483 if (!I::HasHeapObjectTag(obj)) return false;
7484 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7488 template <class T> Value* Value::Cast(T* value) {
7489 return static_cast<Value*>(value);
7493 Local<Boolean> Value::ToBoolean() const {
7494 return ToBoolean(Isolate::GetCurrent());
7498 Local<Number> Value::ToNumber() const {
7499 return ToNumber(Isolate::GetCurrent());
7503 Local<String> Value::ToString() const {
7504 return ToString(Isolate::GetCurrent());
7508 Local<String> Value::ToDetailString() const {
7509 return ToDetailString(Isolate::GetCurrent());
7513 Local<Object> Value::ToObject() const {
7514 return ToObject(Isolate::GetCurrent());
7518 Local<Integer> Value::ToInteger() const {
7519 return ToInteger(Isolate::GetCurrent());
7523 Local<Uint32> Value::ToUint32() const {
7524 return ToUint32(Isolate::GetCurrent());
7528 Local<Int32> Value::ToInt32() const { return ToInt32(Isolate::GetCurrent()); }
7531 Boolean* Boolean::Cast(v8::Value* value) {
7532 #ifdef V8_ENABLE_CHECKS
7535 return static_cast<Boolean*>(value);
7539 Name* Name::Cast(v8::Value* value) {
7540 #ifdef V8_ENABLE_CHECKS
7543 return static_cast<Name*>(value);
7547 Symbol* Symbol::Cast(v8::Value* value) {
7548 #ifdef V8_ENABLE_CHECKS
7551 return static_cast<Symbol*>(value);
7555 Number* Number::Cast(v8::Value* value) {
7556 #ifdef V8_ENABLE_CHECKS
7559 return static_cast<Number*>(value);
7563 Integer* Integer::Cast(v8::Value* value) {
7564 #ifdef V8_ENABLE_CHECKS
7567 return static_cast<Integer*>(value);
7571 Int32* Int32::Cast(v8::Value* value) {
7572 #ifdef V8_ENABLE_CHECKS
7575 return static_cast<Int32*>(value);
7579 Uint32* Uint32::Cast(v8::Value* value) {
7580 #ifdef V8_ENABLE_CHECKS
7583 return static_cast<Uint32*>(value);
7587 Date* Date::Cast(v8::Value* value) {
7588 #ifdef V8_ENABLE_CHECKS
7591 return static_cast<Date*>(value);
7595 StringObject* StringObject::Cast(v8::Value* value) {
7596 #ifdef V8_ENABLE_CHECKS
7599 return static_cast<StringObject*>(value);
7603 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7604 #ifdef V8_ENABLE_CHECKS
7607 return static_cast<SymbolObject*>(value);
7611 NumberObject* NumberObject::Cast(v8::Value* value) {
7612 #ifdef V8_ENABLE_CHECKS
7615 return static_cast<NumberObject*>(value);
7619 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7620 #ifdef V8_ENABLE_CHECKS
7623 return static_cast<BooleanObject*>(value);
7627 RegExp* RegExp::Cast(v8::Value* value) {
7628 #ifdef V8_ENABLE_CHECKS
7631 return static_cast<RegExp*>(value);
7635 Object* Object::Cast(v8::Value* value) {
7636 #ifdef V8_ENABLE_CHECKS
7639 return static_cast<Object*>(value);
7643 Array* Array::Cast(v8::Value* value) {
7644 #ifdef V8_ENABLE_CHECKS
7647 return static_cast<Array*>(value);
7651 Promise* Promise::Cast(v8::Value* value) {
7652 #ifdef V8_ENABLE_CHECKS
7655 return static_cast<Promise*>(value);
7659 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7660 #ifdef V8_ENABLE_CHECKS
7663 return static_cast<Promise::Resolver*>(value);
7667 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7668 #ifdef V8_ENABLE_CHECKS
7671 return static_cast<ArrayBuffer*>(value);
7675 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7676 #ifdef V8_ENABLE_CHECKS
7679 return static_cast<ArrayBufferView*>(value);
7683 TypedArray* TypedArray::Cast(v8::Value* value) {
7684 #ifdef V8_ENABLE_CHECKS
7687 return static_cast<TypedArray*>(value);
7691 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7692 #ifdef V8_ENABLE_CHECKS
7695 return static_cast<Uint8Array*>(value);
7699 Int8Array* Int8Array::Cast(v8::Value* value) {
7700 #ifdef V8_ENABLE_CHECKS
7703 return static_cast<Int8Array*>(value);
7707 Uint16Array* Uint16Array::Cast(v8::Value* value) {
7708 #ifdef V8_ENABLE_CHECKS
7711 return static_cast<Uint16Array*>(value);
7715 Int16Array* Int16Array::Cast(v8::Value* value) {
7716 #ifdef V8_ENABLE_CHECKS
7719 return static_cast<Int16Array*>(value);
7723 Uint32Array* Uint32Array::Cast(v8::Value* value) {
7724 #ifdef V8_ENABLE_CHECKS
7727 return static_cast<Uint32Array*>(value);
7731 Int32Array* Int32Array::Cast(v8::Value* value) {
7732 #ifdef V8_ENABLE_CHECKS
7735 return static_cast<Int32Array*>(value);
7739 Float32Array* Float32Array::Cast(v8::Value* value) {
7740 #ifdef V8_ENABLE_CHECKS
7743 return static_cast<Float32Array*>(value);
7747 Float64Array* Float64Array::Cast(v8::Value* value) {
7748 #ifdef V8_ENABLE_CHECKS
7751 return static_cast<Float64Array*>(value);
7755 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
7756 #ifdef V8_ENABLE_CHECKS
7759 return static_cast<Uint8ClampedArray*>(value);
7763 DataView* DataView::Cast(v8::Value* value) {
7764 #ifdef V8_ENABLE_CHECKS
7767 return static_cast<DataView*>(value);
7771 Function* Function::Cast(v8::Value* value) {
7772 #ifdef V8_ENABLE_CHECKS
7775 return static_cast<Function*>(value);
7779 External* External::Cast(v8::Value* value) {
7780 #ifdef V8_ENABLE_CHECKS
7783 return static_cast<External*>(value);
7787 template<typename T>
7788 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
7789 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
7793 template<typename T>
7794 Local<Value> PropertyCallbackInfo<T>::Data() const {
7795 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
7799 template<typename T>
7800 Local<Object> PropertyCallbackInfo<T>::This() const {
7801 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
7805 template<typename T>
7806 Local<Object> PropertyCallbackInfo<T>::Holder() const {
7807 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
7811 template<typename T>
7812 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
7813 return ReturnValue<T>(&args_[kReturnValueIndex]);
7817 Handle<Primitive> Undefined(Isolate* isolate) {
7818 typedef internal::Object* S;
7819 typedef internal::Internals I;
7820 I::CheckInitialized(isolate);
7821 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
7822 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
7826 Handle<Primitive> Null(Isolate* isolate) {
7827 typedef internal::Object* S;
7828 typedef internal::Internals I;
7829 I::CheckInitialized(isolate);
7830 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
7831 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
7835 Handle<Boolean> True(Isolate* isolate) {
7836 typedef internal::Object* S;
7837 typedef internal::Internals I;
7838 I::CheckInitialized(isolate);
7839 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
7840 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
7844 Handle<Boolean> False(Isolate* isolate) {
7845 typedef internal::Object* S;
7846 typedef internal::Internals I;
7847 I::CheckInitialized(isolate);
7848 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
7849 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
7853 void Isolate::SetData(uint32_t slot, void* data) {
7854 typedef internal::Internals I;
7855 I::SetEmbedderData(this, slot, data);
7859 void* Isolate::GetData(uint32_t slot) {
7860 typedef internal::Internals I;
7861 return I::GetEmbedderData(this, slot);
7865 uint32_t Isolate::GetNumberOfDataSlots() {
7866 typedef internal::Internals I;
7867 return I::kNumIsolateDataSlots;
7871 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
7872 int64_t change_in_bytes) {
7873 typedef internal::Internals I;
7874 int64_t* amount_of_external_allocated_memory =
7875 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
7876 I::kAmountOfExternalAllocatedMemoryOffset);
7877 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
7878 reinterpret_cast<int64_t*>(
7879 reinterpret_cast<uint8_t*>(this) +
7880 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
7881 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
7882 if (change_in_bytes > 0 &&
7883 amount - *amount_of_external_allocated_memory_at_last_global_gc >
7884 I::kExternalAllocationLimit) {
7885 CollectAllGarbage("external memory allocation limit reached.");
7887 *amount_of_external_allocated_memory = amount;
7888 return *amount_of_external_allocated_memory;
7892 template<typename T>
7893 void Isolate::SetObjectGroupId(const Persistent<T>& object,
7895 TYPE_CHECK(Value, T);
7896 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
7900 template<typename T>
7901 void Isolate::SetReferenceFromGroup(UniqueId id,
7902 const Persistent<T>& object) {
7903 TYPE_CHECK(Value, T);
7904 SetReferenceFromGroup(id,
7905 reinterpret_cast<v8::internal::Object**>(object.val_));
7909 template<typename T, typename S>
7910 void Isolate::SetReference(const Persistent<T>& parent,
7911 const Persistent<S>& child) {
7912 TYPE_CHECK(Object, T);
7913 TYPE_CHECK(Value, S);
7914 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
7915 reinterpret_cast<v8::internal::Object**>(child.val_));
7919 Local<Value> Context::GetEmbedderData(int index) {
7920 #ifndef V8_ENABLE_CHECKS
7921 typedef internal::Object O;
7922 typedef internal::HeapObject HO;
7923 typedef internal::Internals I;
7924 HO* context = *reinterpret_cast<HO**>(this);
7926 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
7927 return Local<Value>(reinterpret_cast<Value*>(result));
7929 return SlowGetEmbedderData(index);
7934 void* Context::GetAlignedPointerFromEmbedderData(int index) {
7935 #ifndef V8_ENABLE_CHECKS
7936 typedef internal::Internals I;
7937 return I::ReadEmbedderData<void*>(this, index);
7939 return SlowGetAlignedPointerFromEmbedderData(index);
7944 void V8::SetAllowCodeGenerationFromStringsCallback(
7945 AllowCodeGenerationFromStringsCallback callback) {
7946 Isolate* isolate = Isolate::GetCurrent();
7947 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
7952 Isolate* isolate = Isolate::GetCurrent();
7953 return isolate->IsDead();
7957 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
7958 Isolate* isolate = Isolate::GetCurrent();
7959 return isolate->AddMessageListener(that, data);
7963 void V8::RemoveMessageListeners(MessageCallback that) {
7964 Isolate* isolate = Isolate::GetCurrent();
7965 isolate->RemoveMessageListeners(that);
7969 void V8::SetFailedAccessCheckCallbackFunction(
7970 FailedAccessCheckCallback callback) {
7971 Isolate* isolate = Isolate::GetCurrent();
7972 isolate->SetFailedAccessCheckCallbackFunction(callback);
7976 void V8::SetCaptureStackTraceForUncaughtExceptions(
7977 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
7978 Isolate* isolate = Isolate::GetCurrent();
7979 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
7984 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
7985 Isolate* isolate = Isolate::GetCurrent();
7986 isolate->SetFatalErrorHandler(callback);
7990 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
7991 Isolate* isolate = Isolate::GetCurrent();
7992 isolate->RemoveGCPrologueCallback(
7993 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
7997 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
7998 Isolate* isolate = Isolate::GetCurrent();
7999 isolate->RemoveGCEpilogueCallback(
8000 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
8004 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8006 AllocationAction action) {
8007 Isolate* isolate = Isolate::GetCurrent();
8008 isolate->AddMemoryAllocationCallback(callback, space, action);
8012 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8013 Isolate* isolate = Isolate::GetCurrent();
8014 isolate->RemoveMemoryAllocationCallback(callback);
8018 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8021 bool V8::IsExecutionTerminating(Isolate* isolate) {
8022 if (isolate == NULL) {
8023 isolate = Isolate::GetCurrent();
8025 return isolate->IsExecutionTerminating();
8029 void V8::CancelTerminateExecution(Isolate* isolate) {
8030 isolate->CancelTerminateExecution();
8034 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8035 Isolate* isolate = Isolate::GetCurrent();
8036 isolate->VisitExternalResources(visitor);
8040 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8041 Isolate* isolate = Isolate::GetCurrent();
8042 isolate->VisitHandlesWithClassIds(visitor);
8046 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8047 PersistentHandleVisitor* visitor) {
8048 isolate->VisitHandlesWithClassIds(visitor);
8052 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8053 PersistentHandleVisitor* visitor) {
8054 isolate->VisitHandlesForPartialDependence(visitor);
8059 * A simple shell that takes a list of expressions on the
8060 * command-line and executes them.
8065 * \example process.cc