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;
97 class SharedArrayBuffer;
109 template <class T> class Local;
112 template <class T> class Eternal;
113 template<class T> class NonCopyablePersistentTraits;
114 template<class T> class PersistentBase;
116 class M = NonCopyablePersistentTraits<T> > class Persistent;
119 template<class K, class V, class T> class PersistentValueMap;
120 template <class K, class V, class T>
121 class PersistentValueMapBase;
122 template <class K, class V, class T>
123 class GlobalValueMap;
124 template<class V, class T> class PersistentValueVector;
125 template<class T, class P> class WeakCallbackObject;
126 class FunctionTemplate;
127 class ObjectTemplate;
129 template<typename T> class FunctionCallbackInfo;
130 template<typename T> class PropertyCallbackInfo;
134 class CallHandlerHelper;
135 class EscapableHandleScope;
136 template<typename T> class ReturnValue;
144 struct StreamedSource;
145 template<typename T> class CustomArguments;
146 class PropertyCallbackArguments;
147 class FunctionCallbackArguments;
153 * General purpose unique identifier.
157 explicit UniqueId(intptr_t data)
160 bool operator==(const UniqueId& other) const {
161 return data_ == other.data_;
164 bool operator!=(const UniqueId& other) const {
165 return data_ != other.data_;
168 bool operator<(const UniqueId& other) const {
169 return data_ < other.data_;
178 #define TYPE_CHECK(T, S) \
180 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
185 * An object reference managed by the v8 garbage collector.
187 * All objects returned from v8 have to be tracked by the garbage
188 * collector so that it knows that the objects are still alive. Also,
189 * because the garbage collector may move objects, it is unsafe to
190 * point directly to an object. Instead, all objects are stored in
191 * handles which are known by the garbage collector and updated
192 * whenever an object moves. Handles should always be passed by value
193 * (except in cases like out-parameters) and they should never be
194 * allocated on the heap.
196 * There are two types of handles: local and persistent handles.
197 * Local handles are light-weight and transient and typically used in
198 * local operations. They are managed by HandleScopes. Persistent
199 * handles can be used when storing objects across several independent
200 * operations and have to be explicitly deallocated when they're no
203 * It is safe to extract the object stored in the handle by
204 * dereferencing the handle (for instance, to extract the Object* from
205 * a Local<Object>); the value will still be governed by a handle
206 * behind the scenes and the same rules apply to these values as to
212 V8_INLINE Local() : val_(0) {}
214 V8_INLINE Local(Local<S> that)
215 : val_(reinterpret_cast<T*>(*that)) {
217 * This check fails when trying to convert between incompatible
218 * handles. For example, converting from a Local<String> to a
225 * Returns true if the handle is empty.
227 V8_INLINE bool IsEmpty() const { return val_ == 0; }
230 * Sets the handle to be empty. IsEmpty() will then return true.
232 V8_INLINE void Clear() { val_ = 0; }
234 V8_INLINE T* operator->() const { return val_; }
236 V8_INLINE T* operator*() const { return val_; }
239 * Checks whether two handles are the same.
240 * Returns true if both are empty, or if the objects
241 * to which they refer are identical.
242 * The handles' references are not checked.
245 V8_INLINE bool operator==(const Local<S>& that) const {
246 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
247 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
248 if (a == 0) return b == 0;
249 if (b == 0) return false;
253 template <class S> V8_INLINE bool operator==(
254 const PersistentBase<S>& that) const {
255 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
256 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
257 if (a == 0) return b == 0;
258 if (b == 0) return false;
263 * Checks whether two handles are different.
264 * Returns true if only one of the handles is empty, or if
265 * the objects to which they refer are different.
266 * The handles' references are not checked.
269 V8_INLINE bool operator!=(const Local<S>& that) const {
270 return !operator==(that);
273 template <class S> V8_INLINE bool operator!=(
274 const Persistent<S>& that) const {
275 return !operator==(that);
278 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
279 #ifdef V8_ENABLE_CHECKS
280 // If we're going to perform the type check then we have to check
281 // that the handle isn't empty before doing the checked cast.
282 if (that.IsEmpty()) return Local<T>();
284 return Local<T>(T::Cast(*that));
288 template <class S> V8_INLINE Local<S> As() {
289 return Local<S>::Cast(*this);
293 * Create a local handle for the content of another handle.
294 * The referee is kept alive by the local handle even when
295 * the original handle is destroyed/disposed.
297 V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
298 V8_INLINE static Local<T> New(Isolate* isolate,
299 const PersistentBase<T>& that);
303 template<class F> friend class Eternal;
304 template<class F> friend class PersistentBase;
305 template<class F, class M> friend class Persistent;
306 template<class F> friend class Local;
308 friend class MaybeLocal;
309 template<class F> friend class FunctionCallbackInfo;
310 template<class F> friend class PropertyCallbackInfo;
313 friend class Context;
314 template<class F> friend class internal::CustomArguments;
315 friend Local<Primitive> Undefined(Isolate* isolate);
316 friend Local<Primitive> Null(Isolate* isolate);
317 friend Local<Boolean> True(Isolate* isolate);
318 friend Local<Boolean> False(Isolate* isolate);
319 friend class HandleScope;
320 friend class EscapableHandleScope;
321 template <class F1, class F2, class F3>
322 friend class PersistentValueMapBase;
323 template<class F1, class F2> friend class PersistentValueVector;
326 V8_INLINE Local(S* that)
328 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
333 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
334 // Local is an alias for Local for historical reasons.
336 using Handle = Local<T>;
341 * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
342 * the Local<> is empty before it can be used.
344 * If an API method returns a MaybeLocal<>, the API method can potentially fail
345 * either because an exception is thrown, or because an exception is pending,
346 * e.g. because a previous API call threw an exception that hasn't been caught
347 * yet, or because a TerminateExecution exception was thrown. In that case, an
348 * empty MaybeLocal is returned.
353 V8_INLINE MaybeLocal() : val_(nullptr) {}
355 V8_INLINE MaybeLocal(Local<S> that)
356 : val_(reinterpret_cast<T*>(*that)) {
360 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
363 V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
364 out->val_ = IsEmpty() ? nullptr : this->val_;
368 // Will crash if the MaybeLocal<> is empty.
369 V8_INLINE Local<T> ToLocalChecked();
372 V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
373 return IsEmpty() ? default_value : Local<S>(val_);
381 // Eternal handles are set-once handles that live for the life of the isolate.
382 template <class T> class Eternal {
384 V8_INLINE Eternal() : index_(kInitialValue) { }
386 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
387 Set(isolate, handle);
389 // Can only be safely called if already set.
390 V8_INLINE Local<T> Get(Isolate* isolate);
391 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
392 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
395 static const int kInitialValue = -1;
400 static const int kInternalFieldsInWeakCallback = 2;
403 template <typename T>
404 class WeakCallbackInfo {
406 typedef void (*Callback)(const WeakCallbackInfo<T>& data);
408 WeakCallbackInfo(Isolate* isolate, T* parameter,
409 void* internal_fields[kInternalFieldsInWeakCallback],
411 : isolate_(isolate), parameter_(parameter), callback_(callback) {
412 for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) {
413 internal_fields_[i] = internal_fields[i];
417 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
418 V8_INLINE T* GetParameter() const { return parameter_; }
419 V8_INLINE void* GetInternalField(int index) const;
421 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
422 void* GetInternalField1() const) {
423 return internal_fields_[0];
425 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
426 void* GetInternalField2() const) {
427 return internal_fields_[1];
430 bool IsFirstPass() const { return callback_ != nullptr; }
432 // When first called, the embedder MUST Reset() the Global which triggered the
433 // callback. The Global itself is unusable for anything else. No v8 other api
434 // calls may be called in the first callback. Should additional work be
435 // required, the embedder must set a second pass callback, which will be
436 // called after all the initial callbacks are processed.
437 // Calling SetSecondPassCallback on the second pass will immediately crash.
438 void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
444 void* internal_fields_[kInternalFieldsInWeakCallback];
448 template <class T, class P>
449 class WeakCallbackData {
451 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
453 WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
454 : isolate_(isolate), parameter_(parameter), handle_(handle) {}
456 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
457 V8_INLINE P* GetParameter() const { return parameter_; }
458 V8_INLINE Local<T> GetValue() const { return handle_; }
467 // TODO(dcarney): delete this with WeakCallbackData
469 using PhantomCallbackData = WeakCallbackInfo<T>;
472 enum class WeakCallbackType { kParameter, kInternalFields };
476 * An object reference that is independent of any handle scope. Where
477 * a Local handle only lives as long as the HandleScope in which it was
478 * allocated, a PersistentBase handle remains valid until it is explicitly
481 * A persistent handle contains a reference to a storage cell within
482 * the v8 engine which holds an object value and which is updated by
483 * the garbage collector whenever the object is moved. A new storage
484 * cell can be created using the constructor or PersistentBase::Reset and
485 * existing handles can be disposed using PersistentBase::Reset.
488 template <class T> class PersistentBase {
491 * If non-empty, destroy the underlying storage cell
492 * IsEmpty() will return true after this call.
494 V8_INLINE void Reset();
496 * If non-empty, destroy the underlying storage cell
497 * and create a new one with the contents of other if other is non empty
500 V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
503 * If non-empty, destroy the underlying storage cell
504 * and create a new one with the contents of other if other is non empty
507 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
509 V8_INLINE bool IsEmpty() const { return val_ == NULL; }
510 V8_INLINE void Empty() { val_ = 0; }
513 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
514 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
515 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
516 if (a == NULL) return b == NULL;
517 if (b == NULL) return false;
522 V8_INLINE bool operator==(const Local<S>& that) const {
523 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
524 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
525 if (a == NULL) return b == NULL;
526 if (b == NULL) return false;
531 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
532 return !operator==(that);
536 V8_INLINE bool operator!=(const Local<S>& that) const {
537 return !operator==(that);
541 * Install a finalization callback on this object.
542 * NOTE: There is no guarantee as to *when* or even *if* the callback is
543 * invoked. The invocation is performed solely on a best effort basis.
544 * As always, GC-based finalization should *not* be relied upon for any
545 * critical form of resource management!
547 template <typename P>
548 V8_INLINE V8_DEPRECATE_SOON(
549 "use WeakCallbackInfo version",
550 void SetWeak(P* parameter,
551 typename WeakCallbackData<T, P>::Callback callback));
553 template <typename S, typename P>
554 V8_INLINE V8_DEPRECATE_SOON(
555 "use WeakCallbackInfo version",
556 void SetWeak(P* parameter,
557 typename WeakCallbackData<S, P>::Callback callback));
559 // Phantom persistents work like weak persistents, except that the pointer to
560 // the object being collected is not available in the finalization callback.
561 // This enables the garbage collector to collect the object and any objects
562 // it references transitively in one GC cycle. At the moment you can either
563 // specify a parameter for the callback or the location of two internal
564 // fields in the dying object.
565 template <typename P>
566 V8_INLINE V8_DEPRECATE_SOON(
568 void SetPhantom(P* parameter,
569 typename WeakCallbackInfo<P>::Callback callback,
570 int internal_field_index1 = -1,
571 int internal_field_index2 = -1));
573 template <typename P>
574 V8_INLINE void SetWeak(P* parameter,
575 typename WeakCallbackInfo<P>::Callback callback,
576 WeakCallbackType type);
579 V8_INLINE P* ClearWeak();
581 // TODO(dcarney): remove this.
582 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
585 * Marks the reference to this object independent. Garbage collector is free
586 * to ignore any object groups containing this object. Weak callback for an
587 * independent handle should not assume that it will be preceded by a global
588 * GC prologue callback or followed by a global GC epilogue callback.
590 V8_INLINE void MarkIndependent();
593 * Marks the reference to this object partially dependent. Partially dependent
594 * handles only depend on other partially dependent handles and these
595 * dependencies are provided through object groups. It provides a way to build
596 * smaller object groups for young objects that represent only a subset of all
597 * external dependencies. This mark is automatically cleared after each
598 * garbage collection.
600 V8_INLINE void MarkPartiallyDependent();
602 V8_INLINE bool IsIndependent() const;
604 /** Checks if the handle holds the only reference to an object. */
605 V8_INLINE bool IsNearDeath() const;
607 /** Returns true if the handle's reference is weak. */
608 V8_INLINE bool IsWeak() const;
611 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
612 * description in v8-profiler.h for details.
614 V8_INLINE void SetWrapperClassId(uint16_t class_id);
617 * Returns the class ID previously assigned to this handle or 0 if no class ID
618 * was previously assigned.
620 V8_INLINE uint16_t WrapperClassId() const;
623 friend class Isolate;
625 template<class F> friend class Local;
626 template<class F1, class F2> friend class Persistent;
629 template<class F> friend class PersistentBase;
630 template<class F> friend class ReturnValue;
631 template <class F1, class F2, class F3>
632 friend class PersistentValueMapBase;
633 template<class F1, class F2> friend class PersistentValueVector;
636 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
637 PersistentBase(PersistentBase& other) = delete; // NOLINT
638 void operator=(PersistentBase&) = delete;
639 V8_INLINE static T* New(Isolate* isolate, T* that);
646 * Default traits for Persistent. This class does not allow
647 * use of the copy constructor or assignment operator.
648 * At present kResetInDestructor is not set, but that will change in a future
652 class NonCopyablePersistentTraits {
654 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
655 static const bool kResetInDestructor = false;
656 template<class S, class M>
657 V8_INLINE static void Copy(const Persistent<S, M>& source,
658 NonCopyablePersistent* dest) {
659 Uncompilable<Object>();
661 // TODO(dcarney): come up with a good compile error here.
662 template<class O> V8_INLINE static void Uncompilable() {
663 TYPE_CHECK(O, Primitive);
669 * Helper class traits to allow copying and assignment of Persistent.
670 * This will clone the contents of storage cell, but not any of the flags, etc.
673 struct CopyablePersistentTraits {
674 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
675 static const bool kResetInDestructor = true;
676 template<class S, class M>
677 static V8_INLINE void Copy(const Persistent<S, M>& source,
678 CopyablePersistent* dest) {
679 // do nothing, just allow copy
685 * A PersistentBase which allows copy and assignment.
687 * Copy, assignment and destructor bevavior is controlled by the traits
690 * Note: Persistent class hierarchy is subject to future changes.
692 template <class T, class M> class Persistent : public PersistentBase<T> {
695 * A Persistent with no storage cell.
697 V8_INLINE Persistent() : PersistentBase<T>(0) { }
699 * Construct a Persistent from a Local.
700 * When the Local is non-empty, a new storage cell is created
701 * pointing to the same object, and no flags are set.
704 V8_INLINE Persistent(Isolate* isolate, Local<S> that)
705 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
709 * Construct a Persistent from a Persistent.
710 * When the Persistent is non-empty, a new storage cell is created
711 * pointing to the same object, and no flags are set.
713 template <class S, class M2>
714 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
715 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
719 * The copy constructors and assignment operator create a Persistent
720 * exactly as the Persistent constructor, but the Copy function from the
721 * traits class is called, allowing the setting of flags based on the
724 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
727 template <class S, class M2>
728 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
731 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
735 template <class S, class M2>
736 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
741 * The destructor will dispose the Persistent based on the
742 * kResetInDestructor flags in the traits class. Since not calling dispose
743 * can result in a memory leak, it is recommended to always set this flag.
745 V8_INLINE ~Persistent() {
746 if (M::kResetInDestructor) this->Reset();
749 // TODO(dcarney): this is pretty useless, fix or remove
751 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
752 #ifdef V8_ENABLE_CHECKS
753 // If we're going to perform the type check then we have to check
754 // that the handle isn't empty before doing the checked cast.
755 if (!that.IsEmpty()) T::Cast(*that);
757 return reinterpret_cast<Persistent<T>&>(that);
760 // TODO(dcarney): this is pretty useless, fix or remove
761 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
762 return Persistent<S>::Cast(*this);
766 friend class Isolate;
768 template<class F> friend class Local;
769 template<class F1, class F2> friend class Persistent;
770 template<class F> friend class ReturnValue;
772 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
773 V8_INLINE T* operator*() const { return this->val_; }
774 template<class S, class M2>
775 V8_INLINE void Copy(const Persistent<S, M2>& that);
780 * A PersistentBase which has move semantics.
782 * Note: Persistent class hierarchy is subject to future changes.
785 class Global : public PersistentBase<T> {
788 * A Global with no storage cell.
790 V8_INLINE Global() : PersistentBase<T>(nullptr) {}
792 * Construct a Global from a Local.
793 * When the Local is non-empty, a new storage cell is created
794 * pointing to the same object, and no flags are set.
797 V8_INLINE Global(Isolate* isolate, Local<S> that)
798 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
802 * Construct a Global from a PersistentBase.
803 * When the Persistent is non-empty, a new storage cell is created
804 * pointing to the same object, and no flags are set.
807 V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
808 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
814 V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) {
815 other.val_ = nullptr;
817 V8_INLINE ~Global() { this->Reset(); }
819 * Move via assignment.
822 V8_INLINE Global& operator=(Global<S>&& rhs) {
826 this->val_ = rhs.val_;
832 * Pass allows returning uniques from functions, etc.
834 Global Pass() { return static_cast<Global&&>(*this); }
837 * For compatibility with Chromium's base::Bind (base::Passed).
839 typedef void MoveOnlyTypeForCPP03;
843 friend class ReturnValue;
844 Global(Global&) = delete;
845 void operator=(Global&) = delete;
846 V8_INLINE T* operator*() const { return this->val_; }
850 // UniquePersistent is an alias for Global for historical reason.
852 using UniquePersistent = Global<T>;
856 * A stack-allocated class that governs a number of local handles.
857 * After a handle scope has been created, all local handles will be
858 * allocated within that handle scope until either the handle scope is
859 * deleted or another handle scope is created. If there is already a
860 * handle scope and a new one is created, all allocations will take
861 * place in the new handle scope until it is deleted. After that,
862 * new handles will again be allocated in the original handle scope.
864 * After the handle scope of a local handle has been deleted the
865 * garbage collector will no longer track the object stored in the
866 * handle and may deallocate it. The behavior of accessing a handle
867 * for which the handle scope has been deleted is undefined.
869 class V8_EXPORT HandleScope {
871 HandleScope(Isolate* isolate);
876 * Counts the number of allocated handles.
878 static int NumberOfHandles(Isolate* isolate);
880 V8_INLINE Isolate* GetIsolate() const {
881 return reinterpret_cast<Isolate*>(isolate_);
885 V8_INLINE HandleScope() {}
887 void Initialize(Isolate* isolate);
889 static internal::Object** CreateHandle(internal::Isolate* isolate,
890 internal::Object* value);
893 // Uses heap_object to obtain the current Isolate.
894 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
895 internal::Object* value);
897 // Make it hard to create heap-allocated or illegal handle scopes by
898 // disallowing certain operations.
899 HandleScope(const HandleScope&);
900 void operator=(const HandleScope&);
901 void* operator new(size_t size);
902 void operator delete(void*, size_t);
904 internal::Isolate* isolate_;
905 internal::Object** prev_next_;
906 internal::Object** prev_limit_;
908 // Local::New uses CreateHandle with an Isolate* parameter.
909 template<class F> friend class Local;
911 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
912 // a HeapObject* in their shortcuts.
914 friend class Context;
919 * A HandleScope which first allocates a handle in the current scope
920 * which will be later filled with the escape value.
922 class V8_EXPORT EscapableHandleScope : public HandleScope {
924 EscapableHandleScope(Isolate* isolate);
925 V8_INLINE ~EscapableHandleScope() {}
928 * Pushes the value into the previous scope and returns a handle to it.
929 * Cannot be called twice.
932 V8_INLINE Local<T> Escape(Local<T> value) {
933 internal::Object** slot =
934 Escape(reinterpret_cast<internal::Object**>(*value));
935 return Local<T>(reinterpret_cast<T*>(slot));
939 internal::Object** Escape(internal::Object** escape_value);
941 // Make it hard to create heap-allocated or illegal handle scopes by
942 // disallowing certain operations.
943 EscapableHandleScope(const EscapableHandleScope&);
944 void operator=(const EscapableHandleScope&);
945 void* operator new(size_t size);
946 void operator delete(void*, size_t);
948 internal::Object** escape_slot_;
951 class V8_EXPORT SealHandleScope {
953 SealHandleScope(Isolate* isolate);
957 // Make it hard to create heap-allocated or illegal handle scopes by
958 // disallowing certain operations.
959 SealHandleScope(const SealHandleScope&);
960 void operator=(const SealHandleScope&);
961 void* operator new(size_t size);
962 void operator delete(void*, size_t);
964 internal::Isolate* isolate_;
966 internal::Object** prev_limit_;
970 // --- Special objects ---
974 * The superclass of values and API object templates.
976 class V8_EXPORT Data {
983 * The optional attributes of ScriptOrigin.
985 class ScriptOriginOptions {
987 V8_INLINE ScriptOriginOptions(bool is_embedder_debug_script = false,
988 bool is_shared_cross_origin = false,
989 bool is_opaque = false)
990 : flags_((is_embedder_debug_script ? kIsEmbedderDebugScript : 0) |
991 (is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
992 (is_opaque ? kIsOpaque : 0)) {}
993 V8_INLINE ScriptOriginOptions(int flags)
995 (kIsEmbedderDebugScript | kIsSharedCrossOrigin | kIsOpaque)) {}
996 bool IsEmbedderDebugScript() const {
997 return (flags_ & kIsEmbedderDebugScript) != 0;
999 bool IsSharedCrossOrigin() const {
1000 return (flags_ & kIsSharedCrossOrigin) != 0;
1002 bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1003 int Flags() const { return flags_; }
1007 kIsEmbedderDebugScript = 1,
1008 kIsSharedCrossOrigin = 1 << 1,
1015 * The origin, within a file, of a script.
1017 class ScriptOrigin {
1019 V8_INLINE ScriptOrigin(
1020 Local<Value> resource_name,
1021 Local<Integer> resource_line_offset = Local<Integer>(),
1022 Local<Integer> resource_column_offset = Local<Integer>(),
1023 Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1024 Local<Integer> script_id = Local<Integer>(),
1025 Local<Boolean> resource_is_embedder_debug_script = Local<Boolean>(),
1026 Local<Value> source_map_url = Local<Value>(),
1027 Local<Boolean> resource_is_opaque = Local<Boolean>());
1028 V8_INLINE Local<Value> ResourceName() const;
1029 V8_INLINE Local<Integer> ResourceLineOffset() const;
1030 V8_INLINE Local<Integer> ResourceColumnOffset() const;
1032 * Returns true for embedder's debugger scripts
1034 V8_INLINE Local<Integer> ScriptID() const;
1035 V8_INLINE Local<Value> SourceMapUrl() const;
1036 V8_INLINE ScriptOriginOptions Options() const { return options_; }
1039 Local<Value> resource_name_;
1040 Local<Integer> resource_line_offset_;
1041 Local<Integer> resource_column_offset_;
1042 ScriptOriginOptions options_;
1043 Local<Integer> script_id_;
1044 Local<Value> source_map_url_;
1049 * A compiled JavaScript script, not yet tied to a Context.
1051 class V8_EXPORT UnboundScript {
1054 * Binds the script to the currently entered context.
1056 Local<Script> BindToCurrentContext();
1059 Local<Value> GetScriptName();
1062 * Data read from magic sourceURL comments.
1064 Local<Value> GetSourceURL();
1066 * Data read from magic sourceMappingURL comments.
1068 Local<Value> GetSourceMappingURL();
1071 * Returns zero based line number of the code_pos location in the script.
1072 * -1 will be returned if no information available.
1074 int GetLineNumber(int code_pos);
1076 static const int kNoScriptId = 0;
1081 * A compiled JavaScript script, tied to a Context which was active when the
1082 * script was compiled.
1084 class V8_EXPORT Script {
1087 * A shorthand for ScriptCompiler::Compile().
1089 static V8_DEPRECATE_SOON(
1090 "Use maybe version",
1091 Local<Script> Compile(Local<String> source,
1092 ScriptOrigin* origin = nullptr));
1093 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1094 Local<Context> context, Local<String> source,
1095 ScriptOrigin* origin = nullptr);
1097 static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1098 Compile(Local<String> source,
1099 Local<String> file_name));
1102 * Runs the script returning the resulting value. It will be run in the
1103 * context in which it was created (ScriptCompiler::CompileBound or
1104 * UnboundScript::BindToCurrentContext()).
1106 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1107 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
1110 * Returns the corresponding context-unbound script.
1112 Local<UnboundScript> GetUnboundScript();
1114 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1116 return GetUnboundScript()->GetId();
1122 * For compiling scripts.
1124 class V8_EXPORT ScriptCompiler {
1127 * Compilation data that the embedder can cache and pass back to speed up
1128 * future compilations. The data is produced if the CompilerOptions passed to
1129 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1130 * = true. The data to cache can then can be retrieved from
1133 struct V8_EXPORT CachedData {
1143 buffer_policy(BufferNotOwned) {}
1145 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1146 // data and guarantees that it stays alive until the CachedData object is
1147 // destroyed. If the policy is BufferOwned, the given data will be deleted
1148 // (with delete[]) when the CachedData object is destroyed.
1149 CachedData(const uint8_t* data, int length,
1150 BufferPolicy buffer_policy = BufferNotOwned);
1152 // TODO(marja): Async compilation; add constructors which take a callback
1153 // which will be called when V8 no longer needs the data.
1154 const uint8_t* data;
1157 BufferPolicy buffer_policy;
1160 // Prevent copying. Not implemented.
1161 CachedData(const CachedData&);
1162 CachedData& operator=(const CachedData&);
1166 * Source code which can be then compiled to a UnboundScript or Script.
1170 // Source takes ownership of CachedData.
1171 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1172 CachedData* cached_data = NULL);
1173 V8_INLINE Source(Local<String> source_string,
1174 CachedData* cached_data = NULL);
1175 V8_INLINE ~Source();
1177 // Ownership of the CachedData or its buffers is *not* transferred to the
1178 // caller. The CachedData object is alive as long as the Source object is
1180 V8_INLINE const CachedData* GetCachedData() const;
1183 friend class ScriptCompiler;
1184 // Prevent copying. Not implemented.
1185 Source(const Source&);
1186 Source& operator=(const Source&);
1188 Local<String> source_string;
1190 // Origin information
1191 Local<Value> resource_name;
1192 Local<Integer> resource_line_offset;
1193 Local<Integer> resource_column_offset;
1194 ScriptOriginOptions resource_options;
1195 Local<Value> source_map_url;
1197 // Cached data from previous compilation (if a kConsume*Cache flag is
1198 // set), or hold newly generated cache data (kProduce*Cache flags) are
1199 // set when calling a compile method.
1200 CachedData* cached_data;
1204 * For streaming incomplete script data to V8. The embedder should implement a
1205 * subclass of this class.
1207 class V8_EXPORT ExternalSourceStream {
1209 virtual ~ExternalSourceStream() {}
1212 * V8 calls this to request the next chunk of data from the embedder. This
1213 * function will be called on a background thread, so it's OK to block and
1214 * wait for the data, if the embedder doesn't have data yet. Returns the
1215 * length of the data returned. When the data ends, GetMoreData should
1216 * return 0. Caller takes ownership of the data.
1218 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1219 * two data chunks, but doesn't handle multi-byte characters split between
1220 * more than two data chunks. The embedder can avoid this problem by always
1221 * returning at least 2 bytes of data.
1223 * If the embedder wants to cancel the streaming, they should make the next
1224 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1225 * probably, parsing will fail). The streaming task will return as soon as
1226 * V8 has parsed the data it received so far.
1228 virtual size_t GetMoreData(const uint8_t** src) = 0;
1231 * V8 calls this method to set a 'bookmark' at the current position in
1232 * the source stream, for the purpose of (maybe) later calling
1233 * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1234 * calls to GetMoreData should return the same data as they did when
1235 * SetBookmark was called earlier.
1237 * The embedder may return 'false' to indicate it cannot provide this
1240 virtual bool SetBookmark();
1243 * V8 calls this to return to a previously set bookmark.
1245 virtual void ResetToBookmark();
1250 * Source code which can be streamed into V8 in pieces. It will be parsed
1251 * while streaming. It can be compiled after the streaming is complete.
1252 * StreamedSource must be kept alive while the streaming task is ran (see
1253 * ScriptStreamingTask below).
1255 class V8_EXPORT StreamedSource {
1257 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1259 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1262 // Ownership of the CachedData or its buffers is *not* transferred to the
1263 // caller. The CachedData object is alive as long as the StreamedSource
1265 const CachedData* GetCachedData() const;
1267 internal::StreamedSource* impl() const { return impl_; }
1270 // Prevent copying. Not implemented.
1271 StreamedSource(const StreamedSource&);
1272 StreamedSource& operator=(const StreamedSource&);
1274 internal::StreamedSource* impl_;
1278 * A streaming task which the embedder must run on a background thread to
1279 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1281 class ScriptStreamingTask {
1283 virtual ~ScriptStreamingTask() {}
1284 virtual void Run() = 0;
1287 enum CompileOptions {
1288 kNoCompileOptions = 0,
1289 kProduceParserCache,
1290 kConsumeParserCache,
1296 * Compiles the specified script (context-independent).
1297 * Cached data as part of the source object can be optionally produced to be
1298 * consumed later to speed up compilation of identical source scripts.
1300 * Note that when producing cached data, the source must point to NULL for
1301 * cached data. When consuming cached data, the cached data must have been
1302 * produced by the same version of V8.
1304 * \param source Script source code.
1305 * \return Compiled script object (context independent; for running it must be
1306 * bound to a context).
1308 static V8_DEPRECATE_SOON("Use maybe version",
1309 Local<UnboundScript> CompileUnbound(
1310 Isolate* isolate, Source* source,
1311 CompileOptions options = kNoCompileOptions));
1312 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
1313 Isolate* isolate, Source* source,
1314 CompileOptions options = kNoCompileOptions);
1317 * Compiles the specified script (bound to current context).
1319 * \param source Script source code.
1320 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1321 * using pre_data speeds compilation if it's done multiple times.
1322 * Owned by caller, no references are kept when this function returns.
1323 * \return Compiled script object, bound to the context that was active
1324 * when this function was called. When run it will always use this
1327 static V8_DEPRECATE_SOON(
1328 "Use maybe version",
1329 Local<Script> Compile(Isolate* isolate, Source* source,
1330 CompileOptions options = kNoCompileOptions));
1331 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1332 Local<Context> context, Source* source,
1333 CompileOptions options = kNoCompileOptions);
1336 * Returns a task which streams script data into V8, or NULL if the script
1337 * cannot be streamed. The user is responsible for running the task on a
1338 * background thread and deleting it. When ran, the task starts parsing the
1339 * script, and it will request data from the StreamedSource as needed. When
1340 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1341 * can be compiled (see Compile below).
1343 * This API allows to start the streaming with as little data as possible, and
1344 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1346 static ScriptStreamingTask* StartStreamingScript(
1347 Isolate* isolate, StreamedSource* source,
1348 CompileOptions options = kNoCompileOptions);
1351 * Compiles a streamed script (bound to current context).
1353 * This can only be called after the streaming has finished
1354 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1355 * during streaming, so the embedder needs to pass the full source here.
1357 static V8_DEPRECATE_SOON(
1358 "Use maybe version",
1359 Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1360 Local<String> full_source_string,
1361 const ScriptOrigin& origin));
1362 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1363 Local<Context> context, StreamedSource* source,
1364 Local<String> full_source_string, const ScriptOrigin& origin);
1367 * Return a version tag for CachedData for the current V8 version & flags.
1369 * This value is meant only for determining whether a previously generated
1370 * CachedData instance is still valid; the tag has no other meaing.
1372 * Background: The data carried by CachedData may depend on the exact
1373 * V8 version number or currently compiler flags. This means when
1374 * persisting CachedData, the embedder must take care to not pass in
1375 * data from another V8 version, or the same version with different
1378 * The easiest way to do so is to clear the embedder's cache on any
1381 * Alternatively, this tag can be stored alongside the cached data and
1382 * compared when it is being used.
1384 static uint32_t CachedDataVersionTag();
1387 * Compile an ES6 module.
1389 * This is an experimental feature.
1391 * TODO(adamk): Script is likely the wrong return value for this;
1392 * should return some new Module type.
1394 static V8_DEPRECATE_SOON(
1395 "Use maybe version",
1396 Local<Script> CompileModule(Isolate* isolate, Source* source,
1397 CompileOptions options = kNoCompileOptions));
1398 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> CompileModule(
1399 Local<Context> context, Source* source,
1400 CompileOptions options = kNoCompileOptions);
1403 * Compile a function for a given context. This is equivalent to running
1406 * return function(args) { ... }
1409 * It is possible to specify multiple context extensions (obj in the above
1412 static V8_DEPRECATE_SOON("Use maybe version",
1413 Local<Function> CompileFunctionInContext(
1414 Isolate* isolate, Source* source,
1415 Local<Context> context, size_t arguments_count,
1416 Local<String> arguments[],
1417 size_t context_extension_count,
1418 Local<Object> context_extensions[]));
1419 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
1420 Local<Context> context, Source* source, size_t arguments_count,
1421 Local<String> arguments[], size_t context_extension_count,
1422 Local<Object> context_extensions[]);
1425 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1426 Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1433 class V8_EXPORT Message {
1435 Local<String> Get() const;
1437 V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1438 V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
1439 Local<Context> context) const;
1442 * Returns the origin for the script from where the function causing the
1445 ScriptOrigin GetScriptOrigin() const;
1448 * Returns the resource name for the script from where the function causing
1449 * the error originates.
1451 Local<Value> GetScriptResourceName() const;
1454 * Exception stack trace. By default stack traces are not captured for
1455 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1456 * to change this option.
1458 Local<StackTrace> GetStackTrace() const;
1461 * Returns the number, 1-based, of the line where the error occurred.
1463 V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1464 V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1467 * Returns the index within the script of the first character where
1468 * the error occurred.
1470 int GetStartPosition() const;
1473 * Returns the index within the script of the last character where
1474 * the error occurred.
1476 int GetEndPosition() const;
1479 * Returns the index within the line of the first character where
1480 * the error occurred.
1482 V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1483 V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1486 * Returns the index within the line of the last character where
1487 * the error occurred.
1489 V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn() const);
1490 V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1493 * Passes on the value set by the embedder when it fed the script from which
1494 * this Message was generated to V8.
1496 bool IsSharedCrossOrigin() const;
1497 bool IsOpaque() const;
1499 // TODO(1245381): Print to a string instead of on a FILE.
1500 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1502 static const int kNoLineNumberInfo = 0;
1503 static const int kNoColumnInfo = 0;
1504 static const int kNoScriptIdInfo = 0;
1509 * Representation of a JavaScript stack trace. The information collected is a
1510 * snapshot of the execution stack and the information remains valid after
1511 * execution continues.
1513 class V8_EXPORT StackTrace {
1516 * Flags that determine what information is placed captured for each
1517 * StackFrame when grabbing the current stack trace.
1519 enum StackTraceOptions {
1521 kColumnOffset = 1 << 1 | kLineNumber,
1522 kScriptName = 1 << 2,
1523 kFunctionName = 1 << 3,
1525 kIsConstructor = 1 << 5,
1526 kScriptNameOrSourceURL = 1 << 6,
1528 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1529 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1530 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1534 * Returns a StackFrame at a particular index.
1536 Local<StackFrame> GetFrame(uint32_t index) const;
1539 * Returns the number of StackFrames.
1541 int GetFrameCount() const;
1544 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1546 Local<Array> AsArray();
1549 * Grab a snapshot of the current JavaScript execution stack.
1551 * \param frame_limit The maximum number of stack frames we want to capture.
1552 * \param options Enumerates the set of things we will capture for each
1555 static Local<StackTrace> CurrentStackTrace(
1558 StackTraceOptions options = kOverview);
1563 * A single JavaScript stack frame.
1565 class V8_EXPORT StackFrame {
1568 * Returns the number, 1-based, of the line for the associate function call.
1569 * This method will return Message::kNoLineNumberInfo if it is unable to
1570 * retrieve the line number, or if kLineNumber was not passed as an option
1571 * when capturing the StackTrace.
1573 int GetLineNumber() const;
1576 * Returns the 1-based column offset on the line for the associated function
1578 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1579 * the column number, or if kColumnOffset was not passed as an option when
1580 * capturing the StackTrace.
1582 int GetColumn() const;
1585 * Returns the id of the script for the function for this StackFrame.
1586 * This method will return Message::kNoScriptIdInfo if it is unable to
1587 * retrieve the script id, or if kScriptId was not passed as an option when
1588 * capturing the StackTrace.
1590 int GetScriptId() const;
1593 * Returns the name of the resource that contains the script for the
1594 * function for this StackFrame.
1596 Local<String> GetScriptName() const;
1599 * Returns the name of the resource that contains the script for the
1600 * function for this StackFrame or sourceURL value if the script name
1601 * is undefined and its source ends with //# sourceURL=... string or
1602 * deprecated //@ sourceURL=... string.
1604 Local<String> GetScriptNameOrSourceURL() const;
1607 * Returns the name of the function associated with this stack frame.
1609 Local<String> GetFunctionName() const;
1612 * Returns whether or not the associated function is compiled via a call to
1615 bool IsEval() const;
1618 * Returns whether or not the associated function is called as a
1619 * constructor via "new".
1621 bool IsConstructor() const;
1625 // A StateTag represents a possible state of the VM.
1626 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1629 // A RegisterState represents the current state of registers used
1630 // by the sampling profiler API.
1631 struct RegisterState {
1632 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1633 void* pc; // Instruction pointer.
1634 void* sp; // Stack pointer.
1635 void* fp; // Frame pointer.
1639 // The output structure filled up by GetStackSample API function.
1641 size_t frames_count;
1649 class V8_EXPORT JSON {
1652 * Tries to parse the string |json_string| and returns it as value if
1655 * \param json_string The string to parse.
1656 * \return The corresponding value if successfully parsed.
1658 static V8_DEPRECATE_SOON("Use maybe version",
1659 Local<Value> Parse(Local<String> json_string));
1660 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1661 Isolate* isolate, Local<String> json_string);
1666 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1667 * but can be created without entering a v8::Context and hence shouldn't
1668 * escape to JavaScript.
1670 class V8_EXPORT NativeWeakMap : public Data {
1672 static Local<NativeWeakMap> New(Isolate* isolate);
1673 void Set(Local<Value> key, Local<Value> value);
1674 Local<Value> Get(Local<Value> key);
1675 bool Has(Local<Value> key);
1676 bool Delete(Local<Value> key);
1684 * The superclass of all JavaScript values and objects.
1686 class V8_EXPORT Value : public Data {
1689 * Returns true if this value is the undefined value. See ECMA-262
1692 V8_INLINE bool IsUndefined() const;
1695 * Returns true if this value is the null value. See ECMA-262
1698 V8_INLINE bool IsNull() const;
1701 * Returns true if this value is true.
1703 bool IsTrue() const;
1706 * Returns true if this value is false.
1708 bool IsFalse() const;
1711 * Returns true if this value is a symbol or a string.
1712 * This is an experimental feature.
1714 bool IsName() const;
1717 * Returns true if this value is an instance of the String type.
1720 V8_INLINE bool IsString() const;
1723 * Returns true if this value is a symbol.
1724 * This is an experimental feature.
1726 bool IsSymbol() const;
1729 * Returns true if this value is a function.
1731 bool IsFunction() const;
1734 * Returns true if this value is an array.
1736 bool IsArray() const;
1739 * Returns true if this value is an object.
1741 bool IsObject() const;
1744 * Returns true if this value is boolean.
1746 bool IsBoolean() const;
1749 * Returns true if this value is a number.
1751 bool IsNumber() const;
1754 * Returns true if this value is external.
1756 bool IsExternal() const;
1759 * Returns true if this value is a 32-bit signed integer.
1761 bool IsInt32() const;
1764 * Returns true if this value is a 32-bit unsigned integer.
1766 bool IsUint32() const;
1769 * Returns true if this value is a Date.
1771 bool IsDate() const;
1774 * Returns true if this value is an Arguments object.
1776 bool IsArgumentsObject() const;
1779 * Returns true if this value is a Boolean object.
1781 bool IsBooleanObject() const;
1784 * Returns true if this value is a Number object.
1786 bool IsNumberObject() const;
1789 * Returns true if this value is a String object.
1791 bool IsStringObject() const;
1794 * Returns true if this value is a Symbol object.
1795 * This is an experimental feature.
1797 bool IsSymbolObject() const;
1800 * Returns true if this value is a NativeError.
1802 bool IsNativeError() const;
1805 * Returns true if this value is a RegExp.
1807 bool IsRegExp() const;
1810 * Returns true if this value is a Generator function.
1811 * This is an experimental feature.
1813 bool IsGeneratorFunction() const;
1816 * Returns true if this value is a Generator object (iterator).
1817 * This is an experimental feature.
1819 bool IsGeneratorObject() const;
1822 * Returns true if this value is a Promise.
1823 * This is an experimental feature.
1825 bool IsPromise() const;
1828 * Returns true if this value is a Map.
1833 * Returns true if this value is a Set.
1838 * Returns true if this value is a Map Iterator.
1840 bool IsMapIterator() const;
1843 * Returns true if this value is a Set Iterator.
1845 bool IsSetIterator() const;
1848 * Returns true if this value is a WeakMap.
1850 bool IsWeakMap() const;
1853 * Returns true if this value is a WeakSet.
1855 bool IsWeakSet() const;
1858 * Returns true if this value is an ArrayBuffer.
1859 * This is an experimental feature.
1861 bool IsArrayBuffer() const;
1864 * Returns true if this value is an ArrayBufferView.
1865 * This is an experimental feature.
1867 bool IsArrayBufferView() const;
1870 * Returns true if this value is one of TypedArrays.
1871 * This is an experimental feature.
1873 bool IsTypedArray() const;
1876 * Returns true if this value is an Uint8Array.
1877 * This is an experimental feature.
1879 bool IsUint8Array() const;
1882 * Returns true if this value is an Uint8ClampedArray.
1883 * This is an experimental feature.
1885 bool IsUint8ClampedArray() const;
1888 * Returns true if this value is an Int8Array.
1889 * This is an experimental feature.
1891 bool IsInt8Array() const;
1894 * Returns true if this value is an Uint16Array.
1895 * This is an experimental feature.
1897 bool IsUint16Array() const;
1900 * Returns true if this value is an Int16Array.
1901 * This is an experimental feature.
1903 bool IsInt16Array() const;
1906 * Returns true if this value is an Uint32Array.
1907 * This is an experimental feature.
1909 bool IsUint32Array() const;
1912 * Returns true if this value is an Int32Array.
1913 * This is an experimental feature.
1915 bool IsInt32Array() const;
1918 * Returns true if this value is a Float32Array.
1919 * This is an experimental feature.
1921 bool IsFloat32Array() const;
1924 * Returns true if this value is a Float64Array.
1925 * This is an experimental feature.
1927 bool IsFloat64Array() const;
1930 * Returns true if this value is a SIMD Float32x4.
1931 * This is an experimental feature.
1933 bool IsFloat32x4() const;
1936 * Returns true if this value is a DataView.
1937 * This is an experimental feature.
1939 bool IsDataView() const;
1942 * Returns true if this value is a SharedArrayBuffer.
1943 * This is an experimental feature.
1945 bool IsSharedArrayBuffer() const;
1948 V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
1949 Local<Context> context) const;
1950 V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
1951 Local<Context> context) const;
1952 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
1953 Local<Context> context) const;
1954 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
1955 Local<Context> context) const;
1956 V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
1957 Local<Context> context) const;
1958 V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
1959 Local<Context> context) const;
1960 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
1961 Local<Context> context) const;
1962 V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
1964 V8_DEPRECATE_SOON("Use maybe version",
1965 Local<Boolean> ToBoolean(Isolate* isolate) const);
1966 V8_DEPRECATE_SOON("Use maybe version",
1967 Local<Number> ToNumber(Isolate* isolate) const);
1968 V8_DEPRECATE_SOON("Use maybe version",
1969 Local<String> ToString(Isolate* isolate) const);
1970 V8_DEPRECATE_SOON("Use maybe version",
1971 Local<String> ToDetailString(Isolate* isolate) const);
1972 V8_DEPRECATE_SOON("Use maybe version",
1973 Local<Object> ToObject(Isolate* isolate) const);
1974 V8_DEPRECATE_SOON("Use maybe version",
1975 Local<Integer> ToInteger(Isolate* isolate) const);
1976 V8_DEPRECATE_SOON("Use maybe version",
1977 Local<Uint32> ToUint32(Isolate* isolate) const);
1978 V8_DEPRECATE_SOON("Use maybe version",
1979 Local<Int32> ToInt32(Isolate* isolate) const);
1981 inline V8_DEPRECATE_SOON("Use maybe version",
1982 Local<Boolean> ToBoolean() const);
1983 inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber() const);
1984 inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
1985 inline V8_DEPRECATE_SOON("Use maybe version",
1986 Local<String> ToDetailString() const);
1987 inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
1988 inline V8_DEPRECATE_SOON("Use maybe version",
1989 Local<Integer> ToInteger() const);
1990 inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32() const);
1991 inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32() const);
1994 * Attempts to convert a string to an array index.
1995 * Returns an empty handle if the conversion fails.
1997 V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex() const);
1998 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
1999 Local<Context> context) const;
2001 V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2002 V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2003 V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2004 Local<Context> context) const;
2005 V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2006 Local<Context> context) const;
2007 V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2009 V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2010 V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2011 V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2012 V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2013 V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2016 V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2017 V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2018 Local<Value> that) const;
2019 bool StrictEquals(Local<Value> that) const;
2020 bool SameValue(Local<Value> that) const;
2022 template <class T> V8_INLINE static Value* Cast(T* value);
2025 V8_INLINE bool QuickIsUndefined() const;
2026 V8_INLINE bool QuickIsNull() const;
2027 V8_INLINE bool QuickIsString() const;
2028 bool FullIsUndefined() const;
2029 bool FullIsNull() const;
2030 bool FullIsString() const;
2035 * The superclass of primitive values. See ECMA-262 4.3.2.
2037 class V8_EXPORT Primitive : public Value { };
2041 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2044 class V8_EXPORT Boolean : public Primitive {
2047 V8_INLINE static Boolean* Cast(v8::Value* obj);
2048 V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2051 static void CheckCast(v8::Value* obj);
2056 * A superclass for symbols and strings.
2058 class V8_EXPORT Name : public Primitive {
2061 * Returns the identity hash for this object. The current implementation
2062 * uses an inline property on the object to store the identity hash.
2064 * The return value will never be 0. Also, it is not guaranteed to be
2067 int GetIdentityHash();
2069 V8_INLINE static Name* Cast(v8::Value* obj);
2071 static void CheckCast(v8::Value* obj);
2075 enum class NewStringType { kNormal, kInternalized };
2079 * A JavaScript string value (ECMA-262, 4.3.17).
2081 class V8_EXPORT String : public Name {
2083 static const int kMaxLength = (1 << 28) - 16;
2086 UNKNOWN_ENCODING = 0x1,
2087 TWO_BYTE_ENCODING = 0x0,
2088 ONE_BYTE_ENCODING = 0x4
2091 * Returns the number of characters in this string.
2096 * Returns the number of bytes in the UTF-8 encoded
2097 * representation of this string.
2099 int Utf8Length() const;
2102 * Returns whether this string is known to contain only one byte data.
2103 * Does not read the string.
2104 * False negatives are possible.
2106 bool IsOneByte() const;
2109 * Returns whether this string contain only one byte data.
2110 * Will read the entire string in some cases.
2112 bool ContainsOnlyOneByte() const;
2115 * Write the contents of the string to an external buffer.
2116 * If no arguments are given, expects the buffer to be large
2117 * enough to hold the entire string and NULL terminator. Copies
2118 * the contents of the string and the NULL terminator into the
2121 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2122 * before the end of the buffer.
2124 * Copies up to length characters into the output buffer.
2125 * Only null-terminates if there is enough space in the buffer.
2127 * \param buffer The buffer into which the string will be copied.
2128 * \param start The starting position within the string at which
2130 * \param length The number of characters to copy from the string. For
2131 * WriteUtf8 the number of bytes in the buffer.
2132 * \param nchars_ref The number of characters written, can be NULL.
2133 * \param options Various options that might affect performance of this or
2134 * subsequent operations.
2135 * \return The number of characters copied to the buffer excluding the null
2136 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2137 * including the null terminator (if written).
2141 HINT_MANY_WRITES_EXPECTED = 1,
2142 NO_NULL_TERMINATION = 2,
2143 PRESERVE_ONE_BYTE_NULL = 4,
2144 // Used by WriteUtf8 to replace orphan surrogate code units with the
2145 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2147 REPLACE_INVALID_UTF8 = 8
2150 // 16-bit character codes.
2151 int Write(uint16_t* buffer,
2154 int options = NO_OPTIONS) const;
2155 // One byte characters.
2156 int WriteOneByte(uint8_t* buffer,
2159 int options = NO_OPTIONS) const;
2160 // UTF-8 encoded characters.
2161 int WriteUtf8(char* buffer,
2163 int* nchars_ref = NULL,
2164 int options = NO_OPTIONS) const;
2167 * A zero length string.
2169 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2172 * Returns true if the string is external
2174 bool IsExternal() const;
2177 * Returns true if the string is both external and one-byte.
2179 bool IsExternalOneByte() const;
2181 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2183 virtual ~ExternalStringResourceBase() {}
2186 ExternalStringResourceBase() {}
2189 * Internally V8 will call this Dispose method when the external string
2190 * resource is no longer needed. The default implementation will use the
2191 * delete operator. This method can be overridden in subclasses to
2192 * control how allocated external string resources are disposed.
2194 virtual void Dispose() { delete this; }
2197 // Disallow copying and assigning.
2198 ExternalStringResourceBase(const ExternalStringResourceBase&);
2199 void operator=(const ExternalStringResourceBase&);
2201 friend class v8::internal::Heap;
2205 * An ExternalStringResource is a wrapper around a two-byte string
2206 * buffer that resides outside V8's heap. Implement an
2207 * ExternalStringResource to manage the life cycle of the underlying
2208 * buffer. Note that the string data must be immutable.
2210 class V8_EXPORT ExternalStringResource
2211 : public ExternalStringResourceBase {
2214 * Override the destructor to manage the life cycle of the underlying
2217 virtual ~ExternalStringResource() {}
2220 * The string data from the underlying buffer.
2222 virtual const uint16_t* data() const = 0;
2225 * The length of the string. That is, the number of two-byte characters.
2227 virtual size_t length() const = 0;
2230 ExternalStringResource() {}
2234 * An ExternalOneByteStringResource is a wrapper around an one-byte
2235 * string buffer that resides outside V8's heap. Implement an
2236 * ExternalOneByteStringResource to manage the life cycle of the
2237 * underlying buffer. Note that the string data must be immutable
2238 * and that the data must be Latin-1 and not UTF-8, which would require
2239 * special treatment internally in the engine and do not allow efficient
2240 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2243 class V8_EXPORT ExternalOneByteStringResource
2244 : public ExternalStringResourceBase {
2247 * Override the destructor to manage the life cycle of the underlying
2250 virtual ~ExternalOneByteStringResource() {}
2251 /** The string data from the underlying buffer.*/
2252 virtual const char* data() const = 0;
2253 /** The number of Latin-1 characters in the string.*/
2254 virtual size_t length() const = 0;
2256 ExternalOneByteStringResource() {}
2260 * If the string is an external string, return the ExternalStringResourceBase
2261 * regardless of the encoding, otherwise return NULL. The encoding of the
2262 * string is returned in encoding_out.
2264 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2265 Encoding* encoding_out) const;
2268 * Get the ExternalStringResource for an external string. Returns
2269 * NULL if IsExternal() doesn't return true.
2271 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2274 * Get the ExternalOneByteStringResource for an external one-byte string.
2275 * Returns NULL if IsExternalOneByte() doesn't return true.
2277 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2279 V8_INLINE static String* Cast(v8::Value* obj);
2281 // TODO(dcarney): remove with deprecation of New functions.
2282 enum NewStringType {
2283 kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2284 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2287 /** Allocates a new string from UTF-8 data.*/
2288 static V8_DEPRECATE_SOON(
2289 "Use maybe version",
2290 Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2291 NewStringType type = kNormalString,
2294 /** Allocates a new string from UTF-8 data. Only returns an empty value when
2295 * length > kMaxLength. **/
2296 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2297 Isolate* isolate, const char* data, v8::NewStringType type,
2300 /** Allocates a new string from Latin-1 data.*/
2301 static V8_DEPRECATE_SOON(
2302 "Use maybe version",
2303 Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2304 NewStringType type = kNormalString,
2307 /** Allocates a new string from Latin-1 data. Only returns an empty value
2308 * when length > kMaxLength. **/
2309 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2310 Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2313 /** Allocates a new string from UTF-16 data.*/
2314 static V8_DEPRECATE_SOON(
2315 "Use maybe version",
2316 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2317 NewStringType type = kNormalString,
2320 /** Allocates a new string from UTF-16 data. Only returns an empty value when
2321 * length > kMaxLength. **/
2322 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2323 Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2327 * Creates a new string by concatenating the left and the right strings
2328 * passed in as parameters.
2330 static Local<String> Concat(Local<String> left, Local<String> right);
2333 * Creates a new external string using the data defined in the given
2334 * resource. When the external string is no longer live on V8's heap the
2335 * resource will be disposed by calling its Dispose method. The caller of
2336 * this function should not otherwise delete or modify the resource. Neither
2337 * should the underlying buffer be deallocated or modified except through the
2338 * destructor of the external string resource.
2340 static V8_DEPRECATE_SOON(
2341 "Use maybe version",
2342 Local<String> NewExternal(Isolate* isolate,
2343 ExternalStringResource* resource));
2344 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2345 Isolate* isolate, ExternalStringResource* resource);
2348 * Associate an external string resource with this string by transforming it
2349 * in place so that existing references to this string in the JavaScript heap
2350 * will use the external string resource. The external string resource's
2351 * character contents need to be equivalent to this string.
2352 * Returns true if the string has been changed to be an external string.
2353 * The string is not modified if the operation fails. See NewExternal for
2354 * information on the lifetime of the resource.
2356 bool MakeExternal(ExternalStringResource* resource);
2359 * Creates a new external string using the one-byte data defined in the given
2360 * resource. When the external string is no longer live on V8's heap the
2361 * resource will be disposed by calling its Dispose method. The caller of
2362 * this function should not otherwise delete or modify the resource. Neither
2363 * should the underlying buffer be deallocated or modified except through the
2364 * destructor of the external string resource.
2366 static V8_DEPRECATE_SOON(
2367 "Use maybe version",
2368 Local<String> NewExternal(Isolate* isolate,
2369 ExternalOneByteStringResource* resource));
2370 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2371 Isolate* isolate, ExternalOneByteStringResource* resource);
2374 * Associate an external string resource with this string by transforming it
2375 * in place so that existing references to this string in the JavaScript heap
2376 * will use the external string resource. The external string resource's
2377 * character contents need to be equivalent to this string.
2378 * Returns true if the string has been changed to be an external string.
2379 * The string is not modified if the operation fails. See NewExternal for
2380 * information on the lifetime of the resource.
2382 bool MakeExternal(ExternalOneByteStringResource* resource);
2385 * Returns true if this string can be made external.
2387 bool CanMakeExternal();
2390 * Converts an object to a UTF-8-encoded character array. Useful if
2391 * you want to print the object. If conversion to a string fails
2392 * (e.g. due to an exception in the toString() method of the object)
2393 * then the length() method returns 0 and the * operator returns
2396 class V8_EXPORT Utf8Value {
2398 explicit Utf8Value(Local<v8::Value> obj);
2400 char* operator*() { return str_; }
2401 const char* operator*() const { return str_; }
2402 int length() const { return length_; }
2407 // Disallow copying and assigning.
2408 Utf8Value(const Utf8Value&);
2409 void operator=(const Utf8Value&);
2413 * Converts an object to a two-byte string.
2414 * If conversion to a string fails (eg. due to an exception in the toString()
2415 * method of the object) then the length() method returns 0 and the * operator
2418 class V8_EXPORT Value {
2420 explicit Value(Local<v8::Value> obj);
2422 uint16_t* operator*() { return str_; }
2423 const uint16_t* operator*() const { return str_; }
2424 int length() const { return length_; }
2429 // Disallow copying and assigning.
2430 Value(const Value&);
2431 void operator=(const Value&);
2435 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2436 Encoding encoding) const;
2437 void VerifyExternalStringResource(ExternalStringResource* val) const;
2438 static void CheckCast(v8::Value* obj);
2443 * A JavaScript symbol (ECMA-262 edition 6)
2445 * This is an experimental feature. Use at your own risk.
2447 class V8_EXPORT Symbol : public Name {
2449 // Returns the print name string of the symbol, or undefined if none.
2450 Local<Value> Name() const;
2452 // Create a symbol. If name is not empty, it will be used as the description.
2453 static Local<Symbol> New(
2454 Isolate *isolate, Local<String> name = Local<String>());
2456 // Access global symbol registry.
2457 // Note that symbols created this way are never collected, so
2458 // they should only be used for statically fixed properties.
2459 // Also, there is only one global name space for the names used as keys.
2460 // To minimize the potential for clashes, use qualified names as keys.
2461 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2463 // Retrieve a global symbol. Similar to |For|, but using a separate
2464 // registry that is not accessible by (and cannot clash with) JavaScript code.
2465 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2467 // Well-known symbols
2468 static Local<Symbol> GetIterator(Isolate* isolate);
2469 static Local<Symbol> GetUnscopables(Isolate* isolate);
2470 static Local<Symbol> GetToStringTag(Isolate* isolate);
2472 V8_INLINE static Symbol* Cast(v8::Value* obj);
2476 static void CheckCast(v8::Value* obj);
2481 * A JavaScript number value (ECMA-262, 4.3.20)
2483 class V8_EXPORT Number : public Primitive {
2485 double Value() const;
2486 static Local<Number> New(Isolate* isolate, double value);
2487 V8_INLINE static Number* Cast(v8::Value* obj);
2490 static void CheckCast(v8::Value* obj);
2495 * A JavaScript value representing a signed integer.
2497 class V8_EXPORT Integer : public Number {
2499 static Local<Integer> New(Isolate* isolate, int32_t value);
2500 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2501 int64_t Value() const;
2502 V8_INLINE static Integer* Cast(v8::Value* obj);
2505 static void CheckCast(v8::Value* obj);
2510 * A JavaScript value representing a 32-bit signed integer.
2512 class V8_EXPORT Int32 : public Integer {
2514 int32_t Value() const;
2515 V8_INLINE static Int32* Cast(v8::Value* obj);
2519 static void CheckCast(v8::Value* obj);
2524 * A JavaScript value representing a 32-bit unsigned integer.
2526 class V8_EXPORT Uint32 : public Integer {
2528 uint32_t Value() const;
2529 V8_INLINE static Uint32* Cast(v8::Value* obj);
2533 static void CheckCast(v8::Value* obj);
2537 enum PropertyAttribute {
2545 * Accessor[Getter|Setter] are used as callback functions when
2546 * setting|getting a particular property. See Object and ObjectTemplate's
2547 * method SetAccessor.
2549 typedef void (*AccessorGetterCallback)(
2550 Local<String> property,
2551 const PropertyCallbackInfo<Value>& info);
2552 typedef void (*AccessorNameGetterCallback)(
2553 Local<Name> property,
2554 const PropertyCallbackInfo<Value>& info);
2557 typedef void (*AccessorSetterCallback)(
2558 Local<String> property,
2560 const PropertyCallbackInfo<void>& info);
2561 typedef void (*AccessorNameSetterCallback)(
2562 Local<Name> property,
2564 const PropertyCallbackInfo<void>& info);
2568 * Access control specifications.
2570 * Some accessors should be accessible across contexts. These
2571 * accessors have an explicit access control parameter which specifies
2572 * the kind of cross-context access that should be allowed.
2574 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2576 enum AccessControl {
2579 ALL_CAN_WRITE = 1 << 1,
2580 PROHIBITS_OVERWRITING = 1 << 2
2585 * A JavaScript object (ECMA-262, 4.3.3)
2587 class V8_EXPORT Object : public Value {
2589 V8_DEPRECATE_SOON("Use maybe version",
2590 bool Set(Local<Value> key, Local<Value> value));
2591 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
2592 Local<Value> key, Local<Value> value);
2594 V8_DEPRECATE_SOON("Use maybe version",
2595 bool Set(uint32_t index, Local<Value> value));
2596 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
2597 Local<Value> value);
2599 // Implements CreateDataProperty (ECMA-262, 7.3.4).
2601 // Defines a configurable, writable, enumerable property with the given value
2602 // on the object unless the property already exists and is not configurable
2603 // or the object is not extensible.
2605 // Returns true on success.
2606 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2608 Local<Value> value);
2609 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2611 Local<Value> value);
2613 // Implements DefineOwnProperty.
2615 // In general, CreateDataProperty will be faster, however, does not allow
2616 // for specifying attributes.
2618 // Returns true on success.
2619 V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
2620 Local<Context> context, Local<Name> key, Local<Value> value,
2621 PropertyAttribute attributes = None);
2623 // Sets an own property on this object bypassing interceptors and
2624 // overriding accessors or read-only properties.
2626 // Note that if the object has an interceptor the property will be set
2627 // locally, but since the interceptor takes precedence the local property
2628 // will only be returned if the interceptor doesn't return a value.
2630 // Note also that this only works for named properties.
2631 V8_DEPRECATE_SOON("Use CreateDataProperty",
2632 bool ForceSet(Local<Value> key, Local<Value> value,
2633 PropertyAttribute attribs = None));
2634 V8_DEPRECATE_SOON("Use CreateDataProperty",
2635 Maybe<bool> ForceSet(Local<Context> context,
2636 Local<Value> key, Local<Value> value,
2637 PropertyAttribute attribs = None));
2639 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
2640 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2643 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2644 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2648 * Gets the property attributes of a property which can be None or
2649 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2650 * None when the property doesn't exist.
2652 V8_DEPRECATE_SOON("Use maybe version",
2653 PropertyAttribute GetPropertyAttributes(Local<Value> key));
2654 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
2655 Local<Context> context, Local<Value> key);
2658 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2660 V8_DEPRECATE_SOON("Use maybe version",
2661 Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2662 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
2663 Local<Context> context, Local<String> key);
2665 V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
2666 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2669 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
2670 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2671 Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2673 V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2674 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
2676 V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2677 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2678 Maybe<bool> Delete(Local<Context> context, uint32_t index);
2680 V8_DEPRECATE_SOON("Use maybe version",
2681 bool SetAccessor(Local<String> name,
2682 AccessorGetterCallback getter,
2683 AccessorSetterCallback setter = 0,
2684 Local<Value> data = Local<Value>(),
2685 AccessControl settings = DEFAULT,
2686 PropertyAttribute attribute = None));
2687 V8_DEPRECATE_SOON("Use maybe version",
2688 bool SetAccessor(Local<Name> name,
2689 AccessorNameGetterCallback getter,
2690 AccessorNameSetterCallback setter = 0,
2691 Local<Value> data = Local<Value>(),
2692 AccessControl settings = DEFAULT,
2693 PropertyAttribute attribute = None));
2694 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2695 Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2696 AccessorNameGetterCallback getter,
2697 AccessorNameSetterCallback setter = 0,
2698 MaybeLocal<Value> data = MaybeLocal<Value>(),
2699 AccessControl settings = DEFAULT,
2700 PropertyAttribute attribute = None);
2702 void SetAccessorProperty(Local<Name> name, Local<Function> getter,
2703 Local<Function> setter = Local<Function>(),
2704 PropertyAttribute attribute = None,
2705 AccessControl settings = DEFAULT);
2708 * Returns an array containing the names of the enumerable properties
2709 * of this object, including properties from prototype objects. The
2710 * array returned by this method contains the same values as would
2711 * be enumerated by a for-in statement over this object.
2713 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2714 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
2715 Local<Context> context);
2718 * This function has the same functionality as GetPropertyNames but
2719 * the returned array doesn't contain the names of properties from
2720 * prototype objects.
2722 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2723 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
2724 Local<Context> context);
2727 * Get the prototype object. This does not skip objects marked to
2728 * be skipped by __proto__ and it does not consult the security
2731 Local<Value> GetPrototype();
2734 * Set the prototype object. This does not skip objects marked to
2735 * be skipped by __proto__ and it does not consult the security
2738 V8_DEPRECATE_SOON("Use maybe version",
2739 bool SetPrototype(Local<Value> prototype));
2740 V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
2741 Local<Value> prototype);
2744 * Finds an instance of the given function template in the prototype
2747 Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
2750 * Call builtin Object.prototype.toString on this object.
2751 * This is different from Value::ToString() that may call
2752 * user-defined toString function. This one does not.
2754 V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2755 V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
2756 Local<Context> context);
2759 * Returns the name of the function invoked as a constructor for this object.
2761 Local<String> GetConstructorName();
2763 /** Gets the number of internal fields for this Object. */
2764 int InternalFieldCount();
2766 /** Same as above, but works for Persistents */
2767 V8_INLINE static int InternalFieldCount(
2768 const PersistentBase<Object>& object) {
2769 return object.val_->InternalFieldCount();
2772 /** Gets the value from an internal field. */
2773 V8_INLINE Local<Value> GetInternalField(int index);
2775 /** Sets the value in an internal field. */
2776 void SetInternalField(int index, Local<Value> value);
2779 * Gets a 2-byte-aligned native pointer from an internal field. This field
2780 * must have been set by SetAlignedPointerInInternalField, everything else
2781 * leads to undefined behavior.
2783 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2785 /** Same as above, but works for Persistents */
2786 V8_INLINE static void* GetAlignedPointerFromInternalField(
2787 const PersistentBase<Object>& object, int index) {
2788 return object.val_->GetAlignedPointerFromInternalField(index);
2792 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2793 * a field, GetAlignedPointerFromInternalField must be used, everything else
2794 * leads to undefined behavior.
2796 void SetAlignedPointerInInternalField(int index, void* value);
2798 // Testers for local properties.
2799 V8_DEPRECATE_SOON("Use maybe version",
2800 bool HasOwnProperty(Local<String> key));
2801 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
2803 V8_DEPRECATE_SOON("Use maybe version",
2804 bool HasRealNamedProperty(Local<String> key));
2805 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
2807 V8_DEPRECATE_SOON("Use maybe version",
2808 bool HasRealIndexedProperty(uint32_t index));
2809 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
2810 Local<Context> context, uint32_t index);
2811 V8_DEPRECATE_SOON("Use maybe version",
2812 bool HasRealNamedCallbackProperty(Local<String> key));
2813 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
2814 Local<Context> context, Local<Name> key);
2817 * If result.IsEmpty() no real property was located in the prototype chain.
2818 * This means interceptors in the prototype chain are not called.
2821 "Use maybe version",
2822 Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
2823 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
2824 Local<Context> context, Local<Name> key);
2827 * Gets the property attributes of a real property in the prototype chain,
2828 * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2829 * Interceptors in the prototype chain are not called.
2832 "Use maybe version",
2833 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2834 Local<String> key));
2835 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
2836 GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
2840 * If result.IsEmpty() no real property was located on the object or
2841 * in the prototype chain.
2842 * This means interceptors in the prototype chain are not called.
2844 V8_DEPRECATE_SOON("Use maybe version",
2845 Local<Value> GetRealNamedProperty(Local<String> key));
2846 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
2847 Local<Context> context, Local<Name> key);
2850 * Gets the property attributes of a real property which can be
2851 * None or any combination of ReadOnly, DontEnum and DontDelete.
2852 * Interceptors in the prototype chain are not called.
2854 V8_DEPRECATE_SOON("Use maybe version",
2855 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2856 Local<String> key));
2857 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2858 Local<Context> context, Local<Name> key);
2860 /** Tests for a named lookup interceptor.*/
2861 bool HasNamedLookupInterceptor();
2863 /** Tests for an index lookup interceptor.*/
2864 bool HasIndexedLookupInterceptor();
2867 * Returns the identity hash for this object. The current implementation
2868 * uses a hidden property on the object to store the identity hash.
2870 * The return value will never be 0. Also, it is not guaranteed to be
2873 int GetIdentityHash();
2876 * Access hidden properties on JavaScript objects. These properties are
2877 * hidden from the executing JavaScript and only accessible through the V8
2878 * C++ API. Hidden properties introduced by V8 internally (for example the
2879 * identity hash) are prefixed with "v8::".
2881 // TODO(dcarney): convert these to take a isolate and optionally bailout?
2882 bool SetHiddenValue(Local<String> key, Local<Value> value);
2883 Local<Value> GetHiddenValue(Local<String> key);
2884 bool DeleteHiddenValue(Local<String> key);
2887 * Clone this object with a fast but shallow copy. Values will point
2888 * to the same values as the original object.
2890 // TODO(dcarney): take an isolate and optionally bail out?
2891 Local<Object> Clone();
2894 * Returns the context in which the object was created.
2896 Local<Context> CreationContext();
2899 * Checks whether a callback is set by the
2900 * ObjectTemplate::SetCallAsFunctionHandler method.
2901 * When an Object is callable this method returns true.
2906 * Call an Object as a function if a callback is set by the
2907 * ObjectTemplate::SetCallAsFunctionHandler method.
2909 V8_DEPRECATE_SOON("Use maybe version",
2910 Local<Value> CallAsFunction(Local<Value> recv, int argc,
2911 Local<Value> argv[]));
2912 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
2915 Local<Value> argv[]);
2918 * Call an Object as a constructor if a callback is set by the
2919 * ObjectTemplate::SetCallAsFunctionHandler method.
2920 * Note: This method behaves like the Function::NewInstance method.
2922 V8_DEPRECATE_SOON("Use maybe version",
2923 Local<Value> CallAsConstructor(int argc,
2924 Local<Value> argv[]));
2925 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
2926 Local<Context> context, int argc, Local<Value> argv[]);
2929 * Return the isolate to which the Object belongs to.
2931 V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
2933 static Local<Object> New(Isolate* isolate);
2935 V8_INLINE static Object* Cast(Value* obj);
2939 static void CheckCast(Value* obj);
2940 Local<Value> SlowGetInternalField(int index);
2941 void* SlowGetAlignedPointerFromInternalField(int index);
2946 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2948 class V8_EXPORT Array : public Object {
2950 uint32_t Length() const;
2953 * Clones an element at index |index|. Returns an empty
2954 * handle if cloning fails (for any reason).
2956 V8_DEPRECATE_SOON("Use maybe version",
2957 Local<Object> CloneElementAt(uint32_t index));
2958 V8_WARN_UNUSED_RESULT MaybeLocal<Object> CloneElementAt(
2959 Local<Context> context, uint32_t index);
2962 * Creates a JavaScript array with the given length. If the length
2963 * is negative the returned array will have length 0.
2965 static Local<Array> New(Isolate* isolate, int length = 0);
2967 V8_INLINE static Array* Cast(Value* obj);
2970 static void CheckCast(Value* obj);
2975 * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
2977 class V8_EXPORT Map : public Object {
2979 size_t Size() const;
2981 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2983 V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
2985 Local<Value> value);
2986 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2988 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
2992 * Returns an array of length Size() * 2, where index N is the Nth key and
2993 * index N + 1 is the Nth value.
2995 Local<Array> AsArray() const;
2998 * Creates a new empty Map.
3000 static Local<Map> New(Isolate* isolate);
3003 * Creates a new Map containing the elements of array, which must be formatted
3004 * in the same manner as the array returned from AsArray().
3005 * Guaranteed to be side-effect free if the array contains no holes.
3007 static V8_WARN_UNUSED_RESULT MaybeLocal<Map> FromArray(Local<Context> context,
3008 Local<Array> array);
3010 V8_INLINE static Map* Cast(Value* obj);
3014 static void CheckCast(Value* obj);
3019 * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3021 class V8_EXPORT Set : public Object {
3023 size_t Size() const;
3025 V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3027 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3029 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3033 * Returns an array of the keys in this Set.
3035 Local<Array> AsArray() const;
3038 * Creates a new empty Set.
3040 static Local<Set> New(Isolate* isolate);
3043 * Creates a new Set containing the items in array.
3044 * Guaranteed to be side-effect free if the array contains no holes.
3046 static V8_WARN_UNUSED_RESULT MaybeLocal<Set> FromArray(Local<Context> context,
3047 Local<Array> array);
3049 V8_INLINE static Set* Cast(Value* obj);
3053 static void CheckCast(Value* obj);
3057 template<typename T>
3060 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3061 : value_(that.value_) {
3065 template <typename S>
3066 V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3067 void Set(const Persistent<S>& handle));
3068 template <typename S>
3069 V8_INLINE void Set(const Global<S>& handle);
3070 template <typename S>
3071 V8_INLINE void Set(const Local<S> handle);
3072 // Fast primitive setters
3073 V8_INLINE void Set(bool value);
3074 V8_INLINE void Set(double i);
3075 V8_INLINE void Set(int32_t i);
3076 V8_INLINE void Set(uint32_t i);
3077 // Fast JS primitive setters
3078 V8_INLINE void SetNull();
3079 V8_INLINE void SetUndefined();
3080 V8_INLINE void SetEmptyString();
3081 // Convenience getter for Isolate
3082 V8_INLINE Isolate* GetIsolate();
3084 // Pointer setter: Uncompilable to prevent inadvertent misuse.
3085 template <typename S>
3086 V8_INLINE void Set(S* whatever);
3089 template<class F> friend class ReturnValue;
3090 template<class F> friend class FunctionCallbackInfo;
3091 template<class F> friend class PropertyCallbackInfo;
3092 template <class F, class G, class H>
3093 friend class PersistentValueMapBase;
3094 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3095 V8_INLINE internal::Object* GetDefaultValue();
3096 V8_INLINE explicit ReturnValue(internal::Object** slot);
3097 internal::Object** value_;
3102 * The argument information given to function call callbacks. This
3103 * class provides access to information about the context of the call,
3104 * including the receiver, the number and values of arguments, and
3105 * the holder of the function.
3107 template<typename T>
3108 class FunctionCallbackInfo {
3110 V8_INLINE int Length() const;
3111 V8_INLINE Local<Value> operator[](int i) const;
3112 V8_INLINE Local<Function> Callee() const;
3113 V8_INLINE Local<Object> This() const;
3114 V8_INLINE Local<Object> Holder() const;
3115 V8_INLINE bool IsConstructCall() const;
3116 V8_INLINE Local<Value> Data() const;
3117 V8_INLINE Isolate* GetIsolate() const;
3118 V8_INLINE ReturnValue<T> GetReturnValue() const;
3119 // This shouldn't be public, but the arm compiler needs it.
3120 static const int kArgsLength = 7;
3123 friend class internal::FunctionCallbackArguments;
3124 friend class internal::CustomArguments<FunctionCallbackInfo>;
3125 static const int kHolderIndex = 0;
3126 static const int kIsolateIndex = 1;
3127 static const int kReturnValueDefaultValueIndex = 2;
3128 static const int kReturnValueIndex = 3;
3129 static const int kDataIndex = 4;
3130 static const int kCalleeIndex = 5;
3131 static const int kContextSaveIndex = 6;
3133 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3134 internal::Object** values,
3136 bool is_construct_call);
3137 internal::Object** implicit_args_;
3138 internal::Object** values_;
3140 int is_construct_call_;
3145 * The information passed to a property callback about the context
3146 * of the property access.
3148 template<typename T>
3149 class PropertyCallbackInfo {
3151 V8_INLINE Isolate* GetIsolate() const;
3152 V8_INLINE Local<Value> Data() const;
3153 V8_INLINE Local<Object> This() const;
3154 V8_INLINE Local<Object> Holder() const;
3155 V8_INLINE ReturnValue<T> GetReturnValue() const;
3156 // This shouldn't be public, but the arm compiler needs it.
3157 static const int kArgsLength = 6;
3160 friend class MacroAssembler;
3161 friend class internal::PropertyCallbackArguments;
3162 friend class internal::CustomArguments<PropertyCallbackInfo>;
3163 static const int kHolderIndex = 0;
3164 static const int kIsolateIndex = 1;
3165 static const int kReturnValueDefaultValueIndex = 2;
3166 static const int kReturnValueIndex = 3;
3167 static const int kDataIndex = 4;
3168 static const int kThisIndex = 5;
3170 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3171 internal::Object** args_;
3175 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3179 * A JavaScript function object (ECMA-262, 15.3).
3181 class V8_EXPORT Function : public Object {
3184 * Create a function in the current execution context
3185 * for a given FunctionCallback.
3187 static MaybeLocal<Function> New(Local<Context> context,
3188 FunctionCallback callback,
3189 Local<Value> data = Local<Value>(),
3191 static V8_DEPRECATE_SOON(
3192 "Use maybe version",
3193 Local<Function> New(Isolate* isolate, FunctionCallback callback,
3194 Local<Value> data = Local<Value>(), int length = 0));
3196 V8_DEPRECATE_SOON("Use maybe version",
3197 Local<Object> NewInstance(int argc, Local<Value> argv[])
3199 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3200 Local<Context> context, int argc, Local<Value> argv[]) const;
3202 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance() const);
3203 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3204 Local<Context> context) const {
3205 return NewInstance(context, 0, nullptr);
3208 V8_DEPRECATE_SOON("Use maybe version",
3209 Local<Value> Call(Local<Value> recv, int argc,
3210 Local<Value> argv[]));
3211 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
3212 Local<Value> recv, int argc,
3213 Local<Value> argv[]);
3215 void SetName(Local<String> name);
3216 Local<Value> GetName() const;
3219 * Name inferred from variable or property assignment of this function.
3220 * Used to facilitate debugging and profiling of JavaScript code written
3221 * in an OO style, where many functions are anonymous but are assigned
3222 * to object properties.
3224 Local<Value> GetInferredName() const;
3227 * User-defined name assigned to the "displayName" property of this function.
3228 * Used to facilitate debugging and profiling of JavaScript code.
3230 Local<Value> GetDisplayName() const;
3233 * Returns zero based line number of function body and
3234 * kLineOffsetNotFound if no information available.
3236 int GetScriptLineNumber() const;
3238 * Returns zero based column number of function body and
3239 * kLineOffsetNotFound if no information available.
3241 int GetScriptColumnNumber() const;
3244 * Tells whether this function is builtin.
3246 bool IsBuiltin() const;
3251 int ScriptId() const;
3254 * Returns the original function if this function is bound, else returns
3257 Local<Value> GetBoundFunction() const;
3259 ScriptOrigin GetScriptOrigin() const;
3260 V8_INLINE static Function* Cast(Value* obj);
3261 static const int kLineOffsetNotFound;
3265 static void CheckCast(Value* obj);
3270 * An instance of the built-in Promise constructor (ES6 draft).
3271 * This API is experimental. Only works with --harmony flag.
3273 class V8_EXPORT Promise : public Object {
3275 class V8_EXPORT Resolver : public Object {
3278 * Create a new resolver, along with an associated promise in pending state.
3280 static V8_DEPRECATE_SOON("Use maybe version",
3281 Local<Resolver> New(Isolate* isolate));
3282 static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
3283 Local<Context> context);
3286 * Extract the associated promise.
3288 Local<Promise> GetPromise();
3291 * Resolve/reject the associated promise with a given value.
3292 * Ignored if the promise is no longer pending.
3294 V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3295 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3296 Maybe<bool> Resolve(Local<Context> context, Local<Value> value);
3298 V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3299 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3300 Maybe<bool> Reject(Local<Context> context, Local<Value> value);
3302 V8_INLINE static Resolver* Cast(Value* obj);
3306 static void CheckCast(Value* obj);
3310 * Register a resolution/rejection handler with a promise.
3311 * The handler is given the respective resolution/rejection value as
3312 * an argument. If the promise is already resolved/rejected, the handler is
3313 * invoked at the end of turn.
3315 V8_DEPRECATE_SOON("Use maybe version",
3316 Local<Promise> Chain(Local<Function> handler));
3317 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Chain(Local<Context> context,
3318 Local<Function> handler);
3320 V8_DEPRECATE_SOON("Use maybe version",
3321 Local<Promise> Catch(Local<Function> handler));
3322 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
3323 Local<Function> handler);
3325 V8_DEPRECATE_SOON("Use maybe version",
3326 Local<Promise> Then(Local<Function> handler));
3327 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
3328 Local<Function> handler);
3331 * Returns true if the promise has at least one derived promise, and
3332 * therefore resolve/reject handlers (including default handler).
3336 V8_INLINE static Promise* Cast(Value* obj);
3340 static void CheckCast(Value* obj);
3344 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3345 // The number of required internal fields can be defined by embedder.
3346 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3350 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
3354 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3355 * This API is experimental and may change significantly.
3357 class V8_EXPORT ArrayBuffer : public Object {
3360 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3361 * The allocator is a global V8 setting. It has to be set via
3362 * Isolate::CreateParams.
3364 * This API is experimental and may change significantly.
3366 class V8_EXPORT Allocator { // NOLINT
3368 virtual ~Allocator() {}
3371 * Allocate |length| bytes. Return NULL if allocation is not successful.
3372 * Memory should be initialized to zeroes.
3374 virtual void* Allocate(size_t length) = 0;
3377 * Allocate |length| bytes. Return NULL if allocation is not successful.
3378 * Memory does not have to be initialized.
3380 virtual void* AllocateUninitialized(size_t length) = 0;
3382 * Free the memory block of size |length|, pointed to by |data|.
3383 * That memory is guaranteed to be previously allocated by |Allocate|.
3385 virtual void Free(void* data, size_t length) = 0;
3389 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3390 * returns an instance of this class, populated, with a pointer to data
3393 * The Data pointer of ArrayBuffer::Contents is always allocated with
3394 * Allocator::Allocate that is set via Isolate::CreateParams.
3396 * This API is experimental and may change significantly.
3398 class V8_EXPORT Contents { // NOLINT
3400 Contents() : data_(NULL), byte_length_(0) {}
3402 void* Data() const { return data_; }
3403 size_t ByteLength() const { return byte_length_; }
3407 size_t byte_length_;
3409 friend class ArrayBuffer;
3414 * Data length in bytes.
3416 size_t ByteLength() const;
3419 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3420 * Allocated memory will be owned by a created ArrayBuffer and
3421 * will be deallocated when it is garbage-collected,
3422 * unless the object is externalized.
3424 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3427 * Create a new ArrayBuffer over an existing memory block.
3428 * The created array buffer is by default immediately in externalized state.
3429 * The memory block will not be reclaimed when a created ArrayBuffer
3430 * is garbage-collected.
3432 static Local<ArrayBuffer> New(
3433 Isolate* isolate, void* data, size_t byte_length,
3434 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3437 * Returns true if ArrayBuffer is externalized, that is, does not
3438 * own its memory block.
3440 bool IsExternal() const;
3443 * Returns true if this ArrayBuffer may be neutered.
3445 bool IsNeuterable() const;
3448 * Neuters this ArrayBuffer and all its views (typed arrays).
3449 * Neutering sets the byte length of the buffer and all typed arrays to zero,
3450 * preventing JavaScript from ever accessing underlying backing store.
3451 * ArrayBuffer should have been externalized and must be neuterable.
3456 * Make this ArrayBuffer external. The pointer to underlying memory block
3457 * and byte length are returned as |Contents| structure. After ArrayBuffer
3458 * had been etxrenalized, it does no longer owns the memory block. The caller
3459 * should take steps to free memory when it is no longer needed.
3461 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3462 * that has been set via Isolate::CreateParams.
3464 Contents Externalize();
3467 * Get a pointer to the ArrayBuffer's underlying memory block without
3468 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3469 * will become invalid as soon as the ArrayBuffer became garbage collected.
3471 * The embedder should make sure to hold a strong reference to the
3472 * ArrayBuffer while accessing this pointer.
3474 * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3476 Contents GetContents();
3478 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3480 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3484 static void CheckCast(Value* obj);
3488 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3489 // The number of required internal fields can be defined by embedder.
3490 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3495 * A base class for an instance of one of "views" over ArrayBuffer,
3496 * including TypedArrays and DataView (ES6 draft 15.13).
3498 * This API is experimental and may change significantly.
3500 class V8_EXPORT ArrayBufferView : public Object {
3503 * Returns underlying ArrayBuffer.
3505 Local<ArrayBuffer> Buffer();
3507 * Byte offset in |Buffer|.
3509 size_t ByteOffset();
3511 * Size of a view in bytes.
3513 size_t ByteLength();
3516 * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3517 * memory without additional overhead that calling ArrayBufferView::Buffer
3520 * Will write at most min(|byte_length|, ByteLength) bytes starting at
3521 * ByteOffset of the underling buffer to the memory starting at |dest|.
3522 * Returns the number of bytes actually written.
3524 size_t CopyContents(void* dest, size_t byte_length);
3527 * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3530 bool HasBuffer() const;
3532 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3534 static const int kInternalFieldCount =
3535 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3539 static void CheckCast(Value* obj);
3544 * A base class for an instance of TypedArray series of constructors
3545 * (ES6 draft 15.13.6).
3546 * This API is experimental and may change significantly.
3548 class V8_EXPORT TypedArray : public ArrayBufferView {
3551 * Number of elements in this typed array
3552 * (e.g. for Int16Array, |ByteLength|/2).
3556 V8_INLINE static TypedArray* Cast(Value* obj);
3560 static void CheckCast(Value* obj);
3565 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3566 * This API is experimental and may change significantly.
3568 class V8_EXPORT Uint8Array : public TypedArray {
3570 static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
3571 size_t byte_offset, size_t length);
3572 static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3573 size_t byte_offset, size_t length);
3574 V8_INLINE static Uint8Array* Cast(Value* obj);
3578 static void CheckCast(Value* obj);
3583 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3584 * This API is experimental and may change significantly.
3586 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3588 static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
3589 size_t byte_offset, size_t length);
3590 static Local<Uint8ClampedArray> New(
3591 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
3593 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3596 Uint8ClampedArray();
3597 static void CheckCast(Value* obj);
3601 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3602 * This API is experimental and may change significantly.
3604 class V8_EXPORT Int8Array : public TypedArray {
3606 static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
3607 size_t byte_offset, size_t length);
3608 static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3609 size_t byte_offset, size_t length);
3610 V8_INLINE static Int8Array* Cast(Value* obj);
3614 static void CheckCast(Value* obj);
3619 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3620 * This API is experimental and may change significantly.
3622 class V8_EXPORT Uint16Array : public TypedArray {
3624 static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
3625 size_t byte_offset, size_t length);
3626 static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3627 size_t byte_offset, size_t length);
3628 V8_INLINE static Uint16Array* Cast(Value* obj);
3632 static void CheckCast(Value* obj);
3637 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3638 * This API is experimental and may change significantly.
3640 class V8_EXPORT Int16Array : public TypedArray {
3642 static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
3643 size_t byte_offset, size_t length);
3644 static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3645 size_t byte_offset, size_t length);
3646 V8_INLINE static Int16Array* Cast(Value* obj);
3650 static void CheckCast(Value* obj);
3655 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3656 * This API is experimental and may change significantly.
3658 class V8_EXPORT Uint32Array : public TypedArray {
3660 static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
3661 size_t byte_offset, size_t length);
3662 static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3663 size_t byte_offset, size_t length);
3664 V8_INLINE static Uint32Array* Cast(Value* obj);
3668 static void CheckCast(Value* obj);
3673 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3674 * This API is experimental and may change significantly.
3676 class V8_EXPORT Int32Array : public TypedArray {
3678 static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
3679 size_t byte_offset, size_t length);
3680 static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3681 size_t byte_offset, size_t length);
3682 V8_INLINE static Int32Array* Cast(Value* obj);
3686 static void CheckCast(Value* obj);
3691 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3692 * This API is experimental and may change significantly.
3694 class V8_EXPORT Float32Array : public TypedArray {
3696 static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
3697 size_t byte_offset, size_t length);
3698 static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3699 size_t byte_offset, size_t length);
3700 V8_INLINE static Float32Array* Cast(Value* obj);
3704 static void CheckCast(Value* obj);
3709 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3710 * This API is experimental and may change significantly.
3712 class V8_EXPORT Float64Array : public TypedArray {
3714 static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
3715 size_t byte_offset, size_t length);
3716 static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3717 size_t byte_offset, size_t length);
3718 V8_INLINE static Float64Array* Cast(Value* obj);
3722 static void CheckCast(Value* obj);
3727 * An instance of DataView constructor (ES6 draft 15.13.7).
3728 * This API is experimental and may change significantly.
3730 class V8_EXPORT DataView : public ArrayBufferView {
3732 static Local<DataView> New(Local<ArrayBuffer> array_buffer,
3733 size_t byte_offset, size_t length);
3734 static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
3735 size_t byte_offset, size_t length);
3736 V8_INLINE static DataView* Cast(Value* obj);
3740 static void CheckCast(Value* obj);
3745 * An instance of the built-in SharedArrayBuffer constructor.
3746 * This API is experimental and may change significantly.
3748 class V8_EXPORT SharedArrayBuffer : public Object {
3751 * The contents of an |SharedArrayBuffer|. Externalization of
3752 * |SharedArrayBuffer| returns an instance of this class, populated, with a
3753 * pointer to data and byte length.
3755 * The Data pointer of SharedArrayBuffer::Contents is always allocated with
3756 * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
3757 * v8::Isolate::CreateParams::array_buffer_allocator.
3759 * This API is experimental and may change significantly.
3761 class V8_EXPORT Contents { // NOLINT
3763 Contents() : data_(NULL), byte_length_(0) {}
3765 void* Data() const { return data_; }
3766 size_t ByteLength() const { return byte_length_; }
3770 size_t byte_length_;
3772 friend class SharedArrayBuffer;
3777 * Data length in bytes.
3779 size_t ByteLength() const;
3782 * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
3783 * Allocated memory will be owned by a created SharedArrayBuffer and
3784 * will be deallocated when it is garbage-collected,
3785 * unless the object is externalized.
3787 static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
3790 * Create a new SharedArrayBuffer over an existing memory block. The created
3791 * array buffer is immediately in externalized state unless otherwise
3792 * specified. The memory block will not be reclaimed when a created
3793 * SharedArrayBuffer is garbage-collected.
3795 static Local<SharedArrayBuffer> New(
3796 Isolate* isolate, void* data, size_t byte_length,
3797 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3800 * Returns true if SharedArrayBuffer is externalized, that is, does not
3801 * own its memory block.
3803 bool IsExternal() const;
3806 * Make this SharedArrayBuffer external. The pointer to underlying memory
3807 * block and byte length are returned as |Contents| structure. After
3808 * SharedArrayBuffer had been etxrenalized, it does no longer owns the memory
3809 * block. The caller should take steps to free memory when it is no longer
3812 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3813 * by the allocator specified in
3814 * v8::Isolate::CreateParams::array_buffer_allocator.
3817 Contents Externalize();
3820 * Get a pointer to the ArrayBuffer's underlying memory block without
3821 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3822 * will become invalid as soon as the ArrayBuffer became garbage collected.
3824 * The embedder should make sure to hold a strong reference to the
3825 * ArrayBuffer while accessing this pointer.
3827 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3828 * by the allocator specified in
3829 * v8::Isolate::CreateParams::array_buffer_allocator.
3831 Contents GetContents();
3833 V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
3835 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3838 SharedArrayBuffer();
3839 static void CheckCast(Value* obj);
3844 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3846 class V8_EXPORT Date : public Object {
3848 static V8_DEPRECATE_SOON("Use maybe version.",
3849 Local<Value> New(Isolate* isolate, double time));
3850 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
3854 * A specialization of Value::NumberValue that is more efficient
3855 * because we know the structure of this object.
3857 double ValueOf() const;
3859 V8_INLINE static Date* Cast(v8::Value* obj);
3862 * Notification that the embedder has changed the time zone,
3863 * daylight savings time, or other date / time configuration
3864 * parameters. V8 keeps a cache of various values used for
3865 * date / time computation. This notification will reset
3866 * those cached values for the current context so that date /
3867 * time configuration changes would be reflected in the Date
3870 * This API should not be called more than needed as it will
3871 * negatively impact the performance of date operations.
3873 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3876 static void CheckCast(v8::Value* obj);
3881 * A Number object (ECMA-262, 4.3.21).
3883 class V8_EXPORT NumberObject : public Object {
3885 static Local<Value> New(Isolate* isolate, double value);
3887 double ValueOf() const;
3889 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3892 static void CheckCast(v8::Value* obj);
3897 * A Boolean object (ECMA-262, 4.3.15).
3899 class V8_EXPORT BooleanObject : public Object {
3901 static Local<Value> New(bool value);
3903 bool ValueOf() const;
3905 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3908 static void CheckCast(v8::Value* obj);
3913 * A String object (ECMA-262, 4.3.18).
3915 class V8_EXPORT StringObject : public Object {
3917 static Local<Value> New(Local<String> value);
3919 Local<String> ValueOf() const;
3921 V8_INLINE static StringObject* Cast(v8::Value* obj);
3924 static void CheckCast(v8::Value* obj);
3929 * A Symbol object (ECMA-262 edition 6).
3931 * This is an experimental feature. Use at your own risk.
3933 class V8_EXPORT SymbolObject : public Object {
3935 static Local<Value> New(Isolate* isolate, Local<Symbol> value);
3937 Local<Symbol> ValueOf() const;
3939 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3942 static void CheckCast(v8::Value* obj);
3947 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3949 class V8_EXPORT RegExp : public Object {
3952 * Regular expression flag bits. They can be or'ed to enable a set
3963 * Creates a regular expression from the given pattern string and
3964 * the flags bit field. May throw a JavaScript exception as
3965 * described in ECMA-262, 15.10.4.1.
3968 * RegExp::New(v8::String::New("foo"),
3969 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3970 * is equivalent to evaluating "/foo/gm".
3972 static V8_DEPRECATE_SOON("Use maybe version",
3973 Local<RegExp> New(Local<String> pattern,
3975 static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
3976 Local<String> pattern,
3980 * Returns the value of the source property: a string representing
3981 * the regular expression.
3983 Local<String> GetSource() const;
3986 * Returns the flags bit field.
3988 Flags GetFlags() const;
3990 V8_INLINE static RegExp* Cast(v8::Value* obj);
3993 static void CheckCast(v8::Value* obj);
3998 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3999 * to associate C++ data structures with JavaScript objects.
4001 class V8_EXPORT External : public Value {
4003 static Local<External> New(Isolate* isolate, void* value);
4004 V8_INLINE static External* Cast(Value* obj);
4005 void* Value() const;
4007 static void CheckCast(v8::Value* obj);
4011 // --- Templates ---
4015 * The superclass of object and function templates.
4017 class V8_EXPORT Template : public Data {
4019 /** Adds a property to each instance created by this template.*/
4020 void Set(Local<Name> name, Local<Data> value,
4021 PropertyAttribute attributes = None);
4022 V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
4024 void SetAccessorProperty(
4026 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
4027 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
4028 PropertyAttribute attribute = None,
4029 AccessControl settings = DEFAULT);
4032 * Whenever the property with the given name is accessed on objects
4033 * created from this Template the getter and setter callbacks
4034 * are called instead of getting and setting the property directly
4035 * on the JavaScript object.
4037 * \param name The name of the property for which an accessor is added.
4038 * \param getter The callback to invoke when getting the property.
4039 * \param setter The callback to invoke when setting the property.
4040 * \param data A piece of data that will be passed to the getter and setter
4041 * callbacks whenever they are invoked.
4042 * \param settings Access control settings for the accessor. This is a bit
4043 * field consisting of one of more of
4044 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4045 * The default is to not allow cross-context access.
4046 * ALL_CAN_READ means that all cross-context reads are allowed.
4047 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4048 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4049 * cross-context access.
4050 * \param attribute The attributes of the property for which an accessor
4052 * \param signature The signature describes valid receivers for the accessor
4053 * and is used to perform implicit instance checks against them. If the
4054 * receiver is incompatible (i.e. is not an instance of the constructor as
4055 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4056 * thrown and no callback is invoked.
4058 void SetNativeDataProperty(
4059 Local<String> name, AccessorGetterCallback getter,
4060 AccessorSetterCallback setter = 0,
4061 // TODO(dcarney): gcc can't handle Local below
4062 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4063 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4064 AccessControl settings = DEFAULT);
4065 void SetNativeDataProperty(
4066 Local<Name> name, AccessorNameGetterCallback getter,
4067 AccessorNameSetterCallback setter = 0,
4068 // TODO(dcarney): gcc can't handle Local below
4069 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4070 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4071 AccessControl settings = DEFAULT);
4076 friend class ObjectTemplate;
4077 friend class FunctionTemplate;
4082 * NamedProperty[Getter|Setter] are used as interceptors on object.
4083 * See ObjectTemplate::SetNamedPropertyHandler.
4085 typedef void (*NamedPropertyGetterCallback)(
4086 Local<String> property,
4087 const PropertyCallbackInfo<Value>& info);
4091 * Returns the value if the setter intercepts the request.
4092 * Otherwise, returns an empty handle.
4094 typedef void (*NamedPropertySetterCallback)(
4095 Local<String> property,
4097 const PropertyCallbackInfo<Value>& info);
4101 * Returns a non-empty handle if the interceptor intercepts the request.
4102 * The result is an integer encoding property attributes (like v8::None,
4103 * v8::DontEnum, etc.)
4105 typedef void (*NamedPropertyQueryCallback)(
4106 Local<String> property,
4107 const PropertyCallbackInfo<Integer>& info);
4111 * Returns a non-empty handle if the deleter intercepts the request.
4112 * The return value is true if the property could be deleted and false
4115 typedef void (*NamedPropertyDeleterCallback)(
4116 Local<String> property,
4117 const PropertyCallbackInfo<Boolean>& info);
4121 * Returns an array containing the names of the properties the named
4122 * property getter intercepts.
4124 typedef void (*NamedPropertyEnumeratorCallback)(
4125 const PropertyCallbackInfo<Array>& info);
4128 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
4129 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
4131 * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
4132 * See ObjectTemplate::SetNamedPropertyHandler.
4134 typedef void (*GenericNamedPropertyGetterCallback)(
4135 Local<Name> property, const PropertyCallbackInfo<Value>& info);
4139 * Returns the value if the setter intercepts the request.
4140 * Otherwise, returns an empty handle.
4142 typedef void (*GenericNamedPropertySetterCallback)(
4143 Local<Name> property, Local<Value> value,
4144 const PropertyCallbackInfo<Value>& info);
4148 * Returns a non-empty handle if the interceptor intercepts the request.
4149 * The result is an integer encoding property attributes (like v8::None,
4150 * v8::DontEnum, etc.)
4152 typedef void (*GenericNamedPropertyQueryCallback)(
4153 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4157 * Returns a non-empty handle if the deleter intercepts the request.
4158 * The return value is true if the property could be deleted and false
4161 typedef void (*GenericNamedPropertyDeleterCallback)(
4162 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4166 * Returns an array containing the names of the properties the named
4167 * property getter intercepts.
4169 typedef void (*GenericNamedPropertyEnumeratorCallback)(
4170 const PropertyCallbackInfo<Array>& info);
4174 * Returns the value of the property if the getter intercepts the
4175 * request. Otherwise, returns an empty handle.
4177 typedef void (*IndexedPropertyGetterCallback)(
4179 const PropertyCallbackInfo<Value>& info);
4183 * Returns the value if the setter intercepts the request.
4184 * Otherwise, returns an empty handle.
4186 typedef void (*IndexedPropertySetterCallback)(
4189 const PropertyCallbackInfo<Value>& info);
4193 * Returns a non-empty handle if the interceptor intercepts the request.
4194 * The result is an integer encoding property attributes.
4196 typedef void (*IndexedPropertyQueryCallback)(
4198 const PropertyCallbackInfo<Integer>& info);
4202 * Returns a non-empty handle if the deleter intercepts the request.
4203 * The return value is true if the property could be deleted and false
4206 typedef void (*IndexedPropertyDeleterCallback)(
4208 const PropertyCallbackInfo<Boolean>& info);
4212 * Returns an array containing the indices of the properties the
4213 * indexed property getter intercepts.
4215 typedef void (*IndexedPropertyEnumeratorCallback)(
4216 const PropertyCallbackInfo<Array>& info);
4220 * Access type specification.
4232 * Returns true if cross-context access should be allowed to the named
4233 * property with the given key on the host object.
4235 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4242 * Returns true if cross-context access should be allowed to the indexed
4243 * property with the given index on the host object.
4245 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4252 * A FunctionTemplate is used to create functions at runtime. There
4253 * can only be one function created from a FunctionTemplate in a
4254 * context. The lifetime of the created function is equal to the
4255 * lifetime of the context. So in case the embedder needs to create
4256 * temporary functions that can be collected using Scripts is
4259 * Any modification of a FunctionTemplate after first instantiation will trigger
4262 * A FunctionTemplate can have properties, these properties are added to the
4263 * function object when it is created.
4265 * A FunctionTemplate has a corresponding instance template which is
4266 * used to create object instances when the function is used as a
4267 * constructor. Properties added to the instance template are added to
4268 * each object instance.
4270 * A FunctionTemplate can have a prototype template. The prototype template
4271 * is used to create the prototype object of the function.
4273 * The following example shows how to use a FunctionTemplate:
4276 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4277 * t->Set("func_property", v8::Number::New(1));
4279 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4280 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4281 * proto_t->Set("proto_const", v8::Number::New(2));
4283 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4284 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4285 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4286 * instance_t->Set("instance_property", Number::New(3));
4288 * v8::Local<v8::Function> function = t->GetFunction();
4289 * v8::Local<v8::Object> instance = function->NewInstance();
4292 * Let's use "function" as the JS variable name of the function object
4293 * and "instance" for the instance object created above. The function
4294 * and the instance will have the following properties:
4297 * func_property in function == true;
4298 * function.func_property == 1;
4300 * function.prototype.proto_method() invokes 'InvokeCallback'
4301 * function.prototype.proto_const == 2;
4303 * instance instanceof function == true;
4304 * instance.instance_accessor calls 'InstanceAccessorCallback'
4305 * instance.instance_property == 3;
4308 * A FunctionTemplate can inherit from another one by calling the
4309 * FunctionTemplate::Inherit method. The following graph illustrates
4310 * the semantics of inheritance:
4313 * FunctionTemplate Parent -> Parent() . prototype -> { }
4315 * | Inherit(Parent) | .__proto__
4317 * FunctionTemplate Child -> Child() . prototype -> { }
4320 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4321 * object of the Child() function has __proto__ pointing to the
4322 * Parent() function's prototype object. An instance of the Child
4323 * function has all properties on Parent's instance templates.
4325 * Let Parent be the FunctionTemplate initialized in the previous
4326 * section and create a Child FunctionTemplate by:
4329 * Local<FunctionTemplate> parent = t;
4330 * Local<FunctionTemplate> child = FunctionTemplate::New();
4331 * child->Inherit(parent);
4333 * Local<Function> child_function = child->GetFunction();
4334 * Local<Object> child_instance = child_function->NewInstance();
4337 * The Child function and Child instance will have the following
4341 * child_func.prototype.__proto__ == function.prototype;
4342 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
4343 * child_instance.instance_property == 3;
4346 class V8_EXPORT FunctionTemplate : public Template {
4348 /** Creates a function template.*/
4349 static Local<FunctionTemplate> New(
4350 Isolate* isolate, FunctionCallback callback = 0,
4351 Local<Value> data = Local<Value>(),
4352 Local<Signature> signature = Local<Signature>(), int length = 0);
4354 /** Returns the unique function instance in the current execution context.*/
4355 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4356 V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
4357 Local<Context> context);
4360 * Set the call-handler callback for a FunctionTemplate. This
4361 * callback is called whenever the function created from this
4362 * FunctionTemplate is called.
4364 void SetCallHandler(FunctionCallback callback,
4365 Local<Value> data = Local<Value>());
4367 /** Set the predefined length property for the FunctionTemplate. */
4368 void SetLength(int length);
4370 /** Get the InstanceTemplate. */
4371 Local<ObjectTemplate> InstanceTemplate();
4373 /** Causes the function template to inherit from a parent function template.*/
4374 void Inherit(Local<FunctionTemplate> parent);
4377 * A PrototypeTemplate is the template used to create the prototype object
4378 * of the function created by this template.
4380 Local<ObjectTemplate> PrototypeTemplate();
4383 * Set the class name of the FunctionTemplate. This is used for
4384 * printing objects created with the function created from the
4385 * FunctionTemplate as its constructor.
4387 void SetClassName(Local<String> name);
4391 * When set to true, no access check will be performed on the receiver of a
4392 * function call. Currently defaults to true, but this is subject to change.
4394 void SetAcceptAnyReceiver(bool value);
4397 * Determines whether the __proto__ accessor ignores instances of
4398 * the function template. If instances of the function template are
4399 * ignored, __proto__ skips all instances and instead returns the
4400 * next object in the prototype chain.
4402 * Call with a value of true to make the __proto__ accessor ignore
4403 * instances of the function template. Call with a value of false
4404 * to make the __proto__ accessor not ignore instances of the
4405 * function template. By default, instances of a function template
4408 void SetHiddenPrototype(bool value);
4411 * Sets the ReadOnly flag in the attributes of the 'prototype' property
4412 * of functions created from this FunctionTemplate to true.
4414 void ReadOnlyPrototype();
4417 * Removes the prototype property from functions created from this
4420 void RemovePrototype();
4423 * Returns true if the given object is an instance of this function
4426 bool HasInstance(Local<Value> object);
4430 friend class Context;
4431 friend class ObjectTemplate;
4435 enum class PropertyHandlerFlags {
4437 // See ALL_CAN_READ above.
4439 // Will not call into interceptor for properties on the receiver or prototype
4440 // chain. Currently only valid for named interceptors.
4441 kNonMasking = 1 << 1,
4442 // Will not call into interceptor for symbol lookup. Only meaningful for
4443 // named interceptors.
4444 kOnlyInterceptStrings = 1 << 2,
4448 struct NamedPropertyHandlerConfiguration {
4449 NamedPropertyHandlerConfiguration(
4450 /** Note: getter is required **/
4451 GenericNamedPropertyGetterCallback getter = 0,
4452 GenericNamedPropertySetterCallback setter = 0,
4453 GenericNamedPropertyQueryCallback query = 0,
4454 GenericNamedPropertyDeleterCallback deleter = 0,
4455 GenericNamedPropertyEnumeratorCallback enumerator = 0,
4456 Local<Value> data = Local<Value>(),
4457 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4462 enumerator(enumerator),
4466 GenericNamedPropertyGetterCallback getter;
4467 GenericNamedPropertySetterCallback setter;
4468 GenericNamedPropertyQueryCallback query;
4469 GenericNamedPropertyDeleterCallback deleter;
4470 GenericNamedPropertyEnumeratorCallback enumerator;
4472 PropertyHandlerFlags flags;
4476 struct IndexedPropertyHandlerConfiguration {
4477 IndexedPropertyHandlerConfiguration(
4478 /** Note: getter is required **/
4479 IndexedPropertyGetterCallback getter = 0,
4480 IndexedPropertySetterCallback setter = 0,
4481 IndexedPropertyQueryCallback query = 0,
4482 IndexedPropertyDeleterCallback deleter = 0,
4483 IndexedPropertyEnumeratorCallback enumerator = 0,
4484 Local<Value> data = Local<Value>(),
4485 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4490 enumerator(enumerator),
4494 IndexedPropertyGetterCallback getter;
4495 IndexedPropertySetterCallback setter;
4496 IndexedPropertyQueryCallback query;
4497 IndexedPropertyDeleterCallback deleter;
4498 IndexedPropertyEnumeratorCallback enumerator;
4500 PropertyHandlerFlags flags;
4505 * An ObjectTemplate is used to create objects at runtime.
4507 * Properties added to an ObjectTemplate are added to each object
4508 * created from the ObjectTemplate.
4510 class V8_EXPORT ObjectTemplate : public Template {
4512 /** Creates an ObjectTemplate. */
4513 static Local<ObjectTemplate> New(
4515 Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
4516 static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4518 /** Creates a new instance of this template.*/
4519 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4520 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
4523 * Sets an accessor on the object template.
4525 * Whenever the property with the given name is accessed on objects
4526 * created from this ObjectTemplate the getter and setter callbacks
4527 * are called instead of getting and setting the property directly
4528 * on the JavaScript object.
4530 * \param name The name of the property for which an accessor is added.
4531 * \param getter The callback to invoke when getting the property.
4532 * \param setter The callback to invoke when setting the property.
4533 * \param data A piece of data that will be passed to the getter and setter
4534 * callbacks whenever they are invoked.
4535 * \param settings Access control settings for the accessor. This is a bit
4536 * field consisting of one of more of
4537 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4538 * The default is to not allow cross-context access.
4539 * ALL_CAN_READ means that all cross-context reads are allowed.
4540 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4541 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4542 * cross-context access.
4543 * \param attribute The attributes of the property for which an accessor
4545 * \param signature The signature describes valid receivers for the accessor
4546 * and is used to perform implicit instance checks against them. If the
4547 * receiver is incompatible (i.e. is not an instance of the constructor as
4548 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4549 * thrown and no callback is invoked.
4552 Local<String> name, AccessorGetterCallback getter,
4553 AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4554 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4555 Local<AccessorSignature> signature = Local<AccessorSignature>());
4557 Local<Name> name, AccessorNameGetterCallback getter,
4558 AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4559 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4560 Local<AccessorSignature> signature = Local<AccessorSignature>());
4563 * Sets a named property handler on the object template.
4565 * Whenever a property whose name is a string is accessed on objects created
4566 * from this object template, the provided callback is invoked instead of
4567 * accessing the property directly on the JavaScript object.
4569 * Note that new code should use the second version that can intercept
4570 * symbol-named properties as well as string-named properties.
4572 * \param getter The callback to invoke when getting a property.
4573 * \param setter The callback to invoke when setting a property.
4574 * \param query The callback to invoke to check if a property is present,
4575 * and if present, get its attributes.
4576 * \param deleter The callback to invoke when deleting a property.
4577 * \param enumerator The callback to invoke to enumerate all the named
4578 * properties of an object.
4579 * \param data A piece of data that will be passed to the callbacks
4580 * whenever they are invoked.
4582 // TODO(dcarney): deprecate
4583 void SetNamedPropertyHandler(NamedPropertyGetterCallback getter,
4584 NamedPropertySetterCallback setter = 0,
4585 NamedPropertyQueryCallback query = 0,
4586 NamedPropertyDeleterCallback deleter = 0,
4587 NamedPropertyEnumeratorCallback enumerator = 0,
4588 Local<Value> data = Local<Value>());
4589 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4592 * Sets an indexed property handler on the object template.
4594 * Whenever an indexed property is accessed on objects created from
4595 * this object template, the provided callback is invoked instead of
4596 * accessing the property directly on the JavaScript object.
4598 * \param getter The callback to invoke when getting a property.
4599 * \param setter The callback to invoke when setting a property.
4600 * \param query The callback to invoke to check if an object has a property.
4601 * \param deleter The callback to invoke when deleting a property.
4602 * \param enumerator The callback to invoke to enumerate all the indexed
4603 * properties of an object.
4604 * \param data A piece of data that will be passed to the callbacks
4605 * whenever they are invoked.
4607 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4608 // TODO(dcarney): deprecate
4609 void SetIndexedPropertyHandler(
4610 IndexedPropertyGetterCallback getter,
4611 IndexedPropertySetterCallback setter = 0,
4612 IndexedPropertyQueryCallback query = 0,
4613 IndexedPropertyDeleterCallback deleter = 0,
4614 IndexedPropertyEnumeratorCallback enumerator = 0,
4615 Local<Value> data = Local<Value>()) {
4616 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4617 deleter, enumerator, data));
4620 * Sets the callback to be used when calling instances created from
4621 * this template as a function. If no callback is set, instances
4622 * behave like normal JavaScript objects that cannot be called as a
4625 void SetCallAsFunctionHandler(FunctionCallback callback,
4626 Local<Value> data = Local<Value>());
4629 * Mark object instances of the template as undetectable.
4631 * In many ways, undetectable objects behave as though they are not
4632 * there. They behave like 'undefined' in conditionals and when
4633 * printed. However, properties can be accessed and called as on
4636 void MarkAsUndetectable();
4639 * Sets access check callbacks on the object template and enables
4642 * When accessing properties on instances of this object template,
4643 * the access check callback will be called to determine whether or
4644 * not to allow cross-context access to the properties.
4646 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4647 IndexedSecurityCallback indexed_handler,
4648 Local<Value> data = Local<Value>());
4651 * Gets the number of internal fields for objects generated from
4654 int InternalFieldCount();
4657 * Sets the number of internal fields for objects generated from
4660 void SetInternalFieldCount(int value);
4664 static Local<ObjectTemplate> New(internal::Isolate* isolate,
4665 Local<FunctionTemplate> constructor);
4666 friend class FunctionTemplate;
4671 * A Signature specifies which receiver is valid for a function.
4673 class V8_EXPORT Signature : public Data {
4675 static Local<Signature> New(
4677 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4685 * An AccessorSignature specifies which receivers are valid parameters
4686 * to an accessor callback.
4688 class V8_EXPORT AccessorSignature : public Data {
4690 static Local<AccessorSignature> New(
4692 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4695 AccessorSignature();
4700 * A utility for determining the type of objects based on the template
4701 * they were constructed from.
4703 class V8_EXPORT TypeSwitch : public Data {
4705 static Local<TypeSwitch> New(Local<FunctionTemplate> type);
4706 static Local<TypeSwitch> New(int argc, Local<FunctionTemplate> types[]);
4707 int match(Local<Value> value);
4714 // --- Extensions ---
4716 class V8_EXPORT ExternalOneByteStringResourceImpl
4717 : public String::ExternalOneByteStringResource {
4719 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4720 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4721 : data_(data), length_(length) {}
4722 const char* data() const { return data_; }
4723 size_t length() const { return length_; }
4733 class V8_EXPORT Extension { // NOLINT
4735 // Note that the strings passed into this constructor must live as long
4736 // as the Extension itself.
4737 Extension(const char* name,
4738 const char* source = 0,
4740 const char** deps = 0,
4741 int source_length = -1);
4742 virtual ~Extension() { }
4743 virtual v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
4744 v8::Isolate* isolate, v8::Local<v8::String> name) {
4745 return v8::Local<v8::FunctionTemplate>();
4748 const char* name() const { return name_; }
4749 size_t source_length() const { return source_length_; }
4750 const String::ExternalOneByteStringResource* source() const {
4752 int dependency_count() { return dep_count_; }
4753 const char** dependencies() { return deps_; }
4754 void set_auto_enable(bool value) { auto_enable_ = value; }
4755 bool auto_enable() { return auto_enable_; }
4759 size_t source_length_; // expected to initialize before source_
4760 ExternalOneByteStringResourceImpl source_;
4765 // Disallow copying and assigning.
4766 Extension(const Extension&);
4767 void operator=(const Extension&);
4771 void V8_EXPORT RegisterExtension(Extension* extension);
4776 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
4777 V8_INLINE Local<Primitive> Null(Isolate* isolate);
4778 V8_INLINE Local<Boolean> True(Isolate* isolate);
4779 V8_INLINE Local<Boolean> False(Isolate* isolate);
4783 * A set of constraints that specifies the limits of the runtime's memory use.
4784 * You must set the heap size before initializing the VM - the size cannot be
4785 * adjusted after the VM is initialized.
4787 * If you are using threads then you should hold the V8::Locker lock while
4788 * setting the stack limit and you must set a non-default stack limit separately
4791 class V8_EXPORT ResourceConstraints {
4793 ResourceConstraints();
4796 * Configures the constraints with reasonable default values based on the
4797 * capabilities of the current device the VM is running on.
4799 * \param physical_memory The total amount of physical memory on the current
4801 * \param virtual_memory_limit The amount of virtual memory on the current
4802 * device, in bytes, or zero, if there is no limit.
4804 void ConfigureDefaults(uint64_t physical_memory,
4805 uint64_t virtual_memory_limit);
4807 // Deprecated, will be removed soon.
4808 V8_DEPRECATED("Use two-args version instead",
4809 void ConfigureDefaults(uint64_t physical_memory,
4810 uint64_t virtual_memory_limit,
4811 uint32_t number_of_processors));
4813 int max_semi_space_size() const { return max_semi_space_size_; }
4814 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4815 int max_old_space_size() const { return max_old_space_size_; }
4816 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4817 int max_executable_size() const { return max_executable_size_; }
4818 void set_max_executable_size(int value) { max_executable_size_ = value; }
4819 uint32_t* stack_limit() const { return stack_limit_; }
4820 // Sets an address beyond which the VM's stack may not grow.
4821 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4822 V8_DEPRECATED("Unused, will be removed", int max_available_threads() const) {
4823 return max_available_threads_;
4825 // Set the number of threads available to V8, assuming at least 1.
4826 V8_DEPRECATED("Unused, will be removed",
4827 void set_max_available_threads(int value)) {
4828 max_available_threads_ = value;
4830 size_t code_range_size() const { return code_range_size_; }
4831 void set_code_range_size(size_t value) {
4832 code_range_size_ = value;
4836 int max_semi_space_size_;
4837 int max_old_space_size_;
4838 int max_executable_size_;
4839 uint32_t* stack_limit_;
4840 int max_available_threads_;
4841 size_t code_range_size_;
4845 // --- Exceptions ---
4848 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4851 typedef void (*MessageCallback)(Local<Message> message, Local<Value> error);
4855 typedef void (*LogEventCallback)(const char* name, int event);
4858 * Create new error objects by calling the corresponding error object
4859 * constructor with the message.
4861 class V8_EXPORT Exception {
4863 static Local<Value> RangeError(Local<String> message);
4864 static Local<Value> ReferenceError(Local<String> message);
4865 static Local<Value> SyntaxError(Local<String> message);
4866 static Local<Value> TypeError(Local<String> message);
4867 static Local<Value> Error(Local<String> message);
4870 * Creates an error message for the given exception.
4871 * Will try to reconstruct the original stack trace from the exception value,
4872 * or capture the current stack trace if not available.
4874 static Local<Message> CreateMessage(Local<Value> exception);
4877 * Returns the original stack trace that was captured at the creation time
4878 * of a given exception, or an empty handle if not available.
4880 static Local<StackTrace> GetStackTrace(Local<Value> exception);
4884 // --- Counters Callbacks ---
4886 typedef int* (*CounterLookupCallback)(const char* name);
4888 typedef void* (*CreateHistogramCallback)(const char* name,
4893 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4895 // --- Memory Allocation Callback ---
4897 kObjectSpaceNewSpace = 1 << 0,
4898 kObjectSpaceOldSpace = 1 << 1,
4899 kObjectSpaceCodeSpace = 1 << 2,
4900 kObjectSpaceMapSpace = 1 << 3,
4901 kObjectSpaceLoSpace = 1 << 4,
4902 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldSpace |
4903 kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4907 enum AllocationAction {
4908 kAllocationActionAllocate = 1 << 0,
4909 kAllocationActionFree = 1 << 1,
4910 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4913 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4914 AllocationAction action,
4917 // --- Leave Script Callback ---
4918 typedef void (*CallCompletedCallback)();
4920 // --- Promise Reject Callback ---
4921 enum PromiseRejectEvent {
4922 kPromiseRejectWithNoHandler = 0,
4923 kPromiseHandlerAddedAfterReject = 1
4926 class PromiseRejectMessage {
4928 PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
4929 Local<Value> value, Local<StackTrace> stack_trace)
4930 : promise_(promise),
4933 stack_trace_(stack_trace) {}
4935 V8_INLINE Local<Promise> GetPromise() const { return promise_; }
4936 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4937 V8_INLINE Local<Value> GetValue() const { return value_; }
4939 // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4940 V8_INLINE Local<StackTrace> GetStackTrace() const { return stack_trace_; }
4943 Local<Promise> promise_;
4944 PromiseRejectEvent event_;
4945 Local<Value> value_;
4946 Local<StackTrace> stack_trace_;
4949 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4951 // --- Microtask Callback ---
4952 typedef void (*MicrotaskCallback)(void* data);
4954 // --- Failed Access Check Callback ---
4955 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4959 // --- AllowCodeGenerationFromStrings callbacks ---
4962 * Callback to check if code generation from strings is allowed. See
4963 * Context::AllowCodeGenerationFromStrings.
4965 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4967 // --- Garbage Collection Callbacks ---
4970 * Applications can register callback functions which will be called
4971 * before and after a garbage collection. Allocations are not
4972 * allowed in the callback functions, you therefore cannot manipulate
4973 * objects (set or delete properties for example) since it is possible
4974 * such operations will result in the allocation of objects.
4977 kGCTypeScavenge = 1 << 0,
4978 kGCTypeMarkSweepCompact = 1 << 1,
4979 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4982 enum GCCallbackFlags {
4983 kNoGCCallbackFlags = 0,
4984 kGCCallbackFlagCompacted = 1 << 0,
4985 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4986 kGCCallbackFlagForced = 1 << 2
4989 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4990 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4992 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4996 * Collection of V8 heap information.
4998 * Instances of this class can be passed to v8::V8::HeapStatistics to
4999 * get heap statistics from V8.
5001 class V8_EXPORT HeapStatistics {
5004 size_t total_heap_size() { return total_heap_size_; }
5005 size_t total_heap_size_executable() { return total_heap_size_executable_; }
5006 size_t total_physical_size() { return total_physical_size_; }
5007 size_t total_available_size() { return total_available_size_; }
5008 size_t used_heap_size() { return used_heap_size_; }
5009 size_t heap_size_limit() { return heap_size_limit_; }
5012 size_t total_heap_size_;
5013 size_t total_heap_size_executable_;
5014 size_t total_physical_size_;
5015 size_t total_available_size_;
5016 size_t used_heap_size_;
5017 size_t heap_size_limit_;
5020 friend class Isolate;
5024 class V8_EXPORT HeapSpaceStatistics {
5026 HeapSpaceStatistics();
5027 const char* space_name() { return space_name_; }
5028 size_t space_size() { return space_size_; }
5029 size_t space_used_size() { return space_used_size_; }
5030 size_t space_available_size() { return space_available_size_; }
5031 size_t physical_space_size() { return physical_space_size_; }
5034 const char* space_name_;
5036 size_t space_used_size_;
5037 size_t space_available_size_;
5038 size_t physical_space_size_;
5040 friend class Isolate;
5044 class V8_EXPORT HeapObjectStatistics {
5046 HeapObjectStatistics();
5047 const char* object_type() { return object_type_; }
5048 const char* object_sub_type() { return object_sub_type_; }
5049 size_t object_count() { return object_count_; }
5050 size_t object_size() { return object_size_; }
5053 const char* object_type_;
5054 const char* object_sub_type_;
5055 size_t object_count_;
5056 size_t object_size_;
5058 friend class Isolate;
5062 class RetainedObjectInfo;
5066 * FunctionEntryHook is the type of the profile entry hook called at entry to
5067 * any generated function when function-level profiling is enabled.
5069 * \param function the address of the function that's being entered.
5070 * \param return_addr_location points to a location on stack where the machine
5071 * return address resides. This can be used to identify the caller of
5072 * \p function, and/or modified to divert execution when \p function exits.
5074 * \note the entry hook must not cause garbage collection.
5076 typedef void (*FunctionEntryHook)(uintptr_t function,
5077 uintptr_t return_addr_location);
5080 * A JIT code event is issued each time code is added, moved or removed.
5082 * \note removal events are not currently issued.
5084 struct JitCodeEvent {
5089 CODE_ADD_LINE_POS_INFO,
5090 CODE_START_LINE_INFO_RECORDING,
5091 CODE_END_LINE_INFO_RECORDING
5093 // Definition of the code position type. The "POSITION" type means the place
5094 // in the source code which are of interest when making stack traces to
5095 // pin-point the source location of a stack frame as close as possible.
5096 // The "STATEMENT_POSITION" means the place at the beginning of each
5097 // statement, and is used to indicate possible break locations.
5098 enum PositionType { POSITION, STATEMENT_POSITION };
5102 // Start of the instructions.
5104 // Size of the instructions.
5106 // Script info for CODE_ADDED event.
5107 Local<UnboundScript> script;
5108 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
5109 // code line information which is returned from the
5110 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
5111 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
5115 // Name of the object associated with the code, note that the string is not
5118 // Number of chars in str.
5122 struct line_info_t {
5127 // The position type.
5128 PositionType position_type;
5132 // Only valid for CODE_ADDED.
5135 // Only valid for CODE_ADD_LINE_POS_INFO
5136 struct line_info_t line_info;
5138 // New location of instructions. Only valid for CODE_MOVED.
5139 void* new_code_start;
5144 * Option flags passed to the SetJitCodeEventHandler function.
5146 enum JitCodeEventOptions {
5147 kJitCodeEventDefault = 0,
5148 // Generate callbacks for already existent code.
5149 kJitCodeEventEnumExisting = 1
5154 * Callback function passed to SetJitCodeEventHandler.
5156 * \param event code add, move or removal event.
5158 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
5162 * Interface for iterating through all external resources in the heap.
5164 class V8_EXPORT ExternalResourceVisitor { // NOLINT
5166 virtual ~ExternalResourceVisitor() {}
5167 virtual void VisitExternalString(Local<String> string) {}
5172 * Interface for iterating through all the persistent handles in the heap.
5174 class V8_EXPORT PersistentHandleVisitor { // NOLINT
5176 virtual ~PersistentHandleVisitor() {}
5177 virtual void VisitPersistentHandle(Persistent<Value>* value,
5178 uint16_t class_id) {}
5183 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
5184 * completely separate states. Objects from one isolate must not be used in
5185 * other isolates. The embedder can create multiple isolates and use them in
5186 * parallel in multiple threads. An isolate can be entered by at most one
5187 * thread at any given time. The Locker/Unlocker API must be used to
5190 class V8_EXPORT Isolate {
5193 * Initial configuration parameters for a new Isolate.
5195 struct CreateParams {
5198 code_event_handler(NULL),
5199 snapshot_blob(NULL),
5200 counter_lookup_callback(NULL),
5201 create_histogram_callback(NULL),
5202 add_histogram_sample_callback(NULL),
5203 array_buffer_allocator(NULL) {}
5206 * The optional entry_hook allows the host application to provide the
5207 * address of a function that's invoked on entry to every V8-generated
5208 * function. Note that entry_hook is invoked at the very start of each
5209 * generated function. Furthermore, if an entry_hook is given, V8 will
5210 * always run without a context snapshot.
5212 FunctionEntryHook entry_hook;
5215 * Allows the host application to provide the address of a function that is
5216 * notified each time code is added, moved or removed.
5218 JitCodeEventHandler code_event_handler;
5221 * ResourceConstraints to use for the new Isolate.
5223 ResourceConstraints constraints;
5226 * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5228 StartupData* snapshot_blob;
5232 * Enables the host application to provide a mechanism for recording
5233 * statistics counters.
5235 CounterLookupCallback counter_lookup_callback;
5238 * Enables the host application to provide a mechanism for recording
5239 * histograms. The CreateHistogram function returns a
5240 * histogram which will later be passed to the AddHistogramSample
5243 CreateHistogramCallback create_histogram_callback;
5244 AddHistogramSampleCallback add_histogram_sample_callback;
5247 * The ArrayBuffer::Allocator to use for allocating and freeing the backing
5248 * store of ArrayBuffers.
5250 ArrayBuffer::Allocator* array_buffer_allocator;
5255 * Stack-allocated class which sets the isolate for all operations
5256 * executed within a local scope.
5258 class V8_EXPORT Scope {
5260 explicit Scope(Isolate* isolate) : isolate_(isolate) {
5264 ~Scope() { isolate_->Exit(); }
5267 Isolate* const isolate_;
5269 // Prevent copying of Scope objects.
5270 Scope(const Scope&);
5271 Scope& operator=(const Scope&);
5276 * Assert that no Javascript code is invoked.
5278 class V8_EXPORT DisallowJavascriptExecutionScope {
5280 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
5282 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
5283 ~DisallowJavascriptExecutionScope();
5289 // Prevent copying of Scope objects.
5290 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5291 DisallowJavascriptExecutionScope& operator=(
5292 const DisallowJavascriptExecutionScope&);
5297 * Introduce exception to DisallowJavascriptExecutionScope.
5299 class V8_EXPORT AllowJavascriptExecutionScope {
5301 explicit AllowJavascriptExecutionScope(Isolate* isolate);
5302 ~AllowJavascriptExecutionScope();
5305 void* internal_throws_;
5306 void* internal_assert_;
5308 // Prevent copying of Scope objects.
5309 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5310 AllowJavascriptExecutionScope& operator=(
5311 const AllowJavascriptExecutionScope&);
5315 * Do not run microtasks while this scope is active, even if microtasks are
5316 * automatically executed otherwise.
5318 class V8_EXPORT SuppressMicrotaskExecutionScope {
5320 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
5321 ~SuppressMicrotaskExecutionScope();
5324 internal::Isolate* isolate_;
5326 // Prevent copying of Scope objects.
5327 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5328 SuppressMicrotaskExecutionScope& operator=(
5329 const SuppressMicrotaskExecutionScope&);
5333 * Types of garbage collections that can be requested via
5334 * RequestGarbageCollectionForTesting.
5336 enum GarbageCollectionType {
5337 kFullGarbageCollection,
5338 kMinorGarbageCollection
5342 * Features reported via the SetUseCounterCallback callback. Do not change
5343 * assigned numbers of existing items; add new features to the end of this
5346 enum UseCounterFeature {
5350 kMarkDequeOverflow = 3,
5351 kStoreBufferOverflow = 4,
5352 kSlotsBufferOverflow = 5,
5355 kUseCounterFeatureCount // This enum value must be last.
5358 typedef void (*UseCounterCallback)(Isolate* isolate,
5359 UseCounterFeature feature);
5363 * Creates a new isolate. Does not change the currently entered
5366 * When an isolate is no longer used its resources should be freed
5367 * by calling Dispose(). Using the delete operator is not allowed.
5369 * V8::Initialize() must have run prior to this.
5371 static Isolate* New(const CreateParams& params);
5373 static V8_DEPRECATED("Always pass CreateParams", Isolate* New());
5376 * Returns the entered isolate for the current thread or NULL in
5377 * case there is no current isolate.
5379 * This method must not be invoked before V8::Initialize() was invoked.
5381 static Isolate* GetCurrent();
5384 * Custom callback used by embedders to help V8 determine if it should abort
5385 * when it throws and no internal handler is predicted to catch the
5386 * exception. If --abort-on-uncaught-exception is used on the command line,
5387 * then V8 will abort if either:
5388 * - no custom callback is set.
5389 * - the custom callback set returns true.
5390 * Otherwise, the custom callback will not be called and V8 will not abort.
5392 typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*);
5393 void SetAbortOnUncaughtExceptionCallback(
5394 AbortOnUncaughtExceptionCallback callback);
5397 * Methods below this point require holding a lock (using Locker) in
5398 * a multi-threaded environment.
5402 * Sets this isolate as the entered one for the current thread.
5403 * Saves the previously entered one (if any), so that it can be
5404 * restored when exiting. Re-entering an isolate is allowed.
5409 * Exits this isolate by restoring the previously entered one in the
5410 * current thread. The isolate may still stay the same, if it was
5411 * entered more than once.
5413 * Requires: this == Isolate::GetCurrent().
5418 * Disposes the isolate. The isolate must not be entered by any
5419 * thread to be disposable.
5424 * Associate embedder-specific data with the isolate. |slot| has to be
5425 * between 0 and GetNumberOfDataSlots() - 1.
5427 V8_INLINE void SetData(uint32_t slot, void* data);
5430 * Retrieve embedder-specific data from the isolate.
5431 * Returns NULL if SetData has never been called for the given |slot|.
5433 V8_INLINE void* GetData(uint32_t slot);
5436 * Returns the maximum number of available embedder data slots. Valid slots
5437 * are in the range of 0 - GetNumberOfDataSlots() - 1.
5439 V8_INLINE static uint32_t GetNumberOfDataSlots();
5442 * Get statistics about the heap memory usage.
5444 void GetHeapStatistics(HeapStatistics* heap_statistics);
5447 * Returns the number of spaces in the heap.
5449 size_t NumberOfHeapSpaces();
5452 * Get the memory usage of a space in the heap.
5454 * \param space_statistics The HeapSpaceStatistics object to fill in
5456 * \param index The index of the space to get statistics from, which ranges
5457 * from 0 to NumberOfHeapSpaces() - 1.
5458 * \returns true on success.
5460 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
5464 * Returns the number of types of objects tracked in the heap at GC.
5466 size_t NumberOfTrackedHeapObjectTypes();
5469 * Get statistics about objects in the heap.
5471 * \param object_statistics The HeapObjectStatistics object to fill in
5472 * statistics of objects of given type, which were live in the previous GC.
5473 * \param type_index The index of the type of object to fill details about,
5474 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
5475 * \returns true on success.
5477 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
5481 * Get a call stack sample from the isolate.
5482 * \param state Execution state.
5483 * \param frames Caller allocated buffer to store stack frames.
5484 * \param frames_limit Maximum number of frames to capture. The buffer must
5485 * be large enough to hold the number of frames.
5486 * \param sample_info The sample info is filled up by the function
5487 * provides number of actual captured stack frames and
5488 * the current VM state.
5489 * \note GetStackSample should only be called when the JS thread is paused or
5490 * interrupted. Otherwise the behavior is undefined.
5492 void GetStackSample(const RegisterState& state, void** frames,
5493 size_t frames_limit, SampleInfo* sample_info);
5496 * Adjusts the amount of registered external memory. Used to give V8 an
5497 * indication of the amount of externally allocated memory that is kept alive
5498 * by JavaScript objects. V8 uses this to decide when to perform global
5499 * garbage collections. Registering externally allocated memory will trigger
5500 * global garbage collections more often than it would otherwise in an attempt
5501 * to garbage collect the JavaScript objects that keep the externally
5502 * allocated memory alive.
5504 * \param change_in_bytes the change in externally allocated memory that is
5505 * kept alive by JavaScript objects.
5506 * \returns the adjusted value.
5509 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5512 * Returns heap profiler for this isolate. Will return NULL until the isolate
5515 HeapProfiler* GetHeapProfiler();
5518 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5519 * is initialized. It is the embedder's responsibility to stop all CPU
5520 * profiling activities if it has started any.
5522 CpuProfiler* GetCpuProfiler();
5524 /** Returns true if this isolate has a current context. */
5527 /** Returns the context that is on the top of the stack. */
5528 Local<Context> GetCurrentContext();
5531 * Returns the context of the calling JavaScript code. That is the
5532 * context of the top-most JavaScript frame. If there are no
5533 * JavaScript frames an empty handle is returned.
5535 Local<Context> GetCallingContext();
5537 /** Returns the last entered context. */
5538 Local<Context> GetEnteredContext();
5541 * Schedules an exception to be thrown when returning to JavaScript. When an
5542 * exception has been scheduled it is illegal to invoke any JavaScript
5543 * operation; the caller must return immediately and only after the exception
5544 * has been handled does it become legal to invoke JavaScript operations.
5546 Local<Value> ThrowException(Local<Value> exception);
5549 * Allows the host application to group objects together. If one
5550 * object in the group is alive, all objects in the group are alive.
5551 * After each garbage collection, object groups are removed. It is
5552 * intended to be used in the before-garbage-collection callback
5553 * function, for instance to simulate DOM tree connections among JS
5554 * wrapper objects. Object groups for all dependent handles need to
5555 * be provided for kGCTypeMarkSweepCompact collections, for all other
5556 * garbage collection types it is sufficient to provide object groups
5557 * for partially dependent handles only.
5559 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5563 * Allows the host application to declare implicit references from an object
5564 * group to an object. If the objects of the object group are alive, the child
5565 * object is alive too. After each garbage collection, all implicit references
5566 * are removed. It is intended to be used in the before-garbage-collection
5567 * callback function.
5569 template<typename T> void SetReferenceFromGroup(UniqueId id,
5570 const Persistent<T>& child);
5573 * Allows the host application to declare implicit references from an object
5574 * to another object. If the parent object is alive, the child object is alive
5575 * too. After each garbage collection, all implicit references are removed. It
5576 * is intended to be used in the before-garbage-collection callback function.
5578 template<typename T, typename S>
5579 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5581 typedef void (*GCPrologueCallback)(Isolate* isolate,
5583 GCCallbackFlags flags);
5584 typedef void (*GCEpilogueCallback)(Isolate* isolate,
5586 GCCallbackFlags flags);
5589 * Enables the host application to receive a notification before a
5590 * garbage collection. Allocations are allowed in the callback function,
5591 * but the callback is not re-entrant: if the allocation inside it will
5592 * trigger the garbage collection, the callback won't be called again.
5593 * It is possible to specify the GCType filter for your callback. But it is
5594 * not possible to register the same callback function two times with
5595 * different GCType filters.
5597 void AddGCPrologueCallback(
5598 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5601 * This function removes callback which was installed by
5602 * AddGCPrologueCallback function.
5604 void RemoveGCPrologueCallback(GCPrologueCallback callback);
5607 * Enables the host application to receive a notification after a
5608 * garbage collection. Allocations are allowed in the callback function,
5609 * but the callback is not re-entrant: if the allocation inside it will
5610 * trigger the garbage collection, the callback won't be called again.
5611 * It is possible to specify the GCType filter for your callback. But it is
5612 * not possible to register the same callback function two times with
5613 * different GCType filters.
5615 void AddGCEpilogueCallback(
5616 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5619 * This function removes callback which was installed by
5620 * AddGCEpilogueCallback function.
5622 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5626 * Forcefully terminate the current thread of JavaScript execution
5627 * in the given isolate.
5629 * This method can be used by any thread even if that thread has not
5630 * acquired the V8 lock with a Locker object.
5632 void TerminateExecution();
5635 * Is V8 terminating JavaScript execution.
5637 * Returns true if JavaScript execution is currently terminating
5638 * because of a call to TerminateExecution. In that case there are
5639 * still JavaScript frames on the stack and the termination
5640 * exception is still active.
5642 bool IsExecutionTerminating();
5645 * Resume execution capability in the given isolate, whose execution
5646 * was previously forcefully terminated using TerminateExecution().
5648 * When execution is forcefully terminated using TerminateExecution(),
5649 * the isolate can not resume execution until all JavaScript frames
5650 * have propagated the uncatchable exception which is generated. This
5651 * method allows the program embedding the engine to handle the
5652 * termination event and resume execution capability, even if
5653 * JavaScript frames remain on the stack.
5655 * This method can be used by any thread even if that thread has not
5656 * acquired the V8 lock with a Locker object.
5658 void CancelTerminateExecution();
5661 * Request V8 to interrupt long running JavaScript code and invoke
5662 * the given |callback| passing the given |data| to it. After |callback|
5663 * returns control will be returned to the JavaScript code.
5664 * There may be a number of interrupt requests in flight.
5665 * Can be called from another thread without acquiring a |Locker|.
5666 * Registered |callback| must not reenter interrupted Isolate.
5668 void RequestInterrupt(InterruptCallback callback, void* data);
5671 * Request garbage collection in this Isolate. It is only valid to call this
5672 * function if --expose_gc was specified.
5674 * This should only be used for testing purposes and not to enforce a garbage
5675 * collection schedule. It has strong negative impact on the garbage
5676 * collection performance. Use IdleNotificationDeadline() or
5677 * LowMemoryNotification() instead to influence the garbage collection
5680 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5683 * Set the callback to invoke for logging event.
5685 void SetEventLogger(LogEventCallback that);
5688 * Adds a callback to notify the host application when a script finished
5689 * running. If a script re-enters the runtime during executing, the
5690 * CallCompletedCallback is only invoked when the outer-most script
5691 * execution ends. Executing scripts inside the callback do not trigger
5692 * further callbacks.
5694 void AddCallCompletedCallback(CallCompletedCallback callback);
5697 * Removes callback that was installed by AddCallCompletedCallback.
5699 void RemoveCallCompletedCallback(CallCompletedCallback callback);
5703 * Set callback to notify about promise reject with no handler, or
5704 * revocation of such a previous notification once the handler is added.
5706 void SetPromiseRejectCallback(PromiseRejectCallback callback);
5709 * Experimental: Runs the Microtask Work Queue until empty
5710 * Any exceptions thrown by microtask callbacks are swallowed.
5712 void RunMicrotasks();
5715 * Experimental: Enqueues the callback to the Microtask Work Queue
5717 void EnqueueMicrotask(Local<Function> microtask);
5720 * Experimental: Enqueues the callback to the Microtask Work Queue
5722 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5725 * Experimental: Controls whether the Microtask Work Queue is automatically
5726 * run when the script call depth decrements to zero.
5728 void SetAutorunMicrotasks(bool autorun);
5731 * Experimental: Returns whether the Microtask Work Queue is automatically
5732 * run when the script call depth decrements to zero.
5734 bool WillAutorunMicrotasks() const;
5737 * Sets a callback for counting the number of times a feature of V8 is used.
5739 void SetUseCounterCallback(UseCounterCallback callback);
5742 * Enables the host application to provide a mechanism for recording
5743 * statistics counters.
5745 void SetCounterFunction(CounterLookupCallback);
5748 * Enables the host application to provide a mechanism for recording
5749 * histograms. The CreateHistogram function returns a
5750 * histogram which will later be passed to the AddHistogramSample
5753 void SetCreateHistogramFunction(CreateHistogramCallback);
5754 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5757 * Optional notification that the embedder is idle.
5758 * V8 uses the notification to perform garbage collection.
5759 * This call can be used repeatedly if the embedder remains idle.
5760 * Returns true if the embedder should stop calling IdleNotificationDeadline
5761 * until real work has been done. This indicates that V8 has done
5762 * as much cleanup as it will be able to do.
5764 * The deadline_in_seconds argument specifies the deadline V8 has to finish
5765 * garbage collection work. deadline_in_seconds is compared with
5766 * MonotonicallyIncreasingTime() and should be based on the same timebase as
5767 * that function. There is no guarantee that the actual work will be done
5768 * within the time limit.
5770 bool IdleNotificationDeadline(double deadline_in_seconds);
5772 V8_DEPRECATE_SOON("use IdleNotificationDeadline()",
5773 bool IdleNotification(int idle_time_in_ms));
5776 * Optional notification that the system is running low on memory.
5777 * V8 uses these notifications to attempt to free memory.
5779 void LowMemoryNotification();
5782 * Optional notification that a context has been disposed. V8 uses
5783 * these notifications to guide the GC heuristic. Returns the number
5784 * of context disposals - including this one - since the last time
5785 * V8 had a chance to clean up.
5787 * The optional parameter |dependant_context| specifies whether the disposed
5788 * context was depending on state from other contexts or not.
5790 int ContextDisposedNotification(bool dependant_context = true);
5793 * Allows the host application to provide the address of a function that is
5794 * notified each time code is added, moved or removed.
5796 * \param options options for the JIT code event handler.
5797 * \param event_handler the JIT code event handler, which will be invoked
5798 * each time code is added, moved or removed.
5799 * \note \p event_handler won't get notified of existent code.
5800 * \note since code removal notifications are not currently issued, the
5801 * \p event_handler may get notifications of code that overlaps earlier
5802 * code notifications. This happens when code areas are reused, and the
5803 * earlier overlapping code areas should therefore be discarded.
5804 * \note the events passed to \p event_handler and the strings they point to
5805 * are not guaranteed to live past each call. The \p event_handler must
5806 * copy strings and other parameters it needs to keep around.
5807 * \note the set of events declared in JitCodeEvent::EventType is expected to
5808 * grow over time, and the JitCodeEvent structure is expected to accrue
5809 * new members. The \p event_handler function must ignore event codes
5810 * it does not recognize to maintain future compatibility.
5811 * \note Use Isolate::CreateParams to get events for code executed during
5814 void SetJitCodeEventHandler(JitCodeEventOptions options,
5815 JitCodeEventHandler event_handler);
5818 * Modifies the stack limit for this Isolate.
5820 * \param stack_limit An address beyond which the Vm's stack may not grow.
5822 * \note If you are using threads then you should hold the V8::Locker lock
5823 * while setting the stack limit and you must set a non-default stack
5824 * limit separately for each thread.
5826 void SetStackLimit(uintptr_t stack_limit);
5829 * Returns a memory range that can potentially contain jitted code.
5831 * On Win64, embedders are advised to install function table callbacks for
5832 * these ranges, as default SEH won't be able to unwind through jitted code.
5834 * The first page of the code range is reserved for the embedder and is
5835 * committed, writable, and executable.
5837 * Might be empty on other platforms.
5839 * https://code.google.com/p/v8/issues/detail?id=3598
5841 void GetCodeRange(void** start, size_t* length_in_bytes);
5843 /** Set the callback to invoke in case of fatal errors. */
5844 void SetFatalErrorHandler(FatalErrorCallback that);
5847 * Set the callback to invoke to check if code generation from
5848 * strings should be allowed.
5850 void SetAllowCodeGenerationFromStringsCallback(
5851 AllowCodeGenerationFromStringsCallback callback);
5854 * Check if V8 is dead and therefore unusable. This is the case after
5855 * fatal errors such as out-of-memory situations.
5860 * Adds a message listener.
5862 * The same message listener can be added more than once and in that
5863 * case it will be called more than once for each message.
5865 * If data is specified, it will be passed to the callback when it is called.
5866 * Otherwise, the exception object will be passed to the callback instead.
5868 bool AddMessageListener(MessageCallback that,
5869 Local<Value> data = Local<Value>());
5872 * Remove all message listeners from the specified callback function.
5874 void RemoveMessageListeners(MessageCallback that);
5876 /** Callback function for reporting failed access checks.*/
5877 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5880 * Tells V8 to capture current stack trace when uncaught exception occurs
5881 * and report it to the message listeners. The option is off by default.
5883 void SetCaptureStackTraceForUncaughtExceptions(
5884 bool capture, int frame_limit = 10,
5885 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5888 * Enables the host application to provide a mechanism to be notified
5889 * and perform custom logging when V8 Allocates Executable Memory.
5891 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5892 ObjectSpace space, AllocationAction action);
5895 * Removes callback that was installed by AddMemoryAllocationCallback.
5897 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5900 * Iterates through all external resources referenced from current isolate
5901 * heap. GC is not invoked prior to iterating, therefore there is no
5902 * guarantee that visited objects are still alive.
5904 void VisitExternalResources(ExternalResourceVisitor* visitor);
5907 * Iterates through all the persistent handles in the current isolate's heap
5908 * that have class_ids.
5910 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5913 * Iterates through all the persistent handles in the current isolate's heap
5914 * that have class_ids and are candidates to be marked as partially dependent
5915 * handles. This will visit handles to young objects created since the last
5916 * garbage collection but is free to visit an arbitrary superset of these
5919 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5922 template <class K, class V, class Traits>
5923 friend class PersistentValueMapBase;
5926 Isolate(const Isolate&);
5928 Isolate& operator=(const Isolate&);
5929 void* operator new(size_t size);
5930 void operator delete(void*, size_t);
5932 void SetObjectGroupId(internal::Object** object, UniqueId id);
5933 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5934 void SetReference(internal::Object** parent, internal::Object** child);
5935 void CollectAllGarbage(const char* gc_reason);
5938 class V8_EXPORT StartupData {
5946 * EntropySource is used as a callback function when v8 needs a source
5949 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5953 * ReturnAddressLocationResolver is used as a callback function when v8 is
5954 * resolving the location of a return address on the stack. Profilers that
5955 * change the return address on the stack can use this to resolve the stack
5956 * location to whereever the profiler stashed the original return address.
5958 * \param return_addr_location points to a location on stack where a machine
5959 * return address resides.
5960 * \returns either return_addr_location, or else a pointer to the profiler's
5961 * copy of the original return address.
5963 * \note the resolver function must not cause garbage collection.
5965 typedef uintptr_t (*ReturnAddressLocationResolver)(
5966 uintptr_t return_addr_location);
5970 * Container class for static utility functions.
5972 class V8_EXPORT V8 {
5974 /** Set the callback to invoke in case of fatal errors. */
5975 V8_INLINE static V8_DEPRECATE_SOON(
5976 "Use isolate version",
5977 void SetFatalErrorHandler(FatalErrorCallback that));
5980 * Set the callback to invoke to check if code generation from
5981 * strings should be allowed.
5983 V8_INLINE static V8_DEPRECATE_SOON(
5984 "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
5985 AllowCodeGenerationFromStringsCallback that));
5988 * Set allocator to use for ArrayBuffer memory.
5989 * The allocator should be set only once. The allocator should be set
5990 * before any code tha uses ArrayBuffers is executed.
5991 * This allocator is used in all isolates.
5993 static V8_DEPRECATE_SOON(
5994 "Use isolate version",
5995 void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator));
5998 * Check if V8 is dead and therefore unusable. This is the case after
5999 * fatal errors such as out-of-memory situations.
6001 V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
6004 * Hand startup data to V8, in case the embedder has chosen to build
6005 * V8 with external startup data.
6008 * - By default the startup data is linked into the V8 library, in which
6009 * case this function is not meaningful.
6010 * - If this needs to be called, it needs to be called before V8
6011 * tries to make use of its built-ins.
6012 * - To avoid unnecessary copies of data, V8 will point directly into the
6013 * given data blob, so pretty please keep it around until V8 exit.
6014 * - Compression of the startup blob might be useful, but needs to
6015 * handled entirely on the embedders' side.
6016 * - The call will abort if the data is invalid.
6018 static void SetNativesDataBlob(StartupData* startup_blob);
6019 static void SetSnapshotDataBlob(StartupData* startup_blob);
6022 * Create a new isolate and context for the purpose of capturing a snapshot
6023 * Returns { NULL, 0 } on failure.
6024 * The caller owns the data array in the return value.
6026 static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
6029 * Adds a message listener.
6031 * The same message listener can be added more than once and in that
6032 * case it will be called more than once for each message.
6034 * If data is specified, it will be passed to the callback when it is called.
6035 * Otherwise, the exception object will be passed to the callback instead.
6037 V8_INLINE static V8_DEPRECATE_SOON(
6038 "Use isolate version",
6039 bool AddMessageListener(MessageCallback that,
6040 Local<Value> data = Local<Value>()));
6043 * Remove all message listeners from the specified callback function.
6045 V8_INLINE static V8_DEPRECATE_SOON(
6046 "Use isolate version", void RemoveMessageListeners(MessageCallback that));
6049 * Tells V8 to capture current stack trace when uncaught exception occurs
6050 * and report it to the message listeners. The option is off by default.
6052 V8_INLINE static V8_DEPRECATE_SOON(
6053 "Use isolate version",
6054 void SetCaptureStackTraceForUncaughtExceptions(
6055 bool capture, int frame_limit = 10,
6056 StackTrace::StackTraceOptions options = StackTrace::kOverview));
6059 * Sets V8 flags from a string.
6061 static void SetFlagsFromString(const char* str, int length);
6064 * Sets V8 flags from the command line.
6066 static void SetFlagsFromCommandLine(int* argc,
6070 /** Get the version string. */
6071 static const char* GetVersion();
6073 /** Callback function for reporting failed access checks.*/
6074 V8_INLINE static V8_DEPRECATE_SOON(
6075 "Use isolate version",
6076 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
6079 * Enables the host application to receive a notification before a
6080 * garbage collection. Allocations are not allowed in the
6081 * callback function, you therefore cannot manipulate objects (set
6082 * or delete properties for example) since it is possible such
6083 * operations will result in the allocation of objects. It is possible
6084 * to specify the GCType filter for your callback. But it is not possible to
6085 * register the same callback function two times with different
6088 static V8_DEPRECATE_SOON(
6089 "Use isolate version",
6090 void AddGCPrologueCallback(GCPrologueCallback callback,
6091 GCType gc_type_filter = kGCTypeAll));
6094 * This function removes callback which was installed by
6095 * AddGCPrologueCallback function.
6097 V8_INLINE static V8_DEPRECATE_SOON(
6098 "Use isolate version",
6099 void RemoveGCPrologueCallback(GCPrologueCallback callback));
6102 * Enables the host application to receive a notification after a
6103 * garbage collection. Allocations are not allowed in the
6104 * callback function, you therefore cannot manipulate objects (set
6105 * or delete properties for example) since it is possible such
6106 * operations will result in the allocation of objects. It is possible
6107 * to specify the GCType filter for your callback. But it is not possible to
6108 * register the same callback function two times with different
6111 static V8_DEPRECATE_SOON(
6112 "Use isolate version",
6113 void AddGCEpilogueCallback(GCEpilogueCallback callback,
6114 GCType gc_type_filter = kGCTypeAll));
6117 * This function removes callback which was installed by
6118 * AddGCEpilogueCallback function.
6120 V8_INLINE static V8_DEPRECATE_SOON(
6121 "Use isolate version",
6122 void RemoveGCEpilogueCallback(GCEpilogueCallback callback));
6125 * Enables the host application to provide a mechanism to be notified
6126 * and perform custom logging when V8 Allocates Executable Memory.
6128 V8_INLINE static V8_DEPRECATE_SOON(
6129 "Use isolate version",
6130 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
6132 AllocationAction action));
6135 * Removes callback that was installed by AddMemoryAllocationCallback.
6137 V8_INLINE static V8_DEPRECATE_SOON(
6138 "Use isolate version",
6139 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
6142 * Initializes V8. This function needs to be called before the first Isolate
6143 * is created. It always returns true.
6145 static bool Initialize();
6148 * Allows the host application to provide a callback which can be used
6149 * as a source of entropy for random number generators.
6151 static void SetEntropySource(EntropySource source);
6154 * Allows the host application to provide a callback that allows v8 to
6155 * cooperate with a profiler that rewrites return addresses on stack.
6157 static void SetReturnAddressLocationResolver(
6158 ReturnAddressLocationResolver return_address_resolver);
6161 * Forcefully terminate the current thread of JavaScript execution
6162 * in the given isolate.
6164 * This method can be used by any thread even if that thread has not
6165 * acquired the V8 lock with a Locker object.
6167 * \param isolate The isolate in which to terminate the current JS execution.
6169 V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
6170 void TerminateExecution(Isolate* isolate));
6173 * Is V8 terminating JavaScript execution.
6175 * Returns true if JavaScript execution is currently terminating
6176 * because of a call to TerminateExecution. In that case there are
6177 * still JavaScript frames on the stack and the termination
6178 * exception is still active.
6180 * \param isolate The isolate in which to check.
6182 V8_INLINE static V8_DEPRECATE_SOON(
6183 "Use isolate version",
6184 bool IsExecutionTerminating(Isolate* isolate = NULL));
6187 * Resume execution capability in the given isolate, whose execution
6188 * was previously forcefully terminated using TerminateExecution().
6190 * When execution is forcefully terminated using TerminateExecution(),
6191 * the isolate can not resume execution until all JavaScript frames
6192 * have propagated the uncatchable exception which is generated. This
6193 * method allows the program embedding the engine to handle the
6194 * termination event and resume execution capability, even if
6195 * JavaScript frames remain on the stack.
6197 * This method can be used by any thread even if that thread has not
6198 * acquired the V8 lock with a Locker object.
6200 * \param isolate The isolate in which to resume execution capability.
6202 V8_INLINE static V8_DEPRECATE_SOON(
6203 "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
6206 * Releases any resources used by v8 and stops any utility threads
6207 * that may be running. Note that disposing v8 is permanent, it
6208 * cannot be reinitialized.
6210 * It should generally not be necessary to dispose v8 before exiting
6211 * a process, this should happen automatically. It is only necessary
6212 * to use if the process needs the resources taken up by v8.
6214 static bool Dispose();
6217 * Iterates through all external resources referenced from current isolate
6218 * heap. GC is not invoked prior to iterating, therefore there is no
6219 * guarantee that visited objects are still alive.
6221 V8_INLINE static V8_DEPRECATE_SOON(
6222 "Use isoalte version",
6223 void VisitExternalResources(ExternalResourceVisitor* visitor));
6226 * Iterates through all the persistent handles in the current isolate's heap
6227 * that have class_ids.
6229 V8_INLINE static V8_DEPRECATE_SOON(
6230 "Use isolate version",
6231 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
6234 * Iterates through all the persistent handles in isolate's heap that have
6237 V8_INLINE static V8_DEPRECATE_SOON(
6238 "Use isolate version",
6239 void VisitHandlesWithClassIds(Isolate* isolate,
6240 PersistentHandleVisitor* visitor));
6243 * Iterates through all the persistent handles in the current isolate's heap
6244 * that have class_ids and are candidates to be marked as partially dependent
6245 * handles. This will visit handles to young objects created since the last
6246 * garbage collection but is free to visit an arbitrary superset of these
6249 V8_INLINE static V8_DEPRECATE_SOON(
6250 "Use isolate version",
6251 void VisitHandlesForPartialDependence(Isolate* isolate,
6252 PersistentHandleVisitor* visitor));
6255 * Initialize the ICU library bundled with V8. The embedder should only
6256 * invoke this method when using the bundled ICU. Returns true on success.
6258 * If V8 was compiled with the ICU data in an external file, the location
6259 * of the data file has to be provided.
6261 static bool InitializeICU(const char* icu_data_file = NULL);
6264 * Initialize the external startup data. The embedder only needs to
6265 * invoke this method when external startup data was enabled in a build.
6267 * If V8 was compiled with the startup data in an external file, then
6268 * V8 needs to be given those external files during startup. There are
6269 * three ways to do this:
6270 * - InitializeExternalStartupData(const char*)
6271 * This will look in the given directory for files "natives_blob.bin"
6272 * and "snapshot_blob.bin" - which is what the default build calls them.
6273 * - InitializeExternalStartupData(const char*, const char*)
6274 * As above, but will directly use the two given file names.
6275 * - Call SetNativesDataBlob, SetNativesDataBlob.
6276 * This will read the blobs from the given data structures and will
6277 * not perform any file IO.
6279 static void InitializeExternalStartupData(const char* directory_path);
6280 static void InitializeExternalStartupData(const char* natives_blob,
6281 const char* snapshot_blob);
6283 * Sets the v8::Platform to use. This should be invoked before V8 is
6286 static void InitializePlatform(Platform* platform);
6289 * Clears all references to the v8::Platform. This should be invoked after
6292 static void ShutdownPlatform();
6297 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6298 internal::Object** handle);
6299 static internal::Object** CopyPersistent(internal::Object** handle);
6300 static void DisposeGlobal(internal::Object** global_handle);
6301 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6302 static void MakeWeak(internal::Object** global_handle, void* data,
6303 WeakCallback weak_callback);
6304 static void MakeWeak(internal::Object** global_handle, void* data,
6305 WeakCallbackInfo<void>::Callback weak_callback,
6306 WeakCallbackType type);
6307 static void MakeWeak(internal::Object** global_handle, void* data,
6309 int internal_field_index1,
6311 int internal_field_index2,
6312 WeakCallbackInfo<void>::Callback weak_callback);
6313 static void* ClearWeak(internal::Object** global_handle);
6314 static void Eternalize(Isolate* isolate,
6317 static Local<Value> GetEternal(Isolate* isolate, int index);
6319 static void FromJustIsNothing();
6320 static void ToLocalEmpty();
6321 static void InternalFieldOutOfBounds(int index);
6322 template <class T> friend class Local;
6324 friend class MaybeLocal;
6328 friend class WeakCallbackInfo;
6329 template <class T> friend class Eternal;
6330 template <class T> friend class PersistentBase;
6331 template <class T, class M> friend class Persistent;
6332 friend class Context;
6337 * A simple Maybe type, representing an object which may or may not have a
6338 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6340 * If an API method returns a Maybe<>, the API method can potentially fail
6341 * either because an exception is thrown, or because an exception is pending,
6342 * e.g. because a previous API call threw an exception that hasn't been caught
6343 * yet, or because a TerminateExecution exception was thrown. In that case, a
6344 * "Nothing" value is returned.
6349 V8_INLINE bool IsNothing() const { return !has_value; }
6350 V8_INLINE bool IsJust() const { return has_value; }
6352 // Will crash if the Maybe<> is nothing.
6353 V8_INLINE T FromJust() const {
6354 if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
6358 V8_INLINE T FromMaybe(const T& default_value) const {
6359 return has_value ? value : default_value;
6362 V8_INLINE bool operator==(const Maybe& other) const {
6363 return (IsJust() == other.IsJust()) &&
6364 (!IsJust() || FromJust() == other.FromJust());
6367 V8_INLINE bool operator!=(const Maybe& other) const {
6368 return !operator==(other);
6372 Maybe() : has_value(false) {}
6373 explicit Maybe(const T& t) : has_value(true), value(t) {}
6379 friend Maybe<U> Nothing();
6381 friend Maybe<U> Just(const U& u);
6386 inline Maybe<T> Nothing() {
6392 inline Maybe<T> Just(const T& t) {
6398 * An external exception handler.
6400 class V8_EXPORT TryCatch {
6403 * Creates a new try/catch block and registers it with v8. Note that
6404 * all TryCatch blocks should be stack allocated because the memory
6405 * location itself is compared against JavaScript try/catch blocks.
6407 V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6410 * Creates a new try/catch block and registers it with v8. Note that
6411 * all TryCatch blocks should be stack allocated because the memory
6412 * location itself is compared against JavaScript try/catch blocks.
6414 TryCatch(Isolate* isolate);
6417 * Unregisters and deletes this try/catch block.
6422 * Returns true if an exception has been caught by this try/catch block.
6424 bool HasCaught() const;
6427 * For certain types of exceptions, it makes no sense to continue execution.
6429 * If CanContinue returns false, the correct action is to perform any C++
6430 * cleanup needed and then return. If CanContinue returns false and
6431 * HasTerminated returns true, it is possible to call
6432 * CancelTerminateExecution in order to continue calling into the engine.
6434 bool CanContinue() const;
6437 * Returns true if an exception has been caught due to script execution
6440 * There is no JavaScript representation of an execution termination
6441 * exception. Such exceptions are thrown when the TerminateExecution
6442 * methods are called to terminate a long-running script.
6444 * If such an exception has been thrown, HasTerminated will return true,
6445 * indicating that it is possible to call CancelTerminateExecution in order
6446 * to continue calling into the engine.
6448 bool HasTerminated() const;
6451 * Throws the exception caught by this TryCatch in a way that avoids
6452 * it being caught again by this same TryCatch. As with ThrowException
6453 * it is illegal to execute any JavaScript operations after calling
6454 * ReThrow; the caller must return immediately to where the exception
6457 Local<Value> ReThrow();
6460 * Returns the exception caught by this try/catch block. If no exception has
6461 * been caught an empty handle is returned.
6463 * The returned handle is valid until this TryCatch block has been destroyed.
6465 Local<Value> Exception() const;
6468 * Returns the .stack property of the thrown object. If no .stack
6469 * property is present an empty handle is returned.
6471 V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
6472 V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
6473 Local<Context> context) const;
6476 * Returns the message associated with this exception. If there is
6477 * no message associated an empty handle is returned.
6479 * The returned handle is valid until this TryCatch block has been
6482 Local<v8::Message> Message() const;
6485 * Clears any exceptions that may have been caught by this try/catch block.
6486 * After this method has been called, HasCaught() will return false. Cancels
6487 * the scheduled exception if it is caught and ReThrow() is not called before.
6489 * It is not necessary to clear a try/catch block before using it again; if
6490 * another exception is thrown the previously caught exception will just be
6491 * overwritten. However, it is often a good idea since it makes it easier
6492 * to determine which operation threw a given exception.
6497 * Set verbosity of the external exception handler.
6499 * By default, exceptions that are caught by an external exception
6500 * handler are not reported. Call SetVerbose with true on an
6501 * external exception handler to have exceptions caught by the
6502 * handler reported as if they were not caught.
6504 void SetVerbose(bool value);
6507 * Set whether or not this TryCatch should capture a Message object
6508 * which holds source information about where the exception
6509 * occurred. True by default.
6511 void SetCaptureMessage(bool value);
6514 * There are cases when the raw address of C++ TryCatch object cannot be
6515 * used for comparisons with addresses into the JS stack. The cases are:
6516 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6517 * 2) Address sanitizer allocates local C++ object in the heap when
6518 * UseAfterReturn mode is enabled.
6519 * This method returns address that can be used for comparisons with
6520 * addresses into the JS stack. When neither simulator nor ASAN's
6521 * UseAfterReturn is enabled, then the address returned will be the address
6522 * of the C++ try catch handler itself.
6524 static void* JSStackComparableAddress(v8::TryCatch* handler) {
6525 if (handler == NULL) return NULL;
6526 return handler->js_stack_comparable_address_;
6530 void ResetInternal();
6532 // Make it hard to create heap-allocated TryCatch blocks.
6533 TryCatch(const TryCatch&);
6534 void operator=(const TryCatch&);
6535 void* operator new(size_t size);
6536 void operator delete(void*, size_t);
6538 v8::internal::Isolate* isolate_;
6539 v8::TryCatch* next_;
6542 void* js_stack_comparable_address_;
6543 bool is_verbose_ : 1;
6544 bool can_continue_ : 1;
6545 bool capture_message_ : 1;
6547 bool has_terminated_ : 1;
6549 friend class v8::internal::Isolate;
6557 * A container for extension names.
6559 class V8_EXPORT ExtensionConfiguration {
6561 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6562 ExtensionConfiguration(int name_count, const char* names[])
6563 : name_count_(name_count), names_(names) { }
6565 const char** begin() const { return &names_[0]; }
6566 const char** end() const { return &names_[name_count_]; }
6569 const int name_count_;
6570 const char** names_;
6575 * A sandboxed execution context with its own set of built-in objects
6578 class V8_EXPORT Context {
6581 * Returns the global proxy object.
6583 * Global proxy object is a thin wrapper whose prototype points to actual
6584 * context's global object with the properties like Object, etc. This is done
6585 * that way for security reasons (for more details see
6586 * https://wiki.mozilla.org/Gecko:SplitWindow).
6588 * Please note that changes to global proxy object prototype most probably
6589 * would break VM---v8 expects only global object as a prototype of global
6592 Local<Object> Global();
6595 * Detaches the global object from its context before
6596 * the global object can be reused to create a new context.
6598 void DetachGlobal();
6601 * Creates a new context and returns a handle to the newly allocated
6604 * \param isolate The isolate in which to create the context.
6606 * \param extensions An optional extension configuration containing
6607 * the extensions to be installed in the newly created context.
6609 * \param global_template An optional object template from which the
6610 * global object for the newly created context will be created.
6612 * \param global_object An optional global object to be reused for
6613 * the newly created context. This global object must have been
6614 * created by a previous call to Context::New with the same global
6615 * template. The state of the global object will be completely reset
6616 * and only object identify will remain.
6618 static Local<Context> New(
6619 Isolate* isolate, ExtensionConfiguration* extensions = NULL,
6620 Local<ObjectTemplate> global_template = Local<ObjectTemplate>(),
6621 Local<Value> global_object = Local<Value>());
6624 * Sets the security token for the context. To access an object in
6625 * another context, the security tokens must match.
6627 void SetSecurityToken(Local<Value> token);
6629 /** Restores the security token to the default value. */
6630 void UseDefaultSecurityToken();
6632 /** Returns the security token of this context.*/
6633 Local<Value> GetSecurityToken();
6636 * Enter this context. After entering a context, all code compiled
6637 * and run is compiled and run in this context. If another context
6638 * is already entered, this old context is saved so it can be
6639 * restored when the new context is exited.
6644 * Exit this context. Exiting the current context restores the
6645 * context that was in place when entering the current context.
6649 /** Returns an isolate associated with a current context. */
6650 v8::Isolate* GetIsolate();
6653 * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6654 * The value is propagated to the scripts compiled in given Context and
6655 * can be used for filtering scripts.
6657 enum EmbedderDataFields { kDebugIdIndex = 0 };
6660 * Gets the embedder data with the given index, which must have been set by a
6661 * previous call to SetEmbedderData with the same index. Note that index 0
6662 * currently has a special meaning for Chrome's debugger.
6664 V8_INLINE Local<Value> GetEmbedderData(int index);
6667 * Gets the exports object used by V8 extras. Extra natives get a reference
6668 * to this object and can use it to export functionality.
6670 Local<Object> GetExtrasExportsObject();
6673 * Sets the embedder data with the given index, growing the data as
6674 * needed. Note that index 0 currently has a special meaning for Chrome's
6677 void SetEmbedderData(int index, Local<Value> value);
6680 * Gets a 2-byte-aligned native pointer from the embedder data with the given
6681 * index, which must have bees set by a previous call to
6682 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6683 * currently has a special meaning for Chrome's debugger.
6685 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
6688 * Sets a 2-byte-aligned native pointer in the embedder data with the given
6689 * index, growing the data as needed. Note that index 0 currently has a
6690 * special meaning for Chrome's debugger.
6692 void SetAlignedPointerInEmbedderData(int index, void* value);
6695 * Control whether code generation from strings is allowed. Calling
6696 * this method with false will disable 'eval' and the 'Function'
6697 * constructor for code running in this context. If 'eval' or the
6698 * 'Function' constructor are used an exception will be thrown.
6700 * If code generation from strings is not allowed the
6701 * V8::AllowCodeGenerationFromStrings callback will be invoked if
6702 * set before blocking the call to 'eval' or the 'Function'
6703 * constructor. If that callback returns true, the call will be
6704 * allowed, otherwise an exception will be thrown. If no callback is
6705 * set an exception will be thrown.
6707 void AllowCodeGenerationFromStrings(bool allow);
6710 * Returns true if code generation from strings is allowed for the context.
6711 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6713 bool IsCodeGenerationFromStringsAllowed();
6716 * Sets the error description for the exception that is thrown when
6717 * code generation from strings is not allowed and 'eval' or the 'Function'
6718 * constructor are called.
6720 void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
6723 * Stack-allocated class which sets the execution context for all
6724 * operations executed within a local scope.
6728 explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
6731 V8_INLINE ~Scope() { context_->Exit(); }
6734 Local<Context> context_;
6739 friend class Script;
6740 friend class Object;
6741 friend class Function;
6743 Local<Value> SlowGetEmbedderData(int index);
6744 void* SlowGetAlignedPointerFromEmbedderData(int index);
6749 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6750 * to use any given V8 isolate, see the comments in the Isolate class. The
6751 * definition of 'using a V8 isolate' includes accessing handles or holding onto
6752 * object pointers obtained from V8 handles while in the particular V8 isolate.
6753 * It is up to the user of V8 to ensure, perhaps with locking, that this
6754 * constraint is not violated. In addition to any other synchronization
6755 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6756 * used to signal thead switches to V8.
6758 * v8::Locker is a scoped lock object. While it's active, i.e. between its
6759 * construction and destruction, the current thread is allowed to use the locked
6760 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6761 * any time. In other words, the scope of a v8::Locker is a critical section.
6767 * v8::Locker locker(isolate);
6768 * v8::Isolate::Scope isolate_scope(isolate);
6770 * // Code using V8 and isolate goes here.
6772 * } // Destructor called here
6775 * If you wish to stop using V8 in a thread A you can do this either by
6776 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6782 * v8::Unlocker unlocker(isolate);
6784 * // Code not using V8 goes here while V8 can run in another thread.
6786 * } // Destructor called here.
6790 * The Unlocker object is intended for use in a long-running callback from V8,
6791 * where you want to release the V8 lock for other threads to use.
6793 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6794 * given thread. This can be useful if you have code that can be called either
6795 * from code that holds the lock or from code that does not. The Unlocker is
6796 * not recursive so you can not have several Unlockers on the stack at once, and
6797 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6799 * An unlocker will unlock several lockers if it has to and reinstate the
6800 * correct depth of locking on its destruction, e.g.:
6805 * v8::Locker locker(isolate);
6806 * Isolate::Scope isolate_scope(isolate);
6809 * v8::Locker another_locker(isolate);
6810 * // V8 still locked (2 levels).
6813 * v8::Unlocker unlocker(isolate);
6817 * // V8 locked again (2 levels).
6819 * // V8 still locked (1 level).
6821 * // V8 Now no longer locked.
6824 class V8_EXPORT Unlocker {
6827 * Initialize Unlocker for a given Isolate.
6829 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6833 void Initialize(Isolate* isolate);
6835 internal::Isolate* isolate_;
6839 class V8_EXPORT Locker {
6842 * Initialize Locker for a given Isolate.
6844 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6849 * Returns whether or not the locker for a given isolate, is locked by the
6852 static bool IsLocked(Isolate* isolate);
6855 * Returns whether v8::Locker is being used by this V8 instance.
6857 static bool IsActive();
6860 void Initialize(Isolate* isolate);
6864 internal::Isolate* isolate_;
6866 // Disallow copying and assigning.
6867 Locker(const Locker&);
6868 void operator=(const Locker&);
6872 // --- Implementation ---
6875 namespace internal {
6877 const int kApiPointerSize = sizeof(void*); // NOLINT
6878 const int kApiIntSize = sizeof(int); // NOLINT
6879 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6881 // Tag information for HeapObject.
6882 const int kHeapObjectTag = 1;
6883 const int kHeapObjectTagSize = 2;
6884 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6886 // Tag information for Smi.
6887 const int kSmiTag = 0;
6888 const int kSmiTagSize = 1;
6889 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6891 template <size_t ptr_size> struct SmiTagging;
6893 template<int kSmiShiftSize>
6894 V8_INLINE internal::Object* IntToSmi(int value) {
6895 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6896 uintptr_t tagged_value =
6897 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6898 return reinterpret_cast<internal::Object*>(tagged_value);
6901 // Smi constants for 32-bit systems.
6902 template <> struct SmiTagging<4> {
6903 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6904 static int SmiShiftSize() { return kSmiShiftSize; }
6905 static int SmiValueSize() { return kSmiValueSize; }
6906 V8_INLINE static int SmiToInt(const internal::Object* value) {
6907 int shift_bits = kSmiTagSize + kSmiShiftSize;
6908 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6909 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6911 V8_INLINE static internal::Object* IntToSmi(int value) {
6912 return internal::IntToSmi<kSmiShiftSize>(value);
6914 V8_INLINE static bool IsValidSmi(intptr_t value) {
6915 // To be representable as an tagged small integer, the two
6916 // most-significant bits of 'value' must be either 00 or 11 due to
6917 // sign-extension. To check this we add 01 to the two
6918 // most-significant bits, and check if the most-significant bit is 0
6920 // CAUTION: The original code below:
6921 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6922 // may lead to incorrect results according to the C language spec, and
6923 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6924 // compiler may produce undefined results in case of signed integer
6925 // overflow. The computation must be done w/ unsigned ints.
6926 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6930 // Smi constants for 64-bit systems.
6931 template <> struct SmiTagging<8> {
6932 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6933 static int SmiShiftSize() { return kSmiShiftSize; }
6934 static int SmiValueSize() { return kSmiValueSize; }
6935 V8_INLINE static int SmiToInt(const internal::Object* value) {
6936 int shift_bits = kSmiTagSize + kSmiShiftSize;
6937 // Shift down and throw away top 32 bits.
6938 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6940 V8_INLINE static internal::Object* IntToSmi(int value) {
6941 return internal::IntToSmi<kSmiShiftSize>(value);
6943 V8_INLINE static bool IsValidSmi(intptr_t value) {
6944 // To be representable as a long smi, the value must be a 32-bit integer.
6945 return (value == static_cast<int32_t>(value));
6949 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6950 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6951 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6952 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6953 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6956 * This class exports constants and functionality from within v8 that
6957 * is necessary to implement inline functions in the v8 api. Don't
6958 * depend on functions and constants defined here.
6962 // These values match non-compiler-dependent values defined within
6963 // the implementation of v8.
6964 static const int kHeapObjectMapOffset = 0;
6965 static const int kMapInstanceTypeAndBitFieldOffset =
6966 1 * kApiPointerSize + kApiIntSize;
6967 static const int kStringResourceOffset = 3 * kApiPointerSize;
6969 static const int kOddballKindOffset = 3 * kApiPointerSize;
6970 static const int kForeignAddressOffset = kApiPointerSize;
6971 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6972 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6973 static const int kContextHeaderSize = 2 * kApiPointerSize;
6974 static const int kContextEmbedderDataIndex = 81;
6975 static const int kFullStringRepresentationMask = 0x07;
6976 static const int kStringEncodingMask = 0x4;
6977 static const int kExternalTwoByteRepresentationTag = 0x02;
6978 static const int kExternalOneByteRepresentationTag = 0x06;
6980 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6981 static const int kAmountOfExternalAllocatedMemoryOffset =
6982 4 * kApiPointerSize;
6983 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6984 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6985 static const int kIsolateRootsOffset =
6986 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6988 static const int kUndefinedValueRootIndex = 5;
6989 static const int kNullValueRootIndex = 7;
6990 static const int kTrueValueRootIndex = 8;
6991 static const int kFalseValueRootIndex = 9;
6992 static const int kEmptyStringRootIndex = 10;
6994 // The external allocation limit should be below 256 MB on all architectures
6995 // to avoid that resource-constrained embedders run low on memory.
6996 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6998 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6999 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
7000 static const int kNodeStateMask = 0x7;
7001 static const int kNodeStateIsWeakValue = 2;
7002 static const int kNodeStateIsPendingValue = 3;
7003 static const int kNodeStateIsNearDeathValue = 4;
7004 static const int kNodeIsIndependentShift = 3;
7005 static const int kNodeIsPartiallyDependentShift = 4;
7007 static const int kJSObjectType = 0xbe;
7008 static const int kFirstNonstringType = 0x80;
7009 static const int kOddballType = 0x83;
7010 static const int kForeignType = 0x87;
7012 static const int kUndefinedOddballKind = 5;
7013 static const int kNullOddballKind = 3;
7015 static const uint32_t kNumIsolateDataSlots = 4;
7017 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
7018 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
7019 #ifdef V8_ENABLE_CHECKS
7020 CheckInitializedImpl(isolate);
7024 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
7025 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
7029 V8_INLINE static int SmiValue(const internal::Object* value) {
7030 return PlatformSmiTagging::SmiToInt(value);
7033 V8_INLINE static internal::Object* IntToSmi(int value) {
7034 return PlatformSmiTagging::IntToSmi(value);
7037 V8_INLINE static bool IsValidSmi(intptr_t value) {
7038 return PlatformSmiTagging::IsValidSmi(value);
7041 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
7042 typedef internal::Object O;
7043 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
7044 // Map::InstanceType is defined so that it will always be loaded into
7045 // the LS 8 bits of one 16-bit word, regardless of endianess.
7046 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
7049 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
7050 typedef internal::Object O;
7051 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
7054 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
7055 int representation = (instance_type & kFullStringRepresentationMask);
7056 return representation == kExternalTwoByteRepresentationTag;
7059 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
7060 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7061 return *addr & static_cast<uint8_t>(1U << shift);
7064 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
7065 bool value, int shift) {
7066 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7067 uint8_t mask = static_cast<uint8_t>(1U << shift);
7068 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
7071 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
7072 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7073 return *addr & kNodeStateMask;
7076 V8_INLINE static void UpdateNodeState(internal::Object** obj,
7078 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7079 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
7082 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
7085 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
7086 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7087 *reinterpret_cast<void**>(addr) = data;
7090 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
7092 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
7093 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7094 return *reinterpret_cast<void* const*>(addr);
7097 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
7099 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
7100 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
7103 template <typename T>
7104 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
7105 const uint8_t* addr =
7106 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
7107 return *reinterpret_cast<const T*>(addr);
7110 template <typename T>
7111 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
7112 typedef internal::Object O;
7113 typedef internal::Internals I;
7114 O* ctx = *reinterpret_cast<O* const*>(context);
7115 int embedder_data_offset = I::kContextHeaderSize +
7116 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
7117 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
7119 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
7120 return I::ReadField<T>(embedder_data, value_offset);
7124 } // namespace internal
7128 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
7129 return New(isolate, that.val_);
7133 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
7134 return New(isolate, that.val_);
7139 Local<T> Local<T>::New(Isolate* isolate, T* that) {
7140 if (that == NULL) return Local<T>();
7142 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
7143 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
7144 reinterpret_cast<internal::Isolate*>(isolate), *p)));
7150 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
7152 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
7157 Local<T> Eternal<T>::Get(Isolate* isolate) {
7158 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
7163 Local<T> MaybeLocal<T>::ToLocalChecked() {
7164 if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
7165 return Local<T>(val_);
7170 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
7171 #ifdef V8_ENABLE_CHECKS
7172 if (index < 0 || index >= kInternalFieldsInWeakCallback) {
7173 V8::InternalFieldOutOfBounds(index);
7176 return internal_fields_[index];
7181 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
7182 if (that == NULL) return NULL;
7183 internal::Object** p = reinterpret_cast<internal::Object**>(that);
7184 return reinterpret_cast<T*>(
7185 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
7190 template <class T, class M>
7191 template <class S, class M2>
7192 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
7195 if (that.IsEmpty()) return;
7196 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
7197 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
7198 M::Copy(that, this);
7203 bool PersistentBase<T>::IsIndependent() const {
7204 typedef internal::Internals I;
7205 if (this->IsEmpty()) return false;
7206 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7207 I::kNodeIsIndependentShift);
7212 bool PersistentBase<T>::IsNearDeath() const {
7213 typedef internal::Internals I;
7214 if (this->IsEmpty()) return false;
7215 uint8_t node_state =
7216 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
7217 return node_state == I::kNodeStateIsNearDeathValue ||
7218 node_state == I::kNodeStateIsPendingValue;
7223 bool PersistentBase<T>::IsWeak() const {
7224 typedef internal::Internals I;
7225 if (this->IsEmpty()) return false;
7226 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
7227 I::kNodeStateIsWeakValue;
7232 void PersistentBase<T>::Reset() {
7233 if (this->IsEmpty()) return;
7234 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
7241 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
7244 if (other.IsEmpty()) return;
7245 this->val_ = New(isolate, other.val_);
7251 void PersistentBase<T>::Reset(Isolate* isolate,
7252 const PersistentBase<S>& other) {
7255 if (other.IsEmpty()) return;
7256 this->val_ = New(isolate, other.val_);
7261 template <typename S, typename P>
7262 void PersistentBase<T>::SetWeak(
7264 typename WeakCallbackData<S, P>::Callback callback) {
7266 typedef typename WeakCallbackData<Value, void>::Callback Callback;
7267 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7268 reinterpret_cast<Callback>(callback));
7273 template <typename P>
7274 void PersistentBase<T>::SetWeak(
7276 typename WeakCallbackData<T, P>::Callback callback) {
7277 SetWeak<T, P>(parameter, callback);
7282 template <typename P>
7283 void PersistentBase<T>::SetPhantom(
7284 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7285 int internal_field_index1, int internal_field_index2) {
7286 typedef typename WeakCallbackInfo<void>::Callback Callback;
7287 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7288 internal_field_index1, internal_field_index2,
7289 reinterpret_cast<Callback>(callback));
7294 template <typename P>
7295 V8_INLINE void PersistentBase<T>::SetWeak(
7296 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7297 WeakCallbackType type) {
7298 typedef typename WeakCallbackInfo<void>::Callback Callback;
7299 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7300 reinterpret_cast<Callback>(callback), type);
7305 template <typename P>
7306 P* PersistentBase<T>::ClearWeak() {
7307 return reinterpret_cast<P*>(
7308 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7313 void PersistentBase<T>::MarkIndependent() {
7314 typedef internal::Internals I;
7315 if (this->IsEmpty()) return;
7316 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7318 I::kNodeIsIndependentShift);
7323 void PersistentBase<T>::MarkPartiallyDependent() {
7324 typedef internal::Internals I;
7325 if (this->IsEmpty()) return;
7326 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7328 I::kNodeIsPartiallyDependentShift);
7333 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7334 typedef internal::Internals I;
7335 if (this->IsEmpty()) return;
7336 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7337 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7338 *reinterpret_cast<uint16_t*>(addr) = class_id;
7343 uint16_t PersistentBase<T>::WrapperClassId() const {
7344 typedef internal::Internals I;
7345 if (this->IsEmpty()) return 0;
7346 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7347 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7348 return *reinterpret_cast<uint16_t*>(addr);
7352 template<typename T>
7353 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7355 template<typename T>
7356 template<typename S>
7357 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7359 if (V8_UNLIKELY(handle.IsEmpty())) {
7360 *value_ = GetDefaultValue();
7362 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7366 template <typename T>
7367 template <typename S>
7368 void ReturnValue<T>::Set(const Global<S>& handle) {
7370 if (V8_UNLIKELY(handle.IsEmpty())) {
7371 *value_ = GetDefaultValue();
7373 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7377 template <typename T>
7378 template <typename S>
7379 void ReturnValue<T>::Set(const Local<S> handle) {
7381 if (V8_UNLIKELY(handle.IsEmpty())) {
7382 *value_ = GetDefaultValue();
7384 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7388 template<typename T>
7389 void ReturnValue<T>::Set(double i) {
7390 TYPE_CHECK(T, Number);
7391 Set(Number::New(GetIsolate(), i));
7394 template<typename T>
7395 void ReturnValue<T>::Set(int32_t i) {
7396 TYPE_CHECK(T, Integer);
7397 typedef internal::Internals I;
7398 if (V8_LIKELY(I::IsValidSmi(i))) {
7399 *value_ = I::IntToSmi(i);
7402 Set(Integer::New(GetIsolate(), i));
7405 template<typename T>
7406 void ReturnValue<T>::Set(uint32_t i) {
7407 TYPE_CHECK(T, Integer);
7408 // Can't simply use INT32_MAX here for whatever reason.
7409 bool fits_into_int32_t = (i & (1U << 31)) == 0;
7410 if (V8_LIKELY(fits_into_int32_t)) {
7411 Set(static_cast<int32_t>(i));
7414 Set(Integer::NewFromUnsigned(GetIsolate(), i));
7417 template<typename T>
7418 void ReturnValue<T>::Set(bool value) {
7419 TYPE_CHECK(T, Boolean);
7420 typedef internal::Internals I;
7423 root_index = I::kTrueValueRootIndex;
7425 root_index = I::kFalseValueRootIndex;
7427 *value_ = *I::GetRoot(GetIsolate(), root_index);
7430 template<typename T>
7431 void ReturnValue<T>::SetNull() {
7432 TYPE_CHECK(T, Primitive);
7433 typedef internal::Internals I;
7434 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
7437 template<typename T>
7438 void ReturnValue<T>::SetUndefined() {
7439 TYPE_CHECK(T, Primitive);
7440 typedef internal::Internals I;
7441 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
7444 template<typename T>
7445 void ReturnValue<T>::SetEmptyString() {
7446 TYPE_CHECK(T, String);
7447 typedef internal::Internals I;
7448 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
7451 template<typename T>
7452 Isolate* ReturnValue<T>::GetIsolate() {
7453 // Isolate is always the pointer below the default value on the stack.
7454 return *reinterpret_cast<Isolate**>(&value_[-2]);
7457 template<typename T>
7458 template<typename S>
7459 void ReturnValue<T>::Set(S* whatever) {
7460 // Uncompilable to prevent inadvertent misuse.
7461 TYPE_CHECK(S*, Primitive);
7464 template<typename T>
7465 internal::Object* ReturnValue<T>::GetDefaultValue() {
7466 // Default value is always the pointer below value_ on the stack.
7471 template<typename T>
7472 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
7473 internal::Object** values,
7475 bool is_construct_call)
7476 : implicit_args_(implicit_args),
7479 is_construct_call_(is_construct_call) { }
7482 template<typename T>
7483 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
7484 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7485 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7489 template<typename T>
7490 Local<Function> FunctionCallbackInfo<T>::Callee() const {
7491 return Local<Function>(reinterpret_cast<Function*>(
7492 &implicit_args_[kCalleeIndex]));
7496 template<typename T>
7497 Local<Object> FunctionCallbackInfo<T>::This() const {
7498 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7502 template<typename T>
7503 Local<Object> FunctionCallbackInfo<T>::Holder() const {
7504 return Local<Object>(reinterpret_cast<Object*>(
7505 &implicit_args_[kHolderIndex]));
7509 template<typename T>
7510 Local<Value> FunctionCallbackInfo<T>::Data() const {
7511 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7515 template<typename T>
7516 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
7517 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7521 template<typename T>
7522 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
7523 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
7527 template<typename T>
7528 bool FunctionCallbackInfo<T>::IsConstructCall() const {
7529 return is_construct_call_ & 0x1;
7533 template<typename T>
7534 int FunctionCallbackInfo<T>::Length() const {
7538 ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
7539 Local<Integer> resource_line_offset,
7540 Local<Integer> resource_column_offset,
7541 Local<Boolean> resource_is_shared_cross_origin,
7542 Local<Integer> script_id,
7543 Local<Boolean> resource_is_embedder_debug_script,
7544 Local<Value> source_map_url,
7545 Local<Boolean> resource_is_opaque)
7546 : resource_name_(resource_name),
7547 resource_line_offset_(resource_line_offset),
7548 resource_column_offset_(resource_column_offset),
7549 options_(!resource_is_embedder_debug_script.IsEmpty() &&
7550 resource_is_embedder_debug_script->IsTrue(),
7551 !resource_is_shared_cross_origin.IsEmpty() &&
7552 resource_is_shared_cross_origin->IsTrue(),
7553 !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue()),
7554 script_id_(script_id),
7555 source_map_url_(source_map_url) {}
7557 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
7560 Local<Integer> ScriptOrigin::ResourceLineOffset() const {
7561 return resource_line_offset_;
7565 Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
7566 return resource_column_offset_;
7570 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
7573 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7576 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
7578 : source_string(string),
7579 resource_name(origin.ResourceName()),
7580 resource_line_offset(origin.ResourceLineOffset()),
7581 resource_column_offset(origin.ResourceColumnOffset()),
7582 resource_options(origin.Options()),
7583 source_map_url(origin.SourceMapUrl()),
7584 cached_data(data) {}
7587 ScriptCompiler::Source::Source(Local<String> string,
7589 : source_string(string), cached_data(data) {}
7592 ScriptCompiler::Source::~Source() {
7597 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
7603 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
7604 return value ? True(isolate) : False(isolate);
7608 void Template::Set(Isolate* isolate, const char* name, v8::Local<Data> value) {
7609 Set(v8::String::NewFromUtf8(isolate, name, NewStringType::kNormal)
7615 Local<Value> Object::GetInternalField(int index) {
7616 #ifndef V8_ENABLE_CHECKS
7617 typedef internal::Object O;
7618 typedef internal::HeapObject HO;
7619 typedef internal::Internals I;
7620 O* obj = *reinterpret_cast<O**>(this);
7621 // Fast path: If the object is a plain JSObject, which is the common case, we
7622 // know where to find the internal fields and can return the value directly.
7623 if (I::GetInstanceType(obj) == I::kJSObjectType) {
7624 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7625 O* value = I::ReadField<O*>(obj, offset);
7626 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7627 return Local<Value>(reinterpret_cast<Value*>(result));
7630 return SlowGetInternalField(index);
7634 void* Object::GetAlignedPointerFromInternalField(int index) {
7635 #ifndef V8_ENABLE_CHECKS
7636 typedef internal::Object O;
7637 typedef internal::Internals I;
7638 O* obj = *reinterpret_cast<O**>(this);
7639 // Fast path: If the object is a plain JSObject, which is the common case, we
7640 // know where to find the internal fields and can return the value directly.
7641 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
7642 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7643 return I::ReadField<void*>(obj, offset);
7646 return SlowGetAlignedPointerFromInternalField(index);
7650 String* String::Cast(v8::Value* value) {
7651 #ifdef V8_ENABLE_CHECKS
7654 return static_cast<String*>(value);
7658 Local<String> String::Empty(Isolate* isolate) {
7659 typedef internal::Object* S;
7660 typedef internal::Internals I;
7661 I::CheckInitialized(isolate);
7662 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7663 return Local<String>(reinterpret_cast<String*>(slot));
7667 String::ExternalStringResource* String::GetExternalStringResource() const {
7668 typedef internal::Object O;
7669 typedef internal::Internals I;
7670 O* obj = *reinterpret_cast<O* const*>(this);
7671 String::ExternalStringResource* result;
7672 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
7673 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7674 result = reinterpret_cast<String::ExternalStringResource*>(value);
7678 #ifdef V8_ENABLE_CHECKS
7679 VerifyExternalStringResource(result);
7685 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
7686 String::Encoding* encoding_out) const {
7687 typedef internal::Object O;
7688 typedef internal::Internals I;
7689 O* obj = *reinterpret_cast<O* const*>(this);
7690 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
7691 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7692 ExternalStringResourceBase* resource = NULL;
7693 if (type == I::kExternalOneByteRepresentationTag ||
7694 type == I::kExternalTwoByteRepresentationTag) {
7695 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7696 resource = static_cast<ExternalStringResourceBase*>(value);
7698 #ifdef V8_ENABLE_CHECKS
7699 VerifyExternalStringResourceBase(resource, *encoding_out);
7705 bool Value::IsUndefined() const {
7706 #ifdef V8_ENABLE_CHECKS
7707 return FullIsUndefined();
7709 return QuickIsUndefined();
7713 bool Value::QuickIsUndefined() const {
7714 typedef internal::Object O;
7715 typedef internal::Internals I;
7716 O* obj = *reinterpret_cast<O* const*>(this);
7717 if (!I::HasHeapObjectTag(obj)) return false;
7718 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7719 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
7723 bool Value::IsNull() const {
7724 #ifdef V8_ENABLE_CHECKS
7725 return FullIsNull();
7727 return QuickIsNull();
7731 bool Value::QuickIsNull() const {
7732 typedef internal::Object O;
7733 typedef internal::Internals I;
7734 O* obj = *reinterpret_cast<O* const*>(this);
7735 if (!I::HasHeapObjectTag(obj)) return false;
7736 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7737 return (I::GetOddballKind(obj) == I::kNullOddballKind);
7741 bool Value::IsString() const {
7742 #ifdef V8_ENABLE_CHECKS
7743 return FullIsString();
7745 return QuickIsString();
7749 bool Value::QuickIsString() const {
7750 typedef internal::Object O;
7751 typedef internal::Internals I;
7752 O* obj = *reinterpret_cast<O* const*>(this);
7753 if (!I::HasHeapObjectTag(obj)) return false;
7754 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7758 template <class T> Value* Value::Cast(T* value) {
7759 return static_cast<Value*>(value);
7763 Local<Boolean> Value::ToBoolean() const {
7764 return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
7765 .FromMaybe(Local<Boolean>());
7769 Local<Number> Value::ToNumber() const {
7770 return ToNumber(Isolate::GetCurrent()->GetCurrentContext())
7771 .FromMaybe(Local<Number>());
7775 Local<String> Value::ToString() const {
7776 return ToString(Isolate::GetCurrent()->GetCurrentContext())
7777 .FromMaybe(Local<String>());
7781 Local<String> Value::ToDetailString() const {
7782 return ToDetailString(Isolate::GetCurrent()->GetCurrentContext())
7783 .FromMaybe(Local<String>());
7787 Local<Object> Value::ToObject() const {
7788 return ToObject(Isolate::GetCurrent()->GetCurrentContext())
7789 .FromMaybe(Local<Object>());
7793 Local<Integer> Value::ToInteger() const {
7794 return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
7795 .FromMaybe(Local<Integer>());
7799 Local<Uint32> Value::ToUint32() const {
7800 return ToUint32(Isolate::GetCurrent()->GetCurrentContext())
7801 .FromMaybe(Local<Uint32>());
7805 Local<Int32> Value::ToInt32() const {
7806 return ToInt32(Isolate::GetCurrent()->GetCurrentContext())
7807 .FromMaybe(Local<Int32>());
7811 Boolean* Boolean::Cast(v8::Value* value) {
7812 #ifdef V8_ENABLE_CHECKS
7815 return static_cast<Boolean*>(value);
7819 Name* Name::Cast(v8::Value* value) {
7820 #ifdef V8_ENABLE_CHECKS
7823 return static_cast<Name*>(value);
7827 Symbol* Symbol::Cast(v8::Value* value) {
7828 #ifdef V8_ENABLE_CHECKS
7831 return static_cast<Symbol*>(value);
7835 Number* Number::Cast(v8::Value* value) {
7836 #ifdef V8_ENABLE_CHECKS
7839 return static_cast<Number*>(value);
7843 Integer* Integer::Cast(v8::Value* value) {
7844 #ifdef V8_ENABLE_CHECKS
7847 return static_cast<Integer*>(value);
7851 Int32* Int32::Cast(v8::Value* value) {
7852 #ifdef V8_ENABLE_CHECKS
7855 return static_cast<Int32*>(value);
7859 Uint32* Uint32::Cast(v8::Value* value) {
7860 #ifdef V8_ENABLE_CHECKS
7863 return static_cast<Uint32*>(value);
7867 Date* Date::Cast(v8::Value* value) {
7868 #ifdef V8_ENABLE_CHECKS
7871 return static_cast<Date*>(value);
7875 StringObject* StringObject::Cast(v8::Value* value) {
7876 #ifdef V8_ENABLE_CHECKS
7879 return static_cast<StringObject*>(value);
7883 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7884 #ifdef V8_ENABLE_CHECKS
7887 return static_cast<SymbolObject*>(value);
7891 NumberObject* NumberObject::Cast(v8::Value* value) {
7892 #ifdef V8_ENABLE_CHECKS
7895 return static_cast<NumberObject*>(value);
7899 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7900 #ifdef V8_ENABLE_CHECKS
7903 return static_cast<BooleanObject*>(value);
7907 RegExp* RegExp::Cast(v8::Value* value) {
7908 #ifdef V8_ENABLE_CHECKS
7911 return static_cast<RegExp*>(value);
7915 Object* Object::Cast(v8::Value* value) {
7916 #ifdef V8_ENABLE_CHECKS
7919 return static_cast<Object*>(value);
7923 Array* Array::Cast(v8::Value* value) {
7924 #ifdef V8_ENABLE_CHECKS
7927 return static_cast<Array*>(value);
7931 Map* Map::Cast(v8::Value* value) {
7932 #ifdef V8_ENABLE_CHECKS
7935 return static_cast<Map*>(value);
7939 Set* Set::Cast(v8::Value* value) {
7940 #ifdef V8_ENABLE_CHECKS
7943 return static_cast<Set*>(value);
7947 Promise* Promise::Cast(v8::Value* value) {
7948 #ifdef V8_ENABLE_CHECKS
7951 return static_cast<Promise*>(value);
7955 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7956 #ifdef V8_ENABLE_CHECKS
7959 return static_cast<Promise::Resolver*>(value);
7963 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7964 #ifdef V8_ENABLE_CHECKS
7967 return static_cast<ArrayBuffer*>(value);
7971 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7972 #ifdef V8_ENABLE_CHECKS
7975 return static_cast<ArrayBufferView*>(value);
7979 TypedArray* TypedArray::Cast(v8::Value* value) {
7980 #ifdef V8_ENABLE_CHECKS
7983 return static_cast<TypedArray*>(value);
7987 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7988 #ifdef V8_ENABLE_CHECKS
7991 return static_cast<Uint8Array*>(value);
7995 Int8Array* Int8Array::Cast(v8::Value* value) {
7996 #ifdef V8_ENABLE_CHECKS
7999 return static_cast<Int8Array*>(value);
8003 Uint16Array* Uint16Array::Cast(v8::Value* value) {
8004 #ifdef V8_ENABLE_CHECKS
8007 return static_cast<Uint16Array*>(value);
8011 Int16Array* Int16Array::Cast(v8::Value* value) {
8012 #ifdef V8_ENABLE_CHECKS
8015 return static_cast<Int16Array*>(value);
8019 Uint32Array* Uint32Array::Cast(v8::Value* value) {
8020 #ifdef V8_ENABLE_CHECKS
8023 return static_cast<Uint32Array*>(value);
8027 Int32Array* Int32Array::Cast(v8::Value* value) {
8028 #ifdef V8_ENABLE_CHECKS
8031 return static_cast<Int32Array*>(value);
8035 Float32Array* Float32Array::Cast(v8::Value* value) {
8036 #ifdef V8_ENABLE_CHECKS
8039 return static_cast<Float32Array*>(value);
8043 Float64Array* Float64Array::Cast(v8::Value* value) {
8044 #ifdef V8_ENABLE_CHECKS
8047 return static_cast<Float64Array*>(value);
8051 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
8052 #ifdef V8_ENABLE_CHECKS
8055 return static_cast<Uint8ClampedArray*>(value);
8059 DataView* DataView::Cast(v8::Value* value) {
8060 #ifdef V8_ENABLE_CHECKS
8063 return static_cast<DataView*>(value);
8067 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
8068 #ifdef V8_ENABLE_CHECKS
8071 return static_cast<SharedArrayBuffer*>(value);
8075 Function* Function::Cast(v8::Value* value) {
8076 #ifdef V8_ENABLE_CHECKS
8079 return static_cast<Function*>(value);
8083 External* External::Cast(v8::Value* value) {
8084 #ifdef V8_ENABLE_CHECKS
8087 return static_cast<External*>(value);
8091 template<typename T>
8092 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
8093 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
8097 template<typename T>
8098 Local<Value> PropertyCallbackInfo<T>::Data() const {
8099 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
8103 template<typename T>
8104 Local<Object> PropertyCallbackInfo<T>::This() const {
8105 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
8109 template<typename T>
8110 Local<Object> PropertyCallbackInfo<T>::Holder() const {
8111 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
8115 template<typename T>
8116 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
8117 return ReturnValue<T>(&args_[kReturnValueIndex]);
8121 Local<Primitive> Undefined(Isolate* isolate) {
8122 typedef internal::Object* S;
8123 typedef internal::Internals I;
8124 I::CheckInitialized(isolate);
8125 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
8126 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8130 Local<Primitive> Null(Isolate* isolate) {
8131 typedef internal::Object* S;
8132 typedef internal::Internals I;
8133 I::CheckInitialized(isolate);
8134 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
8135 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8139 Local<Boolean> True(Isolate* isolate) {
8140 typedef internal::Object* S;
8141 typedef internal::Internals I;
8142 I::CheckInitialized(isolate);
8143 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
8144 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8148 Local<Boolean> False(Isolate* isolate) {
8149 typedef internal::Object* S;
8150 typedef internal::Internals I;
8151 I::CheckInitialized(isolate);
8152 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
8153 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8157 void Isolate::SetData(uint32_t slot, void* data) {
8158 typedef internal::Internals I;
8159 I::SetEmbedderData(this, slot, data);
8163 void* Isolate::GetData(uint32_t slot) {
8164 typedef internal::Internals I;
8165 return I::GetEmbedderData(this, slot);
8169 uint32_t Isolate::GetNumberOfDataSlots() {
8170 typedef internal::Internals I;
8171 return I::kNumIsolateDataSlots;
8175 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
8176 int64_t change_in_bytes) {
8177 typedef internal::Internals I;
8178 int64_t* amount_of_external_allocated_memory =
8179 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
8180 I::kAmountOfExternalAllocatedMemoryOffset);
8181 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
8182 reinterpret_cast<int64_t*>(
8183 reinterpret_cast<uint8_t*>(this) +
8184 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
8185 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
8186 if (change_in_bytes > 0 &&
8187 amount - *amount_of_external_allocated_memory_at_last_global_gc >
8188 I::kExternalAllocationLimit) {
8189 CollectAllGarbage("external memory allocation limit reached.");
8191 *amount_of_external_allocated_memory = amount;
8192 return *amount_of_external_allocated_memory;
8196 template<typename T>
8197 void Isolate::SetObjectGroupId(const Persistent<T>& object,
8199 TYPE_CHECK(Value, T);
8200 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
8204 template<typename T>
8205 void Isolate::SetReferenceFromGroup(UniqueId id,
8206 const Persistent<T>& object) {
8207 TYPE_CHECK(Value, T);
8208 SetReferenceFromGroup(id,
8209 reinterpret_cast<v8::internal::Object**>(object.val_));
8213 template<typename T, typename S>
8214 void Isolate::SetReference(const Persistent<T>& parent,
8215 const Persistent<S>& child) {
8216 TYPE_CHECK(Object, T);
8217 TYPE_CHECK(Value, S);
8218 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
8219 reinterpret_cast<v8::internal::Object**>(child.val_));
8223 Local<Value> Context::GetEmbedderData(int index) {
8224 #ifndef V8_ENABLE_CHECKS
8225 typedef internal::Object O;
8226 typedef internal::HeapObject HO;
8227 typedef internal::Internals I;
8228 HO* context = *reinterpret_cast<HO**>(this);
8230 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
8231 return Local<Value>(reinterpret_cast<Value*>(result));
8233 return SlowGetEmbedderData(index);
8238 void* Context::GetAlignedPointerFromEmbedderData(int index) {
8239 #ifndef V8_ENABLE_CHECKS
8240 typedef internal::Internals I;
8241 return I::ReadEmbedderData<void*>(this, index);
8243 return SlowGetAlignedPointerFromEmbedderData(index);
8248 void V8::SetAllowCodeGenerationFromStringsCallback(
8249 AllowCodeGenerationFromStringsCallback callback) {
8250 Isolate* isolate = Isolate::GetCurrent();
8251 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
8256 Isolate* isolate = Isolate::GetCurrent();
8257 return isolate->IsDead();
8261 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
8262 Isolate* isolate = Isolate::GetCurrent();
8263 return isolate->AddMessageListener(that, data);
8267 void V8::RemoveMessageListeners(MessageCallback that) {
8268 Isolate* isolate = Isolate::GetCurrent();
8269 isolate->RemoveMessageListeners(that);
8273 void V8::SetFailedAccessCheckCallbackFunction(
8274 FailedAccessCheckCallback callback) {
8275 Isolate* isolate = Isolate::GetCurrent();
8276 isolate->SetFailedAccessCheckCallbackFunction(callback);
8280 void V8::SetCaptureStackTraceForUncaughtExceptions(
8281 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8282 Isolate* isolate = Isolate::GetCurrent();
8283 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8288 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
8289 Isolate* isolate = Isolate::GetCurrent();
8290 isolate->SetFatalErrorHandler(callback);
8294 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
8295 Isolate* isolate = Isolate::GetCurrent();
8296 isolate->RemoveGCPrologueCallback(
8297 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
8301 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
8302 Isolate* isolate = Isolate::GetCurrent();
8303 isolate->RemoveGCEpilogueCallback(
8304 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
8308 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8310 AllocationAction action) {
8311 Isolate* isolate = Isolate::GetCurrent();
8312 isolate->AddMemoryAllocationCallback(callback, space, action);
8316 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8317 Isolate* isolate = Isolate::GetCurrent();
8318 isolate->RemoveMemoryAllocationCallback(callback);
8322 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8325 bool V8::IsExecutionTerminating(Isolate* isolate) {
8326 if (isolate == NULL) {
8327 isolate = Isolate::GetCurrent();
8329 return isolate->IsExecutionTerminating();
8333 void V8::CancelTerminateExecution(Isolate* isolate) {
8334 isolate->CancelTerminateExecution();
8338 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8339 Isolate* isolate = Isolate::GetCurrent();
8340 isolate->VisitExternalResources(visitor);
8344 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8345 Isolate* isolate = Isolate::GetCurrent();
8346 isolate->VisitHandlesWithClassIds(visitor);
8350 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8351 PersistentHandleVisitor* visitor) {
8352 isolate->VisitHandlesWithClassIds(visitor);
8356 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8357 PersistentHandleVisitor* visitor) {
8358 isolate->VisitHandlesForPartialDependence(visitor);
8363 * A simple shell that takes a list of expressions on the
8364 * command-line and executes them.
8369 * \example process.cc