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;
77 class Float32x4Object;
79 class FunctionTemplate;
81 class ImplementationUtilities;
91 class ObjectOperationDescriptor;
96 class RawOperationDescriptor;
98 class SharedArrayBuffer;
110 template <class T> class Local;
113 template <class T> class Eternal;
114 template<class T> class NonCopyablePersistentTraits;
115 template<class T> class PersistentBase;
117 class M = NonCopyablePersistentTraits<T> > class Persistent;
120 template<class K, class V, class T> class PersistentValueMap;
121 template <class K, class V, class T>
122 class PersistentValueMapBase;
123 template <class K, class V, class T>
124 class GlobalValueMap;
125 template<class V, class T> class PersistentValueVector;
126 template<class T, class P> class WeakCallbackObject;
127 class FunctionTemplate;
128 class ObjectTemplate;
130 template<typename T> class FunctionCallbackInfo;
131 template<typename T> class PropertyCallbackInfo;
135 class CallHandlerHelper;
136 class EscapableHandleScope;
137 template<typename T> class ReturnValue;
145 struct StreamedSource;
146 template<typename T> class CustomArguments;
147 class PropertyCallbackArguments;
148 class FunctionCallbackArguments;
154 * General purpose unique identifier.
158 explicit UniqueId(intptr_t data)
161 bool operator==(const UniqueId& other) const {
162 return data_ == other.data_;
165 bool operator!=(const UniqueId& other) const {
166 return data_ != other.data_;
169 bool operator<(const UniqueId& other) const {
170 return data_ < other.data_;
179 #define TYPE_CHECK(T, S) \
181 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
186 * An object reference managed by the v8 garbage collector.
188 * All objects returned from v8 have to be tracked by the garbage
189 * collector so that it knows that the objects are still alive. Also,
190 * because the garbage collector may move objects, it is unsafe to
191 * point directly to an object. Instead, all objects are stored in
192 * handles which are known by the garbage collector and updated
193 * whenever an object moves. Handles should always be passed by value
194 * (except in cases like out-parameters) and they should never be
195 * allocated on the heap.
197 * There are two types of handles: local and persistent handles.
198 * Local handles are light-weight and transient and typically used in
199 * local operations. They are managed by HandleScopes. Persistent
200 * handles can be used when storing objects across several independent
201 * operations and have to be explicitly deallocated when they're no
204 * It is safe to extract the object stored in the handle by
205 * dereferencing the handle (for instance, to extract the Object* from
206 * a Local<Object>); the value will still be governed by a handle
207 * behind the scenes and the same rules apply to these values as to
213 V8_INLINE Local() : val_(0) {}
215 V8_INLINE Local(Local<S> that)
216 : val_(reinterpret_cast<T*>(*that)) {
218 * This check fails when trying to convert between incompatible
219 * handles. For example, converting from a Local<String> to a
226 * Returns true if the handle is empty.
228 V8_INLINE bool IsEmpty() const { return val_ == 0; }
231 * Sets the handle to be empty. IsEmpty() will then return true.
233 V8_INLINE void Clear() { val_ = 0; }
235 V8_INLINE T* operator->() const { return val_; }
237 V8_INLINE T* operator*() const { return val_; }
240 * Checks whether two handles are the same.
241 * Returns true if both are empty, or if the objects
242 * to which they refer are identical.
243 * The handles' references are not checked.
246 V8_INLINE bool operator==(const Local<S>& that) const {
247 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
248 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
249 if (a == 0) return b == 0;
250 if (b == 0) return false;
254 template <class S> V8_INLINE bool operator==(
255 const PersistentBase<S>& that) const {
256 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
257 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
258 if (a == 0) return b == 0;
259 if (b == 0) return false;
264 * Checks whether two handles are different.
265 * Returns true if only one of the handles is empty, or if
266 * the objects to which they refer are different.
267 * The handles' references are not checked.
270 V8_INLINE bool operator!=(const Local<S>& that) const {
271 return !operator==(that);
274 template <class S> V8_INLINE bool operator!=(
275 const Persistent<S>& that) const {
276 return !operator==(that);
279 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
280 #ifdef V8_ENABLE_CHECKS
281 // If we're going to perform the type check then we have to check
282 // that the handle isn't empty before doing the checked cast.
283 if (that.IsEmpty()) return Local<T>();
285 return Local<T>(T::Cast(*that));
289 template <class S> V8_INLINE Local<S> As() {
290 return Local<S>::Cast(*this);
294 * Create a local handle for the content of another handle.
295 * The referee is kept alive by the local handle even when
296 * the original handle is destroyed/disposed.
298 V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
299 V8_INLINE static Local<T> New(Isolate* isolate,
300 const PersistentBase<T>& that);
304 template<class F> friend class Eternal;
305 template<class F> friend class PersistentBase;
306 template<class F, class M> friend class Persistent;
307 template<class F> friend class Local;
309 friend class MaybeLocal;
310 template<class F> friend class FunctionCallbackInfo;
311 template<class F> friend class PropertyCallbackInfo;
314 friend class Context;
315 template<class F> friend class internal::CustomArguments;
316 friend Local<Primitive> Undefined(Isolate* isolate);
317 friend Local<Primitive> Null(Isolate* isolate);
318 friend Local<Boolean> True(Isolate* isolate);
319 friend Local<Boolean> False(Isolate* isolate);
320 friend class HandleScope;
321 friend class EscapableHandleScope;
322 template <class F1, class F2, class F3>
323 friend class PersistentValueMapBase;
324 template<class F1, class F2> friend class PersistentValueVector;
327 V8_INLINE Local(S* that)
329 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
334 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
335 // Local is an alias for Local for historical reasons.
337 using Handle = Local<T>;
342 * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
343 * the Local<> is empty before it can be used.
345 * If an API method returns a MaybeLocal<>, the API method can potentially fail
346 * either because an exception is thrown, or because an exception is pending,
347 * e.g. because a previous API call threw an exception that hasn't been caught
348 * yet, or because a TerminateExecution exception was thrown. In that case, an
349 * empty MaybeLocal is returned.
354 V8_INLINE MaybeLocal() : val_(nullptr) {}
356 V8_INLINE MaybeLocal(Local<S> that)
357 : val_(reinterpret_cast<T*>(*that)) {
361 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
364 V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
365 out->val_ = IsEmpty() ? nullptr : this->val_;
369 // Will crash if the MaybeLocal<> is empty.
370 V8_INLINE Local<T> ToLocalChecked();
373 V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
374 return IsEmpty() ? default_value : Local<S>(val_);
382 // Eternal handles are set-once handles that live for the life of the isolate.
383 template <class T> class Eternal {
385 V8_INLINE Eternal() : index_(kInitialValue) { }
387 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
388 Set(isolate, handle);
390 // Can only be safely called if already set.
391 V8_INLINE Local<T> Get(Isolate* isolate);
392 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
393 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
396 static const int kInitialValue = -1;
401 static const int kInternalFieldsInWeakCallback = 2;
404 template <typename T>
405 class WeakCallbackInfo {
407 typedef void (*Callback)(const WeakCallbackInfo<T>& data);
409 WeakCallbackInfo(Isolate* isolate, T* parameter,
410 void* internal_fields[kInternalFieldsInWeakCallback],
412 : isolate_(isolate), parameter_(parameter), callback_(callback) {
413 for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) {
414 internal_fields_[i] = internal_fields[i];
418 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
419 V8_INLINE T* GetParameter() const { return parameter_; }
420 V8_INLINE void* GetInternalField(int index) const;
422 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
423 void* GetInternalField1() const) {
424 return internal_fields_[0];
426 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
427 void* GetInternalField2() const) {
428 return internal_fields_[1];
431 bool IsFirstPass() const { return callback_ != nullptr; }
433 // When first called, the embedder MUST Reset() the Global which triggered the
434 // callback. The Global itself is unusable for anything else. No v8 other api
435 // calls may be called in the first callback. Should additional work be
436 // required, the embedder must set a second pass callback, which will be
437 // called after all the initial callbacks are processed.
438 // Calling SetSecondPassCallback on the second pass will immediately crash.
439 void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
445 void* internal_fields_[kInternalFieldsInWeakCallback];
449 template <class T, class P>
450 class WeakCallbackData {
452 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
454 WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
455 : isolate_(isolate), parameter_(parameter), handle_(handle) {}
457 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
458 V8_INLINE P* GetParameter() const { return parameter_; }
459 V8_INLINE Local<T> GetValue() const { return handle_; }
468 // TODO(dcarney): delete this with WeakCallbackData
470 using PhantomCallbackData = WeakCallbackInfo<T>;
473 enum class WeakCallbackType { kParameter, kInternalFields };
477 * An object reference that is independent of any handle scope. Where
478 * a Local handle only lives as long as the HandleScope in which it was
479 * allocated, a PersistentBase handle remains valid until it is explicitly
482 * A persistent handle contains a reference to a storage cell within
483 * the v8 engine which holds an object value and which is updated by
484 * the garbage collector whenever the object is moved. A new storage
485 * cell can be created using the constructor or PersistentBase::Reset and
486 * existing handles can be disposed using PersistentBase::Reset.
489 template <class T> class PersistentBase {
492 * If non-empty, destroy the underlying storage cell
493 * IsEmpty() will return true after this call.
495 V8_INLINE void Reset();
497 * If non-empty, destroy the underlying storage cell
498 * and create a new one with the contents of other if other is non empty
501 V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
504 * If non-empty, destroy the underlying storage cell
505 * and create a new one with the contents of other if other is non empty
508 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
510 V8_INLINE bool IsEmpty() const { return val_ == NULL; }
511 V8_INLINE void Empty() { val_ = 0; }
513 V8_INLINE Local<T> Get(Isolate* isolate) const {
514 return Local<T>::New(isolate, *this);
518 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
519 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
520 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
521 if (a == NULL) return b == NULL;
522 if (b == NULL) return false;
527 V8_INLINE bool operator==(const Local<S>& that) const {
528 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
529 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
530 if (a == NULL) return b == NULL;
531 if (b == NULL) return false;
536 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
537 return !operator==(that);
541 V8_INLINE bool operator!=(const Local<S>& that) const {
542 return !operator==(that);
546 * Install a finalization callback on this object.
547 * NOTE: There is no guarantee as to *when* or even *if* the callback is
548 * invoked. The invocation is performed solely on a best effort basis.
549 * As always, GC-based finalization should *not* be relied upon for any
550 * critical form of resource management!
552 template <typename P>
553 V8_INLINE V8_DEPRECATE_SOON(
554 "use WeakCallbackInfo version",
555 void SetWeak(P* parameter,
556 typename WeakCallbackData<T, P>::Callback callback));
558 template <typename S, typename P>
559 V8_INLINE V8_DEPRECATE_SOON(
560 "use WeakCallbackInfo version",
561 void SetWeak(P* parameter,
562 typename WeakCallbackData<S, P>::Callback callback));
564 // Phantom persistents work like weak persistents, except that the pointer to
565 // the object being collected is not available in the finalization callback.
566 // This enables the garbage collector to collect the object and any objects
567 // it references transitively in one GC cycle. At the moment you can either
568 // specify a parameter for the callback or the location of two internal
569 // fields in the dying object.
570 template <typename P>
571 V8_INLINE V8_DEPRECATE_SOON(
573 void SetPhantom(P* parameter,
574 typename WeakCallbackInfo<P>::Callback callback,
575 int internal_field_index1 = -1,
576 int internal_field_index2 = -1));
578 template <typename P>
579 V8_INLINE void SetWeak(P* parameter,
580 typename WeakCallbackInfo<P>::Callback callback,
581 WeakCallbackType type);
584 V8_INLINE P* ClearWeak();
586 // TODO(dcarney): remove this.
587 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
590 * Marks the reference to this object independent. Garbage collector is free
591 * to ignore any object groups containing this object. Weak callback for an
592 * independent handle should not assume that it will be preceded by a global
593 * GC prologue callback or followed by a global GC epilogue callback.
595 V8_INLINE void MarkIndependent();
598 * Marks the reference to this object partially dependent. Partially dependent
599 * handles only depend on other partially dependent handles and these
600 * dependencies are provided through object groups. It provides a way to build
601 * smaller object groups for young objects that represent only a subset of all
602 * external dependencies. This mark is automatically cleared after each
603 * garbage collection.
605 V8_INLINE void MarkPartiallyDependent();
607 V8_INLINE bool IsIndependent() const;
609 /** Checks if the handle holds the only reference to an object. */
610 V8_INLINE bool IsNearDeath() const;
612 /** Returns true if the handle's reference is weak. */
613 V8_INLINE bool IsWeak() const;
616 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
617 * description in v8-profiler.h for details.
619 V8_INLINE void SetWrapperClassId(uint16_t class_id);
622 * Returns the class ID previously assigned to this handle or 0 if no class ID
623 * was previously assigned.
625 V8_INLINE uint16_t WrapperClassId() const;
628 friend class Isolate;
630 template<class F> friend class Local;
631 template<class F1, class F2> friend class Persistent;
634 template<class F> friend class PersistentBase;
635 template<class F> friend class ReturnValue;
636 template <class F1, class F2, class F3>
637 friend class PersistentValueMapBase;
638 template<class F1, class F2> friend class PersistentValueVector;
641 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
642 PersistentBase(PersistentBase& other) = delete; // NOLINT
643 void operator=(PersistentBase&) = delete;
644 V8_INLINE static T* New(Isolate* isolate, T* that);
651 * Default traits for Persistent. This class does not allow
652 * use of the copy constructor or assignment operator.
653 * At present kResetInDestructor is not set, but that will change in a future
657 class NonCopyablePersistentTraits {
659 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
660 static const bool kResetInDestructor = false;
661 template<class S, class M>
662 V8_INLINE static void Copy(const Persistent<S, M>& source,
663 NonCopyablePersistent* dest) {
664 Uncompilable<Object>();
666 // TODO(dcarney): come up with a good compile error here.
667 template<class O> V8_INLINE static void Uncompilable() {
668 TYPE_CHECK(O, Primitive);
674 * Helper class traits to allow copying and assignment of Persistent.
675 * This will clone the contents of storage cell, but not any of the flags, etc.
678 struct CopyablePersistentTraits {
679 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
680 static const bool kResetInDestructor = true;
681 template<class S, class M>
682 static V8_INLINE void Copy(const Persistent<S, M>& source,
683 CopyablePersistent* dest) {
684 // do nothing, just allow copy
690 * A PersistentBase which allows copy and assignment.
692 * Copy, assignment and destructor bevavior is controlled by the traits
695 * Note: Persistent class hierarchy is subject to future changes.
697 template <class T, class M> class Persistent : public PersistentBase<T> {
700 * A Persistent with no storage cell.
702 V8_INLINE Persistent() : PersistentBase<T>(0) { }
704 * Construct a Persistent from a Local.
705 * When the Local is non-empty, a new storage cell is created
706 * pointing to the same object, and no flags are set.
709 V8_INLINE Persistent(Isolate* isolate, Local<S> that)
710 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
714 * Construct a Persistent from a Persistent.
715 * When the Persistent is non-empty, a new storage cell is created
716 * pointing to the same object, and no flags are set.
718 template <class S, class M2>
719 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
720 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
724 * The copy constructors and assignment operator create a Persistent
725 * exactly as the Persistent constructor, but the Copy function from the
726 * traits class is called, allowing the setting of flags based on the
729 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
732 template <class S, class M2>
733 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
736 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
740 template <class S, class M2>
741 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
746 * The destructor will dispose the Persistent based on the
747 * kResetInDestructor flags in the traits class. Since not calling dispose
748 * can result in a memory leak, it is recommended to always set this flag.
750 V8_INLINE ~Persistent() {
751 if (M::kResetInDestructor) this->Reset();
754 // TODO(dcarney): this is pretty useless, fix or remove
756 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
757 #ifdef V8_ENABLE_CHECKS
758 // If we're going to perform the type check then we have to check
759 // that the handle isn't empty before doing the checked cast.
760 if (!that.IsEmpty()) T::Cast(*that);
762 return reinterpret_cast<Persistent<T>&>(that);
765 // TODO(dcarney): this is pretty useless, fix or remove
766 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
767 return Persistent<S>::Cast(*this);
771 friend class Isolate;
773 template<class F> friend class Local;
774 template<class F1, class F2> friend class Persistent;
775 template<class F> friend class ReturnValue;
777 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
778 V8_INLINE T* operator*() const { return this->val_; }
779 template<class S, class M2>
780 V8_INLINE void Copy(const Persistent<S, M2>& that);
785 * A PersistentBase which has move semantics.
787 * Note: Persistent class hierarchy is subject to future changes.
790 class Global : public PersistentBase<T> {
793 * A Global with no storage cell.
795 V8_INLINE Global() : PersistentBase<T>(nullptr) {}
797 * Construct a Global from a Local.
798 * When the Local is non-empty, a new storage cell is created
799 * pointing to the same object, and no flags are set.
802 V8_INLINE Global(Isolate* isolate, Local<S> that)
803 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
807 * Construct a Global from a PersistentBase.
808 * When the Persistent is non-empty, a new storage cell is created
809 * pointing to the same object, and no flags are set.
812 V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
813 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
819 V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) {
820 other.val_ = nullptr;
822 V8_INLINE ~Global() { this->Reset(); }
824 * Move via assignment.
827 V8_INLINE Global& operator=(Global<S>&& rhs) {
831 this->val_ = rhs.val_;
837 * Pass allows returning uniques from functions, etc.
839 Global Pass() { return static_cast<Global&&>(*this); }
842 * For compatibility with Chromium's base::Bind (base::Passed).
844 typedef void MoveOnlyTypeForCPP03;
848 friend class ReturnValue;
849 Global(Global&) = delete;
850 void operator=(Global&) = delete;
851 V8_INLINE T* operator*() const { return this->val_; }
855 // UniquePersistent is an alias for Global for historical reason.
857 using UniquePersistent = Global<T>;
861 * A stack-allocated class that governs a number of local handles.
862 * After a handle scope has been created, all local handles will be
863 * allocated within that handle scope until either the handle scope is
864 * deleted or another handle scope is created. If there is already a
865 * handle scope and a new one is created, all allocations will take
866 * place in the new handle scope until it is deleted. After that,
867 * new handles will again be allocated in the original handle scope.
869 * After the handle scope of a local handle has been deleted the
870 * garbage collector will no longer track the object stored in the
871 * handle and may deallocate it. The behavior of accessing a handle
872 * for which the handle scope has been deleted is undefined.
874 class V8_EXPORT HandleScope {
876 HandleScope(Isolate* isolate);
881 * Counts the number of allocated handles.
883 static int NumberOfHandles(Isolate* isolate);
885 V8_INLINE Isolate* GetIsolate() const {
886 return reinterpret_cast<Isolate*>(isolate_);
890 V8_INLINE HandleScope() {}
892 void Initialize(Isolate* isolate);
894 static internal::Object** CreateHandle(internal::Isolate* isolate,
895 internal::Object* value);
898 // Uses heap_object to obtain the current Isolate.
899 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
900 internal::Object* value);
902 // Make it hard to create heap-allocated or illegal handle scopes by
903 // disallowing certain operations.
904 HandleScope(const HandleScope&);
905 void operator=(const HandleScope&);
906 void* operator new(size_t size);
907 void operator delete(void*, size_t);
909 internal::Isolate* isolate_;
910 internal::Object** prev_next_;
911 internal::Object** prev_limit_;
913 // Local::New uses CreateHandle with an Isolate* parameter.
914 template<class F> friend class Local;
916 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
917 // a HeapObject* in their shortcuts.
919 friend class Context;
924 * A HandleScope which first allocates a handle in the current scope
925 * which will be later filled with the escape value.
927 class V8_EXPORT EscapableHandleScope : public HandleScope {
929 EscapableHandleScope(Isolate* isolate);
930 V8_INLINE ~EscapableHandleScope() {}
933 * Pushes the value into the previous scope and returns a handle to it.
934 * Cannot be called twice.
937 V8_INLINE Local<T> Escape(Local<T> value) {
938 internal::Object** slot =
939 Escape(reinterpret_cast<internal::Object**>(*value));
940 return Local<T>(reinterpret_cast<T*>(slot));
944 internal::Object** Escape(internal::Object** escape_value);
946 // Make it hard to create heap-allocated or illegal handle scopes by
947 // disallowing certain operations.
948 EscapableHandleScope(const EscapableHandleScope&);
949 void operator=(const EscapableHandleScope&);
950 void* operator new(size_t size);
951 void operator delete(void*, size_t);
953 internal::Object** escape_slot_;
956 class V8_EXPORT SealHandleScope {
958 SealHandleScope(Isolate* isolate);
962 // Make it hard to create heap-allocated or illegal handle scopes by
963 // disallowing certain operations.
964 SealHandleScope(const SealHandleScope&);
965 void operator=(const SealHandleScope&);
966 void* operator new(size_t size);
967 void operator delete(void*, size_t);
969 internal::Isolate* isolate_;
971 internal::Object** prev_limit_;
975 // --- Special objects ---
979 * The superclass of values and API object templates.
981 class V8_EXPORT Data {
988 * The optional attributes of ScriptOrigin.
990 class ScriptOriginOptions {
992 V8_INLINE ScriptOriginOptions(bool is_embedder_debug_script = false,
993 bool is_shared_cross_origin = false,
994 bool is_opaque = false)
995 : flags_((is_embedder_debug_script ? kIsEmbedderDebugScript : 0) |
996 (is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
997 (is_opaque ? kIsOpaque : 0)) {}
998 V8_INLINE ScriptOriginOptions(int flags)
1000 (kIsEmbedderDebugScript | kIsSharedCrossOrigin | kIsOpaque)) {}
1001 bool IsEmbedderDebugScript() const {
1002 return (flags_ & kIsEmbedderDebugScript) != 0;
1004 bool IsSharedCrossOrigin() const {
1005 return (flags_ & kIsSharedCrossOrigin) != 0;
1007 bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1008 int Flags() const { return flags_; }
1012 kIsEmbedderDebugScript = 1,
1013 kIsSharedCrossOrigin = 1 << 1,
1020 * The origin, within a file, of a script.
1022 class ScriptOrigin {
1024 V8_INLINE ScriptOrigin(
1025 Local<Value> resource_name,
1026 Local<Integer> resource_line_offset = Local<Integer>(),
1027 Local<Integer> resource_column_offset = Local<Integer>(),
1028 Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1029 Local<Integer> script_id = Local<Integer>(),
1030 Local<Boolean> resource_is_embedder_debug_script = Local<Boolean>(),
1031 Local<Value> source_map_url = Local<Value>(),
1032 Local<Boolean> resource_is_opaque = Local<Boolean>());
1033 V8_INLINE Local<Value> ResourceName() const;
1034 V8_INLINE Local<Integer> ResourceLineOffset() const;
1035 V8_INLINE Local<Integer> ResourceColumnOffset() const;
1037 * Returns true for embedder's debugger scripts
1039 V8_INLINE Local<Integer> ScriptID() const;
1040 V8_INLINE Local<Value> SourceMapUrl() const;
1041 V8_INLINE ScriptOriginOptions Options() const { return options_; }
1044 Local<Value> resource_name_;
1045 Local<Integer> resource_line_offset_;
1046 Local<Integer> resource_column_offset_;
1047 ScriptOriginOptions options_;
1048 Local<Integer> script_id_;
1049 Local<Value> source_map_url_;
1054 * A compiled JavaScript script, not yet tied to a Context.
1056 class V8_EXPORT UnboundScript {
1059 * Binds the script to the currently entered context.
1061 Local<Script> BindToCurrentContext();
1064 Local<Value> GetScriptName();
1067 * Data read from magic sourceURL comments.
1069 Local<Value> GetSourceURL();
1071 * Data read from magic sourceMappingURL comments.
1073 Local<Value> GetSourceMappingURL();
1076 * Returns zero based line number of the code_pos location in the script.
1077 * -1 will be returned if no information available.
1079 int GetLineNumber(int code_pos);
1081 static const int kNoScriptId = 0;
1086 * A compiled JavaScript script, tied to a Context which was active when the
1087 * script was compiled.
1089 class V8_EXPORT Script {
1092 * A shorthand for ScriptCompiler::Compile().
1094 static V8_DEPRECATE_SOON(
1095 "Use maybe version",
1096 Local<Script> Compile(Local<String> source,
1097 ScriptOrigin* origin = nullptr));
1098 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1099 Local<Context> context, Local<String> source,
1100 ScriptOrigin* origin = nullptr);
1102 static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1103 Compile(Local<String> source,
1104 Local<String> file_name));
1107 * Runs the script returning the resulting value. It will be run in the
1108 * context in which it was created (ScriptCompiler::CompileBound or
1109 * UnboundScript::BindToCurrentContext()).
1111 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1112 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
1115 * Returns the corresponding context-unbound script.
1117 Local<UnboundScript> GetUnboundScript();
1119 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1121 return GetUnboundScript()->GetId();
1127 * For compiling scripts.
1129 class V8_EXPORT ScriptCompiler {
1132 * Compilation data that the embedder can cache and pass back to speed up
1133 * future compilations. The data is produced if the CompilerOptions passed to
1134 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1135 * = true. The data to cache can then can be retrieved from
1138 struct V8_EXPORT CachedData {
1148 buffer_policy(BufferNotOwned) {}
1150 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1151 // data and guarantees that it stays alive until the CachedData object is
1152 // destroyed. If the policy is BufferOwned, the given data will be deleted
1153 // (with delete[]) when the CachedData object is destroyed.
1154 CachedData(const uint8_t* data, int length,
1155 BufferPolicy buffer_policy = BufferNotOwned);
1157 // TODO(marja): Async compilation; add constructors which take a callback
1158 // which will be called when V8 no longer needs the data.
1159 const uint8_t* data;
1162 BufferPolicy buffer_policy;
1165 // Prevent copying. Not implemented.
1166 CachedData(const CachedData&);
1167 CachedData& operator=(const CachedData&);
1171 * Source code which can be then compiled to a UnboundScript or Script.
1175 // Source takes ownership of CachedData.
1176 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1177 CachedData* cached_data = NULL);
1178 V8_INLINE Source(Local<String> source_string,
1179 CachedData* cached_data = NULL);
1180 V8_INLINE ~Source();
1182 // Ownership of the CachedData or its buffers is *not* transferred to the
1183 // caller. The CachedData object is alive as long as the Source object is
1185 V8_INLINE const CachedData* GetCachedData() const;
1188 friend class ScriptCompiler;
1189 // Prevent copying. Not implemented.
1190 Source(const Source&);
1191 Source& operator=(const Source&);
1193 Local<String> source_string;
1195 // Origin information
1196 Local<Value> resource_name;
1197 Local<Integer> resource_line_offset;
1198 Local<Integer> resource_column_offset;
1199 ScriptOriginOptions resource_options;
1200 Local<Value> source_map_url;
1202 // Cached data from previous compilation (if a kConsume*Cache flag is
1203 // set), or hold newly generated cache data (kProduce*Cache flags) are
1204 // set when calling a compile method.
1205 CachedData* cached_data;
1209 * For streaming incomplete script data to V8. The embedder should implement a
1210 * subclass of this class.
1212 class V8_EXPORT ExternalSourceStream {
1214 virtual ~ExternalSourceStream() {}
1217 * V8 calls this to request the next chunk of data from the embedder. This
1218 * function will be called on a background thread, so it's OK to block and
1219 * wait for the data, if the embedder doesn't have data yet. Returns the
1220 * length of the data returned. When the data ends, GetMoreData should
1221 * return 0. Caller takes ownership of the data.
1223 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1224 * two data chunks, but doesn't handle multi-byte characters split between
1225 * more than two data chunks. The embedder can avoid this problem by always
1226 * returning at least 2 bytes of data.
1228 * If the embedder wants to cancel the streaming, they should make the next
1229 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1230 * probably, parsing will fail). The streaming task will return as soon as
1231 * V8 has parsed the data it received so far.
1233 virtual size_t GetMoreData(const uint8_t** src) = 0;
1236 * V8 calls this method to set a 'bookmark' at the current position in
1237 * the source stream, for the purpose of (maybe) later calling
1238 * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1239 * calls to GetMoreData should return the same data as they did when
1240 * SetBookmark was called earlier.
1242 * The embedder may return 'false' to indicate it cannot provide this
1245 virtual bool SetBookmark();
1248 * V8 calls this to return to a previously set bookmark.
1250 virtual void ResetToBookmark();
1255 * Source code which can be streamed into V8 in pieces. It will be parsed
1256 * while streaming. It can be compiled after the streaming is complete.
1257 * StreamedSource must be kept alive while the streaming task is ran (see
1258 * ScriptStreamingTask below).
1260 class V8_EXPORT StreamedSource {
1262 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1264 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1267 // Ownership of the CachedData or its buffers is *not* transferred to the
1268 // caller. The CachedData object is alive as long as the StreamedSource
1270 const CachedData* GetCachedData() const;
1272 internal::StreamedSource* impl() const { return impl_; }
1275 // Prevent copying. Not implemented.
1276 StreamedSource(const StreamedSource&);
1277 StreamedSource& operator=(const StreamedSource&);
1279 internal::StreamedSource* impl_;
1283 * A streaming task which the embedder must run on a background thread to
1284 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1286 class ScriptStreamingTask {
1288 virtual ~ScriptStreamingTask() {}
1289 virtual void Run() = 0;
1292 enum CompileOptions {
1293 kNoCompileOptions = 0,
1294 kProduceParserCache,
1295 kConsumeParserCache,
1301 * Compiles the specified script (context-independent).
1302 * Cached data as part of the source object can be optionally produced to be
1303 * consumed later to speed up compilation of identical source scripts.
1305 * Note that when producing cached data, the source must point to NULL for
1306 * cached data. When consuming cached data, the cached data must have been
1307 * produced by the same version of V8.
1309 * \param source Script source code.
1310 * \return Compiled script object (context independent; for running it must be
1311 * bound to a context).
1313 static V8_DEPRECATE_SOON("Use maybe version",
1314 Local<UnboundScript> CompileUnbound(
1315 Isolate* isolate, Source* source,
1316 CompileOptions options = kNoCompileOptions));
1317 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
1318 Isolate* isolate, Source* source,
1319 CompileOptions options = kNoCompileOptions);
1322 * Compiles the specified script (bound to current context).
1324 * \param source Script source code.
1325 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1326 * using pre_data speeds compilation if it's done multiple times.
1327 * Owned by caller, no references are kept when this function returns.
1328 * \return Compiled script object, bound to the context that was active
1329 * when this function was called. When run it will always use this
1332 static V8_DEPRECATE_SOON(
1333 "Use maybe version",
1334 Local<Script> Compile(Isolate* isolate, Source* source,
1335 CompileOptions options = kNoCompileOptions));
1336 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1337 Local<Context> context, Source* source,
1338 CompileOptions options = kNoCompileOptions);
1341 * Returns a task which streams script data into V8, or NULL if the script
1342 * cannot be streamed. The user is responsible for running the task on a
1343 * background thread and deleting it. When ran, the task starts parsing the
1344 * script, and it will request data from the StreamedSource as needed. When
1345 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1346 * can be compiled (see Compile below).
1348 * This API allows to start the streaming with as little data as possible, and
1349 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1351 static ScriptStreamingTask* StartStreamingScript(
1352 Isolate* isolate, StreamedSource* source,
1353 CompileOptions options = kNoCompileOptions);
1356 * Compiles a streamed script (bound to current context).
1358 * This can only be called after the streaming has finished
1359 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1360 * during streaming, so the embedder needs to pass the full source here.
1362 static V8_DEPRECATE_SOON(
1363 "Use maybe version",
1364 Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1365 Local<String> full_source_string,
1366 const ScriptOrigin& origin));
1367 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1368 Local<Context> context, StreamedSource* source,
1369 Local<String> full_source_string, const ScriptOrigin& origin);
1372 * Return a version tag for CachedData for the current V8 version & flags.
1374 * This value is meant only for determining whether a previously generated
1375 * CachedData instance is still valid; the tag has no other meaing.
1377 * Background: The data carried by CachedData may depend on the exact
1378 * V8 version number or currently compiler flags. This means when
1379 * persisting CachedData, the embedder must take care to not pass in
1380 * data from another V8 version, or the same version with different
1383 * The easiest way to do so is to clear the embedder's cache on any
1386 * Alternatively, this tag can be stored alongside the cached data and
1387 * compared when it is being used.
1389 static uint32_t CachedDataVersionTag();
1392 * Compile an ES6 module.
1394 * This is an experimental feature.
1396 * TODO(adamk): Script is likely the wrong return value for this;
1397 * should return some new Module type.
1399 static V8_DEPRECATE_SOON(
1400 "Use maybe version",
1401 Local<Script> CompileModule(Isolate* isolate, Source* source,
1402 CompileOptions options = kNoCompileOptions));
1403 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> CompileModule(
1404 Local<Context> context, Source* source,
1405 CompileOptions options = kNoCompileOptions);
1408 * Compile a function for a given context. This is equivalent to running
1411 * return function(args) { ... }
1414 * It is possible to specify multiple context extensions (obj in the above
1417 static V8_DEPRECATE_SOON("Use maybe version",
1418 Local<Function> CompileFunctionInContext(
1419 Isolate* isolate, Source* source,
1420 Local<Context> context, size_t arguments_count,
1421 Local<String> arguments[],
1422 size_t context_extension_count,
1423 Local<Object> context_extensions[]));
1424 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
1425 Local<Context> context, Source* source, size_t arguments_count,
1426 Local<String> arguments[], size_t context_extension_count,
1427 Local<Object> context_extensions[]);
1430 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1431 Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1438 class V8_EXPORT Message {
1440 Local<String> Get() const;
1442 V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1443 V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
1444 Local<Context> context) const;
1447 * Returns the origin for the script from where the function causing the
1450 ScriptOrigin GetScriptOrigin() const;
1453 * Returns the resource name for the script from where the function causing
1454 * the error originates.
1456 Local<Value> GetScriptResourceName() const;
1459 * Exception stack trace. By default stack traces are not captured for
1460 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1461 * to change this option.
1463 Local<StackTrace> GetStackTrace() const;
1466 * Returns the number, 1-based, of the line where the error occurred.
1468 V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1469 V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1472 * Returns the index within the script of the first character where
1473 * the error occurred.
1475 int GetStartPosition() const;
1478 * Returns the index within the script of the last character where
1479 * the error occurred.
1481 int GetEndPosition() const;
1484 * Returns the index within the line of the first character where
1485 * the error occurred.
1487 V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1488 V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1491 * Returns the index within the line of the last character where
1492 * the error occurred.
1494 V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn() const);
1495 V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1498 * Passes on the value set by the embedder when it fed the script from which
1499 * this Message was generated to V8.
1501 bool IsSharedCrossOrigin() const;
1502 bool IsOpaque() const;
1504 // TODO(1245381): Print to a string instead of on a FILE.
1505 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1507 static const int kNoLineNumberInfo = 0;
1508 static const int kNoColumnInfo = 0;
1509 static const int kNoScriptIdInfo = 0;
1514 * Representation of a JavaScript stack trace. The information collected is a
1515 * snapshot of the execution stack and the information remains valid after
1516 * execution continues.
1518 class V8_EXPORT StackTrace {
1521 * Flags that determine what information is placed captured for each
1522 * StackFrame when grabbing the current stack trace.
1524 enum StackTraceOptions {
1526 kColumnOffset = 1 << 1 | kLineNumber,
1527 kScriptName = 1 << 2,
1528 kFunctionName = 1 << 3,
1530 kIsConstructor = 1 << 5,
1531 kScriptNameOrSourceURL = 1 << 6,
1533 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1534 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1535 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1539 * Returns a StackFrame at a particular index.
1541 Local<StackFrame> GetFrame(uint32_t index) const;
1544 * Returns the number of StackFrames.
1546 int GetFrameCount() const;
1549 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1551 Local<Array> AsArray();
1554 * Grab a snapshot of the current JavaScript execution stack.
1556 * \param frame_limit The maximum number of stack frames we want to capture.
1557 * \param options Enumerates the set of things we will capture for each
1560 static Local<StackTrace> CurrentStackTrace(
1563 StackTraceOptions options = kOverview);
1568 * A single JavaScript stack frame.
1570 class V8_EXPORT StackFrame {
1573 * Returns the number, 1-based, of the line for the associate function call.
1574 * This method will return Message::kNoLineNumberInfo if it is unable to
1575 * retrieve the line number, or if kLineNumber was not passed as an option
1576 * when capturing the StackTrace.
1578 int GetLineNumber() const;
1581 * Returns the 1-based column offset on the line for the associated function
1583 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1584 * the column number, or if kColumnOffset was not passed as an option when
1585 * capturing the StackTrace.
1587 int GetColumn() const;
1590 * Returns the id of the script for the function for this StackFrame.
1591 * This method will return Message::kNoScriptIdInfo if it is unable to
1592 * retrieve the script id, or if kScriptId was not passed as an option when
1593 * capturing the StackTrace.
1595 int GetScriptId() const;
1598 * Returns the name of the resource that contains the script for the
1599 * function for this StackFrame.
1601 Local<String> GetScriptName() const;
1604 * Returns the name of the resource that contains the script for the
1605 * function for this StackFrame or sourceURL value if the script name
1606 * is undefined and its source ends with //# sourceURL=... string or
1607 * deprecated //@ sourceURL=... string.
1609 Local<String> GetScriptNameOrSourceURL() const;
1612 * Returns the name of the function associated with this stack frame.
1614 Local<String> GetFunctionName() const;
1617 * Returns whether or not the associated function is compiled via a call to
1620 bool IsEval() const;
1623 * Returns whether or not the associated function is called as a
1624 * constructor via "new".
1626 bool IsConstructor() const;
1630 // A StateTag represents a possible state of the VM.
1631 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1634 // A RegisterState represents the current state of registers used
1635 // by the sampling profiler API.
1636 struct RegisterState {
1637 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1638 void* pc; // Instruction pointer.
1639 void* sp; // Stack pointer.
1640 void* fp; // Frame pointer.
1644 // The output structure filled up by GetStackSample API function.
1646 size_t frames_count;
1654 class V8_EXPORT JSON {
1657 * Tries to parse the string |json_string| and returns it as value if
1660 * \param json_string The string to parse.
1661 * \return The corresponding value if successfully parsed.
1663 static V8_DEPRECATE_SOON("Use maybe version",
1664 Local<Value> Parse(Local<String> json_string));
1665 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1666 Isolate* isolate, Local<String> json_string);
1671 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1672 * but can be created without entering a v8::Context and hence shouldn't
1673 * escape to JavaScript.
1675 class V8_EXPORT NativeWeakMap : public Data {
1677 static Local<NativeWeakMap> New(Isolate* isolate);
1678 void Set(Local<Value> key, Local<Value> value);
1679 Local<Value> Get(Local<Value> key);
1680 bool Has(Local<Value> key);
1681 bool Delete(Local<Value> key);
1689 * The superclass of all JavaScript values and objects.
1691 class V8_EXPORT Value : public Data {
1694 * Returns true if this value is the undefined value. See ECMA-262
1697 V8_INLINE bool IsUndefined() const;
1700 * Returns true if this value is the null value. See ECMA-262
1703 V8_INLINE bool IsNull() const;
1706 * Returns true if this value is true.
1708 bool IsTrue() const;
1711 * Returns true if this value is false.
1713 bool IsFalse() const;
1716 * Returns true if this value is a symbol or a string.
1717 * This is an experimental feature.
1719 bool IsName() const;
1722 * Returns true if this value is an instance of the String type.
1725 V8_INLINE bool IsString() const;
1728 * Returns true if this value is a symbol.
1729 * This is an experimental feature.
1731 bool IsSymbol() const;
1734 * Returns true if this value is a function.
1736 bool IsFunction() const;
1739 * Returns true if this value is an array.
1741 bool IsArray() const;
1744 * Returns true if this value is an object.
1746 bool IsObject() const;
1749 * Returns true if this value is boolean.
1751 bool IsBoolean() const;
1754 * Returns true if this value is a number.
1756 bool IsNumber() const;
1759 * Returns true if this value is external.
1761 bool IsExternal() const;
1764 * Returns true if this value is a 32-bit signed integer.
1766 bool IsInt32() const;
1769 * Returns true if this value is a 32-bit unsigned integer.
1771 bool IsUint32() const;
1774 * Returns true if this value is a Date.
1776 bool IsDate() const;
1779 * Returns true if this value is an Arguments object.
1781 bool IsArgumentsObject() const;
1784 * Returns true if this value is a Boolean object.
1786 bool IsBooleanObject() const;
1789 * Returns true if this value is a Number object.
1791 bool IsNumberObject() const;
1794 * Returns true if this value is a String object.
1796 bool IsStringObject() const;
1799 * Returns true if this value is a Symbol object.
1800 * This is an experimental feature.
1802 bool IsSymbolObject() const;
1805 * Returns true if this value is a Float32x4 object.
1806 * This is an experimental feature.
1808 bool IsFloat32x4Object() const;
1811 * Returns true if this value is a NativeError.
1813 bool IsNativeError() const;
1816 * Returns true if this value is a RegExp.
1818 bool IsRegExp() const;
1821 * Returns true if this value is a Generator function.
1822 * This is an experimental feature.
1824 bool IsGeneratorFunction() const;
1827 * Returns true if this value is a Generator object (iterator).
1828 * This is an experimental feature.
1830 bool IsGeneratorObject() const;
1833 * Returns true if this value is a Promise.
1834 * This is an experimental feature.
1836 bool IsPromise() const;
1839 * Returns true if this value is a Map.
1844 * Returns true if this value is a Set.
1849 * Returns true if this value is a Map Iterator.
1851 bool IsMapIterator() const;
1854 * Returns true if this value is a Set Iterator.
1856 bool IsSetIterator() const;
1859 * Returns true if this value is a WeakMap.
1861 bool IsWeakMap() const;
1864 * Returns true if this value is a WeakSet.
1866 bool IsWeakSet() const;
1869 * Returns true if this value is an ArrayBuffer.
1870 * This is an experimental feature.
1872 bool IsArrayBuffer() const;
1875 * Returns true if this value is an ArrayBufferView.
1876 * This is an experimental feature.
1878 bool IsArrayBufferView() const;
1881 * Returns true if this value is one of TypedArrays.
1882 * This is an experimental feature.
1884 bool IsTypedArray() const;
1887 * Returns true if this value is an Uint8Array.
1888 * This is an experimental feature.
1890 bool IsUint8Array() const;
1893 * Returns true if this value is an Uint8ClampedArray.
1894 * This is an experimental feature.
1896 bool IsUint8ClampedArray() const;
1899 * Returns true if this value is an Int8Array.
1900 * This is an experimental feature.
1902 bool IsInt8Array() const;
1905 * Returns true if this value is an Uint16Array.
1906 * This is an experimental feature.
1908 bool IsUint16Array() const;
1911 * Returns true if this value is an Int16Array.
1912 * This is an experimental feature.
1914 bool IsInt16Array() const;
1917 * Returns true if this value is an Uint32Array.
1918 * This is an experimental feature.
1920 bool IsUint32Array() const;
1923 * Returns true if this value is an Int32Array.
1924 * This is an experimental feature.
1926 bool IsInt32Array() const;
1929 * Returns true if this value is a Float32Array.
1930 * This is an experimental feature.
1932 bool IsFloat32Array() const;
1935 * Returns true if this value is a Float64Array.
1936 * This is an experimental feature.
1938 bool IsFloat64Array() const;
1941 * Returns true if this value is a SIMD Float32x4.
1942 * This is an experimental feature.
1944 bool IsFloat32x4() const;
1947 * Returns true if this value is a DataView.
1948 * This is an experimental feature.
1950 bool IsDataView() const;
1953 * Returns true if this value is a SharedArrayBuffer.
1954 * This is an experimental feature.
1956 bool IsSharedArrayBuffer() const;
1959 V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
1960 Local<Context> context) const;
1961 V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
1962 Local<Context> context) const;
1963 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
1964 Local<Context> context) const;
1965 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
1966 Local<Context> context) const;
1967 V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
1968 Local<Context> context) const;
1969 V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
1970 Local<Context> context) const;
1971 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
1972 Local<Context> context) const;
1973 V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
1975 V8_DEPRECATE_SOON("Use maybe version",
1976 Local<Boolean> ToBoolean(Isolate* isolate) const);
1977 V8_DEPRECATE_SOON("Use maybe version",
1978 Local<Number> ToNumber(Isolate* isolate) const);
1979 V8_DEPRECATE_SOON("Use maybe version",
1980 Local<String> ToString(Isolate* isolate) const);
1981 V8_DEPRECATE_SOON("Use maybe version",
1982 Local<String> ToDetailString(Isolate* isolate) const);
1983 V8_DEPRECATE_SOON("Use maybe version",
1984 Local<Object> ToObject(Isolate* isolate) const);
1985 V8_DEPRECATE_SOON("Use maybe version",
1986 Local<Integer> ToInteger(Isolate* isolate) const);
1987 V8_DEPRECATE_SOON("Use maybe version",
1988 Local<Uint32> ToUint32(Isolate* isolate) const);
1989 V8_DEPRECATE_SOON("Use maybe version",
1990 Local<Int32> ToInt32(Isolate* isolate) const);
1992 inline V8_DEPRECATE_SOON("Use maybe version",
1993 Local<Boolean> ToBoolean() const);
1994 inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber() const);
1995 inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
1996 inline V8_DEPRECATE_SOON("Use maybe version",
1997 Local<String> ToDetailString() const);
1998 inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
1999 inline V8_DEPRECATE_SOON("Use maybe version",
2000 Local<Integer> ToInteger() const);
2001 inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32() const);
2002 inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32() const);
2005 * Attempts to convert a string to an array index.
2006 * Returns an empty handle if the conversion fails.
2008 V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex() const);
2009 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
2010 Local<Context> context) const;
2012 V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2013 V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2014 V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2015 Local<Context> context) const;
2016 V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2017 Local<Context> context) const;
2018 V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2020 V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2021 V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2022 V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2023 V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2024 V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2027 V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2028 V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2029 Local<Value> that) const;
2030 bool StrictEquals(Local<Value> that) const;
2031 bool SameValue(Local<Value> that) const;
2033 template <class T> V8_INLINE static Value* Cast(T* value);
2036 V8_INLINE bool QuickIsUndefined() const;
2037 V8_INLINE bool QuickIsNull() const;
2038 V8_INLINE bool QuickIsString() const;
2039 bool FullIsUndefined() const;
2040 bool FullIsNull() const;
2041 bool FullIsString() const;
2046 * The superclass of primitive values. See ECMA-262 4.3.2.
2048 class V8_EXPORT Primitive : public Value { };
2052 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2055 class V8_EXPORT Boolean : public Primitive {
2058 V8_INLINE static Boolean* Cast(v8::Value* obj);
2059 V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2062 static void CheckCast(v8::Value* obj);
2067 * A superclass for symbols and strings.
2069 class V8_EXPORT Name : public Primitive {
2072 * Returns the identity hash for this object. The current implementation
2073 * uses an inline property on the object to store the identity hash.
2075 * The return value will never be 0. Also, it is not guaranteed to be
2078 int GetIdentityHash();
2080 V8_INLINE static Name* Cast(v8::Value* obj);
2082 static void CheckCast(v8::Value* obj);
2086 enum class NewStringType { kNormal, kInternalized };
2090 * A JavaScript string value (ECMA-262, 4.3.17).
2092 class V8_EXPORT String : public Name {
2094 static const int kMaxLength = (1 << 28) - 16;
2097 UNKNOWN_ENCODING = 0x1,
2098 TWO_BYTE_ENCODING = 0x0,
2099 ONE_BYTE_ENCODING = 0x4
2102 * Returns the number of characters in this string.
2107 * Returns the number of bytes in the UTF-8 encoded
2108 * representation of this string.
2110 int Utf8Length() const;
2113 * Returns whether this string is known to contain only one byte data.
2114 * Does not read the string.
2115 * False negatives are possible.
2117 bool IsOneByte() const;
2120 * Returns whether this string contain only one byte data.
2121 * Will read the entire string in some cases.
2123 bool ContainsOnlyOneByte() const;
2126 * Write the contents of the string to an external buffer.
2127 * If no arguments are given, expects the buffer to be large
2128 * enough to hold the entire string and NULL terminator. Copies
2129 * the contents of the string and the NULL terminator into the
2132 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2133 * before the end of the buffer.
2135 * Copies up to length characters into the output buffer.
2136 * Only null-terminates if there is enough space in the buffer.
2138 * \param buffer The buffer into which the string will be copied.
2139 * \param start The starting position within the string at which
2141 * \param length The number of characters to copy from the string. For
2142 * WriteUtf8 the number of bytes in the buffer.
2143 * \param nchars_ref The number of characters written, can be NULL.
2144 * \param options Various options that might affect performance of this or
2145 * subsequent operations.
2146 * \return The number of characters copied to the buffer excluding the null
2147 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2148 * including the null terminator (if written).
2152 HINT_MANY_WRITES_EXPECTED = 1,
2153 NO_NULL_TERMINATION = 2,
2154 PRESERVE_ONE_BYTE_NULL = 4,
2155 // Used by WriteUtf8 to replace orphan surrogate code units with the
2156 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2158 REPLACE_INVALID_UTF8 = 8
2161 // 16-bit character codes.
2162 int Write(uint16_t* buffer,
2165 int options = NO_OPTIONS) const;
2166 // One byte characters.
2167 int WriteOneByte(uint8_t* buffer,
2170 int options = NO_OPTIONS) const;
2171 // UTF-8 encoded characters.
2172 int WriteUtf8(char* buffer,
2174 int* nchars_ref = NULL,
2175 int options = NO_OPTIONS) const;
2178 * A zero length string.
2180 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2183 * Returns true if the string is external
2185 bool IsExternal() const;
2188 * Returns true if the string is both external and one-byte.
2190 bool IsExternalOneByte() const;
2192 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2194 virtual ~ExternalStringResourceBase() {}
2197 ExternalStringResourceBase() {}
2200 * Internally V8 will call this Dispose method when the external string
2201 * resource is no longer needed. The default implementation will use the
2202 * delete operator. This method can be overridden in subclasses to
2203 * control how allocated external string resources are disposed.
2205 virtual void Dispose() { delete this; }
2208 // Disallow copying and assigning.
2209 ExternalStringResourceBase(const ExternalStringResourceBase&);
2210 void operator=(const ExternalStringResourceBase&);
2212 friend class v8::internal::Heap;
2216 * An ExternalStringResource is a wrapper around a two-byte string
2217 * buffer that resides outside V8's heap. Implement an
2218 * ExternalStringResource to manage the life cycle of the underlying
2219 * buffer. Note that the string data must be immutable.
2221 class V8_EXPORT ExternalStringResource
2222 : public ExternalStringResourceBase {
2225 * Override the destructor to manage the life cycle of the underlying
2228 virtual ~ExternalStringResource() {}
2231 * The string data from the underlying buffer.
2233 virtual const uint16_t* data() const = 0;
2236 * The length of the string. That is, the number of two-byte characters.
2238 virtual size_t length() const = 0;
2241 ExternalStringResource() {}
2245 * An ExternalOneByteStringResource is a wrapper around an one-byte
2246 * string buffer that resides outside V8's heap. Implement an
2247 * ExternalOneByteStringResource to manage the life cycle of the
2248 * underlying buffer. Note that the string data must be immutable
2249 * and that the data must be Latin-1 and not UTF-8, which would require
2250 * special treatment internally in the engine and do not allow efficient
2251 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2254 class V8_EXPORT ExternalOneByteStringResource
2255 : public ExternalStringResourceBase {
2258 * Override the destructor to manage the life cycle of the underlying
2261 virtual ~ExternalOneByteStringResource() {}
2262 /** The string data from the underlying buffer.*/
2263 virtual const char* data() const = 0;
2264 /** The number of Latin-1 characters in the string.*/
2265 virtual size_t length() const = 0;
2267 ExternalOneByteStringResource() {}
2271 * If the string is an external string, return the ExternalStringResourceBase
2272 * regardless of the encoding, otherwise return NULL. The encoding of the
2273 * string is returned in encoding_out.
2275 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2276 Encoding* encoding_out) const;
2279 * Get the ExternalStringResource for an external string. Returns
2280 * NULL if IsExternal() doesn't return true.
2282 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2285 * Get the ExternalOneByteStringResource for an external one-byte string.
2286 * Returns NULL if IsExternalOneByte() doesn't return true.
2288 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2290 V8_INLINE static String* Cast(v8::Value* obj);
2292 // TODO(dcarney): remove with deprecation of New functions.
2293 enum NewStringType {
2294 kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2295 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2298 /** Allocates a new string from UTF-8 data.*/
2299 static V8_DEPRECATE_SOON(
2300 "Use maybe version",
2301 Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2302 NewStringType type = kNormalString,
2305 /** Allocates a new string from UTF-8 data. Only returns an empty value when
2306 * length > kMaxLength. **/
2307 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2308 Isolate* isolate, const char* data, v8::NewStringType type,
2311 /** Allocates a new string from Latin-1 data.*/
2312 static V8_DEPRECATE_SOON(
2313 "Use maybe version",
2314 Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2315 NewStringType type = kNormalString,
2318 /** Allocates a new string from Latin-1 data. Only returns an empty value
2319 * when length > kMaxLength. **/
2320 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2321 Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2324 /** Allocates a new string from UTF-16 data.*/
2325 static V8_DEPRECATE_SOON(
2326 "Use maybe version",
2327 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2328 NewStringType type = kNormalString,
2331 /** Allocates a new string from UTF-16 data. Only returns an empty value when
2332 * length > kMaxLength. **/
2333 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2334 Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2338 * Creates a new string by concatenating the left and the right strings
2339 * passed in as parameters.
2341 static Local<String> Concat(Local<String> left, Local<String> right);
2344 * Creates a new external string using the data defined in the given
2345 * resource. When the external string is no longer live on V8's heap the
2346 * resource will be disposed by calling its Dispose method. The caller of
2347 * this function should not otherwise delete or modify the resource. Neither
2348 * should the underlying buffer be deallocated or modified except through the
2349 * destructor of the external string resource.
2351 static V8_DEPRECATE_SOON(
2352 "Use maybe version",
2353 Local<String> NewExternal(Isolate* isolate,
2354 ExternalStringResource* resource));
2355 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2356 Isolate* isolate, ExternalStringResource* resource);
2359 * Associate an external string resource with this string by transforming it
2360 * in place so that existing references to this string in the JavaScript heap
2361 * will use the external string resource. The external string resource's
2362 * character contents need to be equivalent to this string.
2363 * Returns true if the string has been changed to be an external string.
2364 * The string is not modified if the operation fails. See NewExternal for
2365 * information on the lifetime of the resource.
2367 bool MakeExternal(ExternalStringResource* resource);
2370 * Creates a new external string using the one-byte data defined in the given
2371 * resource. When the external string is no longer live on V8's heap the
2372 * resource will be disposed by calling its Dispose method. The caller of
2373 * this function should not otherwise delete or modify the resource. Neither
2374 * should the underlying buffer be deallocated or modified except through the
2375 * destructor of the external string resource.
2377 static V8_DEPRECATE_SOON(
2378 "Use maybe version",
2379 Local<String> NewExternal(Isolate* isolate,
2380 ExternalOneByteStringResource* resource));
2381 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2382 Isolate* isolate, ExternalOneByteStringResource* resource);
2385 * Associate an external string resource with this string by transforming it
2386 * in place so that existing references to this string in the JavaScript heap
2387 * will use the external string resource. The external string resource's
2388 * character contents need to be equivalent to this string.
2389 * Returns true if the string has been changed to be an external string.
2390 * The string is not modified if the operation fails. See NewExternal for
2391 * information on the lifetime of the resource.
2393 bool MakeExternal(ExternalOneByteStringResource* resource);
2396 * Returns true if this string can be made external.
2398 bool CanMakeExternal();
2401 * Converts an object to a UTF-8-encoded character array. Useful if
2402 * you want to print the object. If conversion to a string fails
2403 * (e.g. due to an exception in the toString() method of the object)
2404 * then the length() method returns 0 and the * operator returns
2407 class V8_EXPORT Utf8Value {
2409 explicit Utf8Value(Local<v8::Value> obj);
2411 char* operator*() { return str_; }
2412 const char* operator*() const { return str_; }
2413 int length() const { return length_; }
2418 // Disallow copying and assigning.
2419 Utf8Value(const Utf8Value&);
2420 void operator=(const Utf8Value&);
2424 * Converts an object to a two-byte string.
2425 * If conversion to a string fails (eg. due to an exception in the toString()
2426 * method of the object) then the length() method returns 0 and the * operator
2429 class V8_EXPORT Value {
2431 explicit Value(Local<v8::Value> obj);
2433 uint16_t* operator*() { return str_; }
2434 const uint16_t* operator*() const { return str_; }
2435 int length() const { return length_; }
2440 // Disallow copying and assigning.
2441 Value(const Value&);
2442 void operator=(const Value&);
2446 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2447 Encoding encoding) const;
2448 void VerifyExternalStringResource(ExternalStringResource* val) const;
2449 static void CheckCast(v8::Value* obj);
2454 * A JavaScript symbol (ECMA-262 edition 6)
2456 * This is an experimental feature. Use at your own risk.
2458 class V8_EXPORT Symbol : public Name {
2460 // Returns the print name string of the symbol, or undefined if none.
2461 Local<Value> Name() const;
2463 // Create a symbol. If name is not empty, it will be used as the description.
2464 static Local<Symbol> New(
2465 Isolate *isolate, Local<String> name = Local<String>());
2467 // Access global symbol registry.
2468 // Note that symbols created this way are never collected, so
2469 // they should only be used for statically fixed properties.
2470 // Also, there is only one global name space for the names used as keys.
2471 // To minimize the potential for clashes, use qualified names as keys.
2472 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2474 // Retrieve a global symbol. Similar to |For|, but using a separate
2475 // registry that is not accessible by (and cannot clash with) JavaScript code.
2476 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2478 // Well-known symbols
2479 static Local<Symbol> GetIterator(Isolate* isolate);
2480 static Local<Symbol> GetUnscopables(Isolate* isolate);
2481 static Local<Symbol> GetToStringTag(Isolate* isolate);
2483 V8_INLINE static Symbol* Cast(v8::Value* obj);
2487 static void CheckCast(v8::Value* obj);
2492 * A JavaScript number value (ECMA-262, 4.3.20)
2494 class V8_EXPORT Number : public Primitive {
2496 double Value() const;
2497 static Local<Number> New(Isolate* isolate, double value);
2498 V8_INLINE static Number* Cast(v8::Value* obj);
2501 static void CheckCast(v8::Value* obj);
2506 * A JavaScript value representing a signed integer.
2508 class V8_EXPORT Integer : public Number {
2510 static Local<Integer> New(Isolate* isolate, int32_t value);
2511 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2512 int64_t Value() const;
2513 V8_INLINE static Integer* Cast(v8::Value* obj);
2516 static void CheckCast(v8::Value* obj);
2521 * A JavaScript value representing a 32-bit signed integer.
2523 class V8_EXPORT Int32 : public Integer {
2525 int32_t Value() const;
2526 V8_INLINE static Int32* Cast(v8::Value* obj);
2530 static void CheckCast(v8::Value* obj);
2535 * A JavaScript value representing a 32-bit unsigned integer.
2537 class V8_EXPORT Uint32 : public Integer {
2539 uint32_t Value() const;
2540 V8_INLINE static Uint32* Cast(v8::Value* obj);
2544 static void CheckCast(v8::Value* obj);
2548 enum PropertyAttribute {
2556 * Accessor[Getter|Setter] are used as callback functions when
2557 * setting|getting a particular property. See Object and ObjectTemplate's
2558 * method SetAccessor.
2560 typedef void (*AccessorGetterCallback)(
2561 Local<String> property,
2562 const PropertyCallbackInfo<Value>& info);
2563 typedef void (*AccessorNameGetterCallback)(
2564 Local<Name> property,
2565 const PropertyCallbackInfo<Value>& info);
2568 typedef void (*AccessorSetterCallback)(
2569 Local<String> property,
2571 const PropertyCallbackInfo<void>& info);
2572 typedef void (*AccessorNameSetterCallback)(
2573 Local<Name> property,
2575 const PropertyCallbackInfo<void>& info);
2579 * Access control specifications.
2581 * Some accessors should be accessible across contexts. These
2582 * accessors have an explicit access control parameter which specifies
2583 * the kind of cross-context access that should be allowed.
2585 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2587 enum AccessControl {
2590 ALL_CAN_WRITE = 1 << 1,
2591 PROHIBITS_OVERWRITING = 1 << 2
2596 * A JavaScript object (ECMA-262, 4.3.3)
2598 class V8_EXPORT Object : public Value {
2600 V8_DEPRECATE_SOON("Use maybe version",
2601 bool Set(Local<Value> key, Local<Value> value));
2602 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
2603 Local<Value> key, Local<Value> value);
2605 V8_DEPRECATE_SOON("Use maybe version",
2606 bool Set(uint32_t index, Local<Value> value));
2607 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
2608 Local<Value> value);
2610 // Implements CreateDataProperty (ECMA-262, 7.3.4).
2612 // Defines a configurable, writable, enumerable property with the given value
2613 // on the object unless the property already exists and is not configurable
2614 // or the object is not extensible.
2616 // Returns true on success.
2617 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2619 Local<Value> value);
2620 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2622 Local<Value> value);
2624 // Implements DefineOwnProperty.
2626 // In general, CreateDataProperty will be faster, however, does not allow
2627 // for specifying attributes.
2629 // Returns true on success.
2630 V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
2631 Local<Context> context, Local<Name> key, Local<Value> value,
2632 PropertyAttribute attributes = None);
2634 // Sets an own property on this object bypassing interceptors and
2635 // overriding accessors or read-only properties.
2637 // Note that if the object has an interceptor the property will be set
2638 // locally, but since the interceptor takes precedence the local property
2639 // will only be returned if the interceptor doesn't return a value.
2641 // Note also that this only works for named properties.
2642 V8_DEPRECATE_SOON("Use CreateDataProperty",
2643 bool ForceSet(Local<Value> key, Local<Value> value,
2644 PropertyAttribute attribs = None));
2645 V8_DEPRECATE_SOON("Use CreateDataProperty",
2646 Maybe<bool> ForceSet(Local<Context> context,
2647 Local<Value> key, Local<Value> value,
2648 PropertyAttribute attribs = None));
2650 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
2651 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2654 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2655 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2659 * Gets the property attributes of a property which can be None or
2660 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2661 * None when the property doesn't exist.
2663 V8_DEPRECATE_SOON("Use maybe version",
2664 PropertyAttribute GetPropertyAttributes(Local<Value> key));
2665 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
2666 Local<Context> context, Local<Value> key);
2669 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2671 V8_DEPRECATE_SOON("Use maybe version",
2672 Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2673 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
2674 Local<Context> context, Local<String> key);
2676 V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
2677 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2680 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
2681 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2682 Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2684 V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2685 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
2687 V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2688 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2689 Maybe<bool> Delete(Local<Context> context, uint32_t index);
2691 V8_DEPRECATE_SOON("Use maybe version",
2692 bool SetAccessor(Local<String> name,
2693 AccessorGetterCallback getter,
2694 AccessorSetterCallback setter = 0,
2695 Local<Value> data = Local<Value>(),
2696 AccessControl settings = DEFAULT,
2697 PropertyAttribute attribute = None));
2698 V8_DEPRECATE_SOON("Use maybe version",
2699 bool SetAccessor(Local<Name> name,
2700 AccessorNameGetterCallback getter,
2701 AccessorNameSetterCallback setter = 0,
2702 Local<Value> data = Local<Value>(),
2703 AccessControl settings = DEFAULT,
2704 PropertyAttribute attribute = None));
2705 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2706 Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2707 AccessorNameGetterCallback getter,
2708 AccessorNameSetterCallback setter = 0,
2709 MaybeLocal<Value> data = MaybeLocal<Value>(),
2710 AccessControl settings = DEFAULT,
2711 PropertyAttribute attribute = None);
2713 void SetAccessorProperty(Local<Name> name, Local<Function> getter,
2714 Local<Function> setter = Local<Function>(),
2715 PropertyAttribute attribute = None,
2716 AccessControl settings = DEFAULT);
2719 * Returns an array containing the names of the enumerable properties
2720 * of this object, including properties from prototype objects. The
2721 * array returned by this method contains the same values as would
2722 * be enumerated by a for-in statement over this object.
2724 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2725 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
2726 Local<Context> context);
2729 * This function has the same functionality as GetPropertyNames but
2730 * the returned array doesn't contain the names of properties from
2731 * prototype objects.
2733 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2734 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
2735 Local<Context> context);
2738 * Get the prototype object. This does not skip objects marked to
2739 * be skipped by __proto__ and it does not consult the security
2742 Local<Value> GetPrototype();
2745 * Set the prototype object. This does not skip objects marked to
2746 * be skipped by __proto__ and it does not consult the security
2749 V8_DEPRECATE_SOON("Use maybe version",
2750 bool SetPrototype(Local<Value> prototype));
2751 V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
2752 Local<Value> prototype);
2755 * Finds an instance of the given function template in the prototype
2758 Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
2761 * Call builtin Object.prototype.toString on this object.
2762 * This is different from Value::ToString() that may call
2763 * user-defined toString function. This one does not.
2765 V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2766 V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
2767 Local<Context> context);
2770 * Returns the name of the function invoked as a constructor for this object.
2772 Local<String> GetConstructorName();
2774 /** Gets the number of internal fields for this Object. */
2775 int InternalFieldCount();
2777 /** Same as above, but works for Persistents */
2778 V8_INLINE static int InternalFieldCount(
2779 const PersistentBase<Object>& object) {
2780 return object.val_->InternalFieldCount();
2783 /** Gets the value from an internal field. */
2784 V8_INLINE Local<Value> GetInternalField(int index);
2786 /** Sets the value in an internal field. */
2787 void SetInternalField(int index, Local<Value> value);
2790 * Gets a 2-byte-aligned native pointer from an internal field. This field
2791 * must have been set by SetAlignedPointerInInternalField, everything else
2792 * leads to undefined behavior.
2794 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2796 /** Same as above, but works for Persistents */
2797 V8_INLINE static void* GetAlignedPointerFromInternalField(
2798 const PersistentBase<Object>& object, int index) {
2799 return object.val_->GetAlignedPointerFromInternalField(index);
2803 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2804 * a field, GetAlignedPointerFromInternalField must be used, everything else
2805 * leads to undefined behavior.
2807 void SetAlignedPointerInInternalField(int index, void* value);
2809 // Testers for local properties.
2810 V8_DEPRECATE_SOON("Use maybe version",
2811 bool HasOwnProperty(Local<String> key));
2812 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
2814 V8_DEPRECATE_SOON("Use maybe version",
2815 bool HasRealNamedProperty(Local<String> key));
2816 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
2818 V8_DEPRECATE_SOON("Use maybe version",
2819 bool HasRealIndexedProperty(uint32_t index));
2820 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
2821 Local<Context> context, uint32_t index);
2822 V8_DEPRECATE_SOON("Use maybe version",
2823 bool HasRealNamedCallbackProperty(Local<String> key));
2824 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
2825 Local<Context> context, Local<Name> key);
2828 * If result.IsEmpty() no real property was located in the prototype chain.
2829 * This means interceptors in the prototype chain are not called.
2832 "Use maybe version",
2833 Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
2834 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
2835 Local<Context> context, Local<Name> key);
2838 * Gets the property attributes of a real property in the prototype chain,
2839 * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2840 * Interceptors in the prototype chain are not called.
2843 "Use maybe version",
2844 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2845 Local<String> key));
2846 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
2847 GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
2851 * If result.IsEmpty() no real property was located on the object or
2852 * in the prototype chain.
2853 * This means interceptors in the prototype chain are not called.
2855 V8_DEPRECATE_SOON("Use maybe version",
2856 Local<Value> GetRealNamedProperty(Local<String> key));
2857 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
2858 Local<Context> context, Local<Name> key);
2861 * Gets the property attributes of a real property which can be
2862 * None or any combination of ReadOnly, DontEnum and DontDelete.
2863 * Interceptors in the prototype chain are not called.
2865 V8_DEPRECATE_SOON("Use maybe version",
2866 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2867 Local<String> key));
2868 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2869 Local<Context> context, Local<Name> key);
2871 /** Tests for a named lookup interceptor.*/
2872 bool HasNamedLookupInterceptor();
2874 /** Tests for an index lookup interceptor.*/
2875 bool HasIndexedLookupInterceptor();
2878 * Returns the identity hash for this object. The current implementation
2879 * uses a hidden property on the object to store the identity hash.
2881 * The return value will never be 0. Also, it is not guaranteed to be
2884 int GetIdentityHash();
2887 * Access hidden properties on JavaScript objects. These properties are
2888 * hidden from the executing JavaScript and only accessible through the V8
2889 * C++ API. Hidden properties introduced by V8 internally (for example the
2890 * identity hash) are prefixed with "v8::".
2892 // TODO(dcarney): convert these to take a isolate and optionally bailout?
2893 bool SetHiddenValue(Local<String> key, Local<Value> value);
2894 Local<Value> GetHiddenValue(Local<String> key);
2895 bool DeleteHiddenValue(Local<String> key);
2898 * Clone this object with a fast but shallow copy. Values will point
2899 * to the same values as the original object.
2901 // TODO(dcarney): take an isolate and optionally bail out?
2902 Local<Object> Clone();
2905 * Returns the context in which the object was created.
2907 Local<Context> CreationContext();
2910 * Checks whether a callback is set by the
2911 * ObjectTemplate::SetCallAsFunctionHandler method.
2912 * When an Object is callable this method returns true.
2917 * Call an Object as a function if a callback is set by the
2918 * ObjectTemplate::SetCallAsFunctionHandler method.
2920 V8_DEPRECATE_SOON("Use maybe version",
2921 Local<Value> CallAsFunction(Local<Value> recv, int argc,
2922 Local<Value> argv[]));
2923 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
2926 Local<Value> argv[]);
2929 * Call an Object as a constructor if a callback is set by the
2930 * ObjectTemplate::SetCallAsFunctionHandler method.
2931 * Note: This method behaves like the Function::NewInstance method.
2933 V8_DEPRECATE_SOON("Use maybe version",
2934 Local<Value> CallAsConstructor(int argc,
2935 Local<Value> argv[]));
2936 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
2937 Local<Context> context, int argc, Local<Value> argv[]);
2940 * Return the isolate to which the Object belongs to.
2942 V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
2944 static Local<Object> New(Isolate* isolate);
2946 V8_INLINE static Object* Cast(Value* obj);
2950 static void CheckCast(Value* obj);
2951 Local<Value> SlowGetInternalField(int index);
2952 void* SlowGetAlignedPointerFromInternalField(int index);
2957 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2959 class V8_EXPORT Array : public Object {
2961 uint32_t Length() const;
2964 * Clones an element at index |index|. Returns an empty
2965 * handle if cloning fails (for any reason).
2967 V8_DEPRECATE_SOON("Use maybe version",
2968 Local<Object> CloneElementAt(uint32_t index));
2969 V8_WARN_UNUSED_RESULT MaybeLocal<Object> CloneElementAt(
2970 Local<Context> context, uint32_t index);
2973 * Creates a JavaScript array with the given length. If the length
2974 * is negative the returned array will have length 0.
2976 static Local<Array> New(Isolate* isolate, int length = 0);
2978 V8_INLINE static Array* Cast(Value* obj);
2981 static void CheckCast(Value* obj);
2986 * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
2988 class V8_EXPORT Map : public Object {
2990 size_t Size() const;
2992 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2994 V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
2996 Local<Value> value);
2997 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2999 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3003 * Returns an array of length Size() * 2, where index N is the Nth key and
3004 * index N + 1 is the Nth value.
3006 Local<Array> AsArray() const;
3009 * Creates a new empty Map.
3011 static Local<Map> New(Isolate* isolate);
3014 * Creates a new Map containing the elements of array, which must be formatted
3015 * in the same manner as the array returned from AsArray().
3016 * Guaranteed to be side-effect free if the array contains no holes.
3018 static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3019 "Use mutation methods instead",
3020 MaybeLocal<Map> FromArray(Local<Context> context, Local<Array> array));
3022 V8_INLINE static Map* Cast(Value* obj);
3026 static void CheckCast(Value* obj);
3031 * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3033 class V8_EXPORT Set : public Object {
3035 size_t Size() const;
3037 V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3039 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3041 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3045 * Returns an array of the keys in this Set.
3047 Local<Array> AsArray() const;
3050 * Creates a new empty Set.
3052 static Local<Set> New(Isolate* isolate);
3055 * Creates a new Set containing the items in array.
3056 * Guaranteed to be side-effect free if the array contains no holes.
3058 static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3059 "Use mutation methods instead",
3060 MaybeLocal<Set> FromArray(Local<Context> context, Local<Array> array));
3062 V8_INLINE static Set* Cast(Value* obj);
3066 static void CheckCast(Value* obj);
3070 template<typename T>
3073 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3074 : value_(that.value_) {
3078 template <typename S>
3079 V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3080 void Set(const Persistent<S>& handle));
3081 template <typename S>
3082 V8_INLINE void Set(const Global<S>& handle);
3083 template <typename S>
3084 V8_INLINE void Set(const Local<S> handle);
3085 // Fast primitive setters
3086 V8_INLINE void Set(bool value);
3087 V8_INLINE void Set(double i);
3088 V8_INLINE void Set(int32_t i);
3089 V8_INLINE void Set(uint32_t i);
3090 // Fast JS primitive setters
3091 V8_INLINE void SetNull();
3092 V8_INLINE void SetUndefined();
3093 V8_INLINE void SetEmptyString();
3094 // Convenience getter for Isolate
3095 V8_INLINE Isolate* GetIsolate();
3097 // Pointer setter: Uncompilable to prevent inadvertent misuse.
3098 template <typename S>
3099 V8_INLINE void Set(S* whatever);
3102 template<class F> friend class ReturnValue;
3103 template<class F> friend class FunctionCallbackInfo;
3104 template<class F> friend class PropertyCallbackInfo;
3105 template <class F, class G, class H>
3106 friend class PersistentValueMapBase;
3107 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3108 V8_INLINE internal::Object* GetDefaultValue();
3109 V8_INLINE explicit ReturnValue(internal::Object** slot);
3110 internal::Object** value_;
3115 * The argument information given to function call callbacks. This
3116 * class provides access to information about the context of the call,
3117 * including the receiver, the number and values of arguments, and
3118 * the holder of the function.
3120 template<typename T>
3121 class FunctionCallbackInfo {
3123 V8_INLINE int Length() const;
3124 V8_INLINE Local<Value> operator[](int i) const;
3125 V8_INLINE Local<Function> Callee() const;
3126 V8_INLINE Local<Object> This() const;
3127 V8_INLINE Local<Object> Holder() const;
3128 V8_INLINE bool IsConstructCall() const;
3129 V8_INLINE Local<Value> Data() const;
3130 V8_INLINE Isolate* GetIsolate() const;
3131 V8_INLINE ReturnValue<T> GetReturnValue() const;
3132 // This shouldn't be public, but the arm compiler needs it.
3133 static const int kArgsLength = 7;
3136 friend class internal::FunctionCallbackArguments;
3137 friend class internal::CustomArguments<FunctionCallbackInfo>;
3138 static const int kHolderIndex = 0;
3139 static const int kIsolateIndex = 1;
3140 static const int kReturnValueDefaultValueIndex = 2;
3141 static const int kReturnValueIndex = 3;
3142 static const int kDataIndex = 4;
3143 static const int kCalleeIndex = 5;
3144 static const int kContextSaveIndex = 6;
3146 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3147 internal::Object** values,
3149 bool is_construct_call);
3150 internal::Object** implicit_args_;
3151 internal::Object** values_;
3153 int is_construct_call_;
3158 * The information passed to a property callback about the context
3159 * of the property access.
3161 template<typename T>
3162 class PropertyCallbackInfo {
3164 V8_INLINE Isolate* GetIsolate() const;
3165 V8_INLINE Local<Value> Data() const;
3166 V8_INLINE Local<Object> This() const;
3167 V8_INLINE Local<Object> Holder() const;
3168 V8_INLINE ReturnValue<T> GetReturnValue() const;
3169 // This shouldn't be public, but the arm compiler needs it.
3170 static const int kArgsLength = 6;
3173 friend class MacroAssembler;
3174 friend class internal::PropertyCallbackArguments;
3175 friend class internal::CustomArguments<PropertyCallbackInfo>;
3176 static const int kHolderIndex = 0;
3177 static const int kIsolateIndex = 1;
3178 static const int kReturnValueDefaultValueIndex = 2;
3179 static const int kReturnValueIndex = 3;
3180 static const int kDataIndex = 4;
3181 static const int kThisIndex = 5;
3183 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3184 internal::Object** args_;
3188 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3192 * A JavaScript function object (ECMA-262, 15.3).
3194 class V8_EXPORT Function : public Object {
3197 * Create a function in the current execution context
3198 * for a given FunctionCallback.
3200 static MaybeLocal<Function> New(Local<Context> context,
3201 FunctionCallback callback,
3202 Local<Value> data = Local<Value>(),
3204 static V8_DEPRECATE_SOON(
3205 "Use maybe version",
3206 Local<Function> New(Isolate* isolate, FunctionCallback callback,
3207 Local<Value> data = Local<Value>(), int length = 0));
3209 V8_DEPRECATE_SOON("Use maybe version",
3210 Local<Object> NewInstance(int argc, Local<Value> argv[])
3212 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3213 Local<Context> context, int argc, Local<Value> argv[]) const;
3215 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance() const);
3216 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3217 Local<Context> context) const {
3218 return NewInstance(context, 0, nullptr);
3221 V8_DEPRECATE_SOON("Use maybe version",
3222 Local<Value> Call(Local<Value> recv, int argc,
3223 Local<Value> argv[]));
3224 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
3225 Local<Value> recv, int argc,
3226 Local<Value> argv[]);
3228 void SetName(Local<String> name);
3229 Local<Value> GetName() const;
3232 * Name inferred from variable or property assignment of this function.
3233 * Used to facilitate debugging and profiling of JavaScript code written
3234 * in an OO style, where many functions are anonymous but are assigned
3235 * to object properties.
3237 Local<Value> GetInferredName() const;
3240 * User-defined name assigned to the "displayName" property of this function.
3241 * Used to facilitate debugging and profiling of JavaScript code.
3243 Local<Value> GetDisplayName() const;
3246 * Returns zero based line number of function body and
3247 * kLineOffsetNotFound if no information available.
3249 int GetScriptLineNumber() const;
3251 * Returns zero based column number of function body and
3252 * kLineOffsetNotFound if no information available.
3254 int GetScriptColumnNumber() const;
3257 * Tells whether this function is builtin.
3259 bool IsBuiltin() const;
3264 int ScriptId() const;
3267 * Returns the original function if this function is bound, else returns
3270 Local<Value> GetBoundFunction() const;
3272 ScriptOrigin GetScriptOrigin() const;
3273 V8_INLINE static Function* Cast(Value* obj);
3274 static const int kLineOffsetNotFound;
3278 static void CheckCast(Value* obj);
3283 * An instance of the built-in Promise constructor (ES6 draft).
3284 * This API is experimental. Only works with --harmony flag.
3286 class V8_EXPORT Promise : public Object {
3288 class V8_EXPORT Resolver : public Object {
3291 * Create a new resolver, along with an associated promise in pending state.
3293 static V8_DEPRECATE_SOON("Use maybe version",
3294 Local<Resolver> New(Isolate* isolate));
3295 static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
3296 Local<Context> context);
3299 * Extract the associated promise.
3301 Local<Promise> GetPromise();
3304 * Resolve/reject the associated promise with a given value.
3305 * Ignored if the promise is no longer pending.
3307 V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3308 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3309 Maybe<bool> Resolve(Local<Context> context, Local<Value> value);
3311 V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3312 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3313 Maybe<bool> Reject(Local<Context> context, Local<Value> value);
3315 V8_INLINE static Resolver* Cast(Value* obj);
3319 static void CheckCast(Value* obj);
3323 * Register a resolution/rejection handler with a promise.
3324 * The handler is given the respective resolution/rejection value as
3325 * an argument. If the promise is already resolved/rejected, the handler is
3326 * invoked at the end of turn.
3328 V8_DEPRECATE_SOON("Use maybe version",
3329 Local<Promise> Chain(Local<Function> handler));
3330 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Chain(Local<Context> context,
3331 Local<Function> handler);
3333 V8_DEPRECATE_SOON("Use maybe version",
3334 Local<Promise> Catch(Local<Function> handler));
3335 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
3336 Local<Function> handler);
3338 V8_DEPRECATE_SOON("Use maybe version",
3339 Local<Promise> Then(Local<Function> handler));
3340 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
3341 Local<Function> handler);
3344 * Returns true if the promise has at least one derived promise, and
3345 * therefore resolve/reject handlers (including default handler).
3349 V8_INLINE static Promise* Cast(Value* obj);
3353 static void CheckCast(Value* obj);
3357 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3358 // The number of required internal fields can be defined by embedder.
3359 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3363 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
3367 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3368 * This API is experimental and may change significantly.
3370 class V8_EXPORT ArrayBuffer : public Object {
3373 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3374 * The allocator is a global V8 setting. It has to be set via
3375 * Isolate::CreateParams.
3377 * This API is experimental and may change significantly.
3379 class V8_EXPORT Allocator { // NOLINT
3381 virtual ~Allocator() {}
3384 * Allocate |length| bytes. Return NULL if allocation is not successful.
3385 * Memory should be initialized to zeroes.
3387 virtual void* Allocate(size_t length) = 0;
3390 * Allocate |length| bytes. Return NULL if allocation is not successful.
3391 * Memory does not have to be initialized.
3393 virtual void* AllocateUninitialized(size_t length) = 0;
3395 * Free the memory block of size |length|, pointed to by |data|.
3396 * That memory is guaranteed to be previously allocated by |Allocate|.
3398 virtual void Free(void* data, size_t length) = 0;
3402 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3403 * returns an instance of this class, populated, with a pointer to data
3406 * The Data pointer of ArrayBuffer::Contents is always allocated with
3407 * Allocator::Allocate that is set via Isolate::CreateParams.
3409 * This API is experimental and may change significantly.
3411 class V8_EXPORT Contents { // NOLINT
3413 Contents() : data_(NULL), byte_length_(0) {}
3415 void* Data() const { return data_; }
3416 size_t ByteLength() const { return byte_length_; }
3420 size_t byte_length_;
3422 friend class ArrayBuffer;
3427 * Data length in bytes.
3429 size_t ByteLength() const;
3432 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3433 * Allocated memory will be owned by a created ArrayBuffer and
3434 * will be deallocated when it is garbage-collected,
3435 * unless the object is externalized.
3437 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3440 * Create a new ArrayBuffer over an existing memory block.
3441 * The created array buffer is by default immediately in externalized state.
3442 * The memory block will not be reclaimed when a created ArrayBuffer
3443 * is garbage-collected.
3445 static Local<ArrayBuffer> New(
3446 Isolate* isolate, void* data, size_t byte_length,
3447 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3450 * Returns true if ArrayBuffer is externalized, that is, does not
3451 * own its memory block.
3453 bool IsExternal() const;
3456 * Returns true if this ArrayBuffer may be neutered.
3458 bool IsNeuterable() const;
3461 * Neuters this ArrayBuffer and all its views (typed arrays).
3462 * Neutering sets the byte length of the buffer and all typed arrays to zero,
3463 * preventing JavaScript from ever accessing underlying backing store.
3464 * ArrayBuffer should have been externalized and must be neuterable.
3469 * Make this ArrayBuffer external. The pointer to underlying memory block
3470 * and byte length are returned as |Contents| structure. After ArrayBuffer
3471 * had been etxrenalized, it does no longer owns the memory block. The caller
3472 * should take steps to free memory when it is no longer needed.
3474 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3475 * that has been set via Isolate::CreateParams.
3477 Contents Externalize();
3480 * Get a pointer to the ArrayBuffer's underlying memory block without
3481 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3482 * will become invalid as soon as the ArrayBuffer became garbage collected.
3484 * The embedder should make sure to hold a strong reference to the
3485 * ArrayBuffer while accessing this pointer.
3487 * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3489 Contents GetContents();
3491 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3493 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3497 static void CheckCast(Value* obj);
3501 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3502 // The number of required internal fields can be defined by embedder.
3503 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3508 * A base class for an instance of one of "views" over ArrayBuffer,
3509 * including TypedArrays and DataView (ES6 draft 15.13).
3511 * This API is experimental and may change significantly.
3513 class V8_EXPORT ArrayBufferView : public Object {
3516 * Returns underlying ArrayBuffer.
3518 Local<ArrayBuffer> Buffer();
3520 * Byte offset in |Buffer|.
3522 size_t ByteOffset();
3524 * Size of a view in bytes.
3526 size_t ByteLength();
3529 * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3530 * memory without additional overhead that calling ArrayBufferView::Buffer
3533 * Will write at most min(|byte_length|, ByteLength) bytes starting at
3534 * ByteOffset of the underling buffer to the memory starting at |dest|.
3535 * Returns the number of bytes actually written.
3537 size_t CopyContents(void* dest, size_t byte_length);
3540 * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3543 bool HasBuffer() const;
3545 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3547 static const int kInternalFieldCount =
3548 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3552 static void CheckCast(Value* obj);
3557 * A base class for an instance of TypedArray series of constructors
3558 * (ES6 draft 15.13.6).
3559 * This API is experimental and may change significantly.
3561 class V8_EXPORT TypedArray : public ArrayBufferView {
3564 * Number of elements in this typed array
3565 * (e.g. for Int16Array, |ByteLength|/2).
3569 V8_INLINE static TypedArray* Cast(Value* obj);
3573 static void CheckCast(Value* obj);
3578 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3579 * This API is experimental and may change significantly.
3581 class V8_EXPORT Uint8Array : public TypedArray {
3583 static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
3584 size_t byte_offset, size_t length);
3585 static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3586 size_t byte_offset, size_t length);
3587 V8_INLINE static Uint8Array* Cast(Value* obj);
3591 static void CheckCast(Value* obj);
3596 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3597 * This API is experimental and may change significantly.
3599 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3601 static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
3602 size_t byte_offset, size_t length);
3603 static Local<Uint8ClampedArray> New(
3604 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
3606 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3609 Uint8ClampedArray();
3610 static void CheckCast(Value* obj);
3614 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3615 * This API is experimental and may change significantly.
3617 class V8_EXPORT Int8Array : public TypedArray {
3619 static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
3620 size_t byte_offset, size_t length);
3621 static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3622 size_t byte_offset, size_t length);
3623 V8_INLINE static Int8Array* Cast(Value* obj);
3627 static void CheckCast(Value* obj);
3632 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3633 * This API is experimental and may change significantly.
3635 class V8_EXPORT Uint16Array : public TypedArray {
3637 static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
3638 size_t byte_offset, size_t length);
3639 static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3640 size_t byte_offset, size_t length);
3641 V8_INLINE static Uint16Array* Cast(Value* obj);
3645 static void CheckCast(Value* obj);
3650 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3651 * This API is experimental and may change significantly.
3653 class V8_EXPORT Int16Array : public TypedArray {
3655 static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
3656 size_t byte_offset, size_t length);
3657 static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3658 size_t byte_offset, size_t length);
3659 V8_INLINE static Int16Array* Cast(Value* obj);
3663 static void CheckCast(Value* obj);
3668 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3669 * This API is experimental and may change significantly.
3671 class V8_EXPORT Uint32Array : public TypedArray {
3673 static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
3674 size_t byte_offset, size_t length);
3675 static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3676 size_t byte_offset, size_t length);
3677 V8_INLINE static Uint32Array* Cast(Value* obj);
3681 static void CheckCast(Value* obj);
3686 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3687 * This API is experimental and may change significantly.
3689 class V8_EXPORT Int32Array : public TypedArray {
3691 static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
3692 size_t byte_offset, size_t length);
3693 static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3694 size_t byte_offset, size_t length);
3695 V8_INLINE static Int32Array* Cast(Value* obj);
3699 static void CheckCast(Value* obj);
3704 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3705 * This API is experimental and may change significantly.
3707 class V8_EXPORT Float32Array : public TypedArray {
3709 static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
3710 size_t byte_offset, size_t length);
3711 static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3712 size_t byte_offset, size_t length);
3713 V8_INLINE static Float32Array* Cast(Value* obj);
3717 static void CheckCast(Value* obj);
3722 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3723 * This API is experimental and may change significantly.
3725 class V8_EXPORT Float64Array : public TypedArray {
3727 static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
3728 size_t byte_offset, size_t length);
3729 static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3730 size_t byte_offset, size_t length);
3731 V8_INLINE static Float64Array* Cast(Value* obj);
3735 static void CheckCast(Value* obj);
3740 * An instance of DataView constructor (ES6 draft 15.13.7).
3741 * This API is experimental and may change significantly.
3743 class V8_EXPORT DataView : public ArrayBufferView {
3745 static Local<DataView> New(Local<ArrayBuffer> array_buffer,
3746 size_t byte_offset, size_t length);
3747 static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
3748 size_t byte_offset, size_t length);
3749 V8_INLINE static DataView* Cast(Value* obj);
3753 static void CheckCast(Value* obj);
3758 * An instance of the built-in SharedArrayBuffer constructor.
3759 * This API is experimental and may change significantly.
3761 class V8_EXPORT SharedArrayBuffer : public Object {
3764 * The contents of an |SharedArrayBuffer|. Externalization of
3765 * |SharedArrayBuffer| returns an instance of this class, populated, with a
3766 * pointer to data and byte length.
3768 * The Data pointer of SharedArrayBuffer::Contents is always allocated with
3769 * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
3770 * v8::Isolate::CreateParams::array_buffer_allocator.
3772 * This API is experimental and may change significantly.
3774 class V8_EXPORT Contents { // NOLINT
3776 Contents() : data_(NULL), byte_length_(0) {}
3778 void* Data() const { return data_; }
3779 size_t ByteLength() const { return byte_length_; }
3783 size_t byte_length_;
3785 friend class SharedArrayBuffer;
3790 * Data length in bytes.
3792 size_t ByteLength() const;
3795 * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
3796 * Allocated memory will be owned by a created SharedArrayBuffer and
3797 * will be deallocated when it is garbage-collected,
3798 * unless the object is externalized.
3800 static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
3803 * Create a new SharedArrayBuffer over an existing memory block. The created
3804 * array buffer is immediately in externalized state unless otherwise
3805 * specified. The memory block will not be reclaimed when a created
3806 * SharedArrayBuffer is garbage-collected.
3808 static Local<SharedArrayBuffer> New(
3809 Isolate* isolate, void* data, size_t byte_length,
3810 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3813 * Returns true if SharedArrayBuffer is externalized, that is, does not
3814 * own its memory block.
3816 bool IsExternal() const;
3819 * Make this SharedArrayBuffer external. The pointer to underlying memory
3820 * block and byte length are returned as |Contents| structure. After
3821 * SharedArrayBuffer had been etxrenalized, it does no longer owns the memory
3822 * block. The caller should take steps to free memory when it is no longer
3825 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3826 * by the allocator specified in
3827 * v8::Isolate::CreateParams::array_buffer_allocator.
3830 Contents Externalize();
3833 * Get a pointer to the ArrayBuffer's underlying memory block without
3834 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3835 * will become invalid as soon as the ArrayBuffer became garbage collected.
3837 * The embedder should make sure to hold a strong reference to the
3838 * ArrayBuffer while accessing this pointer.
3840 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3841 * by the allocator specified in
3842 * v8::Isolate::CreateParams::array_buffer_allocator.
3844 Contents GetContents();
3846 V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
3848 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3851 SharedArrayBuffer();
3852 static void CheckCast(Value* obj);
3857 * An instance of Float32x4 constructor.
3858 * (ES7 draft http://littledan.github.io/simd.html).
3859 * This API is experimental and may change significantly.
3861 class V8_EXPORT Float32x4 : public Value {
3863 static Local<Float32x4> New(Isolate* isolate, float w, float x, float y,
3865 V8_INLINE static Float32x4* Cast(Value* obj);
3869 static void CheckCast(Value* obj);
3874 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3876 class V8_EXPORT Date : public Object {
3878 static V8_DEPRECATE_SOON("Use maybe version.",
3879 Local<Value> New(Isolate* isolate, double time));
3880 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
3884 * A specialization of Value::NumberValue that is more efficient
3885 * because we know the structure of this object.
3887 double ValueOf() const;
3889 V8_INLINE static Date* Cast(v8::Value* obj);
3892 * Notification that the embedder has changed the time zone,
3893 * daylight savings time, or other date / time configuration
3894 * parameters. V8 keeps a cache of various values used for
3895 * date / time computation. This notification will reset
3896 * those cached values for the current context so that date /
3897 * time configuration changes would be reflected in the Date
3900 * This API should not be called more than needed as it will
3901 * negatively impact the performance of date operations.
3903 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3906 static void CheckCast(v8::Value* obj);
3911 * A Number object (ECMA-262, 4.3.21).
3913 class V8_EXPORT NumberObject : public Object {
3915 static Local<Value> New(Isolate* isolate, double value);
3917 double ValueOf() const;
3919 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3922 static void CheckCast(v8::Value* obj);
3927 * A Boolean object (ECMA-262, 4.3.15).
3929 class V8_EXPORT BooleanObject : public Object {
3931 static Local<Value> New(bool value);
3933 bool ValueOf() const;
3935 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3938 static void CheckCast(v8::Value* obj);
3943 * A String object (ECMA-262, 4.3.18).
3945 class V8_EXPORT StringObject : public Object {
3947 static Local<Value> New(Local<String> value);
3949 Local<String> ValueOf() const;
3951 V8_INLINE static StringObject* Cast(v8::Value* obj);
3954 static void CheckCast(v8::Value* obj);
3959 * A Symbol object (ECMA-262 edition 6).
3961 * This is an experimental feature. Use at your own risk.
3963 class V8_EXPORT SymbolObject : public Object {
3965 static Local<Value> New(Isolate* isolate, Local<Symbol> value);
3967 Local<Symbol> ValueOf() const;
3969 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3972 static void CheckCast(v8::Value* obj);
3977 * A Float32x4 object.
3978 * (ES7 draft http://littledan.github.io/simd.html).
3979 * This is an experimental feature. Use at your own risk.
3981 class V8_EXPORT Float32x4Object : public Object {
3983 static Local<Value> New(Isolate* isolate, Local<Float32x4> value);
3985 Local<Float32x4> ValueOf() const;
3987 V8_INLINE static Float32x4Object* Cast(v8::Value* obj);
3990 static void CheckCast(v8::Value* obj);
3995 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3997 class V8_EXPORT RegExp : public Object {
4000 * Regular expression flag bits. They can be or'ed to enable a set
4011 * Creates a regular expression from the given pattern string and
4012 * the flags bit field. May throw a JavaScript exception as
4013 * described in ECMA-262, 15.10.4.1.
4016 * RegExp::New(v8::String::New("foo"),
4017 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
4018 * is equivalent to evaluating "/foo/gm".
4020 static V8_DEPRECATE_SOON("Use maybe version",
4021 Local<RegExp> New(Local<String> pattern,
4023 static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
4024 Local<String> pattern,
4028 * Returns the value of the source property: a string representing
4029 * the regular expression.
4031 Local<String> GetSource() const;
4034 * Returns the flags bit field.
4036 Flags GetFlags() const;
4038 V8_INLINE static RegExp* Cast(v8::Value* obj);
4041 static void CheckCast(v8::Value* obj);
4046 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
4047 * to associate C++ data structures with JavaScript objects.
4049 class V8_EXPORT External : public Value {
4051 static Local<External> New(Isolate* isolate, void* value);
4052 V8_INLINE static External* Cast(Value* obj);
4053 void* Value() const;
4055 static void CheckCast(v8::Value* obj);
4059 // --- Templates ---
4063 * The superclass of object and function templates.
4065 class V8_EXPORT Template : public Data {
4067 /** Adds a property to each instance created by this template.*/
4068 void Set(Local<Name> name, Local<Data> value,
4069 PropertyAttribute attributes = None);
4070 V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
4072 void SetAccessorProperty(
4074 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
4075 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
4076 PropertyAttribute attribute = None,
4077 AccessControl settings = DEFAULT);
4080 * Whenever the property with the given name is accessed on objects
4081 * created from this Template the getter and setter callbacks
4082 * are called instead of getting and setting the property directly
4083 * on the JavaScript object.
4085 * \param name The name of the property for which an accessor is added.
4086 * \param getter The callback to invoke when getting the property.
4087 * \param setter The callback to invoke when setting the property.
4088 * \param data A piece of data that will be passed to the getter and setter
4089 * callbacks whenever they are invoked.
4090 * \param settings Access control settings for the accessor. This is a bit
4091 * field consisting of one of more of
4092 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4093 * The default is to not allow cross-context access.
4094 * ALL_CAN_READ means that all cross-context reads are allowed.
4095 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4096 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4097 * cross-context access.
4098 * \param attribute The attributes of the property for which an accessor
4100 * \param signature The signature describes valid receivers for the accessor
4101 * and is used to perform implicit instance checks against them. If the
4102 * receiver is incompatible (i.e. is not an instance of the constructor as
4103 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4104 * thrown and no callback is invoked.
4106 void SetNativeDataProperty(
4107 Local<String> name, AccessorGetterCallback getter,
4108 AccessorSetterCallback setter = 0,
4109 // TODO(dcarney): gcc can't handle Local below
4110 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4111 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4112 AccessControl settings = DEFAULT);
4113 void SetNativeDataProperty(
4114 Local<Name> name, AccessorNameGetterCallback getter,
4115 AccessorNameSetterCallback setter = 0,
4116 // TODO(dcarney): gcc can't handle Local below
4117 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4118 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4119 AccessControl settings = DEFAULT);
4124 friend class ObjectTemplate;
4125 friend class FunctionTemplate;
4130 * NamedProperty[Getter|Setter] are used as interceptors on object.
4131 * See ObjectTemplate::SetNamedPropertyHandler.
4133 typedef void (*NamedPropertyGetterCallback)(
4134 Local<String> property,
4135 const PropertyCallbackInfo<Value>& info);
4139 * Returns the value if the setter intercepts the request.
4140 * Otherwise, returns an empty handle.
4142 typedef void (*NamedPropertySetterCallback)(
4143 Local<String> property,
4145 const PropertyCallbackInfo<Value>& info);
4149 * Returns a non-empty handle if the interceptor intercepts the request.
4150 * The result is an integer encoding property attributes (like v8::None,
4151 * v8::DontEnum, etc.)
4153 typedef void (*NamedPropertyQueryCallback)(
4154 Local<String> property,
4155 const PropertyCallbackInfo<Integer>& info);
4159 * Returns a non-empty handle if the deleter intercepts the request.
4160 * The return value is true if the property could be deleted and false
4163 typedef void (*NamedPropertyDeleterCallback)(
4164 Local<String> property,
4165 const PropertyCallbackInfo<Boolean>& info);
4169 * Returns an array containing the names of the properties the named
4170 * property getter intercepts.
4172 typedef void (*NamedPropertyEnumeratorCallback)(
4173 const PropertyCallbackInfo<Array>& info);
4176 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
4177 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
4179 * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
4180 * See ObjectTemplate::SetNamedPropertyHandler.
4182 typedef void (*GenericNamedPropertyGetterCallback)(
4183 Local<Name> property, const PropertyCallbackInfo<Value>& info);
4187 * Returns the value if the setter intercepts the request.
4188 * Otherwise, returns an empty handle.
4190 typedef void (*GenericNamedPropertySetterCallback)(
4191 Local<Name> property, Local<Value> value,
4192 const PropertyCallbackInfo<Value>& info);
4196 * Returns a non-empty handle if the interceptor intercepts the request.
4197 * The result is an integer encoding property attributes (like v8::None,
4198 * v8::DontEnum, etc.)
4200 typedef void (*GenericNamedPropertyQueryCallback)(
4201 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4205 * Returns a non-empty handle if the deleter intercepts the request.
4206 * The return value is true if the property could be deleted and false
4209 typedef void (*GenericNamedPropertyDeleterCallback)(
4210 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4214 * Returns an array containing the names of the properties the named
4215 * property getter intercepts.
4217 typedef void (*GenericNamedPropertyEnumeratorCallback)(
4218 const PropertyCallbackInfo<Array>& info);
4222 * Returns the value of the property if the getter intercepts the
4223 * request. Otherwise, returns an empty handle.
4225 typedef void (*IndexedPropertyGetterCallback)(
4227 const PropertyCallbackInfo<Value>& info);
4231 * Returns the value if the setter intercepts the request.
4232 * Otherwise, returns an empty handle.
4234 typedef void (*IndexedPropertySetterCallback)(
4237 const PropertyCallbackInfo<Value>& info);
4241 * Returns a non-empty handle if the interceptor intercepts the request.
4242 * The result is an integer encoding property attributes.
4244 typedef void (*IndexedPropertyQueryCallback)(
4246 const PropertyCallbackInfo<Integer>& info);
4250 * Returns a non-empty handle if the deleter intercepts the request.
4251 * The return value is true if the property could be deleted and false
4254 typedef void (*IndexedPropertyDeleterCallback)(
4256 const PropertyCallbackInfo<Boolean>& info);
4260 * Returns an array containing the indices of the properties the
4261 * indexed property getter intercepts.
4263 typedef void (*IndexedPropertyEnumeratorCallback)(
4264 const PropertyCallbackInfo<Array>& info);
4268 * Access type specification.
4280 * Returns true if cross-context access should be allowed to the named
4281 * property with the given key on the host object.
4283 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4290 * Returns true if cross-context access should be allowed to the indexed
4291 * property with the given index on the host object.
4293 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4300 * A FunctionTemplate is used to create functions at runtime. There
4301 * can only be one function created from a FunctionTemplate in a
4302 * context. The lifetime of the created function is equal to the
4303 * lifetime of the context. So in case the embedder needs to create
4304 * temporary functions that can be collected using Scripts is
4307 * Any modification of a FunctionTemplate after first instantiation will trigger
4310 * A FunctionTemplate can have properties, these properties are added to the
4311 * function object when it is created.
4313 * A FunctionTemplate has a corresponding instance template which is
4314 * used to create object instances when the function is used as a
4315 * constructor. Properties added to the instance template are added to
4316 * each object instance.
4318 * A FunctionTemplate can have a prototype template. The prototype template
4319 * is used to create the prototype object of the function.
4321 * The following example shows how to use a FunctionTemplate:
4324 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4325 * t->Set("func_property", v8::Number::New(1));
4327 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4328 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4329 * proto_t->Set("proto_const", v8::Number::New(2));
4331 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4332 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4333 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4334 * instance_t->Set("instance_property", Number::New(3));
4336 * v8::Local<v8::Function> function = t->GetFunction();
4337 * v8::Local<v8::Object> instance = function->NewInstance();
4340 * Let's use "function" as the JS variable name of the function object
4341 * and "instance" for the instance object created above. The function
4342 * and the instance will have the following properties:
4345 * func_property in function == true;
4346 * function.func_property == 1;
4348 * function.prototype.proto_method() invokes 'InvokeCallback'
4349 * function.prototype.proto_const == 2;
4351 * instance instanceof function == true;
4352 * instance.instance_accessor calls 'InstanceAccessorCallback'
4353 * instance.instance_property == 3;
4356 * A FunctionTemplate can inherit from another one by calling the
4357 * FunctionTemplate::Inherit method. The following graph illustrates
4358 * the semantics of inheritance:
4361 * FunctionTemplate Parent -> Parent() . prototype -> { }
4363 * | Inherit(Parent) | .__proto__
4365 * FunctionTemplate Child -> Child() . prototype -> { }
4368 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4369 * object of the Child() function has __proto__ pointing to the
4370 * Parent() function's prototype object. An instance of the Child
4371 * function has all properties on Parent's instance templates.
4373 * Let Parent be the FunctionTemplate initialized in the previous
4374 * section and create a Child FunctionTemplate by:
4377 * Local<FunctionTemplate> parent = t;
4378 * Local<FunctionTemplate> child = FunctionTemplate::New();
4379 * child->Inherit(parent);
4381 * Local<Function> child_function = child->GetFunction();
4382 * Local<Object> child_instance = child_function->NewInstance();
4385 * The Child function and Child instance will have the following
4389 * child_func.prototype.__proto__ == function.prototype;
4390 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
4391 * child_instance.instance_property == 3;
4394 class V8_EXPORT FunctionTemplate : public Template {
4396 /** Creates a function template.*/
4397 static Local<FunctionTemplate> New(
4398 Isolate* isolate, FunctionCallback callback = 0,
4399 Local<Value> data = Local<Value>(),
4400 Local<Signature> signature = Local<Signature>(), int length = 0);
4402 /** Returns the unique function instance in the current execution context.*/
4403 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4404 V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
4405 Local<Context> context);
4408 * Set the call-handler callback for a FunctionTemplate. This
4409 * callback is called whenever the function created from this
4410 * FunctionTemplate is called.
4412 void SetCallHandler(FunctionCallback callback,
4413 Local<Value> data = Local<Value>());
4415 /** Set the predefined length property for the FunctionTemplate. */
4416 void SetLength(int length);
4418 /** Get the InstanceTemplate. */
4419 Local<ObjectTemplate> InstanceTemplate();
4421 /** Causes the function template to inherit from a parent function template.*/
4422 void Inherit(Local<FunctionTemplate> parent);
4425 * A PrototypeTemplate is the template used to create the prototype object
4426 * of the function created by this template.
4428 Local<ObjectTemplate> PrototypeTemplate();
4431 * Set the class name of the FunctionTemplate. This is used for
4432 * printing objects created with the function created from the
4433 * FunctionTemplate as its constructor.
4435 void SetClassName(Local<String> name);
4439 * When set to true, no access check will be performed on the receiver of a
4440 * function call. Currently defaults to true, but this is subject to change.
4442 void SetAcceptAnyReceiver(bool value);
4445 * Determines whether the __proto__ accessor ignores instances of
4446 * the function template. If instances of the function template are
4447 * ignored, __proto__ skips all instances and instead returns the
4448 * next object in the prototype chain.
4450 * Call with a value of true to make the __proto__ accessor ignore
4451 * instances of the function template. Call with a value of false
4452 * to make the __proto__ accessor not ignore instances of the
4453 * function template. By default, instances of a function template
4456 void SetHiddenPrototype(bool value);
4459 * Sets the ReadOnly flag in the attributes of the 'prototype' property
4460 * of functions created from this FunctionTemplate to true.
4462 void ReadOnlyPrototype();
4465 * Removes the prototype property from functions created from this
4468 void RemovePrototype();
4471 * Returns true if the given object is an instance of this function
4474 bool HasInstance(Local<Value> object);
4478 friend class Context;
4479 friend class ObjectTemplate;
4483 enum class PropertyHandlerFlags {
4485 // See ALL_CAN_READ above.
4487 // Will not call into interceptor for properties on the receiver or prototype
4488 // chain. Currently only valid for named interceptors.
4489 kNonMasking = 1 << 1,
4490 // Will not call into interceptor for symbol lookup. Only meaningful for
4491 // named interceptors.
4492 kOnlyInterceptStrings = 1 << 2,
4496 struct NamedPropertyHandlerConfiguration {
4497 NamedPropertyHandlerConfiguration(
4498 /** Note: getter is required **/
4499 GenericNamedPropertyGetterCallback getter = 0,
4500 GenericNamedPropertySetterCallback setter = 0,
4501 GenericNamedPropertyQueryCallback query = 0,
4502 GenericNamedPropertyDeleterCallback deleter = 0,
4503 GenericNamedPropertyEnumeratorCallback enumerator = 0,
4504 Local<Value> data = Local<Value>(),
4505 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4510 enumerator(enumerator),
4514 GenericNamedPropertyGetterCallback getter;
4515 GenericNamedPropertySetterCallback setter;
4516 GenericNamedPropertyQueryCallback query;
4517 GenericNamedPropertyDeleterCallback deleter;
4518 GenericNamedPropertyEnumeratorCallback enumerator;
4520 PropertyHandlerFlags flags;
4524 struct IndexedPropertyHandlerConfiguration {
4525 IndexedPropertyHandlerConfiguration(
4526 /** Note: getter is required **/
4527 IndexedPropertyGetterCallback getter = 0,
4528 IndexedPropertySetterCallback setter = 0,
4529 IndexedPropertyQueryCallback query = 0,
4530 IndexedPropertyDeleterCallback deleter = 0,
4531 IndexedPropertyEnumeratorCallback enumerator = 0,
4532 Local<Value> data = Local<Value>(),
4533 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4538 enumerator(enumerator),
4542 IndexedPropertyGetterCallback getter;
4543 IndexedPropertySetterCallback setter;
4544 IndexedPropertyQueryCallback query;
4545 IndexedPropertyDeleterCallback deleter;
4546 IndexedPropertyEnumeratorCallback enumerator;
4548 PropertyHandlerFlags flags;
4553 * An ObjectTemplate is used to create objects at runtime.
4555 * Properties added to an ObjectTemplate are added to each object
4556 * created from the ObjectTemplate.
4558 class V8_EXPORT ObjectTemplate : public Template {
4560 /** Creates an ObjectTemplate. */
4561 static Local<ObjectTemplate> New(
4563 Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
4564 static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4566 /** Creates a new instance of this template.*/
4567 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4568 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
4571 * Sets an accessor on the object template.
4573 * Whenever the property with the given name is accessed on objects
4574 * created from this ObjectTemplate the getter and setter callbacks
4575 * are called instead of getting and setting the property directly
4576 * on the JavaScript object.
4578 * \param name The name of the property for which an accessor is added.
4579 * \param getter The callback to invoke when getting the property.
4580 * \param setter The callback to invoke when setting the property.
4581 * \param data A piece of data that will be passed to the getter and setter
4582 * callbacks whenever they are invoked.
4583 * \param settings Access control settings for the accessor. This is a bit
4584 * field consisting of one of more of
4585 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4586 * The default is to not allow cross-context access.
4587 * ALL_CAN_READ means that all cross-context reads are allowed.
4588 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4589 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4590 * cross-context access.
4591 * \param attribute The attributes of the property for which an accessor
4593 * \param signature The signature describes valid receivers for the accessor
4594 * and is used to perform implicit instance checks against them. If the
4595 * receiver is incompatible (i.e. is not an instance of the constructor as
4596 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4597 * thrown and no callback is invoked.
4600 Local<String> name, AccessorGetterCallback getter,
4601 AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4602 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4603 Local<AccessorSignature> signature = Local<AccessorSignature>());
4605 Local<Name> name, AccessorNameGetterCallback getter,
4606 AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4607 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4608 Local<AccessorSignature> signature = Local<AccessorSignature>());
4611 * Sets a named property handler on the object template.
4613 * Whenever a property whose name is a string is accessed on objects created
4614 * from this object template, the provided callback is invoked instead of
4615 * accessing the property directly on the JavaScript object.
4617 * Note that new code should use the second version that can intercept
4618 * symbol-named properties as well as string-named properties.
4620 * \param getter The callback to invoke when getting a property.
4621 * \param setter The callback to invoke when setting a property.
4622 * \param query The callback to invoke to check if a property is present,
4623 * and if present, get its attributes.
4624 * \param deleter The callback to invoke when deleting a property.
4625 * \param enumerator The callback to invoke to enumerate all the named
4626 * properties of an object.
4627 * \param data A piece of data that will be passed to the callbacks
4628 * whenever they are invoked.
4630 // TODO(dcarney): deprecate
4631 void SetNamedPropertyHandler(NamedPropertyGetterCallback getter,
4632 NamedPropertySetterCallback setter = 0,
4633 NamedPropertyQueryCallback query = 0,
4634 NamedPropertyDeleterCallback deleter = 0,
4635 NamedPropertyEnumeratorCallback enumerator = 0,
4636 Local<Value> data = Local<Value>());
4637 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4640 * Sets an indexed property handler on the object template.
4642 * Whenever an indexed property is accessed on objects created from
4643 * this object template, the provided callback is invoked instead of
4644 * accessing the property directly on the JavaScript object.
4646 * \param getter The callback to invoke when getting a property.
4647 * \param setter The callback to invoke when setting a property.
4648 * \param query The callback to invoke to check if an object has a property.
4649 * \param deleter The callback to invoke when deleting a property.
4650 * \param enumerator The callback to invoke to enumerate all the indexed
4651 * properties of an object.
4652 * \param data A piece of data that will be passed to the callbacks
4653 * whenever they are invoked.
4655 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4656 // TODO(dcarney): deprecate
4657 void SetIndexedPropertyHandler(
4658 IndexedPropertyGetterCallback getter,
4659 IndexedPropertySetterCallback setter = 0,
4660 IndexedPropertyQueryCallback query = 0,
4661 IndexedPropertyDeleterCallback deleter = 0,
4662 IndexedPropertyEnumeratorCallback enumerator = 0,
4663 Local<Value> data = Local<Value>()) {
4664 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4665 deleter, enumerator, data));
4668 * Sets the callback to be used when calling instances created from
4669 * this template as a function. If no callback is set, instances
4670 * behave like normal JavaScript objects that cannot be called as a
4673 void SetCallAsFunctionHandler(FunctionCallback callback,
4674 Local<Value> data = Local<Value>());
4677 * Mark object instances of the template as undetectable.
4679 * In many ways, undetectable objects behave as though they are not
4680 * there. They behave like 'undefined' in conditionals and when
4681 * printed. However, properties can be accessed and called as on
4684 void MarkAsUndetectable();
4687 * Sets access check callbacks on the object template and enables
4690 * When accessing properties on instances of this object template,
4691 * the access check callback will be called to determine whether or
4692 * not to allow cross-context access to the properties.
4694 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4695 IndexedSecurityCallback indexed_handler,
4696 Local<Value> data = Local<Value>());
4699 * Gets the number of internal fields for objects generated from
4702 int InternalFieldCount();
4705 * Sets the number of internal fields for objects generated from
4708 void SetInternalFieldCount(int value);
4712 static Local<ObjectTemplate> New(internal::Isolate* isolate,
4713 Local<FunctionTemplate> constructor);
4714 friend class FunctionTemplate;
4719 * A Signature specifies which receiver is valid for a function.
4721 class V8_EXPORT Signature : public Data {
4723 static Local<Signature> New(
4725 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4733 * An AccessorSignature specifies which receivers are valid parameters
4734 * to an accessor callback.
4736 class V8_EXPORT AccessorSignature : public Data {
4738 static Local<AccessorSignature> New(
4740 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4743 AccessorSignature();
4748 * A utility for determining the type of objects based on the template
4749 * they were constructed from.
4751 class V8_EXPORT TypeSwitch : public Data {
4753 static Local<TypeSwitch> New(Local<FunctionTemplate> type);
4754 static Local<TypeSwitch> New(int argc, Local<FunctionTemplate> types[]);
4755 int match(Local<Value> value);
4762 // --- Extensions ---
4764 class V8_EXPORT ExternalOneByteStringResourceImpl
4765 : public String::ExternalOneByteStringResource {
4767 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4768 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4769 : data_(data), length_(length) {}
4770 const char* data() const { return data_; }
4771 size_t length() const { return length_; }
4781 class V8_EXPORT Extension { // NOLINT
4783 // Note that the strings passed into this constructor must live as long
4784 // as the Extension itself.
4785 Extension(const char* name,
4786 const char* source = 0,
4788 const char** deps = 0,
4789 int source_length = -1);
4790 virtual ~Extension() { }
4791 virtual v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
4792 v8::Isolate* isolate, v8::Local<v8::String> name) {
4793 return v8::Local<v8::FunctionTemplate>();
4796 const char* name() const { return name_; }
4797 size_t source_length() const { return source_length_; }
4798 const String::ExternalOneByteStringResource* source() const {
4800 int dependency_count() { return dep_count_; }
4801 const char** dependencies() { return deps_; }
4802 void set_auto_enable(bool value) { auto_enable_ = value; }
4803 bool auto_enable() { return auto_enable_; }
4807 size_t source_length_; // expected to initialize before source_
4808 ExternalOneByteStringResourceImpl source_;
4813 // Disallow copying and assigning.
4814 Extension(const Extension&);
4815 void operator=(const Extension&);
4819 void V8_EXPORT RegisterExtension(Extension* extension);
4824 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
4825 V8_INLINE Local<Primitive> Null(Isolate* isolate);
4826 V8_INLINE Local<Boolean> True(Isolate* isolate);
4827 V8_INLINE Local<Boolean> False(Isolate* isolate);
4831 * A set of constraints that specifies the limits of the runtime's memory use.
4832 * You must set the heap size before initializing the VM - the size cannot be
4833 * adjusted after the VM is initialized.
4835 * If you are using threads then you should hold the V8::Locker lock while
4836 * setting the stack limit and you must set a non-default stack limit separately
4839 class V8_EXPORT ResourceConstraints {
4841 ResourceConstraints();
4844 * Configures the constraints with reasonable default values based on the
4845 * capabilities of the current device the VM is running on.
4847 * \param physical_memory The total amount of physical memory on the current
4849 * \param virtual_memory_limit The amount of virtual memory on the current
4850 * device, in bytes, or zero, if there is no limit.
4852 void ConfigureDefaults(uint64_t physical_memory,
4853 uint64_t virtual_memory_limit);
4855 // Deprecated, will be removed soon.
4856 V8_DEPRECATED("Use two-args version instead",
4857 void ConfigureDefaults(uint64_t physical_memory,
4858 uint64_t virtual_memory_limit,
4859 uint32_t number_of_processors));
4861 int max_semi_space_size() const { return max_semi_space_size_; }
4862 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4863 int max_old_space_size() const { return max_old_space_size_; }
4864 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4865 int max_executable_size() const { return max_executable_size_; }
4866 void set_max_executable_size(int value) { max_executable_size_ = value; }
4867 uint32_t* stack_limit() const { return stack_limit_; }
4868 // Sets an address beyond which the VM's stack may not grow.
4869 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4870 V8_DEPRECATED("Unused, will be removed", int max_available_threads() const) {
4871 return max_available_threads_;
4873 // Set the number of threads available to V8, assuming at least 1.
4874 V8_DEPRECATED("Unused, will be removed",
4875 void set_max_available_threads(int value)) {
4876 max_available_threads_ = value;
4878 size_t code_range_size() const { return code_range_size_; }
4879 void set_code_range_size(size_t value) {
4880 code_range_size_ = value;
4884 int max_semi_space_size_;
4885 int max_old_space_size_;
4886 int max_executable_size_;
4887 uint32_t* stack_limit_;
4888 int max_available_threads_;
4889 size_t code_range_size_;
4893 // --- Exceptions ---
4896 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4899 typedef void (*MessageCallback)(Local<Message> message, Local<Value> error);
4903 typedef void (*LogEventCallback)(const char* name, int event);
4906 * Create new error objects by calling the corresponding error object
4907 * constructor with the message.
4909 class V8_EXPORT Exception {
4911 static Local<Value> RangeError(Local<String> message);
4912 static Local<Value> ReferenceError(Local<String> message);
4913 static Local<Value> SyntaxError(Local<String> message);
4914 static Local<Value> TypeError(Local<String> message);
4915 static Local<Value> Error(Local<String> message);
4918 * Creates an error message for the given exception.
4919 * Will try to reconstruct the original stack trace from the exception value,
4920 * or capture the current stack trace if not available.
4922 static Local<Message> CreateMessage(Local<Value> exception);
4925 * Returns the original stack trace that was captured at the creation time
4926 * of a given exception, or an empty handle if not available.
4928 static Local<StackTrace> GetStackTrace(Local<Value> exception);
4932 // --- Counters Callbacks ---
4934 typedef int* (*CounterLookupCallback)(const char* name);
4936 typedef void* (*CreateHistogramCallback)(const char* name,
4941 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4943 // --- Memory Allocation Callback ---
4945 kObjectSpaceNewSpace = 1 << 0,
4946 kObjectSpaceOldSpace = 1 << 1,
4947 kObjectSpaceCodeSpace = 1 << 2,
4948 kObjectSpaceMapSpace = 1 << 3,
4949 kObjectSpaceLoSpace = 1 << 4,
4950 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldSpace |
4951 kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4955 enum AllocationAction {
4956 kAllocationActionAllocate = 1 << 0,
4957 kAllocationActionFree = 1 << 1,
4958 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4961 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4962 AllocationAction action,
4965 // --- Leave Script Callback ---
4966 typedef void (*CallCompletedCallback)();
4968 // --- Promise Reject Callback ---
4969 enum PromiseRejectEvent {
4970 kPromiseRejectWithNoHandler = 0,
4971 kPromiseHandlerAddedAfterReject = 1
4974 class PromiseRejectMessage {
4976 PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
4977 Local<Value> value, Local<StackTrace> stack_trace)
4978 : promise_(promise),
4981 stack_trace_(stack_trace) {}
4983 V8_INLINE Local<Promise> GetPromise() const { return promise_; }
4984 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4985 V8_INLINE Local<Value> GetValue() const { return value_; }
4987 // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4988 V8_INLINE Local<StackTrace> GetStackTrace() const { return stack_trace_; }
4991 Local<Promise> promise_;
4992 PromiseRejectEvent event_;
4993 Local<Value> value_;
4994 Local<StackTrace> stack_trace_;
4997 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4999 // --- Microtask Callback ---
5000 typedef void (*MicrotaskCallback)(void* data);
5002 // --- Failed Access Check Callback ---
5003 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
5007 // --- AllowCodeGenerationFromStrings callbacks ---
5010 * Callback to check if code generation from strings is allowed. See
5011 * Context::AllowCodeGenerationFromStrings.
5013 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
5015 // --- Garbage Collection Callbacks ---
5018 * Applications can register callback functions which will be called
5019 * before and after a garbage collection. Allocations are not
5020 * allowed in the callback functions, you therefore cannot manipulate
5021 * objects (set or delete properties for example) since it is possible
5022 * such operations will result in the allocation of objects.
5025 kGCTypeScavenge = 1 << 0,
5026 kGCTypeMarkSweepCompact = 1 << 1,
5027 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
5030 enum GCCallbackFlags {
5031 kNoGCCallbackFlags = 0,
5032 kGCCallbackFlagCompacted = 1 << 0,
5033 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
5034 kGCCallbackFlagForced = 1 << 2
5037 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
5038 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
5040 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
5044 * Collection of V8 heap information.
5046 * Instances of this class can be passed to v8::V8::HeapStatistics to
5047 * get heap statistics from V8.
5049 class V8_EXPORT HeapStatistics {
5052 size_t total_heap_size() { return total_heap_size_; }
5053 size_t total_heap_size_executable() { return total_heap_size_executable_; }
5054 size_t total_physical_size() { return total_physical_size_; }
5055 size_t total_available_size() { return total_available_size_; }
5056 size_t used_heap_size() { return used_heap_size_; }
5057 size_t heap_size_limit() { return heap_size_limit_; }
5060 size_t total_heap_size_;
5061 size_t total_heap_size_executable_;
5062 size_t total_physical_size_;
5063 size_t total_available_size_;
5064 size_t used_heap_size_;
5065 size_t heap_size_limit_;
5068 friend class Isolate;
5072 class V8_EXPORT HeapSpaceStatistics {
5074 HeapSpaceStatistics();
5075 const char* space_name() { return space_name_; }
5076 size_t space_size() { return space_size_; }
5077 size_t space_used_size() { return space_used_size_; }
5078 size_t space_available_size() { return space_available_size_; }
5079 size_t physical_space_size() { return physical_space_size_; }
5082 const char* space_name_;
5084 size_t space_used_size_;
5085 size_t space_available_size_;
5086 size_t physical_space_size_;
5088 friend class Isolate;
5092 class V8_EXPORT HeapObjectStatistics {
5094 HeapObjectStatistics();
5095 const char* object_type() { return object_type_; }
5096 const char* object_sub_type() { return object_sub_type_; }
5097 size_t object_count() { return object_count_; }
5098 size_t object_size() { return object_size_; }
5101 const char* object_type_;
5102 const char* object_sub_type_;
5103 size_t object_count_;
5104 size_t object_size_;
5106 friend class Isolate;
5110 class RetainedObjectInfo;
5114 * FunctionEntryHook is the type of the profile entry hook called at entry to
5115 * any generated function when function-level profiling is enabled.
5117 * \param function the address of the function that's being entered.
5118 * \param return_addr_location points to a location on stack where the machine
5119 * return address resides. This can be used to identify the caller of
5120 * \p function, and/or modified to divert execution when \p function exits.
5122 * \note the entry hook must not cause garbage collection.
5124 typedef void (*FunctionEntryHook)(uintptr_t function,
5125 uintptr_t return_addr_location);
5128 * A JIT code event is issued each time code is added, moved or removed.
5130 * \note removal events are not currently issued.
5132 struct JitCodeEvent {
5137 CODE_ADD_LINE_POS_INFO,
5138 CODE_START_LINE_INFO_RECORDING,
5139 CODE_END_LINE_INFO_RECORDING
5141 // Definition of the code position type. The "POSITION" type means the place
5142 // in the source code which are of interest when making stack traces to
5143 // pin-point the source location of a stack frame as close as possible.
5144 // The "STATEMENT_POSITION" means the place at the beginning of each
5145 // statement, and is used to indicate possible break locations.
5146 enum PositionType { POSITION, STATEMENT_POSITION };
5150 // Start of the instructions.
5152 // Size of the instructions.
5154 // Script info for CODE_ADDED event.
5155 Local<UnboundScript> script;
5156 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
5157 // code line information which is returned from the
5158 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
5159 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
5163 // Name of the object associated with the code, note that the string is not
5166 // Number of chars in str.
5170 struct line_info_t {
5175 // The position type.
5176 PositionType position_type;
5180 // Only valid for CODE_ADDED.
5183 // Only valid for CODE_ADD_LINE_POS_INFO
5184 struct line_info_t line_info;
5186 // New location of instructions. Only valid for CODE_MOVED.
5187 void* new_code_start;
5192 * Option flags passed to the SetJitCodeEventHandler function.
5194 enum JitCodeEventOptions {
5195 kJitCodeEventDefault = 0,
5196 // Generate callbacks for already existent code.
5197 kJitCodeEventEnumExisting = 1
5202 * Callback function passed to SetJitCodeEventHandler.
5204 * \param event code add, move or removal event.
5206 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
5210 * Interface for iterating through all external resources in the heap.
5212 class V8_EXPORT ExternalResourceVisitor { // NOLINT
5214 virtual ~ExternalResourceVisitor() {}
5215 virtual void VisitExternalString(Local<String> string) {}
5220 * Interface for iterating through all the persistent handles in the heap.
5222 class V8_EXPORT PersistentHandleVisitor { // NOLINT
5224 virtual ~PersistentHandleVisitor() {}
5225 virtual void VisitPersistentHandle(Persistent<Value>* value,
5226 uint16_t class_id) {}
5231 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
5232 * completely separate states. Objects from one isolate must not be used in
5233 * other isolates. The embedder can create multiple isolates and use them in
5234 * parallel in multiple threads. An isolate can be entered by at most one
5235 * thread at any given time. The Locker/Unlocker API must be used to
5238 class V8_EXPORT Isolate {
5241 * Initial configuration parameters for a new Isolate.
5243 struct CreateParams {
5246 code_event_handler(NULL),
5247 snapshot_blob(NULL),
5248 counter_lookup_callback(NULL),
5249 create_histogram_callback(NULL),
5250 add_histogram_sample_callback(NULL),
5251 array_buffer_allocator(NULL) {}
5254 * The optional entry_hook allows the host application to provide the
5255 * address of a function that's invoked on entry to every V8-generated
5256 * function. Note that entry_hook is invoked at the very start of each
5257 * generated function. Furthermore, if an entry_hook is given, V8 will
5258 * always run without a context snapshot.
5260 FunctionEntryHook entry_hook;
5263 * Allows the host application to provide the address of a function that is
5264 * notified each time code is added, moved or removed.
5266 JitCodeEventHandler code_event_handler;
5269 * ResourceConstraints to use for the new Isolate.
5271 ResourceConstraints constraints;
5274 * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5276 StartupData* snapshot_blob;
5280 * Enables the host application to provide a mechanism for recording
5281 * statistics counters.
5283 CounterLookupCallback counter_lookup_callback;
5286 * Enables the host application to provide a mechanism for recording
5287 * histograms. The CreateHistogram function returns a
5288 * histogram which will later be passed to the AddHistogramSample
5291 CreateHistogramCallback create_histogram_callback;
5292 AddHistogramSampleCallback add_histogram_sample_callback;
5295 * The ArrayBuffer::Allocator to use for allocating and freeing the backing
5296 * store of ArrayBuffers.
5298 ArrayBuffer::Allocator* array_buffer_allocator;
5303 * Stack-allocated class which sets the isolate for all operations
5304 * executed within a local scope.
5306 class V8_EXPORT Scope {
5308 explicit Scope(Isolate* isolate) : isolate_(isolate) {
5312 ~Scope() { isolate_->Exit(); }
5315 Isolate* const isolate_;
5317 // Prevent copying of Scope objects.
5318 Scope(const Scope&);
5319 Scope& operator=(const Scope&);
5324 * Assert that no Javascript code is invoked.
5326 class V8_EXPORT DisallowJavascriptExecutionScope {
5328 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
5330 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
5331 ~DisallowJavascriptExecutionScope();
5337 // Prevent copying of Scope objects.
5338 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5339 DisallowJavascriptExecutionScope& operator=(
5340 const DisallowJavascriptExecutionScope&);
5345 * Introduce exception to DisallowJavascriptExecutionScope.
5347 class V8_EXPORT AllowJavascriptExecutionScope {
5349 explicit AllowJavascriptExecutionScope(Isolate* isolate);
5350 ~AllowJavascriptExecutionScope();
5353 void* internal_throws_;
5354 void* internal_assert_;
5356 // Prevent copying of Scope objects.
5357 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5358 AllowJavascriptExecutionScope& operator=(
5359 const AllowJavascriptExecutionScope&);
5363 * Do not run microtasks while this scope is active, even if microtasks are
5364 * automatically executed otherwise.
5366 class V8_EXPORT SuppressMicrotaskExecutionScope {
5368 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
5369 ~SuppressMicrotaskExecutionScope();
5372 internal::Isolate* isolate_;
5374 // Prevent copying of Scope objects.
5375 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5376 SuppressMicrotaskExecutionScope& operator=(
5377 const SuppressMicrotaskExecutionScope&);
5381 * Types of garbage collections that can be requested via
5382 * RequestGarbageCollectionForTesting.
5384 enum GarbageCollectionType {
5385 kFullGarbageCollection,
5386 kMinorGarbageCollection
5390 * Features reported via the SetUseCounterCallback callback. Do not change
5391 * assigned numbers of existing items; add new features to the end of this
5394 enum UseCounterFeature {
5398 kMarkDequeOverflow = 3,
5399 kStoreBufferOverflow = 4,
5400 kSlotsBufferOverflow = 5,
5403 kUseCounterFeatureCount // This enum value must be last.
5406 typedef void (*UseCounterCallback)(Isolate* isolate,
5407 UseCounterFeature feature);
5411 * Creates a new isolate. Does not change the currently entered
5414 * When an isolate is no longer used its resources should be freed
5415 * by calling Dispose(). Using the delete operator is not allowed.
5417 * V8::Initialize() must have run prior to this.
5419 static Isolate* New(const CreateParams& params);
5421 static V8_DEPRECATED("Always pass CreateParams", Isolate* New());
5424 * Returns the entered isolate for the current thread or NULL in
5425 * case there is no current isolate.
5427 * This method must not be invoked before V8::Initialize() was invoked.
5429 static Isolate* GetCurrent();
5432 * Methods below this point require holding a lock (using Locker) in
5433 * a multi-threaded environment.
5437 * Sets this isolate as the entered one for the current thread.
5438 * Saves the previously entered one (if any), so that it can be
5439 * restored when exiting. Re-entering an isolate is allowed.
5444 * Exits this isolate by restoring the previously entered one in the
5445 * current thread. The isolate may still stay the same, if it was
5446 * entered more than once.
5448 * Requires: this == Isolate::GetCurrent().
5453 * Disposes the isolate. The isolate must not be entered by any
5454 * thread to be disposable.
5459 * Associate embedder-specific data with the isolate. |slot| has to be
5460 * between 0 and GetNumberOfDataSlots() - 1.
5462 V8_INLINE void SetData(uint32_t slot, void* data);
5465 * Retrieve embedder-specific data from the isolate.
5466 * Returns NULL if SetData has never been called for the given |slot|.
5468 V8_INLINE void* GetData(uint32_t slot);
5471 * Returns the maximum number of available embedder data slots. Valid slots
5472 * are in the range of 0 - GetNumberOfDataSlots() - 1.
5474 V8_INLINE static uint32_t GetNumberOfDataSlots();
5477 * Get statistics about the heap memory usage.
5479 void GetHeapStatistics(HeapStatistics* heap_statistics);
5482 * Returns the number of spaces in the heap.
5484 size_t NumberOfHeapSpaces();
5487 * Get the memory usage of a space in the heap.
5489 * \param space_statistics The HeapSpaceStatistics object to fill in
5491 * \param index The index of the space to get statistics from, which ranges
5492 * from 0 to NumberOfHeapSpaces() - 1.
5493 * \returns true on success.
5495 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
5499 * Returns the number of types of objects tracked in the heap at GC.
5501 size_t NumberOfTrackedHeapObjectTypes();
5504 * Get statistics about objects in the heap.
5506 * \param object_statistics The HeapObjectStatistics object to fill in
5507 * statistics of objects of given type, which were live in the previous GC.
5508 * \param type_index The index of the type of object to fill details about,
5509 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
5510 * \returns true on success.
5512 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
5516 * Get a call stack sample from the isolate.
5517 * \param state Execution state.
5518 * \param frames Caller allocated buffer to store stack frames.
5519 * \param frames_limit Maximum number of frames to capture. The buffer must
5520 * be large enough to hold the number of frames.
5521 * \param sample_info The sample info is filled up by the function
5522 * provides number of actual captured stack frames and
5523 * the current VM state.
5524 * \note GetStackSample should only be called when the JS thread is paused or
5525 * interrupted. Otherwise the behavior is undefined.
5527 void GetStackSample(const RegisterState& state, void** frames,
5528 size_t frames_limit, SampleInfo* sample_info);
5531 * Adjusts the amount of registered external memory. Used to give V8 an
5532 * indication of the amount of externally allocated memory that is kept alive
5533 * by JavaScript objects. V8 uses this to decide when to perform global
5534 * garbage collections. Registering externally allocated memory will trigger
5535 * global garbage collections more often than it would otherwise in an attempt
5536 * to garbage collect the JavaScript objects that keep the externally
5537 * allocated memory alive.
5539 * \param change_in_bytes the change in externally allocated memory that is
5540 * kept alive by JavaScript objects.
5541 * \returns the adjusted value.
5544 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5547 * Returns heap profiler for this isolate. Will return NULL until the isolate
5550 HeapProfiler* GetHeapProfiler();
5553 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5554 * is initialized. It is the embedder's responsibility to stop all CPU
5555 * profiling activities if it has started any.
5557 CpuProfiler* GetCpuProfiler();
5559 /** Returns true if this isolate has a current context. */
5562 /** Returns the context that is on the top of the stack. */
5563 Local<Context> GetCurrentContext();
5566 * Returns the context of the calling JavaScript code. That is the
5567 * context of the top-most JavaScript frame. If there are no
5568 * JavaScript frames an empty handle is returned.
5570 Local<Context> GetCallingContext();
5572 /** Returns the last entered context. */
5573 Local<Context> GetEnteredContext();
5576 * Schedules an exception to be thrown when returning to JavaScript. When an
5577 * exception has been scheduled it is illegal to invoke any JavaScript
5578 * operation; the caller must return immediately and only after the exception
5579 * has been handled does it become legal to invoke JavaScript operations.
5581 Local<Value> ThrowException(Local<Value> exception);
5584 * Allows the host application to group objects together. If one
5585 * object in the group is alive, all objects in the group are alive.
5586 * After each garbage collection, object groups are removed. It is
5587 * intended to be used in the before-garbage-collection callback
5588 * function, for instance to simulate DOM tree connections among JS
5589 * wrapper objects. Object groups for all dependent handles need to
5590 * be provided for kGCTypeMarkSweepCompact collections, for all other
5591 * garbage collection types it is sufficient to provide object groups
5592 * for partially dependent handles only.
5594 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5598 * Allows the host application to declare implicit references from an object
5599 * group to an object. If the objects of the object group are alive, the child
5600 * object is alive too. After each garbage collection, all implicit references
5601 * are removed. It is intended to be used in the before-garbage-collection
5602 * callback function.
5604 template<typename T> void SetReferenceFromGroup(UniqueId id,
5605 const Persistent<T>& child);
5608 * Allows the host application to declare implicit references from an object
5609 * to another object. If the parent object is alive, the child object is alive
5610 * too. After each garbage collection, all implicit references are removed. It
5611 * is intended to be used in the before-garbage-collection callback function.
5613 template<typename T, typename S>
5614 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5616 typedef void (*GCPrologueCallback)(Isolate* isolate,
5618 GCCallbackFlags flags);
5619 typedef void (*GCEpilogueCallback)(Isolate* isolate,
5621 GCCallbackFlags flags);
5624 * Enables the host application to receive a notification before a
5625 * garbage collection. Allocations are allowed in the callback function,
5626 * but the callback is not re-entrant: if the allocation inside it will
5627 * trigger the garbage collection, the callback won't be called again.
5628 * It is possible to specify the GCType filter for your callback. But it is
5629 * not possible to register the same callback function two times with
5630 * different GCType filters.
5632 void AddGCPrologueCallback(
5633 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5636 * This function removes callback which was installed by
5637 * AddGCPrologueCallback function.
5639 void RemoveGCPrologueCallback(GCPrologueCallback callback);
5642 * Enables the host application to receive a notification after a
5643 * garbage collection. Allocations are allowed in the callback function,
5644 * but the callback is not re-entrant: if the allocation inside it will
5645 * trigger the garbage collection, the callback won't be called again.
5646 * It is possible to specify the GCType filter for your callback. But it is
5647 * not possible to register the same callback function two times with
5648 * different GCType filters.
5650 void AddGCEpilogueCallback(
5651 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5654 * This function removes callback which was installed by
5655 * AddGCEpilogueCallback function.
5657 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5661 * Forcefully terminate the current thread of JavaScript execution
5662 * in the given isolate.
5664 * This method can be used by any thread even if that thread has not
5665 * acquired the V8 lock with a Locker object.
5667 void TerminateExecution();
5670 * Is V8 terminating JavaScript execution.
5672 * Returns true if JavaScript execution is currently terminating
5673 * because of a call to TerminateExecution. In that case there are
5674 * still JavaScript frames on the stack and the termination
5675 * exception is still active.
5677 bool IsExecutionTerminating();
5680 * Resume execution capability in the given isolate, whose execution
5681 * was previously forcefully terminated using TerminateExecution().
5683 * When execution is forcefully terminated using TerminateExecution(),
5684 * the isolate can not resume execution until all JavaScript frames
5685 * have propagated the uncatchable exception which is generated. This
5686 * method allows the program embedding the engine to handle the
5687 * termination event and resume execution capability, even if
5688 * JavaScript frames remain on the stack.
5690 * This method can be used by any thread even if that thread has not
5691 * acquired the V8 lock with a Locker object.
5693 void CancelTerminateExecution();
5696 * Request V8 to interrupt long running JavaScript code and invoke
5697 * the given |callback| passing the given |data| to it. After |callback|
5698 * returns control will be returned to the JavaScript code.
5699 * There may be a number of interrupt requests in flight.
5700 * Can be called from another thread without acquiring a |Locker|.
5701 * Registered |callback| must not reenter interrupted Isolate.
5703 void RequestInterrupt(InterruptCallback callback, void* data);
5706 * Request garbage collection in this Isolate. It is only valid to call this
5707 * function if --expose_gc was specified.
5709 * This should only be used for testing purposes and not to enforce a garbage
5710 * collection schedule. It has strong negative impact on the garbage
5711 * collection performance. Use IdleNotificationDeadline() or
5712 * LowMemoryNotification() instead to influence the garbage collection
5715 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5718 * Set the callback to invoke for logging event.
5720 void SetEventLogger(LogEventCallback that);
5723 * Adds a callback to notify the host application when a script finished
5724 * running. If a script re-enters the runtime during executing, the
5725 * CallCompletedCallback is only invoked when the outer-most script
5726 * execution ends. Executing scripts inside the callback do not trigger
5727 * further callbacks.
5729 void AddCallCompletedCallback(CallCompletedCallback callback);
5732 * Removes callback that was installed by AddCallCompletedCallback.
5734 void RemoveCallCompletedCallback(CallCompletedCallback callback);
5738 * Set callback to notify about promise reject with no handler, or
5739 * revocation of such a previous notification once the handler is added.
5741 void SetPromiseRejectCallback(PromiseRejectCallback callback);
5744 * Experimental: Runs the Microtask Work Queue until empty
5745 * Any exceptions thrown by microtask callbacks are swallowed.
5747 void RunMicrotasks();
5750 * Experimental: Enqueues the callback to the Microtask Work Queue
5752 void EnqueueMicrotask(Local<Function> microtask);
5755 * Experimental: Enqueues the callback to the Microtask Work Queue
5757 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5760 * Experimental: Controls whether the Microtask Work Queue is automatically
5761 * run when the script call depth decrements to zero.
5763 void SetAutorunMicrotasks(bool autorun);
5766 * Experimental: Returns whether the Microtask Work Queue is automatically
5767 * run when the script call depth decrements to zero.
5769 bool WillAutorunMicrotasks() const;
5772 * Sets a callback for counting the number of times a feature of V8 is used.
5774 void SetUseCounterCallback(UseCounterCallback callback);
5777 * Enables the host application to provide a mechanism for recording
5778 * statistics counters.
5780 void SetCounterFunction(CounterLookupCallback);
5783 * Enables the host application to provide a mechanism for recording
5784 * histograms. The CreateHistogram function returns a
5785 * histogram which will later be passed to the AddHistogramSample
5788 void SetCreateHistogramFunction(CreateHistogramCallback);
5789 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5792 * Optional notification that the embedder is idle.
5793 * V8 uses the notification to perform garbage collection.
5794 * This call can be used repeatedly if the embedder remains idle.
5795 * Returns true if the embedder should stop calling IdleNotificationDeadline
5796 * until real work has been done. This indicates that V8 has done
5797 * as much cleanup as it will be able to do.
5799 * The deadline_in_seconds argument specifies the deadline V8 has to finish
5800 * garbage collection work. deadline_in_seconds is compared with
5801 * MonotonicallyIncreasingTime() and should be based on the same timebase as
5802 * that function. There is no guarantee that the actual work will be done
5803 * within the time limit.
5805 bool IdleNotificationDeadline(double deadline_in_seconds);
5807 V8_DEPRECATE_SOON("use IdleNotificationDeadline()",
5808 bool IdleNotification(int idle_time_in_ms));
5811 * Optional notification that the system is running low on memory.
5812 * V8 uses these notifications to attempt to free memory.
5814 void LowMemoryNotification();
5817 * Optional notification that a context has been disposed. V8 uses
5818 * these notifications to guide the GC heuristic. Returns the number
5819 * of context disposals - including this one - since the last time
5820 * V8 had a chance to clean up.
5822 * The optional parameter |dependant_context| specifies whether the disposed
5823 * context was depending on state from other contexts or not.
5825 int ContextDisposedNotification(bool dependant_context = true);
5828 * Allows the host application to provide the address of a function that is
5829 * notified each time code is added, moved or removed.
5831 * \param options options for the JIT code event handler.
5832 * \param event_handler the JIT code event handler, which will be invoked
5833 * each time code is added, moved or removed.
5834 * \note \p event_handler won't get notified of existent code.
5835 * \note since code removal notifications are not currently issued, the
5836 * \p event_handler may get notifications of code that overlaps earlier
5837 * code notifications. This happens when code areas are reused, and the
5838 * earlier overlapping code areas should therefore be discarded.
5839 * \note the events passed to \p event_handler and the strings they point to
5840 * are not guaranteed to live past each call. The \p event_handler must
5841 * copy strings and other parameters it needs to keep around.
5842 * \note the set of events declared in JitCodeEvent::EventType is expected to
5843 * grow over time, and the JitCodeEvent structure is expected to accrue
5844 * new members. The \p event_handler function must ignore event codes
5845 * it does not recognize to maintain future compatibility.
5846 * \note Use Isolate::CreateParams to get events for code executed during
5849 void SetJitCodeEventHandler(JitCodeEventOptions options,
5850 JitCodeEventHandler event_handler);
5853 * Modifies the stack limit for this Isolate.
5855 * \param stack_limit An address beyond which the Vm's stack may not grow.
5857 * \note If you are using threads then you should hold the V8::Locker lock
5858 * while setting the stack limit and you must set a non-default stack
5859 * limit separately for each thread.
5861 void SetStackLimit(uintptr_t stack_limit);
5864 * Returns a memory range that can potentially contain jitted code.
5866 * On Win64, embedders are advised to install function table callbacks for
5867 * these ranges, as default SEH won't be able to unwind through jitted code.
5869 * The first page of the code range is reserved for the embedder and is
5870 * committed, writable, and executable.
5872 * Might be empty on other platforms.
5874 * https://code.google.com/p/v8/issues/detail?id=3598
5876 void GetCodeRange(void** start, size_t* length_in_bytes);
5878 /** Set the callback to invoke in case of fatal errors. */
5879 void SetFatalErrorHandler(FatalErrorCallback that);
5882 * Set the callback to invoke to check if code generation from
5883 * strings should be allowed.
5885 void SetAllowCodeGenerationFromStringsCallback(
5886 AllowCodeGenerationFromStringsCallback callback);
5889 * Check if V8 is dead and therefore unusable. This is the case after
5890 * fatal errors such as out-of-memory situations.
5895 * Adds a message listener.
5897 * The same message listener can be added more than once and in that
5898 * case it will be called more than once for each message.
5900 * If data is specified, it will be passed to the callback when it is called.
5901 * Otherwise, the exception object will be passed to the callback instead.
5903 bool AddMessageListener(MessageCallback that,
5904 Local<Value> data = Local<Value>());
5907 * Remove all message listeners from the specified callback function.
5909 void RemoveMessageListeners(MessageCallback that);
5911 /** Callback function for reporting failed access checks.*/
5912 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5915 * Tells V8 to capture current stack trace when uncaught exception occurs
5916 * and report it to the message listeners. The option is off by default.
5918 void SetCaptureStackTraceForUncaughtExceptions(
5919 bool capture, int frame_limit = 10,
5920 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5923 * Enables the host application to provide a mechanism to be notified
5924 * and perform custom logging when V8 Allocates Executable Memory.
5926 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5927 ObjectSpace space, AllocationAction action);
5930 * Removes callback that was installed by AddMemoryAllocationCallback.
5932 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5935 * Iterates through all external resources referenced from current isolate
5936 * heap. GC is not invoked prior to iterating, therefore there is no
5937 * guarantee that visited objects are still alive.
5939 void VisitExternalResources(ExternalResourceVisitor* visitor);
5942 * Iterates through all the persistent handles in the current isolate's heap
5943 * that have class_ids.
5945 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5948 * Iterates through all the persistent handles in the current isolate's heap
5949 * that have class_ids and are candidates to be marked as partially dependent
5950 * handles. This will visit handles to young objects created since the last
5951 * garbage collection but is free to visit an arbitrary superset of these
5954 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5957 template <class K, class V, class Traits>
5958 friend class PersistentValueMapBase;
5961 Isolate(const Isolate&);
5963 Isolate& operator=(const Isolate&);
5964 void* operator new(size_t size);
5965 void operator delete(void*, size_t);
5967 void SetObjectGroupId(internal::Object** object, UniqueId id);
5968 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5969 void SetReference(internal::Object** parent, internal::Object** child);
5970 void CollectAllGarbage(const char* gc_reason);
5973 class V8_EXPORT StartupData {
5981 * EntropySource is used as a callback function when v8 needs a source
5984 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5988 * ReturnAddressLocationResolver is used as a callback function when v8 is
5989 * resolving the location of a return address on the stack. Profilers that
5990 * change the return address on the stack can use this to resolve the stack
5991 * location to whereever the profiler stashed the original return address.
5993 * \param return_addr_location points to a location on stack where a machine
5994 * return address resides.
5995 * \returns either return_addr_location, or else a pointer to the profiler's
5996 * copy of the original return address.
5998 * \note the resolver function must not cause garbage collection.
6000 typedef uintptr_t (*ReturnAddressLocationResolver)(
6001 uintptr_t return_addr_location);
6005 * Container class for static utility functions.
6007 class V8_EXPORT V8 {
6009 /** Set the callback to invoke in case of fatal errors. */
6010 V8_INLINE static V8_DEPRECATE_SOON(
6011 "Use isolate version",
6012 void SetFatalErrorHandler(FatalErrorCallback that));
6015 * Set the callback to invoke to check if code generation from
6016 * strings should be allowed.
6018 V8_INLINE static V8_DEPRECATE_SOON(
6019 "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
6020 AllowCodeGenerationFromStringsCallback that));
6023 * Set allocator to use for ArrayBuffer memory.
6024 * The allocator should be set only once. The allocator should be set
6025 * before any code tha uses ArrayBuffers is executed.
6026 * This allocator is used in all isolates.
6028 static V8_DEPRECATE_SOON(
6029 "Use isolate version",
6030 void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator));
6033 * Check if V8 is dead and therefore unusable. This is the case after
6034 * fatal errors such as out-of-memory situations.
6036 V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
6039 * Hand startup data to V8, in case the embedder has chosen to build
6040 * V8 with external startup data.
6043 * - By default the startup data is linked into the V8 library, in which
6044 * case this function is not meaningful.
6045 * - If this needs to be called, it needs to be called before V8
6046 * tries to make use of its built-ins.
6047 * - To avoid unnecessary copies of data, V8 will point directly into the
6048 * given data blob, so pretty please keep it around until V8 exit.
6049 * - Compression of the startup blob might be useful, but needs to
6050 * handled entirely on the embedders' side.
6051 * - The call will abort if the data is invalid.
6053 static void SetNativesDataBlob(StartupData* startup_blob);
6054 static void SetSnapshotDataBlob(StartupData* startup_blob);
6057 * Create a new isolate and context for the purpose of capturing a snapshot
6058 * Returns { NULL, 0 } on failure.
6059 * The caller owns the data array in the return value.
6061 static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
6064 * Adds a message listener.
6066 * The same message listener can be added more than once and in that
6067 * case it will be called more than once for each message.
6069 * If data is specified, it will be passed to the callback when it is called.
6070 * Otherwise, the exception object will be passed to the callback instead.
6072 V8_INLINE static V8_DEPRECATE_SOON(
6073 "Use isolate version",
6074 bool AddMessageListener(MessageCallback that,
6075 Local<Value> data = Local<Value>()));
6078 * Remove all message listeners from the specified callback function.
6080 V8_INLINE static V8_DEPRECATE_SOON(
6081 "Use isolate version", void RemoveMessageListeners(MessageCallback that));
6084 * Tells V8 to capture current stack trace when uncaught exception occurs
6085 * and report it to the message listeners. The option is off by default.
6087 V8_INLINE static V8_DEPRECATE_SOON(
6088 "Use isolate version",
6089 void SetCaptureStackTraceForUncaughtExceptions(
6090 bool capture, int frame_limit = 10,
6091 StackTrace::StackTraceOptions options = StackTrace::kOverview));
6094 * Sets V8 flags from a string.
6096 static void SetFlagsFromString(const char* str, int length);
6099 * Sets V8 flags from the command line.
6101 static void SetFlagsFromCommandLine(int* argc,
6105 /** Get the version string. */
6106 static const char* GetVersion();
6108 /** Callback function for reporting failed access checks.*/
6109 V8_INLINE static V8_DEPRECATE_SOON(
6110 "Use isolate version",
6111 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
6114 * Enables the host application to receive a notification before a
6115 * garbage collection. Allocations are not allowed in the
6116 * callback function, you therefore cannot manipulate objects (set
6117 * or delete properties for example) since it is possible such
6118 * operations will result in the allocation of objects. It is possible
6119 * to specify the GCType filter for your callback. But it is not possible to
6120 * register the same callback function two times with different
6123 static V8_DEPRECATE_SOON(
6124 "Use isolate version",
6125 void AddGCPrologueCallback(GCPrologueCallback callback,
6126 GCType gc_type_filter = kGCTypeAll));
6129 * This function removes callback which was installed by
6130 * AddGCPrologueCallback function.
6132 V8_INLINE static V8_DEPRECATE_SOON(
6133 "Use isolate version",
6134 void RemoveGCPrologueCallback(GCPrologueCallback callback));
6137 * Enables the host application to receive a notification after a
6138 * garbage collection. Allocations are not allowed in the
6139 * callback function, you therefore cannot manipulate objects (set
6140 * or delete properties for example) since it is possible such
6141 * operations will result in the allocation of objects. It is possible
6142 * to specify the GCType filter for your callback. But it is not possible to
6143 * register the same callback function two times with different
6146 static V8_DEPRECATE_SOON(
6147 "Use isolate version",
6148 void AddGCEpilogueCallback(GCEpilogueCallback callback,
6149 GCType gc_type_filter = kGCTypeAll));
6152 * This function removes callback which was installed by
6153 * AddGCEpilogueCallback function.
6155 V8_INLINE static V8_DEPRECATE_SOON(
6156 "Use isolate version",
6157 void RemoveGCEpilogueCallback(GCEpilogueCallback callback));
6160 * Enables the host application to provide a mechanism to be notified
6161 * and perform custom logging when V8 Allocates Executable Memory.
6163 V8_INLINE static V8_DEPRECATE_SOON(
6164 "Use isolate version",
6165 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
6167 AllocationAction action));
6170 * Removes callback that was installed by AddMemoryAllocationCallback.
6172 V8_INLINE static V8_DEPRECATE_SOON(
6173 "Use isolate version",
6174 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
6177 * Initializes V8. This function needs to be called before the first Isolate
6178 * is created. It always returns true.
6180 static bool Initialize();
6183 * Allows the host application to provide a callback which can be used
6184 * as a source of entropy for random number generators.
6186 static void SetEntropySource(EntropySource source);
6189 * Allows the host application to provide a callback that allows v8 to
6190 * cooperate with a profiler that rewrites return addresses on stack.
6192 static void SetReturnAddressLocationResolver(
6193 ReturnAddressLocationResolver return_address_resolver);
6196 * Forcefully terminate the current thread of JavaScript execution
6197 * in the given isolate.
6199 * This method can be used by any thread even if that thread has not
6200 * acquired the V8 lock with a Locker object.
6202 * \param isolate The isolate in which to terminate the current JS execution.
6204 V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
6205 void TerminateExecution(Isolate* isolate));
6208 * Is V8 terminating JavaScript execution.
6210 * Returns true if JavaScript execution is currently terminating
6211 * because of a call to TerminateExecution. In that case there are
6212 * still JavaScript frames on the stack and the termination
6213 * exception is still active.
6215 * \param isolate The isolate in which to check.
6217 V8_INLINE static V8_DEPRECATE_SOON(
6218 "Use isolate version",
6219 bool IsExecutionTerminating(Isolate* isolate = NULL));
6222 * Resume execution capability in the given isolate, whose execution
6223 * was previously forcefully terminated using TerminateExecution().
6225 * When execution is forcefully terminated using TerminateExecution(),
6226 * the isolate can not resume execution until all JavaScript frames
6227 * have propagated the uncatchable exception which is generated. This
6228 * method allows the program embedding the engine to handle the
6229 * termination event and resume execution capability, even if
6230 * JavaScript frames remain on the stack.
6232 * This method can be used by any thread even if that thread has not
6233 * acquired the V8 lock with a Locker object.
6235 * \param isolate The isolate in which to resume execution capability.
6237 V8_INLINE static V8_DEPRECATE_SOON(
6238 "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
6241 * Releases any resources used by v8 and stops any utility threads
6242 * that may be running. Note that disposing v8 is permanent, it
6243 * cannot be reinitialized.
6245 * It should generally not be necessary to dispose v8 before exiting
6246 * a process, this should happen automatically. It is only necessary
6247 * to use if the process needs the resources taken up by v8.
6249 static bool Dispose();
6252 * Iterates through all external resources referenced from current isolate
6253 * heap. GC is not invoked prior to iterating, therefore there is no
6254 * guarantee that visited objects are still alive.
6256 V8_INLINE static V8_DEPRECATE_SOON(
6257 "Use isoalte version",
6258 void VisitExternalResources(ExternalResourceVisitor* visitor));
6261 * Iterates through all the persistent handles in the current isolate's heap
6262 * that have class_ids.
6264 V8_INLINE static V8_DEPRECATE_SOON(
6265 "Use isolate version",
6266 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
6269 * Iterates through all the persistent handles in isolate's heap that have
6272 V8_INLINE static V8_DEPRECATE_SOON(
6273 "Use isolate version",
6274 void VisitHandlesWithClassIds(Isolate* isolate,
6275 PersistentHandleVisitor* visitor));
6278 * Iterates through all the persistent handles in the current isolate's heap
6279 * that have class_ids and are candidates to be marked as partially dependent
6280 * handles. This will visit handles to young objects created since the last
6281 * garbage collection but is free to visit an arbitrary superset of these
6284 V8_INLINE static V8_DEPRECATE_SOON(
6285 "Use isolate version",
6286 void VisitHandlesForPartialDependence(Isolate* isolate,
6287 PersistentHandleVisitor* visitor));
6290 * Initialize the ICU library bundled with V8. The embedder should only
6291 * invoke this method when using the bundled ICU. Returns true on success.
6293 * If V8 was compiled with the ICU data in an external file, the location
6294 * of the data file has to be provided.
6296 static bool InitializeICU(const char* icu_data_file = NULL);
6299 * Sets the v8::Platform to use. This should be invoked before V8 is
6302 static void InitializePlatform(Platform* platform);
6305 * Clears all references to the v8::Platform. This should be invoked after
6308 static void ShutdownPlatform();
6313 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6314 internal::Object** handle);
6315 static internal::Object** CopyPersistent(internal::Object** handle);
6316 static void DisposeGlobal(internal::Object** global_handle);
6317 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6318 static void MakeWeak(internal::Object** global_handle, void* data,
6319 WeakCallback weak_callback);
6320 static void MakeWeak(internal::Object** global_handle, void* data,
6321 WeakCallbackInfo<void>::Callback weak_callback,
6322 WeakCallbackType type);
6323 static void MakeWeak(internal::Object** global_handle, void* data,
6325 int internal_field_index1,
6327 int internal_field_index2,
6328 WeakCallbackInfo<void>::Callback weak_callback);
6329 static void* ClearWeak(internal::Object** global_handle);
6330 static void Eternalize(Isolate* isolate,
6333 static Local<Value> GetEternal(Isolate* isolate, int index);
6335 static void FromJustIsNothing();
6336 static void ToLocalEmpty();
6337 static void InternalFieldOutOfBounds(int index);
6338 template <class T> friend class Local;
6340 friend class MaybeLocal;
6344 friend class WeakCallbackInfo;
6345 template <class T> friend class Eternal;
6346 template <class T> friend class PersistentBase;
6347 template <class T, class M> friend class Persistent;
6348 friend class Context;
6353 * A simple Maybe type, representing an object which may or may not have a
6354 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6356 * If an API method returns a Maybe<>, the API method can potentially fail
6357 * either because an exception is thrown, or because an exception is pending,
6358 * e.g. because a previous API call threw an exception that hasn't been caught
6359 * yet, or because a TerminateExecution exception was thrown. In that case, a
6360 * "Nothing" value is returned.
6365 V8_INLINE bool IsNothing() const { return !has_value; }
6366 V8_INLINE bool IsJust() const { return has_value; }
6368 // Will crash if the Maybe<> is nothing.
6369 V8_INLINE T FromJust() const {
6370 if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
6374 V8_INLINE T FromMaybe(const T& default_value) const {
6375 return has_value ? value : default_value;
6378 V8_INLINE bool operator==(const Maybe& other) const {
6379 return (IsJust() == other.IsJust()) &&
6380 (!IsJust() || FromJust() == other.FromJust());
6383 V8_INLINE bool operator!=(const Maybe& other) const {
6384 return !operator==(other);
6388 Maybe() : has_value(false) {}
6389 explicit Maybe(const T& t) : has_value(true), value(t) {}
6395 friend Maybe<U> Nothing();
6397 friend Maybe<U> Just(const U& u);
6402 inline Maybe<T> Nothing() {
6408 inline Maybe<T> Just(const T& t) {
6414 * An external exception handler.
6416 class V8_EXPORT TryCatch {
6419 * Creates a new try/catch block and registers it with v8. Note that
6420 * all TryCatch blocks should be stack allocated because the memory
6421 * location itself is compared against JavaScript try/catch blocks.
6423 V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6426 * Creates a new try/catch block and registers it with v8. Note that
6427 * all TryCatch blocks should be stack allocated because the memory
6428 * location itself is compared against JavaScript try/catch blocks.
6430 TryCatch(Isolate* isolate);
6433 * Unregisters and deletes this try/catch block.
6438 * Returns true if an exception has been caught by this try/catch block.
6440 bool HasCaught() const;
6443 * For certain types of exceptions, it makes no sense to continue execution.
6445 * If CanContinue returns false, the correct action is to perform any C++
6446 * cleanup needed and then return. If CanContinue returns false and
6447 * HasTerminated returns true, it is possible to call
6448 * CancelTerminateExecution in order to continue calling into the engine.
6450 bool CanContinue() const;
6453 * Returns true if an exception has been caught due to script execution
6456 * There is no JavaScript representation of an execution termination
6457 * exception. Such exceptions are thrown when the TerminateExecution
6458 * methods are called to terminate a long-running script.
6460 * If such an exception has been thrown, HasTerminated will return true,
6461 * indicating that it is possible to call CancelTerminateExecution in order
6462 * to continue calling into the engine.
6464 bool HasTerminated() const;
6467 * Throws the exception caught by this TryCatch in a way that avoids
6468 * it being caught again by this same TryCatch. As with ThrowException
6469 * it is illegal to execute any JavaScript operations after calling
6470 * ReThrow; the caller must return immediately to where the exception
6473 Local<Value> ReThrow();
6476 * Returns the exception caught by this try/catch block. If no exception has
6477 * been caught an empty handle is returned.
6479 * The returned handle is valid until this TryCatch block has been destroyed.
6481 Local<Value> Exception() const;
6484 * Returns the .stack property of the thrown object. If no .stack
6485 * property is present an empty handle is returned.
6487 V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
6488 V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
6489 Local<Context> context) const;
6492 * Returns the message associated with this exception. If there is
6493 * no message associated an empty handle is returned.
6495 * The returned handle is valid until this TryCatch block has been
6498 Local<v8::Message> Message() const;
6501 * Clears any exceptions that may have been caught by this try/catch block.
6502 * After this method has been called, HasCaught() will return false. Cancels
6503 * the scheduled exception if it is caught and ReThrow() is not called before.
6505 * It is not necessary to clear a try/catch block before using it again; if
6506 * another exception is thrown the previously caught exception will just be
6507 * overwritten. However, it is often a good idea since it makes it easier
6508 * to determine which operation threw a given exception.
6513 * Set verbosity of the external exception handler.
6515 * By default, exceptions that are caught by an external exception
6516 * handler are not reported. Call SetVerbose with true on an
6517 * external exception handler to have exceptions caught by the
6518 * handler reported as if they were not caught.
6520 void SetVerbose(bool value);
6523 * Set whether or not this TryCatch should capture a Message object
6524 * which holds source information about where the exception
6525 * occurred. True by default.
6527 void SetCaptureMessage(bool value);
6530 * There are cases when the raw address of C++ TryCatch object cannot be
6531 * used for comparisons with addresses into the JS stack. The cases are:
6532 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6533 * 2) Address sanitizer allocates local C++ object in the heap when
6534 * UseAfterReturn mode is enabled.
6535 * This method returns address that can be used for comparisons with
6536 * addresses into the JS stack. When neither simulator nor ASAN's
6537 * UseAfterReturn is enabled, then the address returned will be the address
6538 * of the C++ try catch handler itself.
6540 static void* JSStackComparableAddress(v8::TryCatch* handler) {
6541 if (handler == NULL) return NULL;
6542 return handler->js_stack_comparable_address_;
6546 void ResetInternal();
6548 // Make it hard to create heap-allocated TryCatch blocks.
6549 TryCatch(const TryCatch&);
6550 void operator=(const TryCatch&);
6551 void* operator new(size_t size);
6552 void operator delete(void*, size_t);
6554 v8::internal::Isolate* isolate_;
6555 v8::TryCatch* next_;
6558 void* js_stack_comparable_address_;
6559 bool is_verbose_ : 1;
6560 bool can_continue_ : 1;
6561 bool capture_message_ : 1;
6563 bool has_terminated_ : 1;
6565 friend class v8::internal::Isolate;
6573 * A container for extension names.
6575 class V8_EXPORT ExtensionConfiguration {
6577 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6578 ExtensionConfiguration(int name_count, const char* names[])
6579 : name_count_(name_count), names_(names) { }
6581 const char** begin() const { return &names_[0]; }
6582 const char** end() const { return &names_[name_count_]; }
6585 const int name_count_;
6586 const char** names_;
6591 * A sandboxed execution context with its own set of built-in objects
6594 class V8_EXPORT Context {
6597 * Returns the global proxy object.
6599 * Global proxy object is a thin wrapper whose prototype points to actual
6600 * context's global object with the properties like Object, etc. This is done
6601 * that way for security reasons (for more details see
6602 * https://wiki.mozilla.org/Gecko:SplitWindow).
6604 * Please note that changes to global proxy object prototype most probably
6605 * would break VM---v8 expects only global object as a prototype of global
6608 Local<Object> Global();
6611 * Detaches the global object from its context before
6612 * the global object can be reused to create a new context.
6614 void DetachGlobal();
6617 * Creates a new context and returns a handle to the newly allocated
6620 * \param isolate The isolate in which to create the context.
6622 * \param extensions An optional extension configuration containing
6623 * the extensions to be installed in the newly created context.
6625 * \param global_template An optional object template from which the
6626 * global object for the newly created context will be created.
6628 * \param global_object An optional global object to be reused for
6629 * the newly created context. This global object must have been
6630 * created by a previous call to Context::New with the same global
6631 * template. The state of the global object will be completely reset
6632 * and only object identify will remain.
6634 static Local<Context> New(
6635 Isolate* isolate, ExtensionConfiguration* extensions = NULL,
6636 Local<ObjectTemplate> global_template = Local<ObjectTemplate>(),
6637 Local<Value> global_object = Local<Value>());
6640 * Sets the security token for the context. To access an object in
6641 * another context, the security tokens must match.
6643 void SetSecurityToken(Local<Value> token);
6645 /** Restores the security token to the default value. */
6646 void UseDefaultSecurityToken();
6648 /** Returns the security token of this context.*/
6649 Local<Value> GetSecurityToken();
6652 * Enter this context. After entering a context, all code compiled
6653 * and run is compiled and run in this context. If another context
6654 * is already entered, this old context is saved so it can be
6655 * restored when the new context is exited.
6660 * Exit this context. Exiting the current context restores the
6661 * context that was in place when entering the current context.
6665 /** Returns an isolate associated with a current context. */
6666 v8::Isolate* GetIsolate();
6669 * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6670 * The value is propagated to the scripts compiled in given Context and
6671 * can be used for filtering scripts.
6673 enum EmbedderDataFields { kDebugIdIndex = 0 };
6676 * Gets the embedder data with the given index, which must have been set by a
6677 * previous call to SetEmbedderData with the same index. Note that index 0
6678 * currently has a special meaning for Chrome's debugger.
6680 V8_INLINE Local<Value> GetEmbedderData(int index);
6683 * Gets the exports object used by V8 extras. Extra natives get a reference
6684 * to this object and can use it to export functionality.
6686 Local<Object> GetExtrasExportsObject();
6689 * Sets the embedder data with the given index, growing the data as
6690 * needed. Note that index 0 currently has a special meaning for Chrome's
6693 void SetEmbedderData(int index, Local<Value> value);
6696 * Gets a 2-byte-aligned native pointer from the embedder data with the given
6697 * index, which must have bees set by a previous call to
6698 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6699 * currently has a special meaning for Chrome's debugger.
6701 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
6704 * Sets a 2-byte-aligned native pointer in the embedder data with the given
6705 * index, growing the data as needed. Note that index 0 currently has a
6706 * special meaning for Chrome's debugger.
6708 void SetAlignedPointerInEmbedderData(int index, void* value);
6711 * Control whether code generation from strings is allowed. Calling
6712 * this method with false will disable 'eval' and the 'Function'
6713 * constructor for code running in this context. If 'eval' or the
6714 * 'Function' constructor are used an exception will be thrown.
6716 * If code generation from strings is not allowed the
6717 * V8::AllowCodeGenerationFromStrings callback will be invoked if
6718 * set before blocking the call to 'eval' or the 'Function'
6719 * constructor. If that callback returns true, the call will be
6720 * allowed, otherwise an exception will be thrown. If no callback is
6721 * set an exception will be thrown.
6723 void AllowCodeGenerationFromStrings(bool allow);
6726 * Returns true if code generation from strings is allowed for the context.
6727 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6729 bool IsCodeGenerationFromStringsAllowed();
6732 * Sets the error description for the exception that is thrown when
6733 * code generation from strings is not allowed and 'eval' or the 'Function'
6734 * constructor are called.
6736 void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
6739 * Stack-allocated class which sets the execution context for all
6740 * operations executed within a local scope.
6744 explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
6747 V8_INLINE ~Scope() { context_->Exit(); }
6750 Local<Context> context_;
6755 friend class Script;
6756 friend class Object;
6757 friend class Function;
6759 Local<Value> SlowGetEmbedderData(int index);
6760 void* SlowGetAlignedPointerFromEmbedderData(int index);
6765 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6766 * to use any given V8 isolate, see the comments in the Isolate class. The
6767 * definition of 'using a V8 isolate' includes accessing handles or holding onto
6768 * object pointers obtained from V8 handles while in the particular V8 isolate.
6769 * It is up to the user of V8 to ensure, perhaps with locking, that this
6770 * constraint is not violated. In addition to any other synchronization
6771 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6772 * used to signal thead switches to V8.
6774 * v8::Locker is a scoped lock object. While it's active, i.e. between its
6775 * construction and destruction, the current thread is allowed to use the locked
6776 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6777 * any time. In other words, the scope of a v8::Locker is a critical section.
6783 * v8::Locker locker(isolate);
6784 * v8::Isolate::Scope isolate_scope(isolate);
6786 * // Code using V8 and isolate goes here.
6788 * } // Destructor called here
6791 * If you wish to stop using V8 in a thread A you can do this either by
6792 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6798 * v8::Unlocker unlocker(isolate);
6800 * // Code not using V8 goes here while V8 can run in another thread.
6802 * } // Destructor called here.
6806 * The Unlocker object is intended for use in a long-running callback from V8,
6807 * where you want to release the V8 lock for other threads to use.
6809 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6810 * given thread. This can be useful if you have code that can be called either
6811 * from code that holds the lock or from code that does not. The Unlocker is
6812 * not recursive so you can not have several Unlockers on the stack at once, and
6813 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6815 * An unlocker will unlock several lockers if it has to and reinstate the
6816 * correct depth of locking on its destruction, e.g.:
6821 * v8::Locker locker(isolate);
6822 * Isolate::Scope isolate_scope(isolate);
6825 * v8::Locker another_locker(isolate);
6826 * // V8 still locked (2 levels).
6829 * v8::Unlocker unlocker(isolate);
6833 * // V8 locked again (2 levels).
6835 * // V8 still locked (1 level).
6837 * // V8 Now no longer locked.
6840 class V8_EXPORT Unlocker {
6843 * Initialize Unlocker for a given Isolate.
6845 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6849 void Initialize(Isolate* isolate);
6851 internal::Isolate* isolate_;
6855 class V8_EXPORT Locker {
6858 * Initialize Locker for a given Isolate.
6860 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6865 * Returns whether or not the locker for a given isolate, is locked by the
6868 static bool IsLocked(Isolate* isolate);
6871 * Returns whether v8::Locker is being used by this V8 instance.
6873 static bool IsActive();
6876 void Initialize(Isolate* isolate);
6880 internal::Isolate* isolate_;
6882 // Disallow copying and assigning.
6883 Locker(const Locker&);
6884 void operator=(const Locker&);
6888 // --- Implementation ---
6891 namespace internal {
6893 const int kApiPointerSize = sizeof(void*); // NOLINT
6894 const int kApiIntSize = sizeof(int); // NOLINT
6895 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6897 // Tag information for HeapObject.
6898 const int kHeapObjectTag = 1;
6899 const int kHeapObjectTagSize = 2;
6900 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6902 // Tag information for Smi.
6903 const int kSmiTag = 0;
6904 const int kSmiTagSize = 1;
6905 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6907 template <size_t ptr_size> struct SmiTagging;
6909 template<int kSmiShiftSize>
6910 V8_INLINE internal::Object* IntToSmi(int value) {
6911 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6912 uintptr_t tagged_value =
6913 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6914 return reinterpret_cast<internal::Object*>(tagged_value);
6917 // Smi constants for 32-bit systems.
6918 template <> struct SmiTagging<4> {
6919 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6920 static int SmiShiftSize() { return kSmiShiftSize; }
6921 static int SmiValueSize() { return kSmiValueSize; }
6922 V8_INLINE static int SmiToInt(const internal::Object* value) {
6923 int shift_bits = kSmiTagSize + kSmiShiftSize;
6924 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6925 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6927 V8_INLINE static internal::Object* IntToSmi(int value) {
6928 return internal::IntToSmi<kSmiShiftSize>(value);
6930 V8_INLINE static bool IsValidSmi(intptr_t value) {
6931 // To be representable as an tagged small integer, the two
6932 // most-significant bits of 'value' must be either 00 or 11 due to
6933 // sign-extension. To check this we add 01 to the two
6934 // most-significant bits, and check if the most-significant bit is 0
6936 // CAUTION: The original code below:
6937 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6938 // may lead to incorrect results according to the C language spec, and
6939 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6940 // compiler may produce undefined results in case of signed integer
6941 // overflow. The computation must be done w/ unsigned ints.
6942 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6946 // Smi constants for 64-bit systems.
6947 template <> struct SmiTagging<8> {
6948 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6949 static int SmiShiftSize() { return kSmiShiftSize; }
6950 static int SmiValueSize() { return kSmiValueSize; }
6951 V8_INLINE static int SmiToInt(const internal::Object* value) {
6952 int shift_bits = kSmiTagSize + kSmiShiftSize;
6953 // Shift down and throw away top 32 bits.
6954 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6956 V8_INLINE static internal::Object* IntToSmi(int value) {
6957 return internal::IntToSmi<kSmiShiftSize>(value);
6959 V8_INLINE static bool IsValidSmi(intptr_t value) {
6960 // To be representable as a long smi, the value must be a 32-bit integer.
6961 return (value == static_cast<int32_t>(value));
6965 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6966 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6967 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6968 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6969 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6972 * This class exports constants and functionality from within v8 that
6973 * is necessary to implement inline functions in the v8 api. Don't
6974 * depend on functions and constants defined here.
6978 // These values match non-compiler-dependent values defined within
6979 // the implementation of v8.
6980 static const int kHeapObjectMapOffset = 0;
6981 static const int kMapInstanceTypeAndBitFieldOffset =
6982 1 * kApiPointerSize + kApiIntSize;
6983 static const int kStringResourceOffset = 3 * kApiPointerSize;
6985 static const int kOddballKindOffset = 3 * kApiPointerSize;
6986 static const int kForeignAddressOffset = kApiPointerSize;
6987 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6988 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6989 static const int kContextHeaderSize = 2 * kApiPointerSize;
6990 static const int kContextEmbedderDataIndex = 82;
6991 static const int kFullStringRepresentationMask = 0x07;
6992 static const int kStringEncodingMask = 0x4;
6993 static const int kExternalTwoByteRepresentationTag = 0x02;
6994 static const int kExternalOneByteRepresentationTag = 0x06;
6996 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6997 static const int kAmountOfExternalAllocatedMemoryOffset =
6998 4 * kApiPointerSize;
6999 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
7000 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
7001 static const int kIsolateRootsOffset =
7002 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
7004 static const int kUndefinedValueRootIndex = 5;
7005 static const int kNullValueRootIndex = 7;
7006 static const int kTrueValueRootIndex = 8;
7007 static const int kFalseValueRootIndex = 9;
7008 static const int kEmptyStringRootIndex = 10;
7010 // The external allocation limit should be below 256 MB on all architectures
7011 // to avoid that resource-constrained embedders run low on memory.
7012 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
7014 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
7015 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
7016 static const int kNodeStateMask = 0x7;
7017 static const int kNodeStateIsWeakValue = 2;
7018 static const int kNodeStateIsPendingValue = 3;
7019 static const int kNodeStateIsNearDeathValue = 4;
7020 static const int kNodeIsIndependentShift = 3;
7021 static const int kNodeIsPartiallyDependentShift = 4;
7023 static const int kJSObjectType = 0xbe;
7024 static const int kFirstNonstringType = 0x80;
7025 static const int kOddballType = 0x83;
7026 static const int kForeignType = 0x87;
7028 static const int kUndefinedOddballKind = 5;
7029 static const int kNullOddballKind = 3;
7031 static const uint32_t kNumIsolateDataSlots = 4;
7033 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
7034 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
7035 #ifdef V8_ENABLE_CHECKS
7036 CheckInitializedImpl(isolate);
7040 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
7041 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
7045 V8_INLINE static int SmiValue(const internal::Object* value) {
7046 return PlatformSmiTagging::SmiToInt(value);
7049 V8_INLINE static internal::Object* IntToSmi(int value) {
7050 return PlatformSmiTagging::IntToSmi(value);
7053 V8_INLINE static bool IsValidSmi(intptr_t value) {
7054 return PlatformSmiTagging::IsValidSmi(value);
7057 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
7058 typedef internal::Object O;
7059 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
7060 // Map::InstanceType is defined so that it will always be loaded into
7061 // the LS 8 bits of one 16-bit word, regardless of endianess.
7062 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
7065 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
7066 typedef internal::Object O;
7067 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
7070 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
7071 int representation = (instance_type & kFullStringRepresentationMask);
7072 return representation == kExternalTwoByteRepresentationTag;
7075 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
7076 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7077 return *addr & static_cast<uint8_t>(1U << shift);
7080 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
7081 bool value, int shift) {
7082 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7083 uint8_t mask = static_cast<uint8_t>(1U << shift);
7084 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
7087 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
7088 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7089 return *addr & kNodeStateMask;
7092 V8_INLINE static void UpdateNodeState(internal::Object** obj,
7094 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7095 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
7098 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
7101 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
7102 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7103 *reinterpret_cast<void**>(addr) = data;
7106 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
7108 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
7109 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7110 return *reinterpret_cast<void* const*>(addr);
7113 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
7115 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
7116 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
7119 template <typename T>
7120 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
7121 const uint8_t* addr =
7122 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
7123 return *reinterpret_cast<const T*>(addr);
7126 template <typename T>
7127 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
7128 typedef internal::Object O;
7129 typedef internal::Internals I;
7130 O* ctx = *reinterpret_cast<O* const*>(context);
7131 int embedder_data_offset = I::kContextHeaderSize +
7132 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
7133 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
7135 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
7136 return I::ReadField<T>(embedder_data, value_offset);
7140 } // namespace internal
7144 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
7145 return New(isolate, that.val_);
7149 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
7150 return New(isolate, that.val_);
7155 Local<T> Local<T>::New(Isolate* isolate, T* that) {
7156 if (that == NULL) return Local<T>();
7158 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
7159 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
7160 reinterpret_cast<internal::Isolate*>(isolate), *p)));
7166 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
7168 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
7173 Local<T> Eternal<T>::Get(Isolate* isolate) {
7174 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
7179 Local<T> MaybeLocal<T>::ToLocalChecked() {
7180 if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
7181 return Local<T>(val_);
7186 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
7187 #ifdef V8_ENABLE_CHECKS
7188 if (index < 0 || index >= kInternalFieldsInWeakCallback) {
7189 V8::InternalFieldOutOfBounds(index);
7192 return internal_fields_[index];
7197 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
7198 if (that == NULL) return NULL;
7199 internal::Object** p = reinterpret_cast<internal::Object**>(that);
7200 return reinterpret_cast<T*>(
7201 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
7206 template <class T, class M>
7207 template <class S, class M2>
7208 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
7211 if (that.IsEmpty()) return;
7212 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
7213 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
7214 M::Copy(that, this);
7219 bool PersistentBase<T>::IsIndependent() const {
7220 typedef internal::Internals I;
7221 if (this->IsEmpty()) return false;
7222 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7223 I::kNodeIsIndependentShift);
7228 bool PersistentBase<T>::IsNearDeath() const {
7229 typedef internal::Internals I;
7230 if (this->IsEmpty()) return false;
7231 uint8_t node_state =
7232 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
7233 return node_state == I::kNodeStateIsNearDeathValue ||
7234 node_state == I::kNodeStateIsPendingValue;
7239 bool PersistentBase<T>::IsWeak() const {
7240 typedef internal::Internals I;
7241 if (this->IsEmpty()) return false;
7242 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
7243 I::kNodeStateIsWeakValue;
7248 void PersistentBase<T>::Reset() {
7249 if (this->IsEmpty()) return;
7250 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
7257 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
7260 if (other.IsEmpty()) return;
7261 this->val_ = New(isolate, other.val_);
7267 void PersistentBase<T>::Reset(Isolate* isolate,
7268 const PersistentBase<S>& other) {
7271 if (other.IsEmpty()) return;
7272 this->val_ = New(isolate, other.val_);
7277 template <typename S, typename P>
7278 void PersistentBase<T>::SetWeak(
7280 typename WeakCallbackData<S, P>::Callback callback) {
7282 typedef typename WeakCallbackData<Value, void>::Callback Callback;
7283 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7284 reinterpret_cast<Callback>(callback));
7289 template <typename P>
7290 void PersistentBase<T>::SetWeak(
7292 typename WeakCallbackData<T, P>::Callback callback) {
7293 SetWeak<T, P>(parameter, callback);
7298 template <typename P>
7299 void PersistentBase<T>::SetPhantom(
7300 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7301 int internal_field_index1, int internal_field_index2) {
7302 typedef typename WeakCallbackInfo<void>::Callback Callback;
7303 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7304 internal_field_index1, internal_field_index2,
7305 reinterpret_cast<Callback>(callback));
7310 template <typename P>
7311 V8_INLINE void PersistentBase<T>::SetWeak(
7312 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7313 WeakCallbackType type) {
7314 typedef typename WeakCallbackInfo<void>::Callback Callback;
7315 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7316 reinterpret_cast<Callback>(callback), type);
7321 template <typename P>
7322 P* PersistentBase<T>::ClearWeak() {
7323 return reinterpret_cast<P*>(
7324 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7329 void PersistentBase<T>::MarkIndependent() {
7330 typedef internal::Internals I;
7331 if (this->IsEmpty()) return;
7332 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7334 I::kNodeIsIndependentShift);
7339 void PersistentBase<T>::MarkPartiallyDependent() {
7340 typedef internal::Internals I;
7341 if (this->IsEmpty()) return;
7342 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7344 I::kNodeIsPartiallyDependentShift);
7349 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7350 typedef internal::Internals I;
7351 if (this->IsEmpty()) return;
7352 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7353 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7354 *reinterpret_cast<uint16_t*>(addr) = class_id;
7359 uint16_t PersistentBase<T>::WrapperClassId() const {
7360 typedef internal::Internals I;
7361 if (this->IsEmpty()) return 0;
7362 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7363 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7364 return *reinterpret_cast<uint16_t*>(addr);
7368 template<typename T>
7369 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7371 template<typename T>
7372 template<typename S>
7373 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7375 if (V8_UNLIKELY(handle.IsEmpty())) {
7376 *value_ = GetDefaultValue();
7378 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7382 template <typename T>
7383 template <typename S>
7384 void ReturnValue<T>::Set(const Global<S>& handle) {
7386 if (V8_UNLIKELY(handle.IsEmpty())) {
7387 *value_ = GetDefaultValue();
7389 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7393 template <typename T>
7394 template <typename S>
7395 void ReturnValue<T>::Set(const Local<S> handle) {
7397 if (V8_UNLIKELY(handle.IsEmpty())) {
7398 *value_ = GetDefaultValue();
7400 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7404 template<typename T>
7405 void ReturnValue<T>::Set(double i) {
7406 TYPE_CHECK(T, Number);
7407 Set(Number::New(GetIsolate(), i));
7410 template<typename T>
7411 void ReturnValue<T>::Set(int32_t i) {
7412 TYPE_CHECK(T, Integer);
7413 typedef internal::Internals I;
7414 if (V8_LIKELY(I::IsValidSmi(i))) {
7415 *value_ = I::IntToSmi(i);
7418 Set(Integer::New(GetIsolate(), i));
7421 template<typename T>
7422 void ReturnValue<T>::Set(uint32_t i) {
7423 TYPE_CHECK(T, Integer);
7424 // Can't simply use INT32_MAX here for whatever reason.
7425 bool fits_into_int32_t = (i & (1U << 31)) == 0;
7426 if (V8_LIKELY(fits_into_int32_t)) {
7427 Set(static_cast<int32_t>(i));
7430 Set(Integer::NewFromUnsigned(GetIsolate(), i));
7433 template<typename T>
7434 void ReturnValue<T>::Set(bool value) {
7435 TYPE_CHECK(T, Boolean);
7436 typedef internal::Internals I;
7439 root_index = I::kTrueValueRootIndex;
7441 root_index = I::kFalseValueRootIndex;
7443 *value_ = *I::GetRoot(GetIsolate(), root_index);
7446 template<typename T>
7447 void ReturnValue<T>::SetNull() {
7448 TYPE_CHECK(T, Primitive);
7449 typedef internal::Internals I;
7450 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
7453 template<typename T>
7454 void ReturnValue<T>::SetUndefined() {
7455 TYPE_CHECK(T, Primitive);
7456 typedef internal::Internals I;
7457 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
7460 template<typename T>
7461 void ReturnValue<T>::SetEmptyString() {
7462 TYPE_CHECK(T, String);
7463 typedef internal::Internals I;
7464 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
7467 template<typename T>
7468 Isolate* ReturnValue<T>::GetIsolate() {
7469 // Isolate is always the pointer below the default value on the stack.
7470 return *reinterpret_cast<Isolate**>(&value_[-2]);
7473 template<typename T>
7474 template<typename S>
7475 void ReturnValue<T>::Set(S* whatever) {
7476 // Uncompilable to prevent inadvertent misuse.
7477 TYPE_CHECK(S*, Primitive);
7480 template<typename T>
7481 internal::Object* ReturnValue<T>::GetDefaultValue() {
7482 // Default value is always the pointer below value_ on the stack.
7487 template<typename T>
7488 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
7489 internal::Object** values,
7491 bool is_construct_call)
7492 : implicit_args_(implicit_args),
7495 is_construct_call_(is_construct_call) { }
7498 template<typename T>
7499 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
7500 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7501 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7505 template<typename T>
7506 Local<Function> FunctionCallbackInfo<T>::Callee() const {
7507 return Local<Function>(reinterpret_cast<Function*>(
7508 &implicit_args_[kCalleeIndex]));
7512 template<typename T>
7513 Local<Object> FunctionCallbackInfo<T>::This() const {
7514 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7518 template<typename T>
7519 Local<Object> FunctionCallbackInfo<T>::Holder() const {
7520 return Local<Object>(reinterpret_cast<Object*>(
7521 &implicit_args_[kHolderIndex]));
7525 template<typename T>
7526 Local<Value> FunctionCallbackInfo<T>::Data() const {
7527 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7531 template<typename T>
7532 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
7533 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7537 template<typename T>
7538 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
7539 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
7543 template<typename T>
7544 bool FunctionCallbackInfo<T>::IsConstructCall() const {
7545 return is_construct_call_ & 0x1;
7549 template<typename T>
7550 int FunctionCallbackInfo<T>::Length() const {
7554 ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
7555 Local<Integer> resource_line_offset,
7556 Local<Integer> resource_column_offset,
7557 Local<Boolean> resource_is_shared_cross_origin,
7558 Local<Integer> script_id,
7559 Local<Boolean> resource_is_embedder_debug_script,
7560 Local<Value> source_map_url,
7561 Local<Boolean> resource_is_opaque)
7562 : resource_name_(resource_name),
7563 resource_line_offset_(resource_line_offset),
7564 resource_column_offset_(resource_column_offset),
7565 options_(!resource_is_embedder_debug_script.IsEmpty() &&
7566 resource_is_embedder_debug_script->IsTrue(),
7567 !resource_is_shared_cross_origin.IsEmpty() &&
7568 resource_is_shared_cross_origin->IsTrue(),
7569 !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue()),
7570 script_id_(script_id),
7571 source_map_url_(source_map_url) {}
7573 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
7576 Local<Integer> ScriptOrigin::ResourceLineOffset() const {
7577 return resource_line_offset_;
7581 Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
7582 return resource_column_offset_;
7586 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
7589 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7592 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
7594 : source_string(string),
7595 resource_name(origin.ResourceName()),
7596 resource_line_offset(origin.ResourceLineOffset()),
7597 resource_column_offset(origin.ResourceColumnOffset()),
7598 resource_options(origin.Options()),
7599 source_map_url(origin.SourceMapUrl()),
7600 cached_data(data) {}
7603 ScriptCompiler::Source::Source(Local<String> string,
7605 : source_string(string), cached_data(data) {}
7608 ScriptCompiler::Source::~Source() {
7613 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
7619 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
7620 return value ? True(isolate) : False(isolate);
7624 void Template::Set(Isolate* isolate, const char* name, v8::Local<Data> value) {
7625 Set(v8::String::NewFromUtf8(isolate, name, NewStringType::kNormal)
7631 Local<Value> Object::GetInternalField(int index) {
7632 #ifndef V8_ENABLE_CHECKS
7633 typedef internal::Object O;
7634 typedef internal::HeapObject HO;
7635 typedef internal::Internals I;
7636 O* obj = *reinterpret_cast<O**>(this);
7637 // Fast path: If the object is a plain JSObject, which is the common case, we
7638 // know where to find the internal fields and can return the value directly.
7639 if (I::GetInstanceType(obj) == I::kJSObjectType) {
7640 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7641 O* value = I::ReadField<O*>(obj, offset);
7642 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7643 return Local<Value>(reinterpret_cast<Value*>(result));
7646 return SlowGetInternalField(index);
7650 void* Object::GetAlignedPointerFromInternalField(int index) {
7651 #ifndef V8_ENABLE_CHECKS
7652 typedef internal::Object O;
7653 typedef internal::Internals I;
7654 O* obj = *reinterpret_cast<O**>(this);
7655 // Fast path: If the object is a plain JSObject, which is the common case, we
7656 // know where to find the internal fields and can return the value directly.
7657 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
7658 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7659 return I::ReadField<void*>(obj, offset);
7662 return SlowGetAlignedPointerFromInternalField(index);
7666 String* String::Cast(v8::Value* value) {
7667 #ifdef V8_ENABLE_CHECKS
7670 return static_cast<String*>(value);
7674 Local<String> String::Empty(Isolate* isolate) {
7675 typedef internal::Object* S;
7676 typedef internal::Internals I;
7677 I::CheckInitialized(isolate);
7678 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7679 return Local<String>(reinterpret_cast<String*>(slot));
7683 String::ExternalStringResource* String::GetExternalStringResource() const {
7684 typedef internal::Object O;
7685 typedef internal::Internals I;
7686 O* obj = *reinterpret_cast<O* const*>(this);
7687 String::ExternalStringResource* result;
7688 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
7689 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7690 result = reinterpret_cast<String::ExternalStringResource*>(value);
7694 #ifdef V8_ENABLE_CHECKS
7695 VerifyExternalStringResource(result);
7701 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
7702 String::Encoding* encoding_out) const {
7703 typedef internal::Object O;
7704 typedef internal::Internals I;
7705 O* obj = *reinterpret_cast<O* const*>(this);
7706 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
7707 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7708 ExternalStringResourceBase* resource = NULL;
7709 if (type == I::kExternalOneByteRepresentationTag ||
7710 type == I::kExternalTwoByteRepresentationTag) {
7711 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7712 resource = static_cast<ExternalStringResourceBase*>(value);
7714 #ifdef V8_ENABLE_CHECKS
7715 VerifyExternalStringResourceBase(resource, *encoding_out);
7721 bool Value::IsUndefined() const {
7722 #ifdef V8_ENABLE_CHECKS
7723 return FullIsUndefined();
7725 return QuickIsUndefined();
7729 bool Value::QuickIsUndefined() const {
7730 typedef internal::Object O;
7731 typedef internal::Internals I;
7732 O* obj = *reinterpret_cast<O* const*>(this);
7733 if (!I::HasHeapObjectTag(obj)) return false;
7734 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7735 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
7739 bool Value::IsNull() const {
7740 #ifdef V8_ENABLE_CHECKS
7741 return FullIsNull();
7743 return QuickIsNull();
7747 bool Value::QuickIsNull() const {
7748 typedef internal::Object O;
7749 typedef internal::Internals I;
7750 O* obj = *reinterpret_cast<O* const*>(this);
7751 if (!I::HasHeapObjectTag(obj)) return false;
7752 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7753 return (I::GetOddballKind(obj) == I::kNullOddballKind);
7757 bool Value::IsString() const {
7758 #ifdef V8_ENABLE_CHECKS
7759 return FullIsString();
7761 return QuickIsString();
7765 bool Value::QuickIsString() const {
7766 typedef internal::Object O;
7767 typedef internal::Internals I;
7768 O* obj = *reinterpret_cast<O* const*>(this);
7769 if (!I::HasHeapObjectTag(obj)) return false;
7770 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7774 template <class T> Value* Value::Cast(T* value) {
7775 return static_cast<Value*>(value);
7779 Local<Boolean> Value::ToBoolean() const {
7780 return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
7781 .FromMaybe(Local<Boolean>());
7785 Local<Number> Value::ToNumber() const {
7786 return ToNumber(Isolate::GetCurrent()->GetCurrentContext())
7787 .FromMaybe(Local<Number>());
7791 Local<String> Value::ToString() const {
7792 return ToString(Isolate::GetCurrent()->GetCurrentContext())
7793 .FromMaybe(Local<String>());
7797 Local<String> Value::ToDetailString() const {
7798 return ToDetailString(Isolate::GetCurrent()->GetCurrentContext())
7799 .FromMaybe(Local<String>());
7803 Local<Object> Value::ToObject() const {
7804 return ToObject(Isolate::GetCurrent()->GetCurrentContext())
7805 .FromMaybe(Local<Object>());
7809 Local<Integer> Value::ToInteger() const {
7810 return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
7811 .FromMaybe(Local<Integer>());
7815 Local<Uint32> Value::ToUint32() const {
7816 return ToUint32(Isolate::GetCurrent()->GetCurrentContext())
7817 .FromMaybe(Local<Uint32>());
7821 Local<Int32> Value::ToInt32() const {
7822 return ToInt32(Isolate::GetCurrent()->GetCurrentContext())
7823 .FromMaybe(Local<Int32>());
7827 Boolean* Boolean::Cast(v8::Value* value) {
7828 #ifdef V8_ENABLE_CHECKS
7831 return static_cast<Boolean*>(value);
7835 Name* Name::Cast(v8::Value* value) {
7836 #ifdef V8_ENABLE_CHECKS
7839 return static_cast<Name*>(value);
7843 Symbol* Symbol::Cast(v8::Value* value) {
7844 #ifdef V8_ENABLE_CHECKS
7847 return static_cast<Symbol*>(value);
7851 Number* Number::Cast(v8::Value* value) {
7852 #ifdef V8_ENABLE_CHECKS
7855 return static_cast<Number*>(value);
7859 Integer* Integer::Cast(v8::Value* value) {
7860 #ifdef V8_ENABLE_CHECKS
7863 return static_cast<Integer*>(value);
7867 Int32* Int32::Cast(v8::Value* value) {
7868 #ifdef V8_ENABLE_CHECKS
7871 return static_cast<Int32*>(value);
7875 Uint32* Uint32::Cast(v8::Value* value) {
7876 #ifdef V8_ENABLE_CHECKS
7879 return static_cast<Uint32*>(value);
7883 Date* Date::Cast(v8::Value* value) {
7884 #ifdef V8_ENABLE_CHECKS
7887 return static_cast<Date*>(value);
7891 StringObject* StringObject::Cast(v8::Value* value) {
7892 #ifdef V8_ENABLE_CHECKS
7895 return static_cast<StringObject*>(value);
7899 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7900 #ifdef V8_ENABLE_CHECKS
7903 return static_cast<SymbolObject*>(value);
7907 Float32x4Object* Float32x4Object::Cast(v8::Value* value) {
7908 #ifdef V8_ENABLE_CHECKS
7911 return static_cast<Float32x4Object*>(value);
7915 NumberObject* NumberObject::Cast(v8::Value* value) {
7916 #ifdef V8_ENABLE_CHECKS
7919 return static_cast<NumberObject*>(value);
7923 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7924 #ifdef V8_ENABLE_CHECKS
7927 return static_cast<BooleanObject*>(value);
7931 RegExp* RegExp::Cast(v8::Value* value) {
7932 #ifdef V8_ENABLE_CHECKS
7935 return static_cast<RegExp*>(value);
7939 Object* Object::Cast(v8::Value* value) {
7940 #ifdef V8_ENABLE_CHECKS
7943 return static_cast<Object*>(value);
7947 Array* Array::Cast(v8::Value* value) {
7948 #ifdef V8_ENABLE_CHECKS
7951 return static_cast<Array*>(value);
7955 Map* Map::Cast(v8::Value* value) {
7956 #ifdef V8_ENABLE_CHECKS
7959 return static_cast<Map*>(value);
7963 Set* Set::Cast(v8::Value* value) {
7964 #ifdef V8_ENABLE_CHECKS
7967 return static_cast<Set*>(value);
7971 Promise* Promise::Cast(v8::Value* value) {
7972 #ifdef V8_ENABLE_CHECKS
7975 return static_cast<Promise*>(value);
7979 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7980 #ifdef V8_ENABLE_CHECKS
7983 return static_cast<Promise::Resolver*>(value);
7987 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7988 #ifdef V8_ENABLE_CHECKS
7991 return static_cast<ArrayBuffer*>(value);
7995 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7996 #ifdef V8_ENABLE_CHECKS
7999 return static_cast<ArrayBufferView*>(value);
8003 TypedArray* TypedArray::Cast(v8::Value* value) {
8004 #ifdef V8_ENABLE_CHECKS
8007 return static_cast<TypedArray*>(value);
8011 Uint8Array* Uint8Array::Cast(v8::Value* value) {
8012 #ifdef V8_ENABLE_CHECKS
8015 return static_cast<Uint8Array*>(value);
8019 Int8Array* Int8Array::Cast(v8::Value* value) {
8020 #ifdef V8_ENABLE_CHECKS
8023 return static_cast<Int8Array*>(value);
8027 Uint16Array* Uint16Array::Cast(v8::Value* value) {
8028 #ifdef V8_ENABLE_CHECKS
8031 return static_cast<Uint16Array*>(value);
8035 Int16Array* Int16Array::Cast(v8::Value* value) {
8036 #ifdef V8_ENABLE_CHECKS
8039 return static_cast<Int16Array*>(value);
8043 Uint32Array* Uint32Array::Cast(v8::Value* value) {
8044 #ifdef V8_ENABLE_CHECKS
8047 return static_cast<Uint32Array*>(value);
8051 Int32Array* Int32Array::Cast(v8::Value* value) {
8052 #ifdef V8_ENABLE_CHECKS
8055 return static_cast<Int32Array*>(value);
8059 Float32Array* Float32Array::Cast(v8::Value* value) {
8060 #ifdef V8_ENABLE_CHECKS
8063 return static_cast<Float32Array*>(value);
8067 Float64Array* Float64Array::Cast(v8::Value* value) {
8068 #ifdef V8_ENABLE_CHECKS
8071 return static_cast<Float64Array*>(value);
8075 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
8076 #ifdef V8_ENABLE_CHECKS
8079 return static_cast<Uint8ClampedArray*>(value);
8083 DataView* DataView::Cast(v8::Value* value) {
8084 #ifdef V8_ENABLE_CHECKS
8087 return static_cast<DataView*>(value);
8091 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
8092 #ifdef V8_ENABLE_CHECKS
8095 return static_cast<SharedArrayBuffer*>(value);
8099 Function* Function::Cast(v8::Value* value) {
8100 #ifdef V8_ENABLE_CHECKS
8103 return static_cast<Function*>(value);
8107 External* External::Cast(v8::Value* value) {
8108 #ifdef V8_ENABLE_CHECKS
8111 return static_cast<External*>(value);
8115 template<typename T>
8116 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
8117 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
8121 template<typename T>
8122 Local<Value> PropertyCallbackInfo<T>::Data() const {
8123 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
8127 template<typename T>
8128 Local<Object> PropertyCallbackInfo<T>::This() const {
8129 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
8133 template<typename T>
8134 Local<Object> PropertyCallbackInfo<T>::Holder() const {
8135 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
8139 template<typename T>
8140 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
8141 return ReturnValue<T>(&args_[kReturnValueIndex]);
8145 Local<Primitive> Undefined(Isolate* isolate) {
8146 typedef internal::Object* S;
8147 typedef internal::Internals I;
8148 I::CheckInitialized(isolate);
8149 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
8150 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8154 Local<Primitive> Null(Isolate* isolate) {
8155 typedef internal::Object* S;
8156 typedef internal::Internals I;
8157 I::CheckInitialized(isolate);
8158 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
8159 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8163 Local<Boolean> True(Isolate* isolate) {
8164 typedef internal::Object* S;
8165 typedef internal::Internals I;
8166 I::CheckInitialized(isolate);
8167 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
8168 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8172 Local<Boolean> False(Isolate* isolate) {
8173 typedef internal::Object* S;
8174 typedef internal::Internals I;
8175 I::CheckInitialized(isolate);
8176 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
8177 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8181 void Isolate::SetData(uint32_t slot, void* data) {
8182 typedef internal::Internals I;
8183 I::SetEmbedderData(this, slot, data);
8187 void* Isolate::GetData(uint32_t slot) {
8188 typedef internal::Internals I;
8189 return I::GetEmbedderData(this, slot);
8193 uint32_t Isolate::GetNumberOfDataSlots() {
8194 typedef internal::Internals I;
8195 return I::kNumIsolateDataSlots;
8199 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
8200 int64_t change_in_bytes) {
8201 typedef internal::Internals I;
8202 int64_t* amount_of_external_allocated_memory =
8203 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
8204 I::kAmountOfExternalAllocatedMemoryOffset);
8205 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
8206 reinterpret_cast<int64_t*>(
8207 reinterpret_cast<uint8_t*>(this) +
8208 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
8209 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
8210 if (change_in_bytes > 0 &&
8211 amount - *amount_of_external_allocated_memory_at_last_global_gc >
8212 I::kExternalAllocationLimit) {
8213 CollectAllGarbage("external memory allocation limit reached.");
8215 *amount_of_external_allocated_memory = amount;
8216 return *amount_of_external_allocated_memory;
8220 template<typename T>
8221 void Isolate::SetObjectGroupId(const Persistent<T>& object,
8223 TYPE_CHECK(Value, T);
8224 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
8228 template<typename T>
8229 void Isolate::SetReferenceFromGroup(UniqueId id,
8230 const Persistent<T>& object) {
8231 TYPE_CHECK(Value, T);
8232 SetReferenceFromGroup(id,
8233 reinterpret_cast<v8::internal::Object**>(object.val_));
8237 template<typename T, typename S>
8238 void Isolate::SetReference(const Persistent<T>& parent,
8239 const Persistent<S>& child) {
8240 TYPE_CHECK(Object, T);
8241 TYPE_CHECK(Value, S);
8242 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
8243 reinterpret_cast<v8::internal::Object**>(child.val_));
8247 Local<Value> Context::GetEmbedderData(int index) {
8248 #ifndef V8_ENABLE_CHECKS
8249 typedef internal::Object O;
8250 typedef internal::HeapObject HO;
8251 typedef internal::Internals I;
8252 HO* context = *reinterpret_cast<HO**>(this);
8254 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
8255 return Local<Value>(reinterpret_cast<Value*>(result));
8257 return SlowGetEmbedderData(index);
8262 void* Context::GetAlignedPointerFromEmbedderData(int index) {
8263 #ifndef V8_ENABLE_CHECKS
8264 typedef internal::Internals I;
8265 return I::ReadEmbedderData<void*>(this, index);
8267 return SlowGetAlignedPointerFromEmbedderData(index);
8272 void V8::SetAllowCodeGenerationFromStringsCallback(
8273 AllowCodeGenerationFromStringsCallback callback) {
8274 Isolate* isolate = Isolate::GetCurrent();
8275 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
8280 Isolate* isolate = Isolate::GetCurrent();
8281 return isolate->IsDead();
8285 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
8286 Isolate* isolate = Isolate::GetCurrent();
8287 return isolate->AddMessageListener(that, data);
8291 void V8::RemoveMessageListeners(MessageCallback that) {
8292 Isolate* isolate = Isolate::GetCurrent();
8293 isolate->RemoveMessageListeners(that);
8297 void V8::SetFailedAccessCheckCallbackFunction(
8298 FailedAccessCheckCallback callback) {
8299 Isolate* isolate = Isolate::GetCurrent();
8300 isolate->SetFailedAccessCheckCallbackFunction(callback);
8304 void V8::SetCaptureStackTraceForUncaughtExceptions(
8305 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8306 Isolate* isolate = Isolate::GetCurrent();
8307 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8312 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
8313 Isolate* isolate = Isolate::GetCurrent();
8314 isolate->SetFatalErrorHandler(callback);
8318 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
8319 Isolate* isolate = Isolate::GetCurrent();
8320 isolate->RemoveGCPrologueCallback(
8321 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
8325 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
8326 Isolate* isolate = Isolate::GetCurrent();
8327 isolate->RemoveGCEpilogueCallback(
8328 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
8332 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8334 AllocationAction action) {
8335 Isolate* isolate = Isolate::GetCurrent();
8336 isolate->AddMemoryAllocationCallback(callback, space, action);
8340 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8341 Isolate* isolate = Isolate::GetCurrent();
8342 isolate->RemoveMemoryAllocationCallback(callback);
8346 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8349 bool V8::IsExecutionTerminating(Isolate* isolate) {
8350 if (isolate == NULL) {
8351 isolate = Isolate::GetCurrent();
8353 return isolate->IsExecutionTerminating();
8357 void V8::CancelTerminateExecution(Isolate* isolate) {
8358 isolate->CancelTerminateExecution();
8362 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8363 Isolate* isolate = Isolate::GetCurrent();
8364 isolate->VisitExternalResources(visitor);
8368 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8369 Isolate* isolate = Isolate::GetCurrent();
8370 isolate->VisitHandlesWithClassIds(visitor);
8374 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8375 PersistentHandleVisitor* visitor) {
8376 isolate->VisitHandlesWithClassIds(visitor);
8380 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8381 PersistentHandleVisitor* visitor) {
8382 isolate->VisitHandlesForPartialDependence(visitor);
8387 * A simple shell that takes a list of expressions on the
8388 * command-line and executes them.
8393 * \example process.cc