1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /** \mainpage V8 API Reference Guide
7 * V8 is Google's open source JavaScript engine.
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
12 * For other documentation see http://code.google.com/apis/v8/
22 #include "v8-version.h"
25 // We reserve the V8_* prefix for macros defined in V8 public API and
26 // assume there are no name conflicts with the embedder's code.
30 // Setup for Windows DLL export/import. When building the V8 DLL the
31 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
32 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
33 // static library or building a program which uses the V8 static library neither
34 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
35 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
36 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
37 build configuration to ensure that at most one of these is set
40 #ifdef BUILDING_V8_SHARED
41 # define V8_EXPORT __declspec(dllexport)
43 # define V8_EXPORT __declspec(dllimport)
46 #endif // BUILDING_V8_SHARED
50 // Setup for Linux shared library export.
51 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
52 # ifdef BUILDING_V8_SHARED
53 # define V8_EXPORT __attribute__ ((visibility("default")))
64 * The v8 JavaScript engine.
68 class AccessorSignature;
78 class FunctionTemplate;
80 class ImplementationUtilities;
90 class ObjectOperationDescriptor;
95 class RawOperationDescriptor;
97 class SharedArrayBuffer;
109 template <class T> class Local;
112 template <class T> class Eternal;
113 template<class T> class NonCopyablePersistentTraits;
114 template<class T> class PersistentBase;
116 class M = NonCopyablePersistentTraits<T> > class Persistent;
119 template<class K, class V, class T> class PersistentValueMap;
120 template <class K, class V, class T>
121 class PersistentValueMapBase;
122 template <class K, class V, class T>
123 class GlobalValueMap;
124 template<class V, class T> class PersistentValueVector;
125 template<class T, class P> class WeakCallbackObject;
126 class FunctionTemplate;
127 class ObjectTemplate;
129 template<typename T> class FunctionCallbackInfo;
130 template<typename T> class PropertyCallbackInfo;
134 class CallHandlerHelper;
135 class EscapableHandleScope;
136 template<typename T> class ReturnValue;
144 struct StreamedSource;
145 template<typename T> class CustomArguments;
146 class PropertyCallbackArguments;
147 class FunctionCallbackArguments;
153 * General purpose unique identifier.
157 explicit UniqueId(intptr_t data)
160 bool operator==(const UniqueId& other) const {
161 return data_ == other.data_;
164 bool operator!=(const UniqueId& other) const {
165 return data_ != other.data_;
168 bool operator<(const UniqueId& other) const {
169 return data_ < other.data_;
178 #define TYPE_CHECK(T, S) \
180 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
185 * An object reference managed by the v8 garbage collector.
187 * All objects returned from v8 have to be tracked by the garbage
188 * collector so that it knows that the objects are still alive. Also,
189 * because the garbage collector may move objects, it is unsafe to
190 * point directly to an object. Instead, all objects are stored in
191 * handles which are known by the garbage collector and updated
192 * whenever an object moves. Handles should always be passed by value
193 * (except in cases like out-parameters) and they should never be
194 * allocated on the heap.
196 * There are two types of handles: local and persistent handles.
197 * Local handles are light-weight and transient and typically used in
198 * local operations. They are managed by HandleScopes. Persistent
199 * handles can be used when storing objects across several independent
200 * operations and have to be explicitly deallocated when they're no
203 * It is safe to extract the object stored in the handle by
204 * dereferencing the handle (for instance, to extract the Object* from
205 * a Local<Object>); the value will still be governed by a handle
206 * behind the scenes and the same rules apply to these values as to
212 V8_INLINE Local() : val_(0) {}
214 V8_INLINE Local(Local<S> that)
215 : val_(reinterpret_cast<T*>(*that)) {
217 * This check fails when trying to convert between incompatible
218 * handles. For example, converting from a Local<String> to a
225 * Returns true if the handle is empty.
227 V8_INLINE bool IsEmpty() const { return val_ == 0; }
230 * Sets the handle to be empty. IsEmpty() will then return true.
232 V8_INLINE void Clear() { val_ = 0; }
234 V8_INLINE T* operator->() const { return val_; }
236 V8_INLINE T* operator*() const { return val_; }
239 * Checks whether two handles are the same.
240 * Returns true if both are empty, or if the objects
241 * to which they refer are identical.
242 * The handles' references are not checked.
245 V8_INLINE bool operator==(const Local<S>& that) const {
246 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
247 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
248 if (a == 0) return b == 0;
249 if (b == 0) return false;
253 template <class S> V8_INLINE bool operator==(
254 const PersistentBase<S>& that) const {
255 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
256 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
257 if (a == 0) return b == 0;
258 if (b == 0) return false;
263 * Checks whether two handles are different.
264 * Returns true if only one of the handles is empty, or if
265 * the objects to which they refer are different.
266 * The handles' references are not checked.
269 V8_INLINE bool operator!=(const Local<S>& that) const {
270 return !operator==(that);
273 template <class S> V8_INLINE bool operator!=(
274 const Persistent<S>& that) const {
275 return !operator==(that);
278 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
279 #ifdef V8_ENABLE_CHECKS
280 // If we're going to perform the type check then we have to check
281 // that the handle isn't empty before doing the checked cast.
282 if (that.IsEmpty()) return Local<T>();
284 return Local<T>(T::Cast(*that));
288 template <class S> V8_INLINE Local<S> As() {
289 return Local<S>::Cast(*this);
293 * Create a local handle for the content of another handle.
294 * The referee is kept alive by the local handle even when
295 * the original handle is destroyed/disposed.
297 V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
298 V8_INLINE static Local<T> New(Isolate* isolate,
299 const PersistentBase<T>& that);
303 template<class F> friend class Eternal;
304 template<class F> friend class PersistentBase;
305 template<class F, class M> friend class Persistent;
306 template<class F> friend class Local;
308 friend class MaybeLocal;
309 template<class F> friend class FunctionCallbackInfo;
310 template<class F> friend class PropertyCallbackInfo;
313 friend class Context;
314 template<class F> friend class internal::CustomArguments;
315 friend Local<Primitive> Undefined(Isolate* isolate);
316 friend Local<Primitive> Null(Isolate* isolate);
317 friend Local<Boolean> True(Isolate* isolate);
318 friend Local<Boolean> False(Isolate* isolate);
319 friend class HandleScope;
320 friend class EscapableHandleScope;
321 template <class F1, class F2, class F3>
322 friend class PersistentValueMapBase;
323 template<class F1, class F2> friend class PersistentValueVector;
326 V8_INLINE Local(S* that)
328 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
333 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
334 // Local is an alias for Local for historical reasons.
336 using Handle = Local<T>;
341 * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
342 * the Local<> is empty before it can be used.
344 * If an API method returns a MaybeLocal<>, the API method can potentially fail
345 * either because an exception is thrown, or because an exception is pending,
346 * e.g. because a previous API call threw an exception that hasn't been caught
347 * yet, or because a TerminateExecution exception was thrown. In that case, an
348 * empty MaybeLocal is returned.
353 V8_INLINE MaybeLocal() : val_(nullptr) {}
355 V8_INLINE MaybeLocal(Local<S> that)
356 : val_(reinterpret_cast<T*>(*that)) {
360 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
363 V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
364 out->val_ = IsEmpty() ? nullptr : this->val_;
368 // Will crash if the MaybeLocal<> is empty.
369 V8_INLINE Local<T> ToLocalChecked();
372 V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
373 return IsEmpty() ? default_value : Local<S>(val_);
381 // Eternal handles are set-once handles that live for the life of the isolate.
382 template <class T> class Eternal {
384 V8_INLINE Eternal() : index_(kInitialValue) { }
386 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
387 Set(isolate, handle);
389 // Can only be safely called if already set.
390 V8_INLINE Local<T> Get(Isolate* isolate);
391 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
392 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
395 static const int kInitialValue = -1;
400 static const int kInternalFieldsInWeakCallback = 2;
403 template <typename T>
404 class WeakCallbackInfo {
406 typedef void (*Callback)(const WeakCallbackInfo<T>& data);
408 WeakCallbackInfo(Isolate* isolate, T* parameter,
409 void* internal_fields[kInternalFieldsInWeakCallback],
411 : isolate_(isolate), parameter_(parameter), callback_(callback) {
412 for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) {
413 internal_fields_[i] = internal_fields[i];
417 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
418 V8_INLINE T* GetParameter() const { return parameter_; }
419 V8_INLINE void* GetInternalField(int index) const;
421 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
422 void* GetInternalField1() const) {
423 return internal_fields_[0];
425 V8_INLINE V8_DEPRECATE_SOON("use indexed version",
426 void* GetInternalField2() const) {
427 return internal_fields_[1];
430 bool IsFirstPass() const { return callback_ != nullptr; }
432 // When first called, the embedder MUST Reset() the Global which triggered the
433 // callback. The Global itself is unusable for anything else. No v8 other api
434 // calls may be called in the first callback. Should additional work be
435 // required, the embedder must set a second pass callback, which will be
436 // called after all the initial callbacks are processed.
437 // Calling SetSecondPassCallback on the second pass will immediately crash.
438 void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
444 void* internal_fields_[kInternalFieldsInWeakCallback];
448 template <class T, class P>
449 class WeakCallbackData {
451 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
453 WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
454 : isolate_(isolate), parameter_(parameter), handle_(handle) {}
456 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
457 V8_INLINE P* GetParameter() const { return parameter_; }
458 V8_INLINE Local<T> GetValue() const { return handle_; }
467 // TODO(dcarney): delete this with WeakCallbackData
469 using PhantomCallbackData = WeakCallbackInfo<T>;
472 enum class WeakCallbackType { kParameter, kInternalFields };
476 * An object reference that is independent of any handle scope. Where
477 * a Local handle only lives as long as the HandleScope in which it was
478 * allocated, a PersistentBase handle remains valid until it is explicitly
481 * A persistent handle contains a reference to a storage cell within
482 * the v8 engine which holds an object value and which is updated by
483 * the garbage collector whenever the object is moved. A new storage
484 * cell can be created using the constructor or PersistentBase::Reset and
485 * existing handles can be disposed using PersistentBase::Reset.
488 template <class T> class PersistentBase {
491 * If non-empty, destroy the underlying storage cell
492 * IsEmpty() will return true after this call.
494 V8_INLINE void Reset();
496 * If non-empty, destroy the underlying storage cell
497 * and create a new one with the contents of other if other is non empty
500 V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
503 * If non-empty, destroy the underlying storage cell
504 * and create a new one with the contents of other if other is non empty
507 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
509 V8_INLINE bool IsEmpty() const { return val_ == NULL; }
510 V8_INLINE void Empty() { val_ = 0; }
512 V8_INLINE Local<T> Get(Isolate* isolate) const {
513 return Local<T>::New(isolate, *this);
517 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
518 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
519 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
520 if (a == NULL) return b == NULL;
521 if (b == NULL) return false;
526 V8_INLINE bool operator==(const Local<S>& that) const {
527 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
528 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
529 if (a == NULL) return b == NULL;
530 if (b == NULL) return false;
535 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
536 return !operator==(that);
540 V8_INLINE bool operator!=(const Local<S>& that) const {
541 return !operator==(that);
545 * Install a finalization callback on this object.
546 * NOTE: There is no guarantee as to *when* or even *if* the callback is
547 * invoked. The invocation is performed solely on a best effort basis.
548 * As always, GC-based finalization should *not* be relied upon for any
549 * critical form of resource management!
551 template <typename P>
552 V8_INLINE V8_DEPRECATE_SOON(
553 "use WeakCallbackInfo version",
554 void SetWeak(P* parameter,
555 typename WeakCallbackData<T, P>::Callback callback));
557 template <typename S, typename P>
558 V8_INLINE V8_DEPRECATE_SOON(
559 "use WeakCallbackInfo version",
560 void SetWeak(P* parameter,
561 typename WeakCallbackData<S, P>::Callback callback));
563 // Phantom persistents work like weak persistents, except that the pointer to
564 // the object being collected is not available in the finalization callback.
565 // This enables the garbage collector to collect the object and any objects
566 // it references transitively in one GC cycle. At the moment you can either
567 // specify a parameter for the callback or the location of two internal
568 // fields in the dying object.
569 template <typename P>
570 V8_INLINE V8_DEPRECATE_SOON(
572 void SetPhantom(P* parameter,
573 typename WeakCallbackInfo<P>::Callback callback,
574 int internal_field_index1 = -1,
575 int internal_field_index2 = -1));
577 template <typename P>
578 V8_INLINE void SetWeak(P* parameter,
579 typename WeakCallbackInfo<P>::Callback callback,
580 WeakCallbackType type);
583 V8_INLINE P* ClearWeak();
585 // TODO(dcarney): remove this.
586 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
589 * Marks the reference to this object independent. Garbage collector is free
590 * to ignore any object groups containing this object. Weak callback for an
591 * independent handle should not assume that it will be preceded by a global
592 * GC prologue callback or followed by a global GC epilogue callback.
594 V8_INLINE void MarkIndependent();
597 * Marks the reference to this object partially dependent. Partially dependent
598 * handles only depend on other partially dependent handles and these
599 * dependencies are provided through object groups. It provides a way to build
600 * smaller object groups for young objects that represent only a subset of all
601 * external dependencies. This mark is automatically cleared after each
602 * garbage collection.
604 V8_INLINE void MarkPartiallyDependent();
606 V8_INLINE bool IsIndependent() const;
608 /** Checks if the handle holds the only reference to an object. */
609 V8_INLINE bool IsNearDeath() const;
611 /** Returns true if the handle's reference is weak. */
612 V8_INLINE bool IsWeak() const;
615 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
616 * description in v8-profiler.h for details.
618 V8_INLINE void SetWrapperClassId(uint16_t class_id);
621 * Returns the class ID previously assigned to this handle or 0 if no class ID
622 * was previously assigned.
624 V8_INLINE uint16_t WrapperClassId() const;
627 friend class Isolate;
629 template<class F> friend class Local;
630 template<class F1, class F2> friend class Persistent;
633 template<class F> friend class PersistentBase;
634 template<class F> friend class ReturnValue;
635 template <class F1, class F2, class F3>
636 friend class PersistentValueMapBase;
637 template<class F1, class F2> friend class PersistentValueVector;
640 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
641 PersistentBase(PersistentBase& other) = delete; // NOLINT
642 void operator=(PersistentBase&) = delete;
643 V8_INLINE static T* New(Isolate* isolate, T* that);
650 * Default traits for Persistent. This class does not allow
651 * use of the copy constructor or assignment operator.
652 * At present kResetInDestructor is not set, but that will change in a future
656 class NonCopyablePersistentTraits {
658 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
659 static const bool kResetInDestructor = false;
660 template<class S, class M>
661 V8_INLINE static void Copy(const Persistent<S, M>& source,
662 NonCopyablePersistent* dest) {
663 Uncompilable<Object>();
665 // TODO(dcarney): come up with a good compile error here.
666 template<class O> V8_INLINE static void Uncompilable() {
667 TYPE_CHECK(O, Primitive);
673 * Helper class traits to allow copying and assignment of Persistent.
674 * This will clone the contents of storage cell, but not any of the flags, etc.
677 struct CopyablePersistentTraits {
678 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
679 static const bool kResetInDestructor = true;
680 template<class S, class M>
681 static V8_INLINE void Copy(const Persistent<S, M>& source,
682 CopyablePersistent* dest) {
683 // do nothing, just allow copy
689 * A PersistentBase which allows copy and assignment.
691 * Copy, assignment and destructor bevavior is controlled by the traits
694 * Note: Persistent class hierarchy is subject to future changes.
696 template <class T, class M> class Persistent : public PersistentBase<T> {
699 * A Persistent with no storage cell.
701 V8_INLINE Persistent() : PersistentBase<T>(0) { }
703 * Construct a Persistent from a Local.
704 * When the Local is non-empty, a new storage cell is created
705 * pointing to the same object, and no flags are set.
708 V8_INLINE Persistent(Isolate* isolate, Local<S> that)
709 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
713 * Construct a Persistent from a Persistent.
714 * When the Persistent is non-empty, a new storage cell is created
715 * pointing to the same object, and no flags are set.
717 template <class S, class M2>
718 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
719 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
723 * The copy constructors and assignment operator create a Persistent
724 * exactly as the Persistent constructor, but the Copy function from the
725 * traits class is called, allowing the setting of flags based on the
728 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
731 template <class S, class M2>
732 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
735 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
739 template <class S, class M2>
740 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
745 * The destructor will dispose the Persistent based on the
746 * kResetInDestructor flags in the traits class. Since not calling dispose
747 * can result in a memory leak, it is recommended to always set this flag.
749 V8_INLINE ~Persistent() {
750 if (M::kResetInDestructor) this->Reset();
753 // TODO(dcarney): this is pretty useless, fix or remove
755 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
756 #ifdef V8_ENABLE_CHECKS
757 // If we're going to perform the type check then we have to check
758 // that the handle isn't empty before doing the checked cast.
759 if (!that.IsEmpty()) T::Cast(*that);
761 return reinterpret_cast<Persistent<T>&>(that);
764 // TODO(dcarney): this is pretty useless, fix or remove
765 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
766 return Persistent<S>::Cast(*this);
770 friend class Isolate;
772 template<class F> friend class Local;
773 template<class F1, class F2> friend class Persistent;
774 template<class F> friend class ReturnValue;
776 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
777 V8_INLINE T* operator*() const { return this->val_; }
778 template<class S, class M2>
779 V8_INLINE void Copy(const Persistent<S, M2>& that);
784 * A PersistentBase which has move semantics.
786 * Note: Persistent class hierarchy is subject to future changes.
789 class Global : public PersistentBase<T> {
792 * A Global with no storage cell.
794 V8_INLINE Global() : PersistentBase<T>(nullptr) {}
796 * Construct a Global from a Local.
797 * When the Local is non-empty, a new storage cell is created
798 * pointing to the same object, and no flags are set.
801 V8_INLINE Global(Isolate* isolate, Local<S> that)
802 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
806 * Construct a Global from a PersistentBase.
807 * When the Persistent is non-empty, a new storage cell is created
808 * pointing to the same object, and no flags are set.
811 V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
812 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
818 V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) {
819 other.val_ = nullptr;
821 V8_INLINE ~Global() { this->Reset(); }
823 * Move via assignment.
826 V8_INLINE Global& operator=(Global<S>&& rhs) {
830 this->val_ = rhs.val_;
836 * Pass allows returning uniques from functions, etc.
838 Global Pass() { return static_cast<Global&&>(*this); }
841 * For compatibility with Chromium's base::Bind (base::Passed).
843 typedef void MoveOnlyTypeForCPP03;
847 friend class ReturnValue;
848 Global(Global&) = delete;
849 void operator=(Global&) = delete;
850 V8_INLINE T* operator*() const { return this->val_; }
854 // UniquePersistent is an alias for Global for historical reason.
856 using UniquePersistent = Global<T>;
860 * A stack-allocated class that governs a number of local handles.
861 * After a handle scope has been created, all local handles will be
862 * allocated within that handle scope until either the handle scope is
863 * deleted or another handle scope is created. If there is already a
864 * handle scope and a new one is created, all allocations will take
865 * place in the new handle scope until it is deleted. After that,
866 * new handles will again be allocated in the original handle scope.
868 * After the handle scope of a local handle has been deleted the
869 * garbage collector will no longer track the object stored in the
870 * handle and may deallocate it. The behavior of accessing a handle
871 * for which the handle scope has been deleted is undefined.
873 class V8_EXPORT HandleScope {
875 HandleScope(Isolate* isolate);
880 * Counts the number of allocated handles.
882 static int NumberOfHandles(Isolate* isolate);
884 V8_INLINE Isolate* GetIsolate() const {
885 return reinterpret_cast<Isolate*>(isolate_);
889 V8_INLINE HandleScope() {}
891 void Initialize(Isolate* isolate);
893 static internal::Object** CreateHandle(internal::Isolate* isolate,
894 internal::Object* value);
897 // Uses heap_object to obtain the current Isolate.
898 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
899 internal::Object* value);
901 // Make it hard to create heap-allocated or illegal handle scopes by
902 // disallowing certain operations.
903 HandleScope(const HandleScope&);
904 void operator=(const HandleScope&);
905 void* operator new(size_t size);
906 void operator delete(void*, size_t);
908 internal::Isolate* isolate_;
909 internal::Object** prev_next_;
910 internal::Object** prev_limit_;
912 // Local::New uses CreateHandle with an Isolate* parameter.
913 template<class F> friend class Local;
915 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
916 // a HeapObject* in their shortcuts.
918 friend class Context;
923 * A HandleScope which first allocates a handle in the current scope
924 * which will be later filled with the escape value.
926 class V8_EXPORT EscapableHandleScope : public HandleScope {
928 EscapableHandleScope(Isolate* isolate);
929 V8_INLINE ~EscapableHandleScope() {}
932 * Pushes the value into the previous scope and returns a handle to it.
933 * Cannot be called twice.
936 V8_INLINE Local<T> Escape(Local<T> value) {
937 internal::Object** slot =
938 Escape(reinterpret_cast<internal::Object**>(*value));
939 return Local<T>(reinterpret_cast<T*>(slot));
943 internal::Object** Escape(internal::Object** escape_value);
945 // Make it hard to create heap-allocated or illegal handle scopes by
946 // disallowing certain operations.
947 EscapableHandleScope(const EscapableHandleScope&);
948 void operator=(const EscapableHandleScope&);
949 void* operator new(size_t size);
950 void operator delete(void*, size_t);
952 internal::Object** escape_slot_;
955 class V8_EXPORT SealHandleScope {
957 SealHandleScope(Isolate* isolate);
961 // Make it hard to create heap-allocated or illegal handle scopes by
962 // disallowing certain operations.
963 SealHandleScope(const SealHandleScope&);
964 void operator=(const SealHandleScope&);
965 void* operator new(size_t size);
966 void operator delete(void*, size_t);
968 internal::Isolate* isolate_;
970 internal::Object** prev_limit_;
974 // --- Special objects ---
978 * The superclass of values and API object templates.
980 class V8_EXPORT Data {
987 * The optional attributes of ScriptOrigin.
989 class ScriptOriginOptions {
991 V8_INLINE ScriptOriginOptions(bool is_embedder_debug_script = false,
992 bool is_shared_cross_origin = false,
993 bool is_opaque = false)
994 : flags_((is_embedder_debug_script ? kIsEmbedderDebugScript : 0) |
995 (is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
996 (is_opaque ? kIsOpaque : 0)) {}
997 V8_INLINE ScriptOriginOptions(int flags)
999 (kIsEmbedderDebugScript | kIsSharedCrossOrigin | kIsOpaque)) {}
1000 bool IsEmbedderDebugScript() const {
1001 return (flags_ & kIsEmbedderDebugScript) != 0;
1003 bool IsSharedCrossOrigin() const {
1004 return (flags_ & kIsSharedCrossOrigin) != 0;
1006 bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1007 int Flags() const { return flags_; }
1011 kIsEmbedderDebugScript = 1,
1012 kIsSharedCrossOrigin = 1 << 1,
1019 * The origin, within a file, of a script.
1021 class ScriptOrigin {
1023 V8_INLINE ScriptOrigin(
1024 Local<Value> resource_name,
1025 Local<Integer> resource_line_offset = Local<Integer>(),
1026 Local<Integer> resource_column_offset = Local<Integer>(),
1027 Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1028 Local<Integer> script_id = Local<Integer>(),
1029 Local<Boolean> resource_is_embedder_debug_script = Local<Boolean>(),
1030 Local<Value> source_map_url = Local<Value>(),
1031 Local<Boolean> resource_is_opaque = Local<Boolean>());
1032 V8_INLINE Local<Value> ResourceName() const;
1033 V8_INLINE Local<Integer> ResourceLineOffset() const;
1034 V8_INLINE Local<Integer> ResourceColumnOffset() const;
1036 * Returns true for embedder's debugger scripts
1038 V8_INLINE Local<Integer> ScriptID() const;
1039 V8_INLINE Local<Value> SourceMapUrl() const;
1040 V8_INLINE ScriptOriginOptions Options() const { return options_; }
1043 Local<Value> resource_name_;
1044 Local<Integer> resource_line_offset_;
1045 Local<Integer> resource_column_offset_;
1046 ScriptOriginOptions options_;
1047 Local<Integer> script_id_;
1048 Local<Value> source_map_url_;
1053 * A compiled JavaScript script, not yet tied to a Context.
1055 class V8_EXPORT UnboundScript {
1058 * Binds the script to the currently entered context.
1060 Local<Script> BindToCurrentContext();
1063 Local<Value> GetScriptName();
1066 * Data read from magic sourceURL comments.
1068 Local<Value> GetSourceURL();
1070 * Data read from magic sourceMappingURL comments.
1072 Local<Value> GetSourceMappingURL();
1075 * Returns zero based line number of the code_pos location in the script.
1076 * -1 will be returned if no information available.
1078 int GetLineNumber(int code_pos);
1080 static const int kNoScriptId = 0;
1085 * A compiled JavaScript script, tied to a Context which was active when the
1086 * script was compiled.
1088 class V8_EXPORT Script {
1091 * A shorthand for ScriptCompiler::Compile().
1093 static V8_DEPRECATE_SOON(
1094 "Use maybe version",
1095 Local<Script> Compile(Local<String> source,
1096 ScriptOrigin* origin = nullptr));
1097 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1098 Local<Context> context, Local<String> source,
1099 ScriptOrigin* origin = nullptr);
1101 static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1102 Compile(Local<String> source,
1103 Local<String> file_name));
1106 * Runs the script returning the resulting value. It will be run in the
1107 * context in which it was created (ScriptCompiler::CompileBound or
1108 * UnboundScript::BindToCurrentContext()).
1110 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1111 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
1114 * Returns the corresponding context-unbound script.
1116 Local<UnboundScript> GetUnboundScript();
1118 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1120 return GetUnboundScript()->GetId();
1126 * For compiling scripts.
1128 class V8_EXPORT ScriptCompiler {
1131 * Compilation data that the embedder can cache and pass back to speed up
1132 * future compilations. The data is produced if the CompilerOptions passed to
1133 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1134 * = true. The data to cache can then can be retrieved from
1137 struct V8_EXPORT CachedData {
1147 buffer_policy(BufferNotOwned) {}
1149 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1150 // data and guarantees that it stays alive until the CachedData object is
1151 // destroyed. If the policy is BufferOwned, the given data will be deleted
1152 // (with delete[]) when the CachedData object is destroyed.
1153 CachedData(const uint8_t* data, int length,
1154 BufferPolicy buffer_policy = BufferNotOwned);
1156 // TODO(marja): Async compilation; add constructors which take a callback
1157 // which will be called when V8 no longer needs the data.
1158 const uint8_t* data;
1161 BufferPolicy buffer_policy;
1164 // Prevent copying. Not implemented.
1165 CachedData(const CachedData&);
1166 CachedData& operator=(const CachedData&);
1170 * Source code which can be then compiled to a UnboundScript or Script.
1174 // Source takes ownership of CachedData.
1175 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1176 CachedData* cached_data = NULL);
1177 V8_INLINE Source(Local<String> source_string,
1178 CachedData* cached_data = NULL);
1179 V8_INLINE ~Source();
1181 // Ownership of the CachedData or its buffers is *not* transferred to the
1182 // caller. The CachedData object is alive as long as the Source object is
1184 V8_INLINE const CachedData* GetCachedData() const;
1187 friend class ScriptCompiler;
1188 // Prevent copying. Not implemented.
1189 Source(const Source&);
1190 Source& operator=(const Source&);
1192 Local<String> source_string;
1194 // Origin information
1195 Local<Value> resource_name;
1196 Local<Integer> resource_line_offset;
1197 Local<Integer> resource_column_offset;
1198 ScriptOriginOptions resource_options;
1199 Local<Value> source_map_url;
1201 // Cached data from previous compilation (if a kConsume*Cache flag is
1202 // set), or hold newly generated cache data (kProduce*Cache flags) are
1203 // set when calling a compile method.
1204 CachedData* cached_data;
1208 * For streaming incomplete script data to V8. The embedder should implement a
1209 * subclass of this class.
1211 class V8_EXPORT ExternalSourceStream {
1213 virtual ~ExternalSourceStream() {}
1216 * V8 calls this to request the next chunk of data from the embedder. This
1217 * function will be called on a background thread, so it's OK to block and
1218 * wait for the data, if the embedder doesn't have data yet. Returns the
1219 * length of the data returned. When the data ends, GetMoreData should
1220 * return 0. Caller takes ownership of the data.
1222 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1223 * two data chunks, but doesn't handle multi-byte characters split between
1224 * more than two data chunks. The embedder can avoid this problem by always
1225 * returning at least 2 bytes of data.
1227 * If the embedder wants to cancel the streaming, they should make the next
1228 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1229 * probably, parsing will fail). The streaming task will return as soon as
1230 * V8 has parsed the data it received so far.
1232 virtual size_t GetMoreData(const uint8_t** src) = 0;
1235 * V8 calls this method to set a 'bookmark' at the current position in
1236 * the source stream, for the purpose of (maybe) later calling
1237 * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1238 * calls to GetMoreData should return the same data as they did when
1239 * SetBookmark was called earlier.
1241 * The embedder may return 'false' to indicate it cannot provide this
1244 virtual bool SetBookmark();
1247 * V8 calls this to return to a previously set bookmark.
1249 virtual void ResetToBookmark();
1254 * Source code which can be streamed into V8 in pieces. It will be parsed
1255 * while streaming. It can be compiled after the streaming is complete.
1256 * StreamedSource must be kept alive while the streaming task is ran (see
1257 * ScriptStreamingTask below).
1259 class V8_EXPORT StreamedSource {
1261 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1263 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1266 // Ownership of the CachedData or its buffers is *not* transferred to the
1267 // caller. The CachedData object is alive as long as the StreamedSource
1269 const CachedData* GetCachedData() const;
1271 internal::StreamedSource* impl() const { return impl_; }
1274 // Prevent copying. Not implemented.
1275 StreamedSource(const StreamedSource&);
1276 StreamedSource& operator=(const StreamedSource&);
1278 internal::StreamedSource* impl_;
1282 * A streaming task which the embedder must run on a background thread to
1283 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1285 class ScriptStreamingTask {
1287 virtual ~ScriptStreamingTask() {}
1288 virtual void Run() = 0;
1291 enum CompileOptions {
1292 kNoCompileOptions = 0,
1293 kProduceParserCache,
1294 kConsumeParserCache,
1300 * Compiles the specified script (context-independent).
1301 * Cached data as part of the source object can be optionally produced to be
1302 * consumed later to speed up compilation of identical source scripts.
1304 * Note that when producing cached data, the source must point to NULL for
1305 * cached data. When consuming cached data, the cached data must have been
1306 * produced by the same version of V8.
1308 * \param source Script source code.
1309 * \return Compiled script object (context independent; for running it must be
1310 * bound to a context).
1312 static V8_DEPRECATE_SOON("Use maybe version",
1313 Local<UnboundScript> CompileUnbound(
1314 Isolate* isolate, Source* source,
1315 CompileOptions options = kNoCompileOptions));
1316 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
1317 Isolate* isolate, Source* source,
1318 CompileOptions options = kNoCompileOptions);
1321 * Compiles the specified script (bound to current context).
1323 * \param source Script source code.
1324 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1325 * using pre_data speeds compilation if it's done multiple times.
1326 * Owned by caller, no references are kept when this function returns.
1327 * \return Compiled script object, bound to the context that was active
1328 * when this function was called. When run it will always use this
1331 static V8_DEPRECATE_SOON(
1332 "Use maybe version",
1333 Local<Script> Compile(Isolate* isolate, Source* source,
1334 CompileOptions options = kNoCompileOptions));
1335 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1336 Local<Context> context, Source* source,
1337 CompileOptions options = kNoCompileOptions);
1340 * Returns a task which streams script data into V8, or NULL if the script
1341 * cannot be streamed. The user is responsible for running the task on a
1342 * background thread and deleting it. When ran, the task starts parsing the
1343 * script, and it will request data from the StreamedSource as needed. When
1344 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1345 * can be compiled (see Compile below).
1347 * This API allows to start the streaming with as little data as possible, and
1348 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1350 static ScriptStreamingTask* StartStreamingScript(
1351 Isolate* isolate, StreamedSource* source,
1352 CompileOptions options = kNoCompileOptions);
1355 * Compiles a streamed script (bound to current context).
1357 * This can only be called after the streaming has finished
1358 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1359 * during streaming, so the embedder needs to pass the full source here.
1361 static V8_DEPRECATE_SOON(
1362 "Use maybe version",
1363 Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1364 Local<String> full_source_string,
1365 const ScriptOrigin& origin));
1366 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1367 Local<Context> context, StreamedSource* source,
1368 Local<String> full_source_string, const ScriptOrigin& origin);
1371 * Return a version tag for CachedData for the current V8 version & flags.
1373 * This value is meant only for determining whether a previously generated
1374 * CachedData instance is still valid; the tag has no other meaing.
1376 * Background: The data carried by CachedData may depend on the exact
1377 * V8 version number or currently compiler flags. This means when
1378 * persisting CachedData, the embedder must take care to not pass in
1379 * data from another V8 version, or the same version with different
1382 * The easiest way to do so is to clear the embedder's cache on any
1385 * Alternatively, this tag can be stored alongside the cached data and
1386 * compared when it is being used.
1388 static uint32_t CachedDataVersionTag();
1391 * Compile an ES6 module.
1393 * This is an experimental feature.
1395 * TODO(adamk): Script is likely the wrong return value for this;
1396 * should return some new Module type.
1398 static V8_DEPRECATE_SOON(
1399 "Use maybe version",
1400 Local<Script> CompileModule(Isolate* isolate, Source* source,
1401 CompileOptions options = kNoCompileOptions));
1402 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> CompileModule(
1403 Local<Context> context, Source* source,
1404 CompileOptions options = kNoCompileOptions);
1407 * Compile a function for a given context. This is equivalent to running
1410 * return function(args) { ... }
1413 * It is possible to specify multiple context extensions (obj in the above
1416 static V8_DEPRECATE_SOON("Use maybe version",
1417 Local<Function> CompileFunctionInContext(
1418 Isolate* isolate, Source* source,
1419 Local<Context> context, size_t arguments_count,
1420 Local<String> arguments[],
1421 size_t context_extension_count,
1422 Local<Object> context_extensions[]));
1423 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
1424 Local<Context> context, Source* source, size_t arguments_count,
1425 Local<String> arguments[], size_t context_extension_count,
1426 Local<Object> context_extensions[]);
1429 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1430 Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1437 class V8_EXPORT Message {
1439 Local<String> Get() const;
1441 V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1442 V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
1443 Local<Context> context) const;
1446 * Returns the origin for the script from where the function causing the
1449 ScriptOrigin GetScriptOrigin() const;
1452 * Returns the resource name for the script from where the function causing
1453 * the error originates.
1455 Local<Value> GetScriptResourceName() const;
1458 * Exception stack trace. By default stack traces are not captured for
1459 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1460 * to change this option.
1462 Local<StackTrace> GetStackTrace() const;
1465 * Returns the number, 1-based, of the line where the error occurred.
1467 V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1468 V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1471 * Returns the index within the script of the first character where
1472 * the error occurred.
1474 int GetStartPosition() const;
1477 * Returns the index within the script of the last character where
1478 * the error occurred.
1480 int GetEndPosition() const;
1483 * Returns the index within the line of the first character where
1484 * the error occurred.
1486 V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1487 V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1490 * Returns the index within the line of the last character where
1491 * the error occurred.
1493 V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn() const);
1494 V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1497 * Passes on the value set by the embedder when it fed the script from which
1498 * this Message was generated to V8.
1500 bool IsSharedCrossOrigin() const;
1501 bool IsOpaque() const;
1503 // TODO(1245381): Print to a string instead of on a FILE.
1504 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1506 static const int kNoLineNumberInfo = 0;
1507 static const int kNoColumnInfo = 0;
1508 static const int kNoScriptIdInfo = 0;
1513 * Representation of a JavaScript stack trace. The information collected is a
1514 * snapshot of the execution stack and the information remains valid after
1515 * execution continues.
1517 class V8_EXPORT StackTrace {
1520 * Flags that determine what information is placed captured for each
1521 * StackFrame when grabbing the current stack trace.
1523 enum StackTraceOptions {
1525 kColumnOffset = 1 << 1 | kLineNumber,
1526 kScriptName = 1 << 2,
1527 kFunctionName = 1 << 3,
1529 kIsConstructor = 1 << 5,
1530 kScriptNameOrSourceURL = 1 << 6,
1532 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1533 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1534 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1538 * Returns a StackFrame at a particular index.
1540 Local<StackFrame> GetFrame(uint32_t index) const;
1543 * Returns the number of StackFrames.
1545 int GetFrameCount() const;
1548 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1550 Local<Array> AsArray();
1553 * Grab a snapshot of the current JavaScript execution stack.
1555 * \param frame_limit The maximum number of stack frames we want to capture.
1556 * \param options Enumerates the set of things we will capture for each
1559 static Local<StackTrace> CurrentStackTrace(
1562 StackTraceOptions options = kOverview);
1567 * A single JavaScript stack frame.
1569 class V8_EXPORT StackFrame {
1572 * Returns the number, 1-based, of the line for the associate function call.
1573 * This method will return Message::kNoLineNumberInfo if it is unable to
1574 * retrieve the line number, or if kLineNumber was not passed as an option
1575 * when capturing the StackTrace.
1577 int GetLineNumber() const;
1580 * Returns the 1-based column offset on the line for the associated function
1582 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1583 * the column number, or if kColumnOffset was not passed as an option when
1584 * capturing the StackTrace.
1586 int GetColumn() const;
1589 * Returns the id of the script for the function for this StackFrame.
1590 * This method will return Message::kNoScriptIdInfo if it is unable to
1591 * retrieve the script id, or if kScriptId was not passed as an option when
1592 * capturing the StackTrace.
1594 int GetScriptId() const;
1597 * Returns the name of the resource that contains the script for the
1598 * function for this StackFrame.
1600 Local<String> GetScriptName() const;
1603 * Returns the name of the resource that contains the script for the
1604 * function for this StackFrame or sourceURL value if the script name
1605 * is undefined and its source ends with //# sourceURL=... string or
1606 * deprecated //@ sourceURL=... string.
1608 Local<String> GetScriptNameOrSourceURL() const;
1611 * Returns the name of the function associated with this stack frame.
1613 Local<String> GetFunctionName() const;
1616 * Returns whether or not the associated function is compiled via a call to
1619 bool IsEval() const;
1622 * Returns whether or not the associated function is called as a
1623 * constructor via "new".
1625 bool IsConstructor() const;
1629 // A StateTag represents a possible state of the VM.
1630 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1633 // A RegisterState represents the current state of registers used
1634 // by the sampling profiler API.
1635 struct RegisterState {
1636 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1637 void* pc; // Instruction pointer.
1638 void* sp; // Stack pointer.
1639 void* fp; // Frame pointer.
1643 // The output structure filled up by GetStackSample API function.
1645 size_t frames_count;
1653 class V8_EXPORT JSON {
1656 * Tries to parse the string |json_string| and returns it as value if
1659 * \param json_string The string to parse.
1660 * \return The corresponding value if successfully parsed.
1662 static V8_DEPRECATE_SOON("Use maybe version",
1663 Local<Value> Parse(Local<String> json_string));
1664 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1665 Isolate* isolate, Local<String> json_string);
1670 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1671 * but can be created without entering a v8::Context and hence shouldn't
1672 * escape to JavaScript.
1674 class V8_EXPORT NativeWeakMap : public Data {
1676 static Local<NativeWeakMap> New(Isolate* isolate);
1677 void Set(Local<Value> key, Local<Value> value);
1678 Local<Value> Get(Local<Value> key);
1679 bool Has(Local<Value> key);
1680 bool Delete(Local<Value> key);
1688 * The superclass of all JavaScript values and objects.
1690 class V8_EXPORT Value : public Data {
1693 * Returns true if this value is the undefined value. See ECMA-262
1696 V8_INLINE bool IsUndefined() const;
1699 * Returns true if this value is the null value. See ECMA-262
1702 V8_INLINE bool IsNull() const;
1705 * Returns true if this value is true.
1707 bool IsTrue() const;
1710 * Returns true if this value is false.
1712 bool IsFalse() const;
1715 * Returns true if this value is a symbol or a string.
1716 * This is an experimental feature.
1718 bool IsName() const;
1721 * Returns true if this value is an instance of the String type.
1724 V8_INLINE bool IsString() const;
1727 * Returns true if this value is a symbol.
1728 * This is an experimental feature.
1730 bool IsSymbol() const;
1733 * Returns true if this value is a function.
1735 bool IsFunction() const;
1738 * Returns true if this value is an array.
1740 bool IsArray() const;
1743 * Returns true if this value is an object.
1745 bool IsObject() const;
1748 * Returns true if this value is boolean.
1750 bool IsBoolean() const;
1753 * Returns true if this value is a number.
1755 bool IsNumber() const;
1758 * Returns true if this value is external.
1760 bool IsExternal() const;
1763 * Returns true if this value is a 32-bit signed integer.
1765 bool IsInt32() const;
1768 * Returns true if this value is a 32-bit unsigned integer.
1770 bool IsUint32() const;
1773 * Returns true if this value is a Date.
1775 bool IsDate() const;
1778 * Returns true if this value is an Arguments object.
1780 bool IsArgumentsObject() const;
1783 * Returns true if this value is a Boolean object.
1785 bool IsBooleanObject() const;
1788 * Returns true if this value is a Number object.
1790 bool IsNumberObject() const;
1793 * Returns true if this value is a String object.
1795 bool IsStringObject() const;
1798 * Returns true if this value is a Symbol object.
1799 * This is an experimental feature.
1801 bool IsSymbolObject() const;
1804 * Returns true if this value is a NativeError.
1806 bool IsNativeError() const;
1809 * Returns true if this value is a RegExp.
1811 bool IsRegExp() const;
1814 * Returns true if this value is a Generator function.
1815 * This is an experimental feature.
1817 bool IsGeneratorFunction() const;
1820 * Returns true if this value is a Generator object (iterator).
1821 * This is an experimental feature.
1823 bool IsGeneratorObject() const;
1826 * Returns true if this value is a Promise.
1827 * This is an experimental feature.
1829 bool IsPromise() const;
1832 * Returns true if this value is a Map.
1837 * Returns true if this value is a Set.
1842 * Returns true if this value is a Map Iterator.
1844 bool IsMapIterator() const;
1847 * Returns true if this value is a Set Iterator.
1849 bool IsSetIterator() const;
1852 * Returns true if this value is a WeakMap.
1854 bool IsWeakMap() const;
1857 * Returns true if this value is a WeakSet.
1859 bool IsWeakSet() const;
1862 * Returns true if this value is an ArrayBuffer.
1863 * This is an experimental feature.
1865 bool IsArrayBuffer() const;
1868 * Returns true if this value is an ArrayBufferView.
1869 * This is an experimental feature.
1871 bool IsArrayBufferView() const;
1874 * Returns true if this value is one of TypedArrays.
1875 * This is an experimental feature.
1877 bool IsTypedArray() const;
1880 * Returns true if this value is an Uint8Array.
1881 * This is an experimental feature.
1883 bool IsUint8Array() const;
1886 * Returns true if this value is an Uint8ClampedArray.
1887 * This is an experimental feature.
1889 bool IsUint8ClampedArray() const;
1892 * Returns true if this value is an Int8Array.
1893 * This is an experimental feature.
1895 bool IsInt8Array() const;
1898 * Returns true if this value is an Uint16Array.
1899 * This is an experimental feature.
1901 bool IsUint16Array() const;
1904 * Returns true if this value is an Int16Array.
1905 * This is an experimental feature.
1907 bool IsInt16Array() const;
1910 * Returns true if this value is an Uint32Array.
1911 * This is an experimental feature.
1913 bool IsUint32Array() const;
1916 * Returns true if this value is an Int32Array.
1917 * This is an experimental feature.
1919 bool IsInt32Array() const;
1922 * Returns true if this value is a Float32Array.
1923 * This is an experimental feature.
1925 bool IsFloat32Array() const;
1928 * Returns true if this value is a Float64Array.
1929 * This is an experimental feature.
1931 bool IsFloat64Array() const;
1934 * Returns true if this value is a SIMD Float32x4.
1935 * This is an experimental feature.
1937 bool IsFloat32x4() const;
1940 * Returns true if this value is a DataView.
1941 * This is an experimental feature.
1943 bool IsDataView() const;
1946 * Returns true if this value is a SharedArrayBuffer.
1947 * This is an experimental feature.
1949 bool IsSharedArrayBuffer() const;
1952 V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
1953 Local<Context> context) const;
1954 V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
1955 Local<Context> context) const;
1956 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
1957 Local<Context> context) const;
1958 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
1959 Local<Context> context) const;
1960 V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
1961 Local<Context> context) const;
1962 V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
1963 Local<Context> context) const;
1964 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
1965 Local<Context> context) const;
1966 V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
1968 V8_DEPRECATE_SOON("Use maybe version",
1969 Local<Boolean> ToBoolean(Isolate* isolate) const);
1970 V8_DEPRECATE_SOON("Use maybe version",
1971 Local<Number> ToNumber(Isolate* isolate) const);
1972 V8_DEPRECATE_SOON("Use maybe version",
1973 Local<String> ToString(Isolate* isolate) const);
1974 V8_DEPRECATE_SOON("Use maybe version",
1975 Local<String> ToDetailString(Isolate* isolate) const);
1976 V8_DEPRECATE_SOON("Use maybe version",
1977 Local<Object> ToObject(Isolate* isolate) const);
1978 V8_DEPRECATE_SOON("Use maybe version",
1979 Local<Integer> ToInteger(Isolate* isolate) const);
1980 V8_DEPRECATE_SOON("Use maybe version",
1981 Local<Uint32> ToUint32(Isolate* isolate) const);
1982 V8_DEPRECATE_SOON("Use maybe version",
1983 Local<Int32> ToInt32(Isolate* isolate) const);
1985 inline V8_DEPRECATE_SOON("Use maybe version",
1986 Local<Boolean> ToBoolean() const);
1987 inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber() const);
1988 inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
1989 inline V8_DEPRECATE_SOON("Use maybe version",
1990 Local<String> ToDetailString() const);
1991 inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
1992 inline V8_DEPRECATE_SOON("Use maybe version",
1993 Local<Integer> ToInteger() const);
1994 inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32() const);
1995 inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32() const);
1998 * Attempts to convert a string to an array index.
1999 * Returns an empty handle if the conversion fails.
2001 V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex() const);
2002 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
2003 Local<Context> context) const;
2005 V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2006 V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2007 V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2008 Local<Context> context) const;
2009 V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2010 Local<Context> context) const;
2011 V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2013 V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2014 V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2015 V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2016 V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2017 V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2020 V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2021 V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2022 Local<Value> that) const;
2023 bool StrictEquals(Local<Value> that) const;
2024 bool SameValue(Local<Value> that) const;
2026 template <class T> V8_INLINE static Value* Cast(T* value);
2029 V8_INLINE bool QuickIsUndefined() const;
2030 V8_INLINE bool QuickIsNull() const;
2031 V8_INLINE bool QuickIsString() const;
2032 bool FullIsUndefined() const;
2033 bool FullIsNull() const;
2034 bool FullIsString() const;
2039 * The superclass of primitive values. See ECMA-262 4.3.2.
2041 class V8_EXPORT Primitive : public Value { };
2045 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2048 class V8_EXPORT Boolean : public Primitive {
2051 V8_INLINE static Boolean* Cast(v8::Value* obj);
2052 V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2055 static void CheckCast(v8::Value* obj);
2060 * A superclass for symbols and strings.
2062 class V8_EXPORT Name : public Primitive {
2065 * Returns the identity hash for this object. The current implementation
2066 * uses an inline property on the object to store the identity hash.
2068 * The return value will never be 0. Also, it is not guaranteed to be
2071 int GetIdentityHash();
2073 V8_INLINE static Name* Cast(v8::Value* obj);
2075 static void CheckCast(v8::Value* obj);
2079 enum class NewStringType { kNormal, kInternalized };
2083 * A JavaScript string value (ECMA-262, 4.3.17).
2085 class V8_EXPORT String : public Name {
2087 static const int kMaxLength = (1 << 28) - 16;
2090 UNKNOWN_ENCODING = 0x1,
2091 TWO_BYTE_ENCODING = 0x0,
2092 ONE_BYTE_ENCODING = 0x4
2095 * Returns the number of characters in this string.
2100 * Returns the number of bytes in the UTF-8 encoded
2101 * representation of this string.
2103 int Utf8Length() const;
2106 * Returns whether this string is known to contain only one byte data.
2107 * Does not read the string.
2108 * False negatives are possible.
2110 bool IsOneByte() const;
2113 * Returns whether this string contain only one byte data.
2114 * Will read the entire string in some cases.
2116 bool ContainsOnlyOneByte() const;
2119 * Write the contents of the string to an external buffer.
2120 * If no arguments are given, expects the buffer to be large
2121 * enough to hold the entire string and NULL terminator. Copies
2122 * the contents of the string and the NULL terminator into the
2125 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2126 * before the end of the buffer.
2128 * Copies up to length characters into the output buffer.
2129 * Only null-terminates if there is enough space in the buffer.
2131 * \param buffer The buffer into which the string will be copied.
2132 * \param start The starting position within the string at which
2134 * \param length The number of characters to copy from the string. For
2135 * WriteUtf8 the number of bytes in the buffer.
2136 * \param nchars_ref The number of characters written, can be NULL.
2137 * \param options Various options that might affect performance of this or
2138 * subsequent operations.
2139 * \return The number of characters copied to the buffer excluding the null
2140 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2141 * including the null terminator (if written).
2145 HINT_MANY_WRITES_EXPECTED = 1,
2146 NO_NULL_TERMINATION = 2,
2147 PRESERVE_ONE_BYTE_NULL = 4,
2148 // Used by WriteUtf8 to replace orphan surrogate code units with the
2149 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2151 REPLACE_INVALID_UTF8 = 8
2154 // 16-bit character codes.
2155 int Write(uint16_t* buffer,
2158 int options = NO_OPTIONS) const;
2159 // One byte characters.
2160 int WriteOneByte(uint8_t* buffer,
2163 int options = NO_OPTIONS) const;
2164 // UTF-8 encoded characters.
2165 int WriteUtf8(char* buffer,
2167 int* nchars_ref = NULL,
2168 int options = NO_OPTIONS) const;
2171 * A zero length string.
2173 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2176 * Returns true if the string is external
2178 bool IsExternal() const;
2181 * Returns true if the string is both external and one-byte.
2183 bool IsExternalOneByte() const;
2185 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2187 virtual ~ExternalStringResourceBase() {}
2190 ExternalStringResourceBase() {}
2193 * Internally V8 will call this Dispose method when the external string
2194 * resource is no longer needed. The default implementation will use the
2195 * delete operator. This method can be overridden in subclasses to
2196 * control how allocated external string resources are disposed.
2198 virtual void Dispose() { delete this; }
2201 // Disallow copying and assigning.
2202 ExternalStringResourceBase(const ExternalStringResourceBase&);
2203 void operator=(const ExternalStringResourceBase&);
2205 friend class v8::internal::Heap;
2209 * An ExternalStringResource is a wrapper around a two-byte string
2210 * buffer that resides outside V8's heap. Implement an
2211 * ExternalStringResource to manage the life cycle of the underlying
2212 * buffer. Note that the string data must be immutable.
2214 class V8_EXPORT ExternalStringResource
2215 : public ExternalStringResourceBase {
2218 * Override the destructor to manage the life cycle of the underlying
2221 virtual ~ExternalStringResource() {}
2224 * The string data from the underlying buffer.
2226 virtual const uint16_t* data() const = 0;
2229 * The length of the string. That is, the number of two-byte characters.
2231 virtual size_t length() const = 0;
2234 ExternalStringResource() {}
2238 * An ExternalOneByteStringResource is a wrapper around an one-byte
2239 * string buffer that resides outside V8's heap. Implement an
2240 * ExternalOneByteStringResource to manage the life cycle of the
2241 * underlying buffer. Note that the string data must be immutable
2242 * and that the data must be Latin-1 and not UTF-8, which would require
2243 * special treatment internally in the engine and do not allow efficient
2244 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2247 class V8_EXPORT ExternalOneByteStringResource
2248 : public ExternalStringResourceBase {
2251 * Override the destructor to manage the life cycle of the underlying
2254 virtual ~ExternalOneByteStringResource() {}
2255 /** The string data from the underlying buffer.*/
2256 virtual const char* data() const = 0;
2257 /** The number of Latin-1 characters in the string.*/
2258 virtual size_t length() const = 0;
2260 ExternalOneByteStringResource() {}
2264 * If the string is an external string, return the ExternalStringResourceBase
2265 * regardless of the encoding, otherwise return NULL. The encoding of the
2266 * string is returned in encoding_out.
2268 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2269 Encoding* encoding_out) const;
2272 * Get the ExternalStringResource for an external string. Returns
2273 * NULL if IsExternal() doesn't return true.
2275 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2278 * Get the ExternalOneByteStringResource for an external one-byte string.
2279 * Returns NULL if IsExternalOneByte() doesn't return true.
2281 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2283 V8_INLINE static String* Cast(v8::Value* obj);
2285 // TODO(dcarney): remove with deprecation of New functions.
2286 enum NewStringType {
2287 kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2288 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2291 /** Allocates a new string from UTF-8 data.*/
2292 static V8_DEPRECATE_SOON(
2293 "Use maybe version",
2294 Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2295 NewStringType type = kNormalString,
2298 /** Allocates a new string from UTF-8 data. Only returns an empty value when
2299 * length > kMaxLength. **/
2300 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2301 Isolate* isolate, const char* data, v8::NewStringType type,
2304 /** Allocates a new string from Latin-1 data.*/
2305 static V8_DEPRECATE_SOON(
2306 "Use maybe version",
2307 Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2308 NewStringType type = kNormalString,
2311 /** Allocates a new string from Latin-1 data. Only returns an empty value
2312 * when length > kMaxLength. **/
2313 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2314 Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2317 /** Allocates a new string from UTF-16 data.*/
2318 static V8_DEPRECATE_SOON(
2319 "Use maybe version",
2320 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2321 NewStringType type = kNormalString,
2324 /** Allocates a new string from UTF-16 data. Only returns an empty value when
2325 * length > kMaxLength. **/
2326 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2327 Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2331 * Creates a new string by concatenating the left and the right strings
2332 * passed in as parameters.
2334 static Local<String> Concat(Local<String> left, Local<String> right);
2337 * Creates a new external string using the data defined in the given
2338 * resource. When the external string is no longer live on V8's heap the
2339 * resource will be disposed by calling its Dispose method. The caller of
2340 * this function should not otherwise delete or modify the resource. Neither
2341 * should the underlying buffer be deallocated or modified except through the
2342 * destructor of the external string resource.
2344 static V8_DEPRECATE_SOON(
2345 "Use maybe version",
2346 Local<String> NewExternal(Isolate* isolate,
2347 ExternalStringResource* resource));
2348 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2349 Isolate* isolate, ExternalStringResource* resource);
2352 * Associate an external string resource with this string by transforming it
2353 * in place so that existing references to this string in the JavaScript heap
2354 * will use the external string resource. The external string resource's
2355 * character contents need to be equivalent to this string.
2356 * Returns true if the string has been changed to be an external string.
2357 * The string is not modified if the operation fails. See NewExternal for
2358 * information on the lifetime of the resource.
2360 bool MakeExternal(ExternalStringResource* resource);
2363 * Creates a new external string using the one-byte data defined in the given
2364 * resource. When the external string is no longer live on V8's heap the
2365 * resource will be disposed by calling its Dispose method. The caller of
2366 * this function should not otherwise delete or modify the resource. Neither
2367 * should the underlying buffer be deallocated or modified except through the
2368 * destructor of the external string resource.
2370 static V8_DEPRECATE_SOON(
2371 "Use maybe version",
2372 Local<String> NewExternal(Isolate* isolate,
2373 ExternalOneByteStringResource* resource));
2374 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2375 Isolate* isolate, ExternalOneByteStringResource* resource);
2378 * Associate an external string resource with this string by transforming it
2379 * in place so that existing references to this string in the JavaScript heap
2380 * will use the external string resource. The external string resource's
2381 * character contents need to be equivalent to this string.
2382 * Returns true if the string has been changed to be an external string.
2383 * The string is not modified if the operation fails. See NewExternal for
2384 * information on the lifetime of the resource.
2386 bool MakeExternal(ExternalOneByteStringResource* resource);
2389 * Returns true if this string can be made external.
2391 bool CanMakeExternal();
2394 * Converts an object to a UTF-8-encoded character array. Useful if
2395 * you want to print the object. If conversion to a string fails
2396 * (e.g. due to an exception in the toString() method of the object)
2397 * then the length() method returns 0 and the * operator returns
2400 class V8_EXPORT Utf8Value {
2402 explicit Utf8Value(Local<v8::Value> obj);
2404 char* operator*() { return str_; }
2405 const char* operator*() const { return str_; }
2406 int length() const { return length_; }
2411 // Disallow copying and assigning.
2412 Utf8Value(const Utf8Value&);
2413 void operator=(const Utf8Value&);
2417 * Converts an object to a two-byte string.
2418 * If conversion to a string fails (eg. due to an exception in the toString()
2419 * method of the object) then the length() method returns 0 and the * operator
2422 class V8_EXPORT Value {
2424 explicit Value(Local<v8::Value> obj);
2426 uint16_t* operator*() { return str_; }
2427 const uint16_t* operator*() const { return str_; }
2428 int length() const { return length_; }
2433 // Disallow copying and assigning.
2434 Value(const Value&);
2435 void operator=(const Value&);
2439 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2440 Encoding encoding) const;
2441 void VerifyExternalStringResource(ExternalStringResource* val) const;
2442 static void CheckCast(v8::Value* obj);
2447 * A JavaScript symbol (ECMA-262 edition 6)
2449 * This is an experimental feature. Use at your own risk.
2451 class V8_EXPORT Symbol : public Name {
2453 // Returns the print name string of the symbol, or undefined if none.
2454 Local<Value> Name() const;
2456 // Create a symbol. If name is not empty, it will be used as the description.
2457 static Local<Symbol> New(
2458 Isolate *isolate, Local<String> name = Local<String>());
2460 // Access global symbol registry.
2461 // Note that symbols created this way are never collected, so
2462 // they should only be used for statically fixed properties.
2463 // Also, there is only one global name space for the names used as keys.
2464 // To minimize the potential for clashes, use qualified names as keys.
2465 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2467 // Retrieve a global symbol. Similar to |For|, but using a separate
2468 // registry that is not accessible by (and cannot clash with) JavaScript code.
2469 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2471 // Well-known symbols
2472 static Local<Symbol> GetIterator(Isolate* isolate);
2473 static Local<Symbol> GetUnscopables(Isolate* isolate);
2474 static Local<Symbol> GetToStringTag(Isolate* isolate);
2476 V8_INLINE static Symbol* Cast(v8::Value* obj);
2480 static void CheckCast(v8::Value* obj);
2485 * A JavaScript number value (ECMA-262, 4.3.20)
2487 class V8_EXPORT Number : public Primitive {
2489 double Value() const;
2490 static Local<Number> New(Isolate* isolate, double value);
2491 V8_INLINE static Number* Cast(v8::Value* obj);
2494 static void CheckCast(v8::Value* obj);
2499 * A JavaScript value representing a signed integer.
2501 class V8_EXPORT Integer : public Number {
2503 static Local<Integer> New(Isolate* isolate, int32_t value);
2504 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2505 int64_t Value() const;
2506 V8_INLINE static Integer* Cast(v8::Value* obj);
2509 static void CheckCast(v8::Value* obj);
2514 * A JavaScript value representing a 32-bit signed integer.
2516 class V8_EXPORT Int32 : public Integer {
2518 int32_t Value() const;
2519 V8_INLINE static Int32* Cast(v8::Value* obj);
2523 static void CheckCast(v8::Value* obj);
2528 * A JavaScript value representing a 32-bit unsigned integer.
2530 class V8_EXPORT Uint32 : public Integer {
2532 uint32_t Value() const;
2533 V8_INLINE static Uint32* Cast(v8::Value* obj);
2537 static void CheckCast(v8::Value* obj);
2541 enum PropertyAttribute {
2549 * Accessor[Getter|Setter] are used as callback functions when
2550 * setting|getting a particular property. See Object and ObjectTemplate's
2551 * method SetAccessor.
2553 typedef void (*AccessorGetterCallback)(
2554 Local<String> property,
2555 const PropertyCallbackInfo<Value>& info);
2556 typedef void (*AccessorNameGetterCallback)(
2557 Local<Name> property,
2558 const PropertyCallbackInfo<Value>& info);
2561 typedef void (*AccessorSetterCallback)(
2562 Local<String> property,
2564 const PropertyCallbackInfo<void>& info);
2565 typedef void (*AccessorNameSetterCallback)(
2566 Local<Name> property,
2568 const PropertyCallbackInfo<void>& info);
2572 * Access control specifications.
2574 * Some accessors should be accessible across contexts. These
2575 * accessors have an explicit access control parameter which specifies
2576 * the kind of cross-context access that should be allowed.
2578 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2580 enum AccessControl {
2583 ALL_CAN_WRITE = 1 << 1,
2584 PROHIBITS_OVERWRITING = 1 << 2
2589 * A JavaScript object (ECMA-262, 4.3.3)
2591 class V8_EXPORT Object : public Value {
2593 V8_DEPRECATE_SOON("Use maybe version",
2594 bool Set(Local<Value> key, Local<Value> value));
2595 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
2596 Local<Value> key, Local<Value> value);
2598 V8_DEPRECATE_SOON("Use maybe version",
2599 bool Set(uint32_t index, Local<Value> value));
2600 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
2601 Local<Value> value);
2603 // Implements CreateDataProperty (ECMA-262, 7.3.4).
2605 // Defines a configurable, writable, enumerable property with the given value
2606 // on the object unless the property already exists and is not configurable
2607 // or the object is not extensible.
2609 // Returns true on success.
2610 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2612 Local<Value> value);
2613 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2615 Local<Value> value);
2617 // Implements DefineOwnProperty.
2619 // In general, CreateDataProperty will be faster, however, does not allow
2620 // for specifying attributes.
2622 // Returns true on success.
2623 V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
2624 Local<Context> context, Local<Name> key, Local<Value> value,
2625 PropertyAttribute attributes = None);
2627 // Sets an own property on this object bypassing interceptors and
2628 // overriding accessors or read-only properties.
2630 // Note that if the object has an interceptor the property will be set
2631 // locally, but since the interceptor takes precedence the local property
2632 // will only be returned if the interceptor doesn't return a value.
2634 // Note also that this only works for named properties.
2635 V8_DEPRECATE_SOON("Use CreateDataProperty",
2636 bool ForceSet(Local<Value> key, Local<Value> value,
2637 PropertyAttribute attribs = None));
2638 V8_DEPRECATE_SOON("Use CreateDataProperty",
2639 Maybe<bool> ForceSet(Local<Context> context,
2640 Local<Value> key, Local<Value> value,
2641 PropertyAttribute attribs = None));
2643 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
2644 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2647 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2648 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2652 * Gets the property attributes of a property which can be None or
2653 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2654 * None when the property doesn't exist.
2656 V8_DEPRECATE_SOON("Use maybe version",
2657 PropertyAttribute GetPropertyAttributes(Local<Value> key));
2658 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
2659 Local<Context> context, Local<Value> key);
2662 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2664 V8_DEPRECATE_SOON("Use maybe version",
2665 Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2666 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
2667 Local<Context> context, Local<String> key);
2669 V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
2670 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2673 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
2674 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2675 Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2677 V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2678 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
2680 V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2681 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2682 Maybe<bool> Delete(Local<Context> context, uint32_t index);
2684 V8_DEPRECATE_SOON("Use maybe version",
2685 bool SetAccessor(Local<String> name,
2686 AccessorGetterCallback getter,
2687 AccessorSetterCallback setter = 0,
2688 Local<Value> data = Local<Value>(),
2689 AccessControl settings = DEFAULT,
2690 PropertyAttribute attribute = None));
2691 V8_DEPRECATE_SOON("Use maybe version",
2692 bool SetAccessor(Local<Name> name,
2693 AccessorNameGetterCallback getter,
2694 AccessorNameSetterCallback setter = 0,
2695 Local<Value> data = Local<Value>(),
2696 AccessControl settings = DEFAULT,
2697 PropertyAttribute attribute = None));
2698 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2699 Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2700 AccessorNameGetterCallback getter,
2701 AccessorNameSetterCallback setter = 0,
2702 MaybeLocal<Value> data = MaybeLocal<Value>(),
2703 AccessControl settings = DEFAULT,
2704 PropertyAttribute attribute = None);
2706 void SetAccessorProperty(Local<Name> name, Local<Function> getter,
2707 Local<Function> setter = Local<Function>(),
2708 PropertyAttribute attribute = None,
2709 AccessControl settings = DEFAULT);
2712 * Returns an array containing the names of the enumerable properties
2713 * of this object, including properties from prototype objects. The
2714 * array returned by this method contains the same values as would
2715 * be enumerated by a for-in statement over this object.
2717 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2718 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
2719 Local<Context> context);
2722 * This function has the same functionality as GetPropertyNames but
2723 * the returned array doesn't contain the names of properties from
2724 * prototype objects.
2726 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2727 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
2728 Local<Context> context);
2731 * Get the prototype object. This does not skip objects marked to
2732 * be skipped by __proto__ and it does not consult the security
2735 Local<Value> GetPrototype();
2738 * Set the prototype object. This does not skip objects marked to
2739 * be skipped by __proto__ and it does not consult the security
2742 V8_DEPRECATE_SOON("Use maybe version",
2743 bool SetPrototype(Local<Value> prototype));
2744 V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
2745 Local<Value> prototype);
2748 * Finds an instance of the given function template in the prototype
2751 Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
2754 * Call builtin Object.prototype.toString on this object.
2755 * This is different from Value::ToString() that may call
2756 * user-defined toString function. This one does not.
2758 V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2759 V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
2760 Local<Context> context);
2763 * Returns the name of the function invoked as a constructor for this object.
2765 Local<String> GetConstructorName();
2767 /** Gets the number of internal fields for this Object. */
2768 int InternalFieldCount();
2770 /** Same as above, but works for Persistents */
2771 V8_INLINE static int InternalFieldCount(
2772 const PersistentBase<Object>& object) {
2773 return object.val_->InternalFieldCount();
2776 /** Gets the value from an internal field. */
2777 V8_INLINE Local<Value> GetInternalField(int index);
2779 /** Sets the value in an internal field. */
2780 void SetInternalField(int index, Local<Value> value);
2783 * Gets a 2-byte-aligned native pointer from an internal field. This field
2784 * must have been set by SetAlignedPointerInInternalField, everything else
2785 * leads to undefined behavior.
2787 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2789 /** Same as above, but works for Persistents */
2790 V8_INLINE static void* GetAlignedPointerFromInternalField(
2791 const PersistentBase<Object>& object, int index) {
2792 return object.val_->GetAlignedPointerFromInternalField(index);
2796 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2797 * a field, GetAlignedPointerFromInternalField must be used, everything else
2798 * leads to undefined behavior.
2800 void SetAlignedPointerInInternalField(int index, void* value);
2802 // Testers for local properties.
2803 V8_DEPRECATE_SOON("Use maybe version",
2804 bool HasOwnProperty(Local<String> key));
2805 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
2807 V8_DEPRECATE_SOON("Use maybe version",
2808 bool HasRealNamedProperty(Local<String> key));
2809 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
2811 V8_DEPRECATE_SOON("Use maybe version",
2812 bool HasRealIndexedProperty(uint32_t index));
2813 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
2814 Local<Context> context, uint32_t index);
2815 V8_DEPRECATE_SOON("Use maybe version",
2816 bool HasRealNamedCallbackProperty(Local<String> key));
2817 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
2818 Local<Context> context, Local<Name> key);
2821 * If result.IsEmpty() no real property was located in the prototype chain.
2822 * This means interceptors in the prototype chain are not called.
2825 "Use maybe version",
2826 Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
2827 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
2828 Local<Context> context, Local<Name> key);
2831 * Gets the property attributes of a real property in the prototype chain,
2832 * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2833 * Interceptors in the prototype chain are not called.
2836 "Use maybe version",
2837 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2838 Local<String> key));
2839 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
2840 GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
2844 * If result.IsEmpty() no real property was located on the object or
2845 * in the prototype chain.
2846 * This means interceptors in the prototype chain are not called.
2848 V8_DEPRECATE_SOON("Use maybe version",
2849 Local<Value> GetRealNamedProperty(Local<String> key));
2850 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
2851 Local<Context> context, Local<Name> key);
2854 * Gets the property attributes of a real property which can be
2855 * None or any combination of ReadOnly, DontEnum and DontDelete.
2856 * Interceptors in the prototype chain are not called.
2858 V8_DEPRECATE_SOON("Use maybe version",
2859 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2860 Local<String> key));
2861 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2862 Local<Context> context, Local<Name> key);
2864 /** Tests for a named lookup interceptor.*/
2865 bool HasNamedLookupInterceptor();
2867 /** Tests for an index lookup interceptor.*/
2868 bool HasIndexedLookupInterceptor();
2871 * Returns the identity hash for this object. The current implementation
2872 * uses a hidden property on the object to store the identity hash.
2874 * The return value will never be 0. Also, it is not guaranteed to be
2877 int GetIdentityHash();
2880 * Access hidden properties on JavaScript objects. These properties are
2881 * hidden from the executing JavaScript and only accessible through the V8
2882 * C++ API. Hidden properties introduced by V8 internally (for example the
2883 * identity hash) are prefixed with "v8::".
2885 // TODO(dcarney): convert these to take a isolate and optionally bailout?
2886 bool SetHiddenValue(Local<String> key, Local<Value> value);
2887 Local<Value> GetHiddenValue(Local<String> key);
2888 bool DeleteHiddenValue(Local<String> key);
2891 * Clone this object with a fast but shallow copy. Values will point
2892 * to the same values as the original object.
2894 // TODO(dcarney): take an isolate and optionally bail out?
2895 Local<Object> Clone();
2898 * Returns the context in which the object was created.
2900 Local<Context> CreationContext();
2903 * Checks whether a callback is set by the
2904 * ObjectTemplate::SetCallAsFunctionHandler method.
2905 * When an Object is callable this method returns true.
2910 * Call an Object as a function if a callback is set by the
2911 * ObjectTemplate::SetCallAsFunctionHandler method.
2913 V8_DEPRECATE_SOON("Use maybe version",
2914 Local<Value> CallAsFunction(Local<Value> recv, int argc,
2915 Local<Value> argv[]));
2916 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
2919 Local<Value> argv[]);
2922 * Call an Object as a constructor if a callback is set by the
2923 * ObjectTemplate::SetCallAsFunctionHandler method.
2924 * Note: This method behaves like the Function::NewInstance method.
2926 V8_DEPRECATE_SOON("Use maybe version",
2927 Local<Value> CallAsConstructor(int argc,
2928 Local<Value> argv[]));
2929 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
2930 Local<Context> context, int argc, Local<Value> argv[]);
2933 * Return the isolate to which the Object belongs to.
2935 V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
2937 static Local<Object> New(Isolate* isolate);
2939 V8_INLINE static Object* Cast(Value* obj);
2943 static void CheckCast(Value* obj);
2944 Local<Value> SlowGetInternalField(int index);
2945 void* SlowGetAlignedPointerFromInternalField(int index);
2950 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2952 class V8_EXPORT Array : public Object {
2954 uint32_t Length() const;
2957 * Clones an element at index |index|. Returns an empty
2958 * handle if cloning fails (for any reason).
2960 V8_DEPRECATE_SOON("Use maybe version",
2961 Local<Object> CloneElementAt(uint32_t index));
2962 V8_WARN_UNUSED_RESULT MaybeLocal<Object> CloneElementAt(
2963 Local<Context> context, uint32_t index);
2966 * Creates a JavaScript array with the given length. If the length
2967 * is negative the returned array will have length 0.
2969 static Local<Array> New(Isolate* isolate, int length = 0);
2971 V8_INLINE static Array* Cast(Value* obj);
2974 static void CheckCast(Value* obj);
2979 * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
2981 class V8_EXPORT Map : public Object {
2983 size_t Size() const;
2985 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2987 V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
2989 Local<Value> value);
2990 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2992 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
2996 * Returns an array of length Size() * 2, where index N is the Nth key and
2997 * index N + 1 is the Nth value.
2999 Local<Array> AsArray() const;
3002 * Creates a new empty Map.
3004 static Local<Map> New(Isolate* isolate);
3007 * Creates a new Map containing the elements of array, which must be formatted
3008 * in the same manner as the array returned from AsArray().
3009 * Guaranteed to be side-effect free if the array contains no holes.
3011 static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3012 "Use mutation methods instead",
3013 MaybeLocal<Map> FromArray(Local<Context> context, Local<Array> array));
3015 V8_INLINE static Map* Cast(Value* obj);
3019 static void CheckCast(Value* obj);
3024 * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3026 class V8_EXPORT Set : public Object {
3028 size_t Size() const;
3030 V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3032 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3034 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3038 * Returns an array of the keys in this Set.
3040 Local<Array> AsArray() const;
3043 * Creates a new empty Set.
3045 static Local<Set> New(Isolate* isolate);
3048 * Creates a new Set containing the items in array.
3049 * Guaranteed to be side-effect free if the array contains no holes.
3051 static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3052 "Use mutation methods instead",
3053 MaybeLocal<Set> FromArray(Local<Context> context, Local<Array> array));
3055 V8_INLINE static Set* Cast(Value* obj);
3059 static void CheckCast(Value* obj);
3063 template<typename T>
3066 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3067 : value_(that.value_) {
3071 template <typename S>
3072 V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3073 void Set(const Persistent<S>& handle));
3074 template <typename S>
3075 V8_INLINE void Set(const Global<S>& handle);
3076 template <typename S>
3077 V8_INLINE void Set(const Local<S> handle);
3078 // Fast primitive setters
3079 V8_INLINE void Set(bool value);
3080 V8_INLINE void Set(double i);
3081 V8_INLINE void Set(int32_t i);
3082 V8_INLINE void Set(uint32_t i);
3083 // Fast JS primitive setters
3084 V8_INLINE void SetNull();
3085 V8_INLINE void SetUndefined();
3086 V8_INLINE void SetEmptyString();
3087 // Convenience getter for Isolate
3088 V8_INLINE Isolate* GetIsolate();
3090 // Pointer setter: Uncompilable to prevent inadvertent misuse.
3091 template <typename S>
3092 V8_INLINE void Set(S* whatever);
3095 template<class F> friend class ReturnValue;
3096 template<class F> friend class FunctionCallbackInfo;
3097 template<class F> friend class PropertyCallbackInfo;
3098 template <class F, class G, class H>
3099 friend class PersistentValueMapBase;
3100 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3101 V8_INLINE internal::Object* GetDefaultValue();
3102 V8_INLINE explicit ReturnValue(internal::Object** slot);
3103 internal::Object** value_;
3108 * The argument information given to function call callbacks. This
3109 * class provides access to information about the context of the call,
3110 * including the receiver, the number and values of arguments, and
3111 * the holder of the function.
3113 template<typename T>
3114 class FunctionCallbackInfo {
3116 V8_INLINE int Length() const;
3117 V8_INLINE Local<Value> operator[](int i) const;
3118 V8_INLINE Local<Function> Callee() const;
3119 V8_INLINE Local<Object> This() const;
3120 V8_INLINE Local<Object> Holder() const;
3121 V8_INLINE bool IsConstructCall() const;
3122 V8_INLINE Local<Value> Data() const;
3123 V8_INLINE Isolate* GetIsolate() const;
3124 V8_INLINE ReturnValue<T> GetReturnValue() const;
3125 // This shouldn't be public, but the arm compiler needs it.
3126 static const int kArgsLength = 7;
3129 friend class internal::FunctionCallbackArguments;
3130 friend class internal::CustomArguments<FunctionCallbackInfo>;
3131 static const int kHolderIndex = 0;
3132 static const int kIsolateIndex = 1;
3133 static const int kReturnValueDefaultValueIndex = 2;
3134 static const int kReturnValueIndex = 3;
3135 static const int kDataIndex = 4;
3136 static const int kCalleeIndex = 5;
3137 static const int kContextSaveIndex = 6;
3139 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3140 internal::Object** values,
3142 bool is_construct_call);
3143 internal::Object** implicit_args_;
3144 internal::Object** values_;
3146 int is_construct_call_;
3151 * The information passed to a property callback about the context
3152 * of the property access.
3154 template<typename T>
3155 class PropertyCallbackInfo {
3157 V8_INLINE Isolate* GetIsolate() const;
3158 V8_INLINE Local<Value> Data() const;
3159 V8_INLINE Local<Object> This() const;
3160 V8_INLINE Local<Object> Holder() const;
3161 V8_INLINE ReturnValue<T> GetReturnValue() const;
3162 // This shouldn't be public, but the arm compiler needs it.
3163 static const int kArgsLength = 6;
3166 friend class MacroAssembler;
3167 friend class internal::PropertyCallbackArguments;
3168 friend class internal::CustomArguments<PropertyCallbackInfo>;
3169 static const int kHolderIndex = 0;
3170 static const int kIsolateIndex = 1;
3171 static const int kReturnValueDefaultValueIndex = 2;
3172 static const int kReturnValueIndex = 3;
3173 static const int kDataIndex = 4;
3174 static const int kThisIndex = 5;
3176 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3177 internal::Object** args_;
3181 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3185 * A JavaScript function object (ECMA-262, 15.3).
3187 class V8_EXPORT Function : public Object {
3190 * Create a function in the current execution context
3191 * for a given FunctionCallback.
3193 static MaybeLocal<Function> New(Local<Context> context,
3194 FunctionCallback callback,
3195 Local<Value> data = Local<Value>(),
3197 static V8_DEPRECATE_SOON(
3198 "Use maybe version",
3199 Local<Function> New(Isolate* isolate, FunctionCallback callback,
3200 Local<Value> data = Local<Value>(), int length = 0));
3202 V8_DEPRECATE_SOON("Use maybe version",
3203 Local<Object> NewInstance(int argc, Local<Value> argv[])
3205 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3206 Local<Context> context, int argc, Local<Value> argv[]) const;
3208 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance() const);
3209 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3210 Local<Context> context) const {
3211 return NewInstance(context, 0, nullptr);
3214 V8_DEPRECATE_SOON("Use maybe version",
3215 Local<Value> Call(Local<Value> recv, int argc,
3216 Local<Value> argv[]));
3217 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
3218 Local<Value> recv, int argc,
3219 Local<Value> argv[]);
3221 void SetName(Local<String> name);
3222 Local<Value> GetName() const;
3225 * Name inferred from variable or property assignment of this function.
3226 * Used to facilitate debugging and profiling of JavaScript code written
3227 * in an OO style, where many functions are anonymous but are assigned
3228 * to object properties.
3230 Local<Value> GetInferredName() const;
3233 * User-defined name assigned to the "displayName" property of this function.
3234 * Used to facilitate debugging and profiling of JavaScript code.
3236 Local<Value> GetDisplayName() const;
3239 * Returns zero based line number of function body and
3240 * kLineOffsetNotFound if no information available.
3242 int GetScriptLineNumber() const;
3244 * Returns zero based column number of function body and
3245 * kLineOffsetNotFound if no information available.
3247 int GetScriptColumnNumber() const;
3250 * Tells whether this function is builtin.
3252 bool IsBuiltin() const;
3257 int ScriptId() const;
3260 * Returns the original function if this function is bound, else returns
3263 Local<Value> GetBoundFunction() const;
3265 ScriptOrigin GetScriptOrigin() const;
3266 V8_INLINE static Function* Cast(Value* obj);
3267 static const int kLineOffsetNotFound;
3271 static void CheckCast(Value* obj);
3276 * An instance of the built-in Promise constructor (ES6 draft).
3277 * This API is experimental. Only works with --harmony flag.
3279 class V8_EXPORT Promise : public Object {
3281 class V8_EXPORT Resolver : public Object {
3284 * Create a new resolver, along with an associated promise in pending state.
3286 static V8_DEPRECATE_SOON("Use maybe version",
3287 Local<Resolver> New(Isolate* isolate));
3288 static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
3289 Local<Context> context);
3292 * Extract the associated promise.
3294 Local<Promise> GetPromise();
3297 * Resolve/reject the associated promise with a given value.
3298 * Ignored if the promise is no longer pending.
3300 V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3301 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3302 Maybe<bool> Resolve(Local<Context> context, Local<Value> value);
3304 V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3305 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3306 Maybe<bool> Reject(Local<Context> context, Local<Value> value);
3308 V8_INLINE static Resolver* Cast(Value* obj);
3312 static void CheckCast(Value* obj);
3316 * Register a resolution/rejection handler with a promise.
3317 * The handler is given the respective resolution/rejection value as
3318 * an argument. If the promise is already resolved/rejected, the handler is
3319 * invoked at the end of turn.
3321 V8_DEPRECATE_SOON("Use maybe version",
3322 Local<Promise> Chain(Local<Function> handler));
3323 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Chain(Local<Context> context,
3324 Local<Function> handler);
3326 V8_DEPRECATE_SOON("Use maybe version",
3327 Local<Promise> Catch(Local<Function> handler));
3328 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
3329 Local<Function> handler);
3331 V8_DEPRECATE_SOON("Use maybe version",
3332 Local<Promise> Then(Local<Function> handler));
3333 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
3334 Local<Function> handler);
3337 * Returns true if the promise has at least one derived promise, and
3338 * therefore resolve/reject handlers (including default handler).
3342 V8_INLINE static Promise* Cast(Value* obj);
3346 static void CheckCast(Value* obj);
3350 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3351 // The number of required internal fields can be defined by embedder.
3352 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3356 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
3360 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3361 * This API is experimental and may change significantly.
3363 class V8_EXPORT ArrayBuffer : public Object {
3366 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3367 * The allocator is a global V8 setting. It has to be set via
3368 * Isolate::CreateParams.
3370 * This API is experimental and may change significantly.
3372 class V8_EXPORT Allocator { // NOLINT
3374 virtual ~Allocator() {}
3377 * Allocate |length| bytes. Return NULL if allocation is not successful.
3378 * Memory should be initialized to zeroes.
3380 virtual void* Allocate(size_t length) = 0;
3383 * Allocate |length| bytes. Return NULL if allocation is not successful.
3384 * Memory does not have to be initialized.
3386 virtual void* AllocateUninitialized(size_t length) = 0;
3388 * Free the memory block of size |length|, pointed to by |data|.
3389 * That memory is guaranteed to be previously allocated by |Allocate|.
3391 virtual void Free(void* data, size_t length) = 0;
3395 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3396 * returns an instance of this class, populated, with a pointer to data
3399 * The Data pointer of ArrayBuffer::Contents is always allocated with
3400 * Allocator::Allocate that is set via Isolate::CreateParams.
3402 * This API is experimental and may change significantly.
3404 class V8_EXPORT Contents { // NOLINT
3406 Contents() : data_(NULL), byte_length_(0) {}
3408 void* Data() const { return data_; }
3409 size_t ByteLength() const { return byte_length_; }
3413 size_t byte_length_;
3415 friend class ArrayBuffer;
3420 * Data length in bytes.
3422 size_t ByteLength() const;
3425 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3426 * Allocated memory will be owned by a created ArrayBuffer and
3427 * will be deallocated when it is garbage-collected,
3428 * unless the object is externalized.
3430 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3433 * Create a new ArrayBuffer over an existing memory block.
3434 * The created array buffer is by default immediately in externalized state.
3435 * The memory block will not be reclaimed when a created ArrayBuffer
3436 * is garbage-collected.
3438 static Local<ArrayBuffer> New(
3439 Isolate* isolate, void* data, size_t byte_length,
3440 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3443 * Returns true if ArrayBuffer is externalized, that is, does not
3444 * own its memory block.
3446 bool IsExternal() const;
3449 * Returns true if this ArrayBuffer may be neutered.
3451 bool IsNeuterable() const;
3454 * Neuters this ArrayBuffer and all its views (typed arrays).
3455 * Neutering sets the byte length of the buffer and all typed arrays to zero,
3456 * preventing JavaScript from ever accessing underlying backing store.
3457 * ArrayBuffer should have been externalized and must be neuterable.
3462 * Make this ArrayBuffer external. The pointer to underlying memory block
3463 * and byte length are returned as |Contents| structure. After ArrayBuffer
3464 * had been etxrenalized, it does no longer owns the memory block. The caller
3465 * should take steps to free memory when it is no longer needed.
3467 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3468 * that has been set via Isolate::CreateParams.
3470 Contents Externalize();
3473 * Get a pointer to the ArrayBuffer's underlying memory block without
3474 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3475 * will become invalid as soon as the ArrayBuffer became garbage collected.
3477 * The embedder should make sure to hold a strong reference to the
3478 * ArrayBuffer while accessing this pointer.
3480 * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3482 Contents GetContents();
3484 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3486 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3490 static void CheckCast(Value* obj);
3494 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3495 // The number of required internal fields can be defined by embedder.
3496 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3501 * A base class for an instance of one of "views" over ArrayBuffer,
3502 * including TypedArrays and DataView (ES6 draft 15.13).
3504 * This API is experimental and may change significantly.
3506 class V8_EXPORT ArrayBufferView : public Object {
3509 * Returns underlying ArrayBuffer.
3511 Local<ArrayBuffer> Buffer();
3513 * Byte offset in |Buffer|.
3515 size_t ByteOffset();
3517 * Size of a view in bytes.
3519 size_t ByteLength();
3522 * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3523 * memory without additional overhead that calling ArrayBufferView::Buffer
3526 * Will write at most min(|byte_length|, ByteLength) bytes starting at
3527 * ByteOffset of the underling buffer to the memory starting at |dest|.
3528 * Returns the number of bytes actually written.
3530 size_t CopyContents(void* dest, size_t byte_length);
3533 * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3536 bool HasBuffer() const;
3538 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3540 static const int kInternalFieldCount =
3541 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3545 static void CheckCast(Value* obj);
3550 * A base class for an instance of TypedArray series of constructors
3551 * (ES6 draft 15.13.6).
3552 * This API is experimental and may change significantly.
3554 class V8_EXPORT TypedArray : public ArrayBufferView {
3557 * Number of elements in this typed array
3558 * (e.g. for Int16Array, |ByteLength|/2).
3562 V8_INLINE static TypedArray* Cast(Value* obj);
3566 static void CheckCast(Value* obj);
3571 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3572 * This API is experimental and may change significantly.
3574 class V8_EXPORT Uint8Array : public TypedArray {
3576 static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
3577 size_t byte_offset, size_t length);
3578 static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3579 size_t byte_offset, size_t length);
3580 V8_INLINE static Uint8Array* Cast(Value* obj);
3584 static void CheckCast(Value* obj);
3589 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3590 * This API is experimental and may change significantly.
3592 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3594 static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
3595 size_t byte_offset, size_t length);
3596 static Local<Uint8ClampedArray> New(
3597 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
3599 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3602 Uint8ClampedArray();
3603 static void CheckCast(Value* obj);
3607 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3608 * This API is experimental and may change significantly.
3610 class V8_EXPORT Int8Array : public TypedArray {
3612 static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
3613 size_t byte_offset, size_t length);
3614 static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3615 size_t byte_offset, size_t length);
3616 V8_INLINE static Int8Array* Cast(Value* obj);
3620 static void CheckCast(Value* obj);
3625 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3626 * This API is experimental and may change significantly.
3628 class V8_EXPORT Uint16Array : public TypedArray {
3630 static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
3631 size_t byte_offset, size_t length);
3632 static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3633 size_t byte_offset, size_t length);
3634 V8_INLINE static Uint16Array* Cast(Value* obj);
3638 static void CheckCast(Value* obj);
3643 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3644 * This API is experimental and may change significantly.
3646 class V8_EXPORT Int16Array : public TypedArray {
3648 static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
3649 size_t byte_offset, size_t length);
3650 static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3651 size_t byte_offset, size_t length);
3652 V8_INLINE static Int16Array* Cast(Value* obj);
3656 static void CheckCast(Value* obj);
3661 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3662 * This API is experimental and may change significantly.
3664 class V8_EXPORT Uint32Array : public TypedArray {
3666 static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
3667 size_t byte_offset, size_t length);
3668 static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3669 size_t byte_offset, size_t length);
3670 V8_INLINE static Uint32Array* Cast(Value* obj);
3674 static void CheckCast(Value* obj);
3679 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3680 * This API is experimental and may change significantly.
3682 class V8_EXPORT Int32Array : public TypedArray {
3684 static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
3685 size_t byte_offset, size_t length);
3686 static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3687 size_t byte_offset, size_t length);
3688 V8_INLINE static Int32Array* Cast(Value* obj);
3692 static void CheckCast(Value* obj);
3697 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3698 * This API is experimental and may change significantly.
3700 class V8_EXPORT Float32Array : public TypedArray {
3702 static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
3703 size_t byte_offset, size_t length);
3704 static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3705 size_t byte_offset, size_t length);
3706 V8_INLINE static Float32Array* Cast(Value* obj);
3710 static void CheckCast(Value* obj);
3715 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3716 * This API is experimental and may change significantly.
3718 class V8_EXPORT Float64Array : public TypedArray {
3720 static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
3721 size_t byte_offset, size_t length);
3722 static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3723 size_t byte_offset, size_t length);
3724 V8_INLINE static Float64Array* Cast(Value* obj);
3728 static void CheckCast(Value* obj);
3733 * An instance of DataView constructor (ES6 draft 15.13.7).
3734 * This API is experimental and may change significantly.
3736 class V8_EXPORT DataView : public ArrayBufferView {
3738 static Local<DataView> New(Local<ArrayBuffer> array_buffer,
3739 size_t byte_offset, size_t length);
3740 static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
3741 size_t byte_offset, size_t length);
3742 V8_INLINE static DataView* Cast(Value* obj);
3746 static void CheckCast(Value* obj);
3751 * An instance of the built-in SharedArrayBuffer constructor.
3752 * This API is experimental and may change significantly.
3754 class V8_EXPORT SharedArrayBuffer : public Object {
3757 * The contents of an |SharedArrayBuffer|. Externalization of
3758 * |SharedArrayBuffer| returns an instance of this class, populated, with a
3759 * pointer to data and byte length.
3761 * The Data pointer of SharedArrayBuffer::Contents is always allocated with
3762 * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
3763 * v8::Isolate::CreateParams::array_buffer_allocator.
3765 * This API is experimental and may change significantly.
3767 class V8_EXPORT Contents { // NOLINT
3769 Contents() : data_(NULL), byte_length_(0) {}
3771 void* Data() const { return data_; }
3772 size_t ByteLength() const { return byte_length_; }
3776 size_t byte_length_;
3778 friend class SharedArrayBuffer;
3783 * Data length in bytes.
3785 size_t ByteLength() const;
3788 * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
3789 * Allocated memory will be owned by a created SharedArrayBuffer and
3790 * will be deallocated when it is garbage-collected,
3791 * unless the object is externalized.
3793 static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
3796 * Create a new SharedArrayBuffer over an existing memory block. The created
3797 * array buffer is immediately in externalized state unless otherwise
3798 * specified. The memory block will not be reclaimed when a created
3799 * SharedArrayBuffer is garbage-collected.
3801 static Local<SharedArrayBuffer> New(
3802 Isolate* isolate, void* data, size_t byte_length,
3803 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3806 * Returns true if SharedArrayBuffer is externalized, that is, does not
3807 * own its memory block.
3809 bool IsExternal() const;
3812 * Make this SharedArrayBuffer external. The pointer to underlying memory
3813 * block and byte length are returned as |Contents| structure. After
3814 * SharedArrayBuffer had been etxrenalized, it does no longer owns the memory
3815 * block. The caller should take steps to free memory when it is no longer
3818 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3819 * by the allocator specified in
3820 * v8::Isolate::CreateParams::array_buffer_allocator.
3823 Contents Externalize();
3826 * Get a pointer to the ArrayBuffer's underlying memory block without
3827 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3828 * will become invalid as soon as the ArrayBuffer became garbage collected.
3830 * The embedder should make sure to hold a strong reference to the
3831 * ArrayBuffer while accessing this pointer.
3833 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3834 * by the allocator specified in
3835 * v8::Isolate::CreateParams::array_buffer_allocator.
3837 Contents GetContents();
3839 V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
3841 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3844 SharedArrayBuffer();
3845 static void CheckCast(Value* obj);
3850 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3852 class V8_EXPORT Date : public Object {
3854 static V8_DEPRECATE_SOON("Use maybe version.",
3855 Local<Value> New(Isolate* isolate, double time));
3856 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
3860 * A specialization of Value::NumberValue that is more efficient
3861 * because we know the structure of this object.
3863 double ValueOf() const;
3865 V8_INLINE static Date* Cast(v8::Value* obj);
3868 * Notification that the embedder has changed the time zone,
3869 * daylight savings time, or other date / time configuration
3870 * parameters. V8 keeps a cache of various values used for
3871 * date / time computation. This notification will reset
3872 * those cached values for the current context so that date /
3873 * time configuration changes would be reflected in the Date
3876 * This API should not be called more than needed as it will
3877 * negatively impact the performance of date operations.
3879 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3882 static void CheckCast(v8::Value* obj);
3887 * A Number object (ECMA-262, 4.3.21).
3889 class V8_EXPORT NumberObject : public Object {
3891 static Local<Value> New(Isolate* isolate, double value);
3893 double ValueOf() const;
3895 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3898 static void CheckCast(v8::Value* obj);
3903 * A Boolean object (ECMA-262, 4.3.15).
3905 class V8_EXPORT BooleanObject : public Object {
3907 static Local<Value> New(bool value);
3909 bool ValueOf() const;
3911 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3914 static void CheckCast(v8::Value* obj);
3919 * A String object (ECMA-262, 4.3.18).
3921 class V8_EXPORT StringObject : public Object {
3923 static Local<Value> New(Local<String> value);
3925 Local<String> ValueOf() const;
3927 V8_INLINE static StringObject* Cast(v8::Value* obj);
3930 static void CheckCast(v8::Value* obj);
3935 * A Symbol object (ECMA-262 edition 6).
3937 * This is an experimental feature. Use at your own risk.
3939 class V8_EXPORT SymbolObject : public Object {
3941 static Local<Value> New(Isolate* isolate, Local<Symbol> value);
3943 Local<Symbol> ValueOf() const;
3945 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3948 static void CheckCast(v8::Value* obj);
3953 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3955 class V8_EXPORT RegExp : public Object {
3958 * Regular expression flag bits. They can be or'ed to enable a set
3969 * Creates a regular expression from the given pattern string and
3970 * the flags bit field. May throw a JavaScript exception as
3971 * described in ECMA-262, 15.10.4.1.
3974 * RegExp::New(v8::String::New("foo"),
3975 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3976 * is equivalent to evaluating "/foo/gm".
3978 static V8_DEPRECATE_SOON("Use maybe version",
3979 Local<RegExp> New(Local<String> pattern,
3981 static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
3982 Local<String> pattern,
3986 * Returns the value of the source property: a string representing
3987 * the regular expression.
3989 Local<String> GetSource() const;
3992 * Returns the flags bit field.
3994 Flags GetFlags() const;
3996 V8_INLINE static RegExp* Cast(v8::Value* obj);
3999 static void CheckCast(v8::Value* obj);
4004 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
4005 * to associate C++ data structures with JavaScript objects.
4007 class V8_EXPORT External : public Value {
4009 static Local<External> New(Isolate* isolate, void* value);
4010 V8_INLINE static External* Cast(Value* obj);
4011 void* Value() const;
4013 static void CheckCast(v8::Value* obj);
4017 // --- Templates ---
4021 * The superclass of object and function templates.
4023 class V8_EXPORT Template : public Data {
4025 /** Adds a property to each instance created by this template.*/
4026 void Set(Local<Name> name, Local<Data> value,
4027 PropertyAttribute attributes = None);
4028 V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
4030 void SetAccessorProperty(
4032 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
4033 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
4034 PropertyAttribute attribute = None,
4035 AccessControl settings = DEFAULT);
4038 * Whenever the property with the given name is accessed on objects
4039 * created from this Template the getter and setter callbacks
4040 * are called instead of getting and setting the property directly
4041 * on the JavaScript object.
4043 * \param name The name of the property for which an accessor is added.
4044 * \param getter The callback to invoke when getting the property.
4045 * \param setter The callback to invoke when setting the property.
4046 * \param data A piece of data that will be passed to the getter and setter
4047 * callbacks whenever they are invoked.
4048 * \param settings Access control settings for the accessor. This is a bit
4049 * field consisting of one of more of
4050 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4051 * The default is to not allow cross-context access.
4052 * ALL_CAN_READ means that all cross-context reads are allowed.
4053 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4054 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4055 * cross-context access.
4056 * \param attribute The attributes of the property for which an accessor
4058 * \param signature The signature describes valid receivers for the accessor
4059 * and is used to perform implicit instance checks against them. If the
4060 * receiver is incompatible (i.e. is not an instance of the constructor as
4061 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4062 * thrown and no callback is invoked.
4064 void SetNativeDataProperty(
4065 Local<String> name, AccessorGetterCallback getter,
4066 AccessorSetterCallback setter = 0,
4067 // TODO(dcarney): gcc can't handle Local below
4068 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4069 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4070 AccessControl settings = DEFAULT);
4071 void SetNativeDataProperty(
4072 Local<Name> name, AccessorNameGetterCallback getter,
4073 AccessorNameSetterCallback setter = 0,
4074 // TODO(dcarney): gcc can't handle Local below
4075 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4076 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4077 AccessControl settings = DEFAULT);
4082 friend class ObjectTemplate;
4083 friend class FunctionTemplate;
4088 * NamedProperty[Getter|Setter] are used as interceptors on object.
4089 * See ObjectTemplate::SetNamedPropertyHandler.
4091 typedef void (*NamedPropertyGetterCallback)(
4092 Local<String> property,
4093 const PropertyCallbackInfo<Value>& info);
4097 * Returns the value if the setter intercepts the request.
4098 * Otherwise, returns an empty handle.
4100 typedef void (*NamedPropertySetterCallback)(
4101 Local<String> property,
4103 const PropertyCallbackInfo<Value>& info);
4107 * Returns a non-empty handle if the interceptor intercepts the request.
4108 * The result is an integer encoding property attributes (like v8::None,
4109 * v8::DontEnum, etc.)
4111 typedef void (*NamedPropertyQueryCallback)(
4112 Local<String> property,
4113 const PropertyCallbackInfo<Integer>& info);
4117 * Returns a non-empty handle if the deleter intercepts the request.
4118 * The return value is true if the property could be deleted and false
4121 typedef void (*NamedPropertyDeleterCallback)(
4122 Local<String> property,
4123 const PropertyCallbackInfo<Boolean>& info);
4127 * Returns an array containing the names of the properties the named
4128 * property getter intercepts.
4130 typedef void (*NamedPropertyEnumeratorCallback)(
4131 const PropertyCallbackInfo<Array>& info);
4134 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
4135 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
4137 * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
4138 * See ObjectTemplate::SetNamedPropertyHandler.
4140 typedef void (*GenericNamedPropertyGetterCallback)(
4141 Local<Name> property, const PropertyCallbackInfo<Value>& info);
4145 * Returns the value if the setter intercepts the request.
4146 * Otherwise, returns an empty handle.
4148 typedef void (*GenericNamedPropertySetterCallback)(
4149 Local<Name> property, Local<Value> value,
4150 const PropertyCallbackInfo<Value>& info);
4154 * Returns a non-empty handle if the interceptor intercepts the request.
4155 * The result is an integer encoding property attributes (like v8::None,
4156 * v8::DontEnum, etc.)
4158 typedef void (*GenericNamedPropertyQueryCallback)(
4159 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4163 * Returns a non-empty handle if the deleter intercepts the request.
4164 * The return value is true if the property could be deleted and false
4167 typedef void (*GenericNamedPropertyDeleterCallback)(
4168 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4172 * Returns an array containing the names of the properties the named
4173 * property getter intercepts.
4175 typedef void (*GenericNamedPropertyEnumeratorCallback)(
4176 const PropertyCallbackInfo<Array>& info);
4180 * Returns the value of the property if the getter intercepts the
4181 * request. Otherwise, returns an empty handle.
4183 typedef void (*IndexedPropertyGetterCallback)(
4185 const PropertyCallbackInfo<Value>& info);
4189 * Returns the value if the setter intercepts the request.
4190 * Otherwise, returns an empty handle.
4192 typedef void (*IndexedPropertySetterCallback)(
4195 const PropertyCallbackInfo<Value>& info);
4199 * Returns a non-empty handle if the interceptor intercepts the request.
4200 * The result is an integer encoding property attributes.
4202 typedef void (*IndexedPropertyQueryCallback)(
4204 const PropertyCallbackInfo<Integer>& info);
4208 * Returns a non-empty handle if the deleter intercepts the request.
4209 * The return value is true if the property could be deleted and false
4212 typedef void (*IndexedPropertyDeleterCallback)(
4214 const PropertyCallbackInfo<Boolean>& info);
4218 * Returns an array containing the indices of the properties the
4219 * indexed property getter intercepts.
4221 typedef void (*IndexedPropertyEnumeratorCallback)(
4222 const PropertyCallbackInfo<Array>& info);
4226 * Access type specification.
4238 * Returns true if cross-context access should be allowed to the named
4239 * property with the given key on the host object.
4241 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4248 * Returns true if cross-context access should be allowed to the indexed
4249 * property with the given index on the host object.
4251 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4258 * A FunctionTemplate is used to create functions at runtime. There
4259 * can only be one function created from a FunctionTemplate in a
4260 * context. The lifetime of the created function is equal to the
4261 * lifetime of the context. So in case the embedder needs to create
4262 * temporary functions that can be collected using Scripts is
4265 * Any modification of a FunctionTemplate after first instantiation will trigger
4268 * A FunctionTemplate can have properties, these properties are added to the
4269 * function object when it is created.
4271 * A FunctionTemplate has a corresponding instance template which is
4272 * used to create object instances when the function is used as a
4273 * constructor. Properties added to the instance template are added to
4274 * each object instance.
4276 * A FunctionTemplate can have a prototype template. The prototype template
4277 * is used to create the prototype object of the function.
4279 * The following example shows how to use a FunctionTemplate:
4282 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4283 * t->Set("func_property", v8::Number::New(1));
4285 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4286 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4287 * proto_t->Set("proto_const", v8::Number::New(2));
4289 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4290 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4291 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4292 * instance_t->Set("instance_property", Number::New(3));
4294 * v8::Local<v8::Function> function = t->GetFunction();
4295 * v8::Local<v8::Object> instance = function->NewInstance();
4298 * Let's use "function" as the JS variable name of the function object
4299 * and "instance" for the instance object created above. The function
4300 * and the instance will have the following properties:
4303 * func_property in function == true;
4304 * function.func_property == 1;
4306 * function.prototype.proto_method() invokes 'InvokeCallback'
4307 * function.prototype.proto_const == 2;
4309 * instance instanceof function == true;
4310 * instance.instance_accessor calls 'InstanceAccessorCallback'
4311 * instance.instance_property == 3;
4314 * A FunctionTemplate can inherit from another one by calling the
4315 * FunctionTemplate::Inherit method. The following graph illustrates
4316 * the semantics of inheritance:
4319 * FunctionTemplate Parent -> Parent() . prototype -> { }
4321 * | Inherit(Parent) | .__proto__
4323 * FunctionTemplate Child -> Child() . prototype -> { }
4326 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4327 * object of the Child() function has __proto__ pointing to the
4328 * Parent() function's prototype object. An instance of the Child
4329 * function has all properties on Parent's instance templates.
4331 * Let Parent be the FunctionTemplate initialized in the previous
4332 * section and create a Child FunctionTemplate by:
4335 * Local<FunctionTemplate> parent = t;
4336 * Local<FunctionTemplate> child = FunctionTemplate::New();
4337 * child->Inherit(parent);
4339 * Local<Function> child_function = child->GetFunction();
4340 * Local<Object> child_instance = child_function->NewInstance();
4343 * The Child function and Child instance will have the following
4347 * child_func.prototype.__proto__ == function.prototype;
4348 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
4349 * child_instance.instance_property == 3;
4352 class V8_EXPORT FunctionTemplate : public Template {
4354 /** Creates a function template.*/
4355 static Local<FunctionTemplate> New(
4356 Isolate* isolate, FunctionCallback callback = 0,
4357 Local<Value> data = Local<Value>(),
4358 Local<Signature> signature = Local<Signature>(), int length = 0);
4360 /** Returns the unique function instance in the current execution context.*/
4361 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4362 V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
4363 Local<Context> context);
4366 * Set the call-handler callback for a FunctionTemplate. This
4367 * callback is called whenever the function created from this
4368 * FunctionTemplate is called.
4370 void SetCallHandler(FunctionCallback callback,
4371 Local<Value> data = Local<Value>());
4373 /** Set the predefined length property for the FunctionTemplate. */
4374 void SetLength(int length);
4376 /** Get the InstanceTemplate. */
4377 Local<ObjectTemplate> InstanceTemplate();
4379 /** Causes the function template to inherit from a parent function template.*/
4380 void Inherit(Local<FunctionTemplate> parent);
4383 * A PrototypeTemplate is the template used to create the prototype object
4384 * of the function created by this template.
4386 Local<ObjectTemplate> PrototypeTemplate();
4389 * Set the class name of the FunctionTemplate. This is used for
4390 * printing objects created with the function created from the
4391 * FunctionTemplate as its constructor.
4393 void SetClassName(Local<String> name);
4397 * When set to true, no access check will be performed on the receiver of a
4398 * function call. Currently defaults to true, but this is subject to change.
4400 void SetAcceptAnyReceiver(bool value);
4403 * Determines whether the __proto__ accessor ignores instances of
4404 * the function template. If instances of the function template are
4405 * ignored, __proto__ skips all instances and instead returns the
4406 * next object in the prototype chain.
4408 * Call with a value of true to make the __proto__ accessor ignore
4409 * instances of the function template. Call with a value of false
4410 * to make the __proto__ accessor not ignore instances of the
4411 * function template. By default, instances of a function template
4414 void SetHiddenPrototype(bool value);
4417 * Sets the ReadOnly flag in the attributes of the 'prototype' property
4418 * of functions created from this FunctionTemplate to true.
4420 void ReadOnlyPrototype();
4423 * Removes the prototype property from functions created from this
4426 void RemovePrototype();
4429 * Returns true if the given object is an instance of this function
4432 bool HasInstance(Local<Value> object);
4436 friend class Context;
4437 friend class ObjectTemplate;
4441 enum class PropertyHandlerFlags {
4443 // See ALL_CAN_READ above.
4445 // Will not call into interceptor for properties on the receiver or prototype
4446 // chain. Currently only valid for named interceptors.
4447 kNonMasking = 1 << 1,
4448 // Will not call into interceptor for symbol lookup. Only meaningful for
4449 // named interceptors.
4450 kOnlyInterceptStrings = 1 << 2,
4454 struct NamedPropertyHandlerConfiguration {
4455 NamedPropertyHandlerConfiguration(
4456 /** Note: getter is required **/
4457 GenericNamedPropertyGetterCallback getter = 0,
4458 GenericNamedPropertySetterCallback setter = 0,
4459 GenericNamedPropertyQueryCallback query = 0,
4460 GenericNamedPropertyDeleterCallback deleter = 0,
4461 GenericNamedPropertyEnumeratorCallback enumerator = 0,
4462 Local<Value> data = Local<Value>(),
4463 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4468 enumerator(enumerator),
4472 GenericNamedPropertyGetterCallback getter;
4473 GenericNamedPropertySetterCallback setter;
4474 GenericNamedPropertyQueryCallback query;
4475 GenericNamedPropertyDeleterCallback deleter;
4476 GenericNamedPropertyEnumeratorCallback enumerator;
4478 PropertyHandlerFlags flags;
4482 struct IndexedPropertyHandlerConfiguration {
4483 IndexedPropertyHandlerConfiguration(
4484 /** Note: getter is required **/
4485 IndexedPropertyGetterCallback getter = 0,
4486 IndexedPropertySetterCallback setter = 0,
4487 IndexedPropertyQueryCallback query = 0,
4488 IndexedPropertyDeleterCallback deleter = 0,
4489 IndexedPropertyEnumeratorCallback enumerator = 0,
4490 Local<Value> data = Local<Value>(),
4491 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4496 enumerator(enumerator),
4500 IndexedPropertyGetterCallback getter;
4501 IndexedPropertySetterCallback setter;
4502 IndexedPropertyQueryCallback query;
4503 IndexedPropertyDeleterCallback deleter;
4504 IndexedPropertyEnumeratorCallback enumerator;
4506 PropertyHandlerFlags flags;
4511 * An ObjectTemplate is used to create objects at runtime.
4513 * Properties added to an ObjectTemplate are added to each object
4514 * created from the ObjectTemplate.
4516 class V8_EXPORT ObjectTemplate : public Template {
4518 /** Creates an ObjectTemplate. */
4519 static Local<ObjectTemplate> New(
4521 Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
4522 static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4524 /** Creates a new instance of this template.*/
4525 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4526 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
4529 * Sets an accessor on the object template.
4531 * Whenever the property with the given name is accessed on objects
4532 * created from this ObjectTemplate the getter and setter callbacks
4533 * are called instead of getting and setting the property directly
4534 * on the JavaScript object.
4536 * \param name The name of the property for which an accessor is added.
4537 * \param getter The callback to invoke when getting the property.
4538 * \param setter The callback to invoke when setting the property.
4539 * \param data A piece of data that will be passed to the getter and setter
4540 * callbacks whenever they are invoked.
4541 * \param settings Access control settings for the accessor. This is a bit
4542 * field consisting of one of more of
4543 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4544 * The default is to not allow cross-context access.
4545 * ALL_CAN_READ means that all cross-context reads are allowed.
4546 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4547 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4548 * cross-context access.
4549 * \param attribute The attributes of the property for which an accessor
4551 * \param signature The signature describes valid receivers for the accessor
4552 * and is used to perform implicit instance checks against them. If the
4553 * receiver is incompatible (i.e. is not an instance of the constructor as
4554 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4555 * thrown and no callback is invoked.
4558 Local<String> name, AccessorGetterCallback getter,
4559 AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4560 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4561 Local<AccessorSignature> signature = Local<AccessorSignature>());
4563 Local<Name> name, AccessorNameGetterCallback getter,
4564 AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4565 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4566 Local<AccessorSignature> signature = Local<AccessorSignature>());
4569 * Sets a named property handler on the object template.
4571 * Whenever a property whose name is a string is accessed on objects created
4572 * from this object template, the provided callback is invoked instead of
4573 * accessing the property directly on the JavaScript object.
4575 * Note that new code should use the second version that can intercept
4576 * symbol-named properties as well as string-named properties.
4578 * \param getter The callback to invoke when getting a property.
4579 * \param setter The callback to invoke when setting a property.
4580 * \param query The callback to invoke to check if a property is present,
4581 * and if present, get its attributes.
4582 * \param deleter The callback to invoke when deleting a property.
4583 * \param enumerator The callback to invoke to enumerate all the named
4584 * properties of an object.
4585 * \param data A piece of data that will be passed to the callbacks
4586 * whenever they are invoked.
4588 // TODO(dcarney): deprecate
4589 void SetNamedPropertyHandler(NamedPropertyGetterCallback getter,
4590 NamedPropertySetterCallback setter = 0,
4591 NamedPropertyQueryCallback query = 0,
4592 NamedPropertyDeleterCallback deleter = 0,
4593 NamedPropertyEnumeratorCallback enumerator = 0,
4594 Local<Value> data = Local<Value>());
4595 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4598 * Sets an indexed property handler on the object template.
4600 * Whenever an indexed property is accessed on objects created from
4601 * this object template, the provided callback is invoked instead of
4602 * accessing the property directly on the JavaScript object.
4604 * \param getter The callback to invoke when getting a property.
4605 * \param setter The callback to invoke when setting a property.
4606 * \param query The callback to invoke to check if an object has a property.
4607 * \param deleter The callback to invoke when deleting a property.
4608 * \param enumerator The callback to invoke to enumerate all the indexed
4609 * properties of an object.
4610 * \param data A piece of data that will be passed to the callbacks
4611 * whenever they are invoked.
4613 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4614 // TODO(dcarney): deprecate
4615 void SetIndexedPropertyHandler(
4616 IndexedPropertyGetterCallback getter,
4617 IndexedPropertySetterCallback setter = 0,
4618 IndexedPropertyQueryCallback query = 0,
4619 IndexedPropertyDeleterCallback deleter = 0,
4620 IndexedPropertyEnumeratorCallback enumerator = 0,
4621 Local<Value> data = Local<Value>()) {
4622 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4623 deleter, enumerator, data));
4626 * Sets the callback to be used when calling instances created from
4627 * this template as a function. If no callback is set, instances
4628 * behave like normal JavaScript objects that cannot be called as a
4631 void SetCallAsFunctionHandler(FunctionCallback callback,
4632 Local<Value> data = Local<Value>());
4635 * Mark object instances of the template as undetectable.
4637 * In many ways, undetectable objects behave as though they are not
4638 * there. They behave like 'undefined' in conditionals and when
4639 * printed. However, properties can be accessed and called as on
4642 void MarkAsUndetectable();
4645 * Sets access check callbacks on the object template and enables
4648 * When accessing properties on instances of this object template,
4649 * the access check callback will be called to determine whether or
4650 * not to allow cross-context access to the properties.
4652 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4653 IndexedSecurityCallback indexed_handler,
4654 Local<Value> data = Local<Value>());
4657 * Gets the number of internal fields for objects generated from
4660 int InternalFieldCount();
4663 * Sets the number of internal fields for objects generated from
4666 void SetInternalFieldCount(int value);
4670 static Local<ObjectTemplate> New(internal::Isolate* isolate,
4671 Local<FunctionTemplate> constructor);
4672 friend class FunctionTemplate;
4677 * A Signature specifies which receiver is valid for a function.
4679 class V8_EXPORT Signature : public Data {
4681 static Local<Signature> New(
4683 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4691 * An AccessorSignature specifies which receivers are valid parameters
4692 * to an accessor callback.
4694 class V8_EXPORT AccessorSignature : public Data {
4696 static Local<AccessorSignature> New(
4698 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4701 AccessorSignature();
4706 * A utility for determining the type of objects based on the template
4707 * they were constructed from.
4709 class V8_EXPORT TypeSwitch : public Data {
4711 static Local<TypeSwitch> New(Local<FunctionTemplate> type);
4712 static Local<TypeSwitch> New(int argc, Local<FunctionTemplate> types[]);
4713 int match(Local<Value> value);
4720 // --- Extensions ---
4722 class V8_EXPORT ExternalOneByteStringResourceImpl
4723 : public String::ExternalOneByteStringResource {
4725 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4726 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4727 : data_(data), length_(length) {}
4728 const char* data() const { return data_; }
4729 size_t length() const { return length_; }
4739 class V8_EXPORT Extension { // NOLINT
4741 // Note that the strings passed into this constructor must live as long
4742 // as the Extension itself.
4743 Extension(const char* name,
4744 const char* source = 0,
4746 const char** deps = 0,
4747 int source_length = -1);
4748 virtual ~Extension() { }
4749 virtual v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
4750 v8::Isolate* isolate, v8::Local<v8::String> name) {
4751 return v8::Local<v8::FunctionTemplate>();
4754 const char* name() const { return name_; }
4755 size_t source_length() const { return source_length_; }
4756 const String::ExternalOneByteStringResource* source() const {
4758 int dependency_count() { return dep_count_; }
4759 const char** dependencies() { return deps_; }
4760 void set_auto_enable(bool value) { auto_enable_ = value; }
4761 bool auto_enable() { return auto_enable_; }
4765 size_t source_length_; // expected to initialize before source_
4766 ExternalOneByteStringResourceImpl source_;
4771 // Disallow copying and assigning.
4772 Extension(const Extension&);
4773 void operator=(const Extension&);
4777 void V8_EXPORT RegisterExtension(Extension* extension);
4782 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
4783 V8_INLINE Local<Primitive> Null(Isolate* isolate);
4784 V8_INLINE Local<Boolean> True(Isolate* isolate);
4785 V8_INLINE Local<Boolean> False(Isolate* isolate);
4789 * A set of constraints that specifies the limits of the runtime's memory use.
4790 * You must set the heap size before initializing the VM - the size cannot be
4791 * adjusted after the VM is initialized.
4793 * If you are using threads then you should hold the V8::Locker lock while
4794 * setting the stack limit and you must set a non-default stack limit separately
4797 class V8_EXPORT ResourceConstraints {
4799 ResourceConstraints();
4802 * Configures the constraints with reasonable default values based on the
4803 * capabilities of the current device the VM is running on.
4805 * \param physical_memory The total amount of physical memory on the current
4807 * \param virtual_memory_limit The amount of virtual memory on the current
4808 * device, in bytes, or zero, if there is no limit.
4810 void ConfigureDefaults(uint64_t physical_memory,
4811 uint64_t virtual_memory_limit);
4813 // Deprecated, will be removed soon.
4814 V8_DEPRECATED("Use two-args version instead",
4815 void ConfigureDefaults(uint64_t physical_memory,
4816 uint64_t virtual_memory_limit,
4817 uint32_t number_of_processors));
4819 int max_semi_space_size() const { return max_semi_space_size_; }
4820 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4821 int max_old_space_size() const { return max_old_space_size_; }
4822 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4823 int max_executable_size() const { return max_executable_size_; }
4824 void set_max_executable_size(int value) { max_executable_size_ = value; }
4825 uint32_t* stack_limit() const { return stack_limit_; }
4826 // Sets an address beyond which the VM's stack may not grow.
4827 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4828 V8_DEPRECATED("Unused, will be removed", int max_available_threads() const) {
4829 return max_available_threads_;
4831 // Set the number of threads available to V8, assuming at least 1.
4832 V8_DEPRECATED("Unused, will be removed",
4833 void set_max_available_threads(int value)) {
4834 max_available_threads_ = value;
4836 size_t code_range_size() const { return code_range_size_; }
4837 void set_code_range_size(size_t value) {
4838 code_range_size_ = value;
4842 int max_semi_space_size_;
4843 int max_old_space_size_;
4844 int max_executable_size_;
4845 uint32_t* stack_limit_;
4846 int max_available_threads_;
4847 size_t code_range_size_;
4851 // --- Exceptions ---
4854 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4857 typedef void (*MessageCallback)(Local<Message> message, Local<Value> error);
4861 typedef void (*LogEventCallback)(const char* name, int event);
4864 * Create new error objects by calling the corresponding error object
4865 * constructor with the message.
4867 class V8_EXPORT Exception {
4869 static Local<Value> RangeError(Local<String> message);
4870 static Local<Value> ReferenceError(Local<String> message);
4871 static Local<Value> SyntaxError(Local<String> message);
4872 static Local<Value> TypeError(Local<String> message);
4873 static Local<Value> Error(Local<String> message);
4876 * Creates an error message for the given exception.
4877 * Will try to reconstruct the original stack trace from the exception value,
4878 * or capture the current stack trace if not available.
4880 static Local<Message> CreateMessage(Local<Value> exception);
4883 * Returns the original stack trace that was captured at the creation time
4884 * of a given exception, or an empty handle if not available.
4886 static Local<StackTrace> GetStackTrace(Local<Value> exception);
4890 // --- Counters Callbacks ---
4892 typedef int* (*CounterLookupCallback)(const char* name);
4894 typedef void* (*CreateHistogramCallback)(const char* name,
4899 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4901 // --- Memory Allocation Callback ---
4903 kObjectSpaceNewSpace = 1 << 0,
4904 kObjectSpaceOldSpace = 1 << 1,
4905 kObjectSpaceCodeSpace = 1 << 2,
4906 kObjectSpaceMapSpace = 1 << 3,
4907 kObjectSpaceLoSpace = 1 << 4,
4908 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldSpace |
4909 kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4913 enum AllocationAction {
4914 kAllocationActionAllocate = 1 << 0,
4915 kAllocationActionFree = 1 << 1,
4916 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4919 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4920 AllocationAction action,
4923 // --- Leave Script Callback ---
4924 typedef void (*CallCompletedCallback)();
4926 // --- Promise Reject Callback ---
4927 enum PromiseRejectEvent {
4928 kPromiseRejectWithNoHandler = 0,
4929 kPromiseHandlerAddedAfterReject = 1
4932 class PromiseRejectMessage {
4934 PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
4935 Local<Value> value, Local<StackTrace> stack_trace)
4936 : promise_(promise),
4939 stack_trace_(stack_trace) {}
4941 V8_INLINE Local<Promise> GetPromise() const { return promise_; }
4942 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4943 V8_INLINE Local<Value> GetValue() const { return value_; }
4945 // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4946 V8_INLINE Local<StackTrace> GetStackTrace() const { return stack_trace_; }
4949 Local<Promise> promise_;
4950 PromiseRejectEvent event_;
4951 Local<Value> value_;
4952 Local<StackTrace> stack_trace_;
4955 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4957 // --- Microtask Callback ---
4958 typedef void (*MicrotaskCallback)(void* data);
4960 // --- Failed Access Check Callback ---
4961 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4965 // --- AllowCodeGenerationFromStrings callbacks ---
4968 * Callback to check if code generation from strings is allowed. See
4969 * Context::AllowCodeGenerationFromStrings.
4971 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4973 // --- Garbage Collection Callbacks ---
4976 * Applications can register callback functions which will be called
4977 * before and after a garbage collection. Allocations are not
4978 * allowed in the callback functions, you therefore cannot manipulate
4979 * objects (set or delete properties for example) since it is possible
4980 * such operations will result in the allocation of objects.
4983 kGCTypeScavenge = 1 << 0,
4984 kGCTypeMarkSweepCompact = 1 << 1,
4985 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4988 enum GCCallbackFlags {
4989 kNoGCCallbackFlags = 0,
4990 kGCCallbackFlagCompacted = 1 << 0,
4991 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4992 kGCCallbackFlagForced = 1 << 2
4995 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4996 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4998 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
5002 * Collection of V8 heap information.
5004 * Instances of this class can be passed to v8::V8::HeapStatistics to
5005 * get heap statistics from V8.
5007 class V8_EXPORT HeapStatistics {
5010 size_t total_heap_size() { return total_heap_size_; }
5011 size_t total_heap_size_executable() { return total_heap_size_executable_; }
5012 size_t total_physical_size() { return total_physical_size_; }
5013 size_t total_available_size() { return total_available_size_; }
5014 size_t used_heap_size() { return used_heap_size_; }
5015 size_t heap_size_limit() { return heap_size_limit_; }
5018 size_t total_heap_size_;
5019 size_t total_heap_size_executable_;
5020 size_t total_physical_size_;
5021 size_t total_available_size_;
5022 size_t used_heap_size_;
5023 size_t heap_size_limit_;
5026 friend class Isolate;
5030 class V8_EXPORT HeapSpaceStatistics {
5032 HeapSpaceStatistics();
5033 const char* space_name() { return space_name_; }
5034 size_t space_size() { return space_size_; }
5035 size_t space_used_size() { return space_used_size_; }
5036 size_t space_available_size() { return space_available_size_; }
5037 size_t physical_space_size() { return physical_space_size_; }
5040 const char* space_name_;
5042 size_t space_used_size_;
5043 size_t space_available_size_;
5044 size_t physical_space_size_;
5046 friend class Isolate;
5050 class V8_EXPORT HeapObjectStatistics {
5052 HeapObjectStatistics();
5053 const char* object_type() { return object_type_; }
5054 const char* object_sub_type() { return object_sub_type_; }
5055 size_t object_count() { return object_count_; }
5056 size_t object_size() { return object_size_; }
5059 const char* object_type_;
5060 const char* object_sub_type_;
5061 size_t object_count_;
5062 size_t object_size_;
5064 friend class Isolate;
5068 class RetainedObjectInfo;
5072 * FunctionEntryHook is the type of the profile entry hook called at entry to
5073 * any generated function when function-level profiling is enabled.
5075 * \param function the address of the function that's being entered.
5076 * \param return_addr_location points to a location on stack where the machine
5077 * return address resides. This can be used to identify the caller of
5078 * \p function, and/or modified to divert execution when \p function exits.
5080 * \note the entry hook must not cause garbage collection.
5082 typedef void (*FunctionEntryHook)(uintptr_t function,
5083 uintptr_t return_addr_location);
5086 * A JIT code event is issued each time code is added, moved or removed.
5088 * \note removal events are not currently issued.
5090 struct JitCodeEvent {
5095 CODE_ADD_LINE_POS_INFO,
5096 CODE_START_LINE_INFO_RECORDING,
5097 CODE_END_LINE_INFO_RECORDING
5099 // Definition of the code position type. The "POSITION" type means the place
5100 // in the source code which are of interest when making stack traces to
5101 // pin-point the source location of a stack frame as close as possible.
5102 // The "STATEMENT_POSITION" means the place at the beginning of each
5103 // statement, and is used to indicate possible break locations.
5104 enum PositionType { POSITION, STATEMENT_POSITION };
5108 // Start of the instructions.
5110 // Size of the instructions.
5112 // Script info for CODE_ADDED event.
5113 Local<UnboundScript> script;
5114 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
5115 // code line information which is returned from the
5116 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
5117 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
5121 // Name of the object associated with the code, note that the string is not
5124 // Number of chars in str.
5128 struct line_info_t {
5133 // The position type.
5134 PositionType position_type;
5138 // Only valid for CODE_ADDED.
5141 // Only valid for CODE_ADD_LINE_POS_INFO
5142 struct line_info_t line_info;
5144 // New location of instructions. Only valid for CODE_MOVED.
5145 void* new_code_start;
5150 * Option flags passed to the SetJitCodeEventHandler function.
5152 enum JitCodeEventOptions {
5153 kJitCodeEventDefault = 0,
5154 // Generate callbacks for already existent code.
5155 kJitCodeEventEnumExisting = 1
5160 * Callback function passed to SetJitCodeEventHandler.
5162 * \param event code add, move or removal event.
5164 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
5168 * Interface for iterating through all external resources in the heap.
5170 class V8_EXPORT ExternalResourceVisitor { // NOLINT
5172 virtual ~ExternalResourceVisitor() {}
5173 virtual void VisitExternalString(Local<String> string) {}
5178 * Interface for iterating through all the persistent handles in the heap.
5180 class V8_EXPORT PersistentHandleVisitor { // NOLINT
5182 virtual ~PersistentHandleVisitor() {}
5183 virtual void VisitPersistentHandle(Persistent<Value>* value,
5184 uint16_t class_id) {}
5189 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
5190 * completely separate states. Objects from one isolate must not be used in
5191 * other isolates. The embedder can create multiple isolates and use them in
5192 * parallel in multiple threads. An isolate can be entered by at most one
5193 * thread at any given time. The Locker/Unlocker API must be used to
5196 class V8_EXPORT Isolate {
5199 * Initial configuration parameters for a new Isolate.
5201 struct CreateParams {
5204 code_event_handler(NULL),
5205 snapshot_blob(NULL),
5206 counter_lookup_callback(NULL),
5207 create_histogram_callback(NULL),
5208 add_histogram_sample_callback(NULL),
5209 array_buffer_allocator(NULL) {}
5212 * The optional entry_hook allows the host application to provide the
5213 * address of a function that's invoked on entry to every V8-generated
5214 * function. Note that entry_hook is invoked at the very start of each
5215 * generated function. Furthermore, if an entry_hook is given, V8 will
5216 * always run without a context snapshot.
5218 FunctionEntryHook entry_hook;
5221 * Allows the host application to provide the address of a function that is
5222 * notified each time code is added, moved or removed.
5224 JitCodeEventHandler code_event_handler;
5227 * ResourceConstraints to use for the new Isolate.
5229 ResourceConstraints constraints;
5232 * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5234 StartupData* snapshot_blob;
5238 * Enables the host application to provide a mechanism for recording
5239 * statistics counters.
5241 CounterLookupCallback counter_lookup_callback;
5244 * Enables the host application to provide a mechanism for recording
5245 * histograms. The CreateHistogram function returns a
5246 * histogram which will later be passed to the AddHistogramSample
5249 CreateHistogramCallback create_histogram_callback;
5250 AddHistogramSampleCallback add_histogram_sample_callback;
5253 * The ArrayBuffer::Allocator to use for allocating and freeing the backing
5254 * store of ArrayBuffers.
5256 ArrayBuffer::Allocator* array_buffer_allocator;
5261 * Stack-allocated class which sets the isolate for all operations
5262 * executed within a local scope.
5264 class V8_EXPORT Scope {
5266 explicit Scope(Isolate* isolate) : isolate_(isolate) {
5270 ~Scope() { isolate_->Exit(); }
5273 Isolate* const isolate_;
5275 // Prevent copying of Scope objects.
5276 Scope(const Scope&);
5277 Scope& operator=(const Scope&);
5282 * Assert that no Javascript code is invoked.
5284 class V8_EXPORT DisallowJavascriptExecutionScope {
5286 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
5288 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
5289 ~DisallowJavascriptExecutionScope();
5295 // Prevent copying of Scope objects.
5296 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5297 DisallowJavascriptExecutionScope& operator=(
5298 const DisallowJavascriptExecutionScope&);
5303 * Introduce exception to DisallowJavascriptExecutionScope.
5305 class V8_EXPORT AllowJavascriptExecutionScope {
5307 explicit AllowJavascriptExecutionScope(Isolate* isolate);
5308 ~AllowJavascriptExecutionScope();
5311 void* internal_throws_;
5312 void* internal_assert_;
5314 // Prevent copying of Scope objects.
5315 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5316 AllowJavascriptExecutionScope& operator=(
5317 const AllowJavascriptExecutionScope&);
5321 * Do not run microtasks while this scope is active, even if microtasks are
5322 * automatically executed otherwise.
5324 class V8_EXPORT SuppressMicrotaskExecutionScope {
5326 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
5327 ~SuppressMicrotaskExecutionScope();
5330 internal::Isolate* isolate_;
5332 // Prevent copying of Scope objects.
5333 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5334 SuppressMicrotaskExecutionScope& operator=(
5335 const SuppressMicrotaskExecutionScope&);
5339 * Types of garbage collections that can be requested via
5340 * RequestGarbageCollectionForTesting.
5342 enum GarbageCollectionType {
5343 kFullGarbageCollection,
5344 kMinorGarbageCollection
5348 * Features reported via the SetUseCounterCallback callback. Do not change
5349 * assigned numbers of existing items; add new features to the end of this
5352 enum UseCounterFeature {
5356 kMarkDequeOverflow = 3,
5357 kStoreBufferOverflow = 4,
5358 kSlotsBufferOverflow = 5,
5361 kUseCounterFeatureCount // This enum value must be last.
5364 typedef void (*UseCounterCallback)(Isolate* isolate,
5365 UseCounterFeature feature);
5369 * Creates a new isolate. Does not change the currently entered
5372 * When an isolate is no longer used its resources should be freed
5373 * by calling Dispose(). Using the delete operator is not allowed.
5375 * V8::Initialize() must have run prior to this.
5377 static Isolate* New(const CreateParams& params);
5379 static V8_DEPRECATED("Always pass CreateParams", Isolate* New());
5382 * Returns the entered isolate for the current thread or NULL in
5383 * case there is no current isolate.
5385 * This method must not be invoked before V8::Initialize() was invoked.
5387 static Isolate* GetCurrent();
5390 * Methods below this point require holding a lock (using Locker) in
5391 * a multi-threaded environment.
5395 * Sets this isolate as the entered one for the current thread.
5396 * Saves the previously entered one (if any), so that it can be
5397 * restored when exiting. Re-entering an isolate is allowed.
5402 * Exits this isolate by restoring the previously entered one in the
5403 * current thread. The isolate may still stay the same, if it was
5404 * entered more than once.
5406 * Requires: this == Isolate::GetCurrent().
5411 * Disposes the isolate. The isolate must not be entered by any
5412 * thread to be disposable.
5417 * Associate embedder-specific data with the isolate. |slot| has to be
5418 * between 0 and GetNumberOfDataSlots() - 1.
5420 V8_INLINE void SetData(uint32_t slot, void* data);
5423 * Retrieve embedder-specific data from the isolate.
5424 * Returns NULL if SetData has never been called for the given |slot|.
5426 V8_INLINE void* GetData(uint32_t slot);
5429 * Returns the maximum number of available embedder data slots. Valid slots
5430 * are in the range of 0 - GetNumberOfDataSlots() - 1.
5432 V8_INLINE static uint32_t GetNumberOfDataSlots();
5435 * Get statistics about the heap memory usage.
5437 void GetHeapStatistics(HeapStatistics* heap_statistics);
5440 * Returns the number of spaces in the heap.
5442 size_t NumberOfHeapSpaces();
5445 * Get the memory usage of a space in the heap.
5447 * \param space_statistics The HeapSpaceStatistics object to fill in
5449 * \param index The index of the space to get statistics from, which ranges
5450 * from 0 to NumberOfHeapSpaces() - 1.
5451 * \returns true on success.
5453 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
5457 * Returns the number of types of objects tracked in the heap at GC.
5459 size_t NumberOfTrackedHeapObjectTypes();
5462 * Get statistics about objects in the heap.
5464 * \param object_statistics The HeapObjectStatistics object to fill in
5465 * statistics of objects of given type, which were live in the previous GC.
5466 * \param type_index The index of the type of object to fill details about,
5467 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
5468 * \returns true on success.
5470 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
5474 * Get a call stack sample from the isolate.
5475 * \param state Execution state.
5476 * \param frames Caller allocated buffer to store stack frames.
5477 * \param frames_limit Maximum number of frames to capture. The buffer must
5478 * be large enough to hold the number of frames.
5479 * \param sample_info The sample info is filled up by the function
5480 * provides number of actual captured stack frames and
5481 * the current VM state.
5482 * \note GetStackSample should only be called when the JS thread is paused or
5483 * interrupted. Otherwise the behavior is undefined.
5485 void GetStackSample(const RegisterState& state, void** frames,
5486 size_t frames_limit, SampleInfo* sample_info);
5489 * Adjusts the amount of registered external memory. Used to give V8 an
5490 * indication of the amount of externally allocated memory that is kept alive
5491 * by JavaScript objects. V8 uses this to decide when to perform global
5492 * garbage collections. Registering externally allocated memory will trigger
5493 * global garbage collections more often than it would otherwise in an attempt
5494 * to garbage collect the JavaScript objects that keep the externally
5495 * allocated memory alive.
5497 * \param change_in_bytes the change in externally allocated memory that is
5498 * kept alive by JavaScript objects.
5499 * \returns the adjusted value.
5502 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5505 * Returns heap profiler for this isolate. Will return NULL until the isolate
5508 HeapProfiler* GetHeapProfiler();
5511 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5512 * is initialized. It is the embedder's responsibility to stop all CPU
5513 * profiling activities if it has started any.
5515 CpuProfiler* GetCpuProfiler();
5517 /** Returns true if this isolate has a current context. */
5520 /** Returns the context that is on the top of the stack. */
5521 Local<Context> GetCurrentContext();
5524 * Returns the context of the calling JavaScript code. That is the
5525 * context of the top-most JavaScript frame. If there are no
5526 * JavaScript frames an empty handle is returned.
5528 Local<Context> GetCallingContext();
5530 /** Returns the last entered context. */
5531 Local<Context> GetEnteredContext();
5534 * Schedules an exception to be thrown when returning to JavaScript. When an
5535 * exception has been scheduled it is illegal to invoke any JavaScript
5536 * operation; the caller must return immediately and only after the exception
5537 * has been handled does it become legal to invoke JavaScript operations.
5539 Local<Value> ThrowException(Local<Value> exception);
5542 * Allows the host application to group objects together. If one
5543 * object in the group is alive, all objects in the group are alive.
5544 * After each garbage collection, object groups are removed. It is
5545 * intended to be used in the before-garbage-collection callback
5546 * function, for instance to simulate DOM tree connections among JS
5547 * wrapper objects. Object groups for all dependent handles need to
5548 * be provided for kGCTypeMarkSweepCompact collections, for all other
5549 * garbage collection types it is sufficient to provide object groups
5550 * for partially dependent handles only.
5552 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5556 * Allows the host application to declare implicit references from an object
5557 * group to an object. If the objects of the object group are alive, the child
5558 * object is alive too. After each garbage collection, all implicit references
5559 * are removed. It is intended to be used in the before-garbage-collection
5560 * callback function.
5562 template<typename T> void SetReferenceFromGroup(UniqueId id,
5563 const Persistent<T>& child);
5566 * Allows the host application to declare implicit references from an object
5567 * to another object. If the parent object is alive, the child object is alive
5568 * too. After each garbage collection, all implicit references are removed. It
5569 * is intended to be used in the before-garbage-collection callback function.
5571 template<typename T, typename S>
5572 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5574 typedef void (*GCPrologueCallback)(Isolate* isolate,
5576 GCCallbackFlags flags);
5577 typedef void (*GCEpilogueCallback)(Isolate* isolate,
5579 GCCallbackFlags flags);
5582 * Enables the host application to receive a notification before a
5583 * garbage collection. Allocations are allowed in the callback function,
5584 * but the callback is not re-entrant: if the allocation inside it will
5585 * trigger the garbage collection, the callback won't be called again.
5586 * It is possible to specify the GCType filter for your callback. But it is
5587 * not possible to register the same callback function two times with
5588 * different GCType filters.
5590 void AddGCPrologueCallback(
5591 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5594 * This function removes callback which was installed by
5595 * AddGCPrologueCallback function.
5597 void RemoveGCPrologueCallback(GCPrologueCallback callback);
5600 * Enables the host application to receive a notification after a
5601 * garbage collection. Allocations are allowed in the callback function,
5602 * but the callback is not re-entrant: if the allocation inside it will
5603 * trigger the garbage collection, the callback won't be called again.
5604 * It is possible to specify the GCType filter for your callback. But it is
5605 * not possible to register the same callback function two times with
5606 * different GCType filters.
5608 void AddGCEpilogueCallback(
5609 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5612 * This function removes callback which was installed by
5613 * AddGCEpilogueCallback function.
5615 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5619 * Forcefully terminate the current thread of JavaScript execution
5620 * in the given isolate.
5622 * This method can be used by any thread even if that thread has not
5623 * acquired the V8 lock with a Locker object.
5625 void TerminateExecution();
5628 * Is V8 terminating JavaScript execution.
5630 * Returns true if JavaScript execution is currently terminating
5631 * because of a call to TerminateExecution. In that case there are
5632 * still JavaScript frames on the stack and the termination
5633 * exception is still active.
5635 bool IsExecutionTerminating();
5638 * Resume execution capability in the given isolate, whose execution
5639 * was previously forcefully terminated using TerminateExecution().
5641 * When execution is forcefully terminated using TerminateExecution(),
5642 * the isolate can not resume execution until all JavaScript frames
5643 * have propagated the uncatchable exception which is generated. This
5644 * method allows the program embedding the engine to handle the
5645 * termination event and resume execution capability, even if
5646 * JavaScript frames remain on the stack.
5648 * This method can be used by any thread even if that thread has not
5649 * acquired the V8 lock with a Locker object.
5651 void CancelTerminateExecution();
5654 * Request V8 to interrupt long running JavaScript code and invoke
5655 * the given |callback| passing the given |data| to it. After |callback|
5656 * returns control will be returned to the JavaScript code.
5657 * There may be a number of interrupt requests in flight.
5658 * Can be called from another thread without acquiring a |Locker|.
5659 * Registered |callback| must not reenter interrupted Isolate.
5661 void RequestInterrupt(InterruptCallback callback, void* data);
5664 * Request garbage collection in this Isolate. It is only valid to call this
5665 * function if --expose_gc was specified.
5667 * This should only be used for testing purposes and not to enforce a garbage
5668 * collection schedule. It has strong negative impact on the garbage
5669 * collection performance. Use IdleNotificationDeadline() or
5670 * LowMemoryNotification() instead to influence the garbage collection
5673 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5676 * Set the callback to invoke for logging event.
5678 void SetEventLogger(LogEventCallback that);
5681 * Adds a callback to notify the host application when a script finished
5682 * running. If a script re-enters the runtime during executing, the
5683 * CallCompletedCallback is only invoked when the outer-most script
5684 * execution ends. Executing scripts inside the callback do not trigger
5685 * further callbacks.
5687 void AddCallCompletedCallback(CallCompletedCallback callback);
5690 * Removes callback that was installed by AddCallCompletedCallback.
5692 void RemoveCallCompletedCallback(CallCompletedCallback callback);
5696 * Set callback to notify about promise reject with no handler, or
5697 * revocation of such a previous notification once the handler is added.
5699 void SetPromiseRejectCallback(PromiseRejectCallback callback);
5702 * Experimental: Runs the Microtask Work Queue until empty
5703 * Any exceptions thrown by microtask callbacks are swallowed.
5705 void RunMicrotasks();
5708 * Experimental: Enqueues the callback to the Microtask Work Queue
5710 void EnqueueMicrotask(Local<Function> microtask);
5713 * Experimental: Enqueues the callback to the Microtask Work Queue
5715 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5718 * Experimental: Controls whether the Microtask Work Queue is automatically
5719 * run when the script call depth decrements to zero.
5721 void SetAutorunMicrotasks(bool autorun);
5724 * Experimental: Returns whether the Microtask Work Queue is automatically
5725 * run when the script call depth decrements to zero.
5727 bool WillAutorunMicrotasks() const;
5730 * Sets a callback for counting the number of times a feature of V8 is used.
5732 void SetUseCounterCallback(UseCounterCallback callback);
5735 * Enables the host application to provide a mechanism for recording
5736 * statistics counters.
5738 void SetCounterFunction(CounterLookupCallback);
5741 * Enables the host application to provide a mechanism for recording
5742 * histograms. The CreateHistogram function returns a
5743 * histogram which will later be passed to the AddHistogramSample
5746 void SetCreateHistogramFunction(CreateHistogramCallback);
5747 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5750 * Optional notification that the embedder is idle.
5751 * V8 uses the notification to perform garbage collection.
5752 * This call can be used repeatedly if the embedder remains idle.
5753 * Returns true if the embedder should stop calling IdleNotificationDeadline
5754 * until real work has been done. This indicates that V8 has done
5755 * as much cleanup as it will be able to do.
5757 * The deadline_in_seconds argument specifies the deadline V8 has to finish
5758 * garbage collection work. deadline_in_seconds is compared with
5759 * MonotonicallyIncreasingTime() and should be based on the same timebase as
5760 * that function. There is no guarantee that the actual work will be done
5761 * within the time limit.
5763 bool IdleNotificationDeadline(double deadline_in_seconds);
5765 V8_DEPRECATE_SOON("use IdleNotificationDeadline()",
5766 bool IdleNotification(int idle_time_in_ms));
5769 * Optional notification that the system is running low on memory.
5770 * V8 uses these notifications to attempt to free memory.
5772 void LowMemoryNotification();
5775 * Optional notification that a context has been disposed. V8 uses
5776 * these notifications to guide the GC heuristic. Returns the number
5777 * of context disposals - including this one - since the last time
5778 * V8 had a chance to clean up.
5780 * The optional parameter |dependant_context| specifies whether the disposed
5781 * context was depending on state from other contexts or not.
5783 int ContextDisposedNotification(bool dependant_context = true);
5786 * Allows the host application to provide the address of a function that is
5787 * notified each time code is added, moved or removed.
5789 * \param options options for the JIT code event handler.
5790 * \param event_handler the JIT code event handler, which will be invoked
5791 * each time code is added, moved or removed.
5792 * \note \p event_handler won't get notified of existent code.
5793 * \note since code removal notifications are not currently issued, the
5794 * \p event_handler may get notifications of code that overlaps earlier
5795 * code notifications. This happens when code areas are reused, and the
5796 * earlier overlapping code areas should therefore be discarded.
5797 * \note the events passed to \p event_handler and the strings they point to
5798 * are not guaranteed to live past each call. The \p event_handler must
5799 * copy strings and other parameters it needs to keep around.
5800 * \note the set of events declared in JitCodeEvent::EventType is expected to
5801 * grow over time, and the JitCodeEvent structure is expected to accrue
5802 * new members. The \p event_handler function must ignore event codes
5803 * it does not recognize to maintain future compatibility.
5804 * \note Use Isolate::CreateParams to get events for code executed during
5807 void SetJitCodeEventHandler(JitCodeEventOptions options,
5808 JitCodeEventHandler event_handler);
5811 * Modifies the stack limit for this Isolate.
5813 * \param stack_limit An address beyond which the Vm's stack may not grow.
5815 * \note If you are using threads then you should hold the V8::Locker lock
5816 * while setting the stack limit and you must set a non-default stack
5817 * limit separately for each thread.
5819 void SetStackLimit(uintptr_t stack_limit);
5822 * Returns a memory range that can potentially contain jitted code.
5824 * On Win64, embedders are advised to install function table callbacks for
5825 * these ranges, as default SEH won't be able to unwind through jitted code.
5827 * The first page of the code range is reserved for the embedder and is
5828 * committed, writable, and executable.
5830 * Might be empty on other platforms.
5832 * https://code.google.com/p/v8/issues/detail?id=3598
5834 void GetCodeRange(void** start, size_t* length_in_bytes);
5836 /** Set the callback to invoke in case of fatal errors. */
5837 void SetFatalErrorHandler(FatalErrorCallback that);
5840 * Set the callback to invoke to check if code generation from
5841 * strings should be allowed.
5843 void SetAllowCodeGenerationFromStringsCallback(
5844 AllowCodeGenerationFromStringsCallback callback);
5847 * Check if V8 is dead and therefore unusable. This is the case after
5848 * fatal errors such as out-of-memory situations.
5853 * Adds a message listener.
5855 * The same message listener can be added more than once and in that
5856 * case it will be called more than once for each message.
5858 * If data is specified, it will be passed to the callback when it is called.
5859 * Otherwise, the exception object will be passed to the callback instead.
5861 bool AddMessageListener(MessageCallback that,
5862 Local<Value> data = Local<Value>());
5865 * Remove all message listeners from the specified callback function.
5867 void RemoveMessageListeners(MessageCallback that);
5869 /** Callback function for reporting failed access checks.*/
5870 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5873 * Tells V8 to capture current stack trace when uncaught exception occurs
5874 * and report it to the message listeners. The option is off by default.
5876 void SetCaptureStackTraceForUncaughtExceptions(
5877 bool capture, int frame_limit = 10,
5878 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5881 * Enables the host application to provide a mechanism to be notified
5882 * and perform custom logging when V8 Allocates Executable Memory.
5884 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5885 ObjectSpace space, AllocationAction action);
5888 * Removes callback that was installed by AddMemoryAllocationCallback.
5890 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5893 * Iterates through all external resources referenced from current isolate
5894 * heap. GC is not invoked prior to iterating, therefore there is no
5895 * guarantee that visited objects are still alive.
5897 void VisitExternalResources(ExternalResourceVisitor* visitor);
5900 * Iterates through all the persistent handles in the current isolate's heap
5901 * that have class_ids.
5903 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5906 * Iterates through all the persistent handles in the current isolate's heap
5907 * that have class_ids and are candidates to be marked as partially dependent
5908 * handles. This will visit handles to young objects created since the last
5909 * garbage collection but is free to visit an arbitrary superset of these
5912 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5915 template <class K, class V, class Traits>
5916 friend class PersistentValueMapBase;
5919 Isolate(const Isolate&);
5921 Isolate& operator=(const Isolate&);
5922 void* operator new(size_t size);
5923 void operator delete(void*, size_t);
5925 void SetObjectGroupId(internal::Object** object, UniqueId id);
5926 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5927 void SetReference(internal::Object** parent, internal::Object** child);
5928 void CollectAllGarbage(const char* gc_reason);
5931 class V8_EXPORT StartupData {
5939 * EntropySource is used as a callback function when v8 needs a source
5942 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5946 * ReturnAddressLocationResolver is used as a callback function when v8 is
5947 * resolving the location of a return address on the stack. Profilers that
5948 * change the return address on the stack can use this to resolve the stack
5949 * location to whereever the profiler stashed the original return address.
5951 * \param return_addr_location points to a location on stack where a machine
5952 * return address resides.
5953 * \returns either return_addr_location, or else a pointer to the profiler's
5954 * copy of the original return address.
5956 * \note the resolver function must not cause garbage collection.
5958 typedef uintptr_t (*ReturnAddressLocationResolver)(
5959 uintptr_t return_addr_location);
5963 * Container class for static utility functions.
5965 class V8_EXPORT V8 {
5967 /** Set the callback to invoke in case of fatal errors. */
5968 V8_INLINE static V8_DEPRECATE_SOON(
5969 "Use isolate version",
5970 void SetFatalErrorHandler(FatalErrorCallback that));
5973 * Set the callback to invoke to check if code generation from
5974 * strings should be allowed.
5976 V8_INLINE static V8_DEPRECATE_SOON(
5977 "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
5978 AllowCodeGenerationFromStringsCallback that));
5981 * Set allocator to use for ArrayBuffer memory.
5982 * The allocator should be set only once. The allocator should be set
5983 * before any code tha uses ArrayBuffers is executed.
5984 * This allocator is used in all isolates.
5986 static V8_DEPRECATE_SOON(
5987 "Use isolate version",
5988 void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator));
5991 * Check if V8 is dead and therefore unusable. This is the case after
5992 * fatal errors such as out-of-memory situations.
5994 V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
5997 * Hand startup data to V8, in case the embedder has chosen to build
5998 * V8 with external startup data.
6001 * - By default the startup data is linked into the V8 library, in which
6002 * case this function is not meaningful.
6003 * - If this needs to be called, it needs to be called before V8
6004 * tries to make use of its built-ins.
6005 * - To avoid unnecessary copies of data, V8 will point directly into the
6006 * given data blob, so pretty please keep it around until V8 exit.
6007 * - Compression of the startup blob might be useful, but needs to
6008 * handled entirely on the embedders' side.
6009 * - The call will abort if the data is invalid.
6011 static void SetNativesDataBlob(StartupData* startup_blob);
6012 static void SetSnapshotDataBlob(StartupData* startup_blob);
6015 * Create a new isolate and context for the purpose of capturing a snapshot
6016 * Returns { NULL, 0 } on failure.
6017 * The caller owns the data array in the return value.
6019 static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
6022 * Adds a message listener.
6024 * The same message listener can be added more than once and in that
6025 * case it will be called more than once for each message.
6027 * If data is specified, it will be passed to the callback when it is called.
6028 * Otherwise, the exception object will be passed to the callback instead.
6030 V8_INLINE static V8_DEPRECATE_SOON(
6031 "Use isolate version",
6032 bool AddMessageListener(MessageCallback that,
6033 Local<Value> data = Local<Value>()));
6036 * Remove all message listeners from the specified callback function.
6038 V8_INLINE static V8_DEPRECATE_SOON(
6039 "Use isolate version", void RemoveMessageListeners(MessageCallback that));
6042 * Tells V8 to capture current stack trace when uncaught exception occurs
6043 * and report it to the message listeners. The option is off by default.
6045 V8_INLINE static V8_DEPRECATE_SOON(
6046 "Use isolate version",
6047 void SetCaptureStackTraceForUncaughtExceptions(
6048 bool capture, int frame_limit = 10,
6049 StackTrace::StackTraceOptions options = StackTrace::kOverview));
6052 * Sets V8 flags from a string.
6054 static void SetFlagsFromString(const char* str, int length);
6057 * Sets V8 flags from the command line.
6059 static void SetFlagsFromCommandLine(int* argc,
6063 /** Get the version string. */
6064 static const char* GetVersion();
6066 /** Callback function for reporting failed access checks.*/
6067 V8_INLINE static V8_DEPRECATE_SOON(
6068 "Use isolate version",
6069 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
6072 * Enables the host application to receive a notification before a
6073 * garbage collection. Allocations are not allowed in the
6074 * callback function, you therefore cannot manipulate objects (set
6075 * or delete properties for example) since it is possible such
6076 * operations will result in the allocation of objects. It is possible
6077 * to specify the GCType filter for your callback. But it is not possible to
6078 * register the same callback function two times with different
6081 static V8_DEPRECATE_SOON(
6082 "Use isolate version",
6083 void AddGCPrologueCallback(GCPrologueCallback callback,
6084 GCType gc_type_filter = kGCTypeAll));
6087 * This function removes callback which was installed by
6088 * AddGCPrologueCallback function.
6090 V8_INLINE static V8_DEPRECATE_SOON(
6091 "Use isolate version",
6092 void RemoveGCPrologueCallback(GCPrologueCallback callback));
6095 * Enables the host application to receive a notification after a
6096 * garbage collection. Allocations are not allowed in the
6097 * callback function, you therefore cannot manipulate objects (set
6098 * or delete properties for example) since it is possible such
6099 * operations will result in the allocation of objects. It is possible
6100 * to specify the GCType filter for your callback. But it is not possible to
6101 * register the same callback function two times with different
6104 static V8_DEPRECATE_SOON(
6105 "Use isolate version",
6106 void AddGCEpilogueCallback(GCEpilogueCallback callback,
6107 GCType gc_type_filter = kGCTypeAll));
6110 * This function removes callback which was installed by
6111 * AddGCEpilogueCallback function.
6113 V8_INLINE static V8_DEPRECATE_SOON(
6114 "Use isolate version",
6115 void RemoveGCEpilogueCallback(GCEpilogueCallback callback));
6118 * Enables the host application to provide a mechanism to be notified
6119 * and perform custom logging when V8 Allocates Executable Memory.
6121 V8_INLINE static V8_DEPRECATE_SOON(
6122 "Use isolate version",
6123 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
6125 AllocationAction action));
6128 * Removes callback that was installed by AddMemoryAllocationCallback.
6130 V8_INLINE static V8_DEPRECATE_SOON(
6131 "Use isolate version",
6132 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
6135 * Initializes V8. This function needs to be called before the first Isolate
6136 * is created. It always returns true.
6138 static bool Initialize();
6141 * Allows the host application to provide a callback which can be used
6142 * as a source of entropy for random number generators.
6144 static void SetEntropySource(EntropySource source);
6147 * Allows the host application to provide a callback that allows v8 to
6148 * cooperate with a profiler that rewrites return addresses on stack.
6150 static void SetReturnAddressLocationResolver(
6151 ReturnAddressLocationResolver return_address_resolver);
6154 * Forcefully terminate the current thread of JavaScript execution
6155 * in the given isolate.
6157 * This method can be used by any thread even if that thread has not
6158 * acquired the V8 lock with a Locker object.
6160 * \param isolate The isolate in which to terminate the current JS execution.
6162 V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
6163 void TerminateExecution(Isolate* isolate));
6166 * Is V8 terminating JavaScript execution.
6168 * Returns true if JavaScript execution is currently terminating
6169 * because of a call to TerminateExecution. In that case there are
6170 * still JavaScript frames on the stack and the termination
6171 * exception is still active.
6173 * \param isolate The isolate in which to check.
6175 V8_INLINE static V8_DEPRECATE_SOON(
6176 "Use isolate version",
6177 bool IsExecutionTerminating(Isolate* isolate = NULL));
6180 * Resume execution capability in the given isolate, whose execution
6181 * was previously forcefully terminated using TerminateExecution().
6183 * When execution is forcefully terminated using TerminateExecution(),
6184 * the isolate can not resume execution until all JavaScript frames
6185 * have propagated the uncatchable exception which is generated. This
6186 * method allows the program embedding the engine to handle the
6187 * termination event and resume execution capability, even if
6188 * JavaScript frames remain on the stack.
6190 * This method can be used by any thread even if that thread has not
6191 * acquired the V8 lock with a Locker object.
6193 * \param isolate The isolate in which to resume execution capability.
6195 V8_INLINE static V8_DEPRECATE_SOON(
6196 "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
6199 * Releases any resources used by v8 and stops any utility threads
6200 * that may be running. Note that disposing v8 is permanent, it
6201 * cannot be reinitialized.
6203 * It should generally not be necessary to dispose v8 before exiting
6204 * a process, this should happen automatically. It is only necessary
6205 * to use if the process needs the resources taken up by v8.
6207 static bool Dispose();
6210 * Iterates through all external resources referenced from current isolate
6211 * heap. GC is not invoked prior to iterating, therefore there is no
6212 * guarantee that visited objects are still alive.
6214 V8_INLINE static V8_DEPRECATE_SOON(
6215 "Use isoalte version",
6216 void VisitExternalResources(ExternalResourceVisitor* visitor));
6219 * Iterates through all the persistent handles in the current isolate's heap
6220 * that have class_ids.
6222 V8_INLINE static V8_DEPRECATE_SOON(
6223 "Use isolate version",
6224 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
6227 * Iterates through all the persistent handles in isolate's heap that have
6230 V8_INLINE static V8_DEPRECATE_SOON(
6231 "Use isolate version",
6232 void VisitHandlesWithClassIds(Isolate* isolate,
6233 PersistentHandleVisitor* visitor));
6236 * Iterates through all the persistent handles in the current isolate's heap
6237 * that have class_ids and are candidates to be marked as partially dependent
6238 * handles. This will visit handles to young objects created since the last
6239 * garbage collection but is free to visit an arbitrary superset of these
6242 V8_INLINE static V8_DEPRECATE_SOON(
6243 "Use isolate version",
6244 void VisitHandlesForPartialDependence(Isolate* isolate,
6245 PersistentHandleVisitor* visitor));
6248 * Initialize the ICU library bundled with V8. The embedder should only
6249 * invoke this method when using the bundled ICU. Returns true on success.
6251 * If V8 was compiled with the ICU data in an external file, the location
6252 * of the data file has to be provided.
6254 static bool InitializeICU(const char* icu_data_file = NULL);
6257 * Sets the v8::Platform to use. This should be invoked before V8 is
6260 static void InitializePlatform(Platform* platform);
6263 * Clears all references to the v8::Platform. This should be invoked after
6266 static void ShutdownPlatform();
6271 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6272 internal::Object** handle);
6273 static internal::Object** CopyPersistent(internal::Object** handle);
6274 static void DisposeGlobal(internal::Object** global_handle);
6275 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6276 static void MakeWeak(internal::Object** global_handle, void* data,
6277 WeakCallback weak_callback);
6278 static void MakeWeak(internal::Object** global_handle, void* data,
6279 WeakCallbackInfo<void>::Callback weak_callback,
6280 WeakCallbackType type);
6281 static void MakeWeak(internal::Object** global_handle, void* data,
6283 int internal_field_index1,
6285 int internal_field_index2,
6286 WeakCallbackInfo<void>::Callback weak_callback);
6287 static void* ClearWeak(internal::Object** global_handle);
6288 static void Eternalize(Isolate* isolate,
6291 static Local<Value> GetEternal(Isolate* isolate, int index);
6293 static void FromJustIsNothing();
6294 static void ToLocalEmpty();
6295 static void InternalFieldOutOfBounds(int index);
6296 template <class T> friend class Local;
6298 friend class MaybeLocal;
6302 friend class WeakCallbackInfo;
6303 template <class T> friend class Eternal;
6304 template <class T> friend class PersistentBase;
6305 template <class T, class M> friend class Persistent;
6306 friend class Context;
6311 * A simple Maybe type, representing an object which may or may not have a
6312 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6314 * If an API method returns a Maybe<>, the API method can potentially fail
6315 * either because an exception is thrown, or because an exception is pending,
6316 * e.g. because a previous API call threw an exception that hasn't been caught
6317 * yet, or because a TerminateExecution exception was thrown. In that case, a
6318 * "Nothing" value is returned.
6323 V8_INLINE bool IsNothing() const { return !has_value; }
6324 V8_INLINE bool IsJust() const { return has_value; }
6326 // Will crash if the Maybe<> is nothing.
6327 V8_INLINE T FromJust() const {
6328 if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
6332 V8_INLINE T FromMaybe(const T& default_value) const {
6333 return has_value ? value : default_value;
6336 V8_INLINE bool operator==(const Maybe& other) const {
6337 return (IsJust() == other.IsJust()) &&
6338 (!IsJust() || FromJust() == other.FromJust());
6341 V8_INLINE bool operator!=(const Maybe& other) const {
6342 return !operator==(other);
6346 Maybe() : has_value(false) {}
6347 explicit Maybe(const T& t) : has_value(true), value(t) {}
6353 friend Maybe<U> Nothing();
6355 friend Maybe<U> Just(const U& u);
6360 inline Maybe<T> Nothing() {
6366 inline Maybe<T> Just(const T& t) {
6372 * An external exception handler.
6374 class V8_EXPORT TryCatch {
6377 * Creates a new try/catch block and registers it with v8. Note that
6378 * all TryCatch blocks should be stack allocated because the memory
6379 * location itself is compared against JavaScript try/catch blocks.
6381 V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6384 * Creates a new try/catch block and registers it with v8. Note that
6385 * all TryCatch blocks should be stack allocated because the memory
6386 * location itself is compared against JavaScript try/catch blocks.
6388 TryCatch(Isolate* isolate);
6391 * Unregisters and deletes this try/catch block.
6396 * Returns true if an exception has been caught by this try/catch block.
6398 bool HasCaught() const;
6401 * For certain types of exceptions, it makes no sense to continue execution.
6403 * If CanContinue returns false, the correct action is to perform any C++
6404 * cleanup needed and then return. If CanContinue returns false and
6405 * HasTerminated returns true, it is possible to call
6406 * CancelTerminateExecution in order to continue calling into the engine.
6408 bool CanContinue() const;
6411 * Returns true if an exception has been caught due to script execution
6414 * There is no JavaScript representation of an execution termination
6415 * exception. Such exceptions are thrown when the TerminateExecution
6416 * methods are called to terminate a long-running script.
6418 * If such an exception has been thrown, HasTerminated will return true,
6419 * indicating that it is possible to call CancelTerminateExecution in order
6420 * to continue calling into the engine.
6422 bool HasTerminated() const;
6425 * Throws the exception caught by this TryCatch in a way that avoids
6426 * it being caught again by this same TryCatch. As with ThrowException
6427 * it is illegal to execute any JavaScript operations after calling
6428 * ReThrow; the caller must return immediately to where the exception
6431 Local<Value> ReThrow();
6434 * Returns the exception caught by this try/catch block. If no exception has
6435 * been caught an empty handle is returned.
6437 * The returned handle is valid until this TryCatch block has been destroyed.
6439 Local<Value> Exception() const;
6442 * Returns the .stack property of the thrown object. If no .stack
6443 * property is present an empty handle is returned.
6445 V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
6446 V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
6447 Local<Context> context) const;
6450 * Returns the message associated with this exception. If there is
6451 * no message associated an empty handle is returned.
6453 * The returned handle is valid until this TryCatch block has been
6456 Local<v8::Message> Message() const;
6459 * Clears any exceptions that may have been caught by this try/catch block.
6460 * After this method has been called, HasCaught() will return false. Cancels
6461 * the scheduled exception if it is caught and ReThrow() is not called before.
6463 * It is not necessary to clear a try/catch block before using it again; if
6464 * another exception is thrown the previously caught exception will just be
6465 * overwritten. However, it is often a good idea since it makes it easier
6466 * to determine which operation threw a given exception.
6471 * Set verbosity of the external exception handler.
6473 * By default, exceptions that are caught by an external exception
6474 * handler are not reported. Call SetVerbose with true on an
6475 * external exception handler to have exceptions caught by the
6476 * handler reported as if they were not caught.
6478 void SetVerbose(bool value);
6481 * Set whether or not this TryCatch should capture a Message object
6482 * which holds source information about where the exception
6483 * occurred. True by default.
6485 void SetCaptureMessage(bool value);
6488 * There are cases when the raw address of C++ TryCatch object cannot be
6489 * used for comparisons with addresses into the JS stack. The cases are:
6490 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6491 * 2) Address sanitizer allocates local C++ object in the heap when
6492 * UseAfterReturn mode is enabled.
6493 * This method returns address that can be used for comparisons with
6494 * addresses into the JS stack. When neither simulator nor ASAN's
6495 * UseAfterReturn is enabled, then the address returned will be the address
6496 * of the C++ try catch handler itself.
6498 static void* JSStackComparableAddress(v8::TryCatch* handler) {
6499 if (handler == NULL) return NULL;
6500 return handler->js_stack_comparable_address_;
6504 void ResetInternal();
6506 // Make it hard to create heap-allocated TryCatch blocks.
6507 TryCatch(const TryCatch&);
6508 void operator=(const TryCatch&);
6509 void* operator new(size_t size);
6510 void operator delete(void*, size_t);
6512 v8::internal::Isolate* isolate_;
6513 v8::TryCatch* next_;
6516 void* js_stack_comparable_address_;
6517 bool is_verbose_ : 1;
6518 bool can_continue_ : 1;
6519 bool capture_message_ : 1;
6521 bool has_terminated_ : 1;
6523 friend class v8::internal::Isolate;
6531 * A container for extension names.
6533 class V8_EXPORT ExtensionConfiguration {
6535 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6536 ExtensionConfiguration(int name_count, const char* names[])
6537 : name_count_(name_count), names_(names) { }
6539 const char** begin() const { return &names_[0]; }
6540 const char** end() const { return &names_[name_count_]; }
6543 const int name_count_;
6544 const char** names_;
6549 * A sandboxed execution context with its own set of built-in objects
6552 class V8_EXPORT Context {
6555 * Returns the global proxy object.
6557 * Global proxy object is a thin wrapper whose prototype points to actual
6558 * context's global object with the properties like Object, etc. This is done
6559 * that way for security reasons (for more details see
6560 * https://wiki.mozilla.org/Gecko:SplitWindow).
6562 * Please note that changes to global proxy object prototype most probably
6563 * would break VM---v8 expects only global object as a prototype of global
6566 Local<Object> Global();
6569 * Detaches the global object from its context before
6570 * the global object can be reused to create a new context.
6572 void DetachGlobal();
6575 * Creates a new context and returns a handle to the newly allocated
6578 * \param isolate The isolate in which to create the context.
6580 * \param extensions An optional extension configuration containing
6581 * the extensions to be installed in the newly created context.
6583 * \param global_template An optional object template from which the
6584 * global object for the newly created context will be created.
6586 * \param global_object An optional global object to be reused for
6587 * the newly created context. This global object must have been
6588 * created by a previous call to Context::New with the same global
6589 * template. The state of the global object will be completely reset
6590 * and only object identify will remain.
6592 static Local<Context> New(
6593 Isolate* isolate, ExtensionConfiguration* extensions = NULL,
6594 Local<ObjectTemplate> global_template = Local<ObjectTemplate>(),
6595 Local<Value> global_object = Local<Value>());
6598 * Sets the security token for the context. To access an object in
6599 * another context, the security tokens must match.
6601 void SetSecurityToken(Local<Value> token);
6603 /** Restores the security token to the default value. */
6604 void UseDefaultSecurityToken();
6606 /** Returns the security token of this context.*/
6607 Local<Value> GetSecurityToken();
6610 * Enter this context. After entering a context, all code compiled
6611 * and run is compiled and run in this context. If another context
6612 * is already entered, this old context is saved so it can be
6613 * restored when the new context is exited.
6618 * Exit this context. Exiting the current context restores the
6619 * context that was in place when entering the current context.
6623 /** Returns an isolate associated with a current context. */
6624 v8::Isolate* GetIsolate();
6627 * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6628 * The value is propagated to the scripts compiled in given Context and
6629 * can be used for filtering scripts.
6631 enum EmbedderDataFields { kDebugIdIndex = 0 };
6634 * Gets the embedder data with the given index, which must have been set by a
6635 * previous call to SetEmbedderData with the same index. Note that index 0
6636 * currently has a special meaning for Chrome's debugger.
6638 V8_INLINE Local<Value> GetEmbedderData(int index);
6641 * Gets the exports object used by V8 extras. Extra natives get a reference
6642 * to this object and can use it to export functionality.
6644 Local<Object> GetExtrasExportsObject();
6647 * Sets the embedder data with the given index, growing the data as
6648 * needed. Note that index 0 currently has a special meaning for Chrome's
6651 void SetEmbedderData(int index, Local<Value> value);
6654 * Gets a 2-byte-aligned native pointer from the embedder data with the given
6655 * index, which must have bees set by a previous call to
6656 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6657 * currently has a special meaning for Chrome's debugger.
6659 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
6662 * Sets a 2-byte-aligned native pointer in the embedder data with the given
6663 * index, growing the data as needed. Note that index 0 currently has a
6664 * special meaning for Chrome's debugger.
6666 void SetAlignedPointerInEmbedderData(int index, void* value);
6669 * Control whether code generation from strings is allowed. Calling
6670 * this method with false will disable 'eval' and the 'Function'
6671 * constructor for code running in this context. If 'eval' or the
6672 * 'Function' constructor are used an exception will be thrown.
6674 * If code generation from strings is not allowed the
6675 * V8::AllowCodeGenerationFromStrings callback will be invoked if
6676 * set before blocking the call to 'eval' or the 'Function'
6677 * constructor. If that callback returns true, the call will be
6678 * allowed, otherwise an exception will be thrown. If no callback is
6679 * set an exception will be thrown.
6681 void AllowCodeGenerationFromStrings(bool allow);
6684 * Returns true if code generation from strings is allowed for the context.
6685 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6687 bool IsCodeGenerationFromStringsAllowed();
6690 * Sets the error description for the exception that is thrown when
6691 * code generation from strings is not allowed and 'eval' or the 'Function'
6692 * constructor are called.
6694 void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
6697 * Stack-allocated class which sets the execution context for all
6698 * operations executed within a local scope.
6702 explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
6705 V8_INLINE ~Scope() { context_->Exit(); }
6708 Local<Context> context_;
6713 friend class Script;
6714 friend class Object;
6715 friend class Function;
6717 Local<Value> SlowGetEmbedderData(int index);
6718 void* SlowGetAlignedPointerFromEmbedderData(int index);
6723 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6724 * to use any given V8 isolate, see the comments in the Isolate class. The
6725 * definition of 'using a V8 isolate' includes accessing handles or holding onto
6726 * object pointers obtained from V8 handles while in the particular V8 isolate.
6727 * It is up to the user of V8 to ensure, perhaps with locking, that this
6728 * constraint is not violated. In addition to any other synchronization
6729 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6730 * used to signal thead switches to V8.
6732 * v8::Locker is a scoped lock object. While it's active, i.e. between its
6733 * construction and destruction, the current thread is allowed to use the locked
6734 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6735 * any time. In other words, the scope of a v8::Locker is a critical section.
6741 * v8::Locker locker(isolate);
6742 * v8::Isolate::Scope isolate_scope(isolate);
6744 * // Code using V8 and isolate goes here.
6746 * } // Destructor called here
6749 * If you wish to stop using V8 in a thread A you can do this either by
6750 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6756 * v8::Unlocker unlocker(isolate);
6758 * // Code not using V8 goes here while V8 can run in another thread.
6760 * } // Destructor called here.
6764 * The Unlocker object is intended for use in a long-running callback from V8,
6765 * where you want to release the V8 lock for other threads to use.
6767 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6768 * given thread. This can be useful if you have code that can be called either
6769 * from code that holds the lock or from code that does not. The Unlocker is
6770 * not recursive so you can not have several Unlockers on the stack at once, and
6771 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6773 * An unlocker will unlock several lockers if it has to and reinstate the
6774 * correct depth of locking on its destruction, e.g.:
6779 * v8::Locker locker(isolate);
6780 * Isolate::Scope isolate_scope(isolate);
6783 * v8::Locker another_locker(isolate);
6784 * // V8 still locked (2 levels).
6787 * v8::Unlocker unlocker(isolate);
6791 * // V8 locked again (2 levels).
6793 * // V8 still locked (1 level).
6795 * // V8 Now no longer locked.
6798 class V8_EXPORT Unlocker {
6801 * Initialize Unlocker for a given Isolate.
6803 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6807 void Initialize(Isolate* isolate);
6809 internal::Isolate* isolate_;
6813 class V8_EXPORT Locker {
6816 * Initialize Locker for a given Isolate.
6818 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6823 * Returns whether or not the locker for a given isolate, is locked by the
6826 static bool IsLocked(Isolate* isolate);
6829 * Returns whether v8::Locker is being used by this V8 instance.
6831 static bool IsActive();
6834 void Initialize(Isolate* isolate);
6838 internal::Isolate* isolate_;
6840 // Disallow copying and assigning.
6841 Locker(const Locker&);
6842 void operator=(const Locker&);
6846 // --- Implementation ---
6849 namespace internal {
6851 const int kApiPointerSize = sizeof(void*); // NOLINT
6852 const int kApiIntSize = sizeof(int); // NOLINT
6853 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6855 // Tag information for HeapObject.
6856 const int kHeapObjectTag = 1;
6857 const int kHeapObjectTagSize = 2;
6858 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6860 // Tag information for Smi.
6861 const int kSmiTag = 0;
6862 const int kSmiTagSize = 1;
6863 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6865 template <size_t ptr_size> struct SmiTagging;
6867 template<int kSmiShiftSize>
6868 V8_INLINE internal::Object* IntToSmi(int value) {
6869 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6870 uintptr_t tagged_value =
6871 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6872 return reinterpret_cast<internal::Object*>(tagged_value);
6875 // Smi constants for 32-bit systems.
6876 template <> struct SmiTagging<4> {
6877 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6878 static int SmiShiftSize() { return kSmiShiftSize; }
6879 static int SmiValueSize() { return kSmiValueSize; }
6880 V8_INLINE static int SmiToInt(const internal::Object* value) {
6881 int shift_bits = kSmiTagSize + kSmiShiftSize;
6882 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6883 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6885 V8_INLINE static internal::Object* IntToSmi(int value) {
6886 return internal::IntToSmi<kSmiShiftSize>(value);
6888 V8_INLINE static bool IsValidSmi(intptr_t value) {
6889 // To be representable as an tagged small integer, the two
6890 // most-significant bits of 'value' must be either 00 or 11 due to
6891 // sign-extension. To check this we add 01 to the two
6892 // most-significant bits, and check if the most-significant bit is 0
6894 // CAUTION: The original code below:
6895 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6896 // may lead to incorrect results according to the C language spec, and
6897 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6898 // compiler may produce undefined results in case of signed integer
6899 // overflow. The computation must be done w/ unsigned ints.
6900 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6904 // Smi constants for 64-bit systems.
6905 template <> struct SmiTagging<8> {
6906 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6907 static int SmiShiftSize() { return kSmiShiftSize; }
6908 static int SmiValueSize() { return kSmiValueSize; }
6909 V8_INLINE static int SmiToInt(const internal::Object* value) {
6910 int shift_bits = kSmiTagSize + kSmiShiftSize;
6911 // Shift down and throw away top 32 bits.
6912 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6914 V8_INLINE static internal::Object* IntToSmi(int value) {
6915 return internal::IntToSmi<kSmiShiftSize>(value);
6917 V8_INLINE static bool IsValidSmi(intptr_t value) {
6918 // To be representable as a long smi, the value must be a 32-bit integer.
6919 return (value == static_cast<int32_t>(value));
6923 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6924 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6925 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6926 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6927 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6930 * This class exports constants and functionality from within v8 that
6931 * is necessary to implement inline functions in the v8 api. Don't
6932 * depend on functions and constants defined here.
6936 // These values match non-compiler-dependent values defined within
6937 // the implementation of v8.
6938 static const int kHeapObjectMapOffset = 0;
6939 static const int kMapInstanceTypeAndBitFieldOffset =
6940 1 * kApiPointerSize + kApiIntSize;
6941 static const int kStringResourceOffset = 3 * kApiPointerSize;
6943 static const int kOddballKindOffset = 3 * kApiPointerSize;
6944 static const int kForeignAddressOffset = kApiPointerSize;
6945 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6946 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6947 static const int kContextHeaderSize = 2 * kApiPointerSize;
6948 static const int kContextEmbedderDataIndex = 81;
6949 static const int kFullStringRepresentationMask = 0x07;
6950 static const int kStringEncodingMask = 0x4;
6951 static const int kExternalTwoByteRepresentationTag = 0x02;
6952 static const int kExternalOneByteRepresentationTag = 0x06;
6954 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6955 static const int kAmountOfExternalAllocatedMemoryOffset =
6956 4 * kApiPointerSize;
6957 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6958 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6959 static const int kIsolateRootsOffset =
6960 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6962 static const int kUndefinedValueRootIndex = 5;
6963 static const int kNullValueRootIndex = 7;
6964 static const int kTrueValueRootIndex = 8;
6965 static const int kFalseValueRootIndex = 9;
6966 static const int kEmptyStringRootIndex = 10;
6968 // The external allocation limit should be below 256 MB on all architectures
6969 // to avoid that resource-constrained embedders run low on memory.
6970 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6972 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6973 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6974 static const int kNodeStateMask = 0x7;
6975 static const int kNodeStateIsWeakValue = 2;
6976 static const int kNodeStateIsPendingValue = 3;
6977 static const int kNodeStateIsNearDeathValue = 4;
6978 static const int kNodeIsIndependentShift = 3;
6979 static const int kNodeIsPartiallyDependentShift = 4;
6981 static const int kJSObjectType = 0xbe;
6982 static const int kFirstNonstringType = 0x80;
6983 static const int kOddballType = 0x83;
6984 static const int kForeignType = 0x87;
6986 static const int kUndefinedOddballKind = 5;
6987 static const int kNullOddballKind = 3;
6989 static const uint32_t kNumIsolateDataSlots = 4;
6991 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
6992 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
6993 #ifdef V8_ENABLE_CHECKS
6994 CheckInitializedImpl(isolate);
6998 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
6999 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
7003 V8_INLINE static int SmiValue(const internal::Object* value) {
7004 return PlatformSmiTagging::SmiToInt(value);
7007 V8_INLINE static internal::Object* IntToSmi(int value) {
7008 return PlatformSmiTagging::IntToSmi(value);
7011 V8_INLINE static bool IsValidSmi(intptr_t value) {
7012 return PlatformSmiTagging::IsValidSmi(value);
7015 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
7016 typedef internal::Object O;
7017 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
7018 // Map::InstanceType is defined so that it will always be loaded into
7019 // the LS 8 bits of one 16-bit word, regardless of endianess.
7020 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
7023 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
7024 typedef internal::Object O;
7025 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
7028 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
7029 int representation = (instance_type & kFullStringRepresentationMask);
7030 return representation == kExternalTwoByteRepresentationTag;
7033 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
7034 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7035 return *addr & static_cast<uint8_t>(1U << shift);
7038 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
7039 bool value, int shift) {
7040 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7041 uint8_t mask = static_cast<uint8_t>(1U << shift);
7042 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
7045 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
7046 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7047 return *addr & kNodeStateMask;
7050 V8_INLINE static void UpdateNodeState(internal::Object** obj,
7052 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7053 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
7056 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
7059 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
7060 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7061 *reinterpret_cast<void**>(addr) = data;
7064 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
7066 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
7067 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7068 return *reinterpret_cast<void* const*>(addr);
7071 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
7073 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
7074 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
7077 template <typename T>
7078 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
7079 const uint8_t* addr =
7080 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
7081 return *reinterpret_cast<const T*>(addr);
7084 template <typename T>
7085 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
7086 typedef internal::Object O;
7087 typedef internal::Internals I;
7088 O* ctx = *reinterpret_cast<O* const*>(context);
7089 int embedder_data_offset = I::kContextHeaderSize +
7090 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
7091 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
7093 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
7094 return I::ReadField<T>(embedder_data, value_offset);
7098 } // namespace internal
7102 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
7103 return New(isolate, that.val_);
7107 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
7108 return New(isolate, that.val_);
7113 Local<T> Local<T>::New(Isolate* isolate, T* that) {
7114 if (that == NULL) return Local<T>();
7116 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
7117 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
7118 reinterpret_cast<internal::Isolate*>(isolate), *p)));
7124 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
7126 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
7131 Local<T> Eternal<T>::Get(Isolate* isolate) {
7132 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
7137 Local<T> MaybeLocal<T>::ToLocalChecked() {
7138 if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
7139 return Local<T>(val_);
7144 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
7145 #ifdef V8_ENABLE_CHECKS
7146 if (index < 0 || index >= kInternalFieldsInWeakCallback) {
7147 V8::InternalFieldOutOfBounds(index);
7150 return internal_fields_[index];
7155 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
7156 if (that == NULL) return NULL;
7157 internal::Object** p = reinterpret_cast<internal::Object**>(that);
7158 return reinterpret_cast<T*>(
7159 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
7164 template <class T, class M>
7165 template <class S, class M2>
7166 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
7169 if (that.IsEmpty()) return;
7170 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
7171 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
7172 M::Copy(that, this);
7177 bool PersistentBase<T>::IsIndependent() const {
7178 typedef internal::Internals I;
7179 if (this->IsEmpty()) return false;
7180 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7181 I::kNodeIsIndependentShift);
7186 bool PersistentBase<T>::IsNearDeath() const {
7187 typedef internal::Internals I;
7188 if (this->IsEmpty()) return false;
7189 uint8_t node_state =
7190 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
7191 return node_state == I::kNodeStateIsNearDeathValue ||
7192 node_state == I::kNodeStateIsPendingValue;
7197 bool PersistentBase<T>::IsWeak() const {
7198 typedef internal::Internals I;
7199 if (this->IsEmpty()) return false;
7200 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
7201 I::kNodeStateIsWeakValue;
7206 void PersistentBase<T>::Reset() {
7207 if (this->IsEmpty()) return;
7208 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
7215 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
7218 if (other.IsEmpty()) return;
7219 this->val_ = New(isolate, other.val_);
7225 void PersistentBase<T>::Reset(Isolate* isolate,
7226 const PersistentBase<S>& other) {
7229 if (other.IsEmpty()) return;
7230 this->val_ = New(isolate, other.val_);
7235 template <typename S, typename P>
7236 void PersistentBase<T>::SetWeak(
7238 typename WeakCallbackData<S, P>::Callback callback) {
7240 typedef typename WeakCallbackData<Value, void>::Callback Callback;
7241 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7242 reinterpret_cast<Callback>(callback));
7247 template <typename P>
7248 void PersistentBase<T>::SetWeak(
7250 typename WeakCallbackData<T, P>::Callback callback) {
7251 SetWeak<T, P>(parameter, callback);
7256 template <typename P>
7257 void PersistentBase<T>::SetPhantom(
7258 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7259 int internal_field_index1, int internal_field_index2) {
7260 typedef typename WeakCallbackInfo<void>::Callback Callback;
7261 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7262 internal_field_index1, internal_field_index2,
7263 reinterpret_cast<Callback>(callback));
7268 template <typename P>
7269 V8_INLINE void PersistentBase<T>::SetWeak(
7270 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7271 WeakCallbackType type) {
7272 typedef typename WeakCallbackInfo<void>::Callback Callback;
7273 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7274 reinterpret_cast<Callback>(callback), type);
7279 template <typename P>
7280 P* PersistentBase<T>::ClearWeak() {
7281 return reinterpret_cast<P*>(
7282 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7287 void PersistentBase<T>::MarkIndependent() {
7288 typedef internal::Internals I;
7289 if (this->IsEmpty()) return;
7290 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7292 I::kNodeIsIndependentShift);
7297 void PersistentBase<T>::MarkPartiallyDependent() {
7298 typedef internal::Internals I;
7299 if (this->IsEmpty()) return;
7300 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7302 I::kNodeIsPartiallyDependentShift);
7307 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7308 typedef internal::Internals I;
7309 if (this->IsEmpty()) return;
7310 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7311 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7312 *reinterpret_cast<uint16_t*>(addr) = class_id;
7317 uint16_t PersistentBase<T>::WrapperClassId() const {
7318 typedef internal::Internals I;
7319 if (this->IsEmpty()) return 0;
7320 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7321 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7322 return *reinterpret_cast<uint16_t*>(addr);
7326 template<typename T>
7327 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7329 template<typename T>
7330 template<typename S>
7331 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7333 if (V8_UNLIKELY(handle.IsEmpty())) {
7334 *value_ = GetDefaultValue();
7336 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7340 template <typename T>
7341 template <typename S>
7342 void ReturnValue<T>::Set(const Global<S>& handle) {
7344 if (V8_UNLIKELY(handle.IsEmpty())) {
7345 *value_ = GetDefaultValue();
7347 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7351 template <typename T>
7352 template <typename S>
7353 void ReturnValue<T>::Set(const Local<S> handle) {
7355 if (V8_UNLIKELY(handle.IsEmpty())) {
7356 *value_ = GetDefaultValue();
7358 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7362 template<typename T>
7363 void ReturnValue<T>::Set(double i) {
7364 TYPE_CHECK(T, Number);
7365 Set(Number::New(GetIsolate(), i));
7368 template<typename T>
7369 void ReturnValue<T>::Set(int32_t i) {
7370 TYPE_CHECK(T, Integer);
7371 typedef internal::Internals I;
7372 if (V8_LIKELY(I::IsValidSmi(i))) {
7373 *value_ = I::IntToSmi(i);
7376 Set(Integer::New(GetIsolate(), i));
7379 template<typename T>
7380 void ReturnValue<T>::Set(uint32_t i) {
7381 TYPE_CHECK(T, Integer);
7382 // Can't simply use INT32_MAX here for whatever reason.
7383 bool fits_into_int32_t = (i & (1U << 31)) == 0;
7384 if (V8_LIKELY(fits_into_int32_t)) {
7385 Set(static_cast<int32_t>(i));
7388 Set(Integer::NewFromUnsigned(GetIsolate(), i));
7391 template<typename T>
7392 void ReturnValue<T>::Set(bool value) {
7393 TYPE_CHECK(T, Boolean);
7394 typedef internal::Internals I;
7397 root_index = I::kTrueValueRootIndex;
7399 root_index = I::kFalseValueRootIndex;
7401 *value_ = *I::GetRoot(GetIsolate(), root_index);
7404 template<typename T>
7405 void ReturnValue<T>::SetNull() {
7406 TYPE_CHECK(T, Primitive);
7407 typedef internal::Internals I;
7408 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
7411 template<typename T>
7412 void ReturnValue<T>::SetUndefined() {
7413 TYPE_CHECK(T, Primitive);
7414 typedef internal::Internals I;
7415 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
7418 template<typename T>
7419 void ReturnValue<T>::SetEmptyString() {
7420 TYPE_CHECK(T, String);
7421 typedef internal::Internals I;
7422 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
7425 template<typename T>
7426 Isolate* ReturnValue<T>::GetIsolate() {
7427 // Isolate is always the pointer below the default value on the stack.
7428 return *reinterpret_cast<Isolate**>(&value_[-2]);
7431 template<typename T>
7432 template<typename S>
7433 void ReturnValue<T>::Set(S* whatever) {
7434 // Uncompilable to prevent inadvertent misuse.
7435 TYPE_CHECK(S*, Primitive);
7438 template<typename T>
7439 internal::Object* ReturnValue<T>::GetDefaultValue() {
7440 // Default value is always the pointer below value_ on the stack.
7445 template<typename T>
7446 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
7447 internal::Object** values,
7449 bool is_construct_call)
7450 : implicit_args_(implicit_args),
7453 is_construct_call_(is_construct_call) { }
7456 template<typename T>
7457 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
7458 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7459 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7463 template<typename T>
7464 Local<Function> FunctionCallbackInfo<T>::Callee() const {
7465 return Local<Function>(reinterpret_cast<Function*>(
7466 &implicit_args_[kCalleeIndex]));
7470 template<typename T>
7471 Local<Object> FunctionCallbackInfo<T>::This() const {
7472 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7476 template<typename T>
7477 Local<Object> FunctionCallbackInfo<T>::Holder() const {
7478 return Local<Object>(reinterpret_cast<Object*>(
7479 &implicit_args_[kHolderIndex]));
7483 template<typename T>
7484 Local<Value> FunctionCallbackInfo<T>::Data() const {
7485 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7489 template<typename T>
7490 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
7491 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7495 template<typename T>
7496 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
7497 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
7501 template<typename T>
7502 bool FunctionCallbackInfo<T>::IsConstructCall() const {
7503 return is_construct_call_ & 0x1;
7507 template<typename T>
7508 int FunctionCallbackInfo<T>::Length() const {
7512 ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
7513 Local<Integer> resource_line_offset,
7514 Local<Integer> resource_column_offset,
7515 Local<Boolean> resource_is_shared_cross_origin,
7516 Local<Integer> script_id,
7517 Local<Boolean> resource_is_embedder_debug_script,
7518 Local<Value> source_map_url,
7519 Local<Boolean> resource_is_opaque)
7520 : resource_name_(resource_name),
7521 resource_line_offset_(resource_line_offset),
7522 resource_column_offset_(resource_column_offset),
7523 options_(!resource_is_embedder_debug_script.IsEmpty() &&
7524 resource_is_embedder_debug_script->IsTrue(),
7525 !resource_is_shared_cross_origin.IsEmpty() &&
7526 resource_is_shared_cross_origin->IsTrue(),
7527 !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue()),
7528 script_id_(script_id),
7529 source_map_url_(source_map_url) {}
7531 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
7534 Local<Integer> ScriptOrigin::ResourceLineOffset() const {
7535 return resource_line_offset_;
7539 Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
7540 return resource_column_offset_;
7544 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
7547 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7550 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
7552 : source_string(string),
7553 resource_name(origin.ResourceName()),
7554 resource_line_offset(origin.ResourceLineOffset()),
7555 resource_column_offset(origin.ResourceColumnOffset()),
7556 resource_options(origin.Options()),
7557 source_map_url(origin.SourceMapUrl()),
7558 cached_data(data) {}
7561 ScriptCompiler::Source::Source(Local<String> string,
7563 : source_string(string), cached_data(data) {}
7566 ScriptCompiler::Source::~Source() {
7571 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
7577 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
7578 return value ? True(isolate) : False(isolate);
7582 void Template::Set(Isolate* isolate, const char* name, v8::Local<Data> value) {
7583 Set(v8::String::NewFromUtf8(isolate, name, NewStringType::kNormal)
7589 Local<Value> Object::GetInternalField(int index) {
7590 #ifndef V8_ENABLE_CHECKS
7591 typedef internal::Object O;
7592 typedef internal::HeapObject HO;
7593 typedef internal::Internals I;
7594 O* obj = *reinterpret_cast<O**>(this);
7595 // Fast path: If the object is a plain JSObject, which is the common case, we
7596 // know where to find the internal fields and can return the value directly.
7597 if (I::GetInstanceType(obj) == I::kJSObjectType) {
7598 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7599 O* value = I::ReadField<O*>(obj, offset);
7600 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7601 return Local<Value>(reinterpret_cast<Value*>(result));
7604 return SlowGetInternalField(index);
7608 void* Object::GetAlignedPointerFromInternalField(int index) {
7609 #ifndef V8_ENABLE_CHECKS
7610 typedef internal::Object O;
7611 typedef internal::Internals I;
7612 O* obj = *reinterpret_cast<O**>(this);
7613 // Fast path: If the object is a plain JSObject, which is the common case, we
7614 // know where to find the internal fields and can return the value directly.
7615 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
7616 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7617 return I::ReadField<void*>(obj, offset);
7620 return SlowGetAlignedPointerFromInternalField(index);
7624 String* String::Cast(v8::Value* value) {
7625 #ifdef V8_ENABLE_CHECKS
7628 return static_cast<String*>(value);
7632 Local<String> String::Empty(Isolate* isolate) {
7633 typedef internal::Object* S;
7634 typedef internal::Internals I;
7635 I::CheckInitialized(isolate);
7636 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7637 return Local<String>(reinterpret_cast<String*>(slot));
7641 String::ExternalStringResource* String::GetExternalStringResource() const {
7642 typedef internal::Object O;
7643 typedef internal::Internals I;
7644 O* obj = *reinterpret_cast<O* const*>(this);
7645 String::ExternalStringResource* result;
7646 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
7647 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7648 result = reinterpret_cast<String::ExternalStringResource*>(value);
7652 #ifdef V8_ENABLE_CHECKS
7653 VerifyExternalStringResource(result);
7659 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
7660 String::Encoding* encoding_out) const {
7661 typedef internal::Object O;
7662 typedef internal::Internals I;
7663 O* obj = *reinterpret_cast<O* const*>(this);
7664 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
7665 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7666 ExternalStringResourceBase* resource = NULL;
7667 if (type == I::kExternalOneByteRepresentationTag ||
7668 type == I::kExternalTwoByteRepresentationTag) {
7669 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7670 resource = static_cast<ExternalStringResourceBase*>(value);
7672 #ifdef V8_ENABLE_CHECKS
7673 VerifyExternalStringResourceBase(resource, *encoding_out);
7679 bool Value::IsUndefined() const {
7680 #ifdef V8_ENABLE_CHECKS
7681 return FullIsUndefined();
7683 return QuickIsUndefined();
7687 bool Value::QuickIsUndefined() const {
7688 typedef internal::Object O;
7689 typedef internal::Internals I;
7690 O* obj = *reinterpret_cast<O* const*>(this);
7691 if (!I::HasHeapObjectTag(obj)) return false;
7692 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7693 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
7697 bool Value::IsNull() const {
7698 #ifdef V8_ENABLE_CHECKS
7699 return FullIsNull();
7701 return QuickIsNull();
7705 bool Value::QuickIsNull() const {
7706 typedef internal::Object O;
7707 typedef internal::Internals I;
7708 O* obj = *reinterpret_cast<O* const*>(this);
7709 if (!I::HasHeapObjectTag(obj)) return false;
7710 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7711 return (I::GetOddballKind(obj) == I::kNullOddballKind);
7715 bool Value::IsString() const {
7716 #ifdef V8_ENABLE_CHECKS
7717 return FullIsString();
7719 return QuickIsString();
7723 bool Value::QuickIsString() const {
7724 typedef internal::Object O;
7725 typedef internal::Internals I;
7726 O* obj = *reinterpret_cast<O* const*>(this);
7727 if (!I::HasHeapObjectTag(obj)) return false;
7728 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7732 template <class T> Value* Value::Cast(T* value) {
7733 return static_cast<Value*>(value);
7737 Local<Boolean> Value::ToBoolean() const {
7738 return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
7739 .FromMaybe(Local<Boolean>());
7743 Local<Number> Value::ToNumber() const {
7744 return ToNumber(Isolate::GetCurrent()->GetCurrentContext())
7745 .FromMaybe(Local<Number>());
7749 Local<String> Value::ToString() const {
7750 return ToString(Isolate::GetCurrent()->GetCurrentContext())
7751 .FromMaybe(Local<String>());
7755 Local<String> Value::ToDetailString() const {
7756 return ToDetailString(Isolate::GetCurrent()->GetCurrentContext())
7757 .FromMaybe(Local<String>());
7761 Local<Object> Value::ToObject() const {
7762 return ToObject(Isolate::GetCurrent()->GetCurrentContext())
7763 .FromMaybe(Local<Object>());
7767 Local<Integer> Value::ToInteger() const {
7768 return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
7769 .FromMaybe(Local<Integer>());
7773 Local<Uint32> Value::ToUint32() const {
7774 return ToUint32(Isolate::GetCurrent()->GetCurrentContext())
7775 .FromMaybe(Local<Uint32>());
7779 Local<Int32> Value::ToInt32() const {
7780 return ToInt32(Isolate::GetCurrent()->GetCurrentContext())
7781 .FromMaybe(Local<Int32>());
7785 Boolean* Boolean::Cast(v8::Value* value) {
7786 #ifdef V8_ENABLE_CHECKS
7789 return static_cast<Boolean*>(value);
7793 Name* Name::Cast(v8::Value* value) {
7794 #ifdef V8_ENABLE_CHECKS
7797 return static_cast<Name*>(value);
7801 Symbol* Symbol::Cast(v8::Value* value) {
7802 #ifdef V8_ENABLE_CHECKS
7805 return static_cast<Symbol*>(value);
7809 Number* Number::Cast(v8::Value* value) {
7810 #ifdef V8_ENABLE_CHECKS
7813 return static_cast<Number*>(value);
7817 Integer* Integer::Cast(v8::Value* value) {
7818 #ifdef V8_ENABLE_CHECKS
7821 return static_cast<Integer*>(value);
7825 Int32* Int32::Cast(v8::Value* value) {
7826 #ifdef V8_ENABLE_CHECKS
7829 return static_cast<Int32*>(value);
7833 Uint32* Uint32::Cast(v8::Value* value) {
7834 #ifdef V8_ENABLE_CHECKS
7837 return static_cast<Uint32*>(value);
7841 Date* Date::Cast(v8::Value* value) {
7842 #ifdef V8_ENABLE_CHECKS
7845 return static_cast<Date*>(value);
7849 StringObject* StringObject::Cast(v8::Value* value) {
7850 #ifdef V8_ENABLE_CHECKS
7853 return static_cast<StringObject*>(value);
7857 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7858 #ifdef V8_ENABLE_CHECKS
7861 return static_cast<SymbolObject*>(value);
7865 NumberObject* NumberObject::Cast(v8::Value* value) {
7866 #ifdef V8_ENABLE_CHECKS
7869 return static_cast<NumberObject*>(value);
7873 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7874 #ifdef V8_ENABLE_CHECKS
7877 return static_cast<BooleanObject*>(value);
7881 RegExp* RegExp::Cast(v8::Value* value) {
7882 #ifdef V8_ENABLE_CHECKS
7885 return static_cast<RegExp*>(value);
7889 Object* Object::Cast(v8::Value* value) {
7890 #ifdef V8_ENABLE_CHECKS
7893 return static_cast<Object*>(value);
7897 Array* Array::Cast(v8::Value* value) {
7898 #ifdef V8_ENABLE_CHECKS
7901 return static_cast<Array*>(value);
7905 Map* Map::Cast(v8::Value* value) {
7906 #ifdef V8_ENABLE_CHECKS
7909 return static_cast<Map*>(value);
7913 Set* Set::Cast(v8::Value* value) {
7914 #ifdef V8_ENABLE_CHECKS
7917 return static_cast<Set*>(value);
7921 Promise* Promise::Cast(v8::Value* value) {
7922 #ifdef V8_ENABLE_CHECKS
7925 return static_cast<Promise*>(value);
7929 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7930 #ifdef V8_ENABLE_CHECKS
7933 return static_cast<Promise::Resolver*>(value);
7937 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7938 #ifdef V8_ENABLE_CHECKS
7941 return static_cast<ArrayBuffer*>(value);
7945 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7946 #ifdef V8_ENABLE_CHECKS
7949 return static_cast<ArrayBufferView*>(value);
7953 TypedArray* TypedArray::Cast(v8::Value* value) {
7954 #ifdef V8_ENABLE_CHECKS
7957 return static_cast<TypedArray*>(value);
7961 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7962 #ifdef V8_ENABLE_CHECKS
7965 return static_cast<Uint8Array*>(value);
7969 Int8Array* Int8Array::Cast(v8::Value* value) {
7970 #ifdef V8_ENABLE_CHECKS
7973 return static_cast<Int8Array*>(value);
7977 Uint16Array* Uint16Array::Cast(v8::Value* value) {
7978 #ifdef V8_ENABLE_CHECKS
7981 return static_cast<Uint16Array*>(value);
7985 Int16Array* Int16Array::Cast(v8::Value* value) {
7986 #ifdef V8_ENABLE_CHECKS
7989 return static_cast<Int16Array*>(value);
7993 Uint32Array* Uint32Array::Cast(v8::Value* value) {
7994 #ifdef V8_ENABLE_CHECKS
7997 return static_cast<Uint32Array*>(value);
8001 Int32Array* Int32Array::Cast(v8::Value* value) {
8002 #ifdef V8_ENABLE_CHECKS
8005 return static_cast<Int32Array*>(value);
8009 Float32Array* Float32Array::Cast(v8::Value* value) {
8010 #ifdef V8_ENABLE_CHECKS
8013 return static_cast<Float32Array*>(value);
8017 Float64Array* Float64Array::Cast(v8::Value* value) {
8018 #ifdef V8_ENABLE_CHECKS
8021 return static_cast<Float64Array*>(value);
8025 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
8026 #ifdef V8_ENABLE_CHECKS
8029 return static_cast<Uint8ClampedArray*>(value);
8033 DataView* DataView::Cast(v8::Value* value) {
8034 #ifdef V8_ENABLE_CHECKS
8037 return static_cast<DataView*>(value);
8041 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
8042 #ifdef V8_ENABLE_CHECKS
8045 return static_cast<SharedArrayBuffer*>(value);
8049 Function* Function::Cast(v8::Value* value) {
8050 #ifdef V8_ENABLE_CHECKS
8053 return static_cast<Function*>(value);
8057 External* External::Cast(v8::Value* value) {
8058 #ifdef V8_ENABLE_CHECKS
8061 return static_cast<External*>(value);
8065 template<typename T>
8066 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
8067 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
8071 template<typename T>
8072 Local<Value> PropertyCallbackInfo<T>::Data() const {
8073 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
8077 template<typename T>
8078 Local<Object> PropertyCallbackInfo<T>::This() const {
8079 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
8083 template<typename T>
8084 Local<Object> PropertyCallbackInfo<T>::Holder() const {
8085 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
8089 template<typename T>
8090 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
8091 return ReturnValue<T>(&args_[kReturnValueIndex]);
8095 Local<Primitive> Undefined(Isolate* isolate) {
8096 typedef internal::Object* S;
8097 typedef internal::Internals I;
8098 I::CheckInitialized(isolate);
8099 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
8100 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8104 Local<Primitive> Null(Isolate* isolate) {
8105 typedef internal::Object* S;
8106 typedef internal::Internals I;
8107 I::CheckInitialized(isolate);
8108 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
8109 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8113 Local<Boolean> True(Isolate* isolate) {
8114 typedef internal::Object* S;
8115 typedef internal::Internals I;
8116 I::CheckInitialized(isolate);
8117 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
8118 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8122 Local<Boolean> False(Isolate* isolate) {
8123 typedef internal::Object* S;
8124 typedef internal::Internals I;
8125 I::CheckInitialized(isolate);
8126 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
8127 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8131 void Isolate::SetData(uint32_t slot, void* data) {
8132 typedef internal::Internals I;
8133 I::SetEmbedderData(this, slot, data);
8137 void* Isolate::GetData(uint32_t slot) {
8138 typedef internal::Internals I;
8139 return I::GetEmbedderData(this, slot);
8143 uint32_t Isolate::GetNumberOfDataSlots() {
8144 typedef internal::Internals I;
8145 return I::kNumIsolateDataSlots;
8149 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
8150 int64_t change_in_bytes) {
8151 typedef internal::Internals I;
8152 int64_t* amount_of_external_allocated_memory =
8153 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
8154 I::kAmountOfExternalAllocatedMemoryOffset);
8155 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
8156 reinterpret_cast<int64_t*>(
8157 reinterpret_cast<uint8_t*>(this) +
8158 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
8159 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
8160 if (change_in_bytes > 0 &&
8161 amount - *amount_of_external_allocated_memory_at_last_global_gc >
8162 I::kExternalAllocationLimit) {
8163 CollectAllGarbage("external memory allocation limit reached.");
8165 *amount_of_external_allocated_memory = amount;
8166 return *amount_of_external_allocated_memory;
8170 template<typename T>
8171 void Isolate::SetObjectGroupId(const Persistent<T>& object,
8173 TYPE_CHECK(Value, T);
8174 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
8178 template<typename T>
8179 void Isolate::SetReferenceFromGroup(UniqueId id,
8180 const Persistent<T>& object) {
8181 TYPE_CHECK(Value, T);
8182 SetReferenceFromGroup(id,
8183 reinterpret_cast<v8::internal::Object**>(object.val_));
8187 template<typename T, typename S>
8188 void Isolate::SetReference(const Persistent<T>& parent,
8189 const Persistent<S>& child) {
8190 TYPE_CHECK(Object, T);
8191 TYPE_CHECK(Value, S);
8192 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
8193 reinterpret_cast<v8::internal::Object**>(child.val_));
8197 Local<Value> Context::GetEmbedderData(int index) {
8198 #ifndef V8_ENABLE_CHECKS
8199 typedef internal::Object O;
8200 typedef internal::HeapObject HO;
8201 typedef internal::Internals I;
8202 HO* context = *reinterpret_cast<HO**>(this);
8204 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
8205 return Local<Value>(reinterpret_cast<Value*>(result));
8207 return SlowGetEmbedderData(index);
8212 void* Context::GetAlignedPointerFromEmbedderData(int index) {
8213 #ifndef V8_ENABLE_CHECKS
8214 typedef internal::Internals I;
8215 return I::ReadEmbedderData<void*>(this, index);
8217 return SlowGetAlignedPointerFromEmbedderData(index);
8222 void V8::SetAllowCodeGenerationFromStringsCallback(
8223 AllowCodeGenerationFromStringsCallback callback) {
8224 Isolate* isolate = Isolate::GetCurrent();
8225 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
8230 Isolate* isolate = Isolate::GetCurrent();
8231 return isolate->IsDead();
8235 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
8236 Isolate* isolate = Isolate::GetCurrent();
8237 return isolate->AddMessageListener(that, data);
8241 void V8::RemoveMessageListeners(MessageCallback that) {
8242 Isolate* isolate = Isolate::GetCurrent();
8243 isolate->RemoveMessageListeners(that);
8247 void V8::SetFailedAccessCheckCallbackFunction(
8248 FailedAccessCheckCallback callback) {
8249 Isolate* isolate = Isolate::GetCurrent();
8250 isolate->SetFailedAccessCheckCallbackFunction(callback);
8254 void V8::SetCaptureStackTraceForUncaughtExceptions(
8255 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8256 Isolate* isolate = Isolate::GetCurrent();
8257 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8262 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
8263 Isolate* isolate = Isolate::GetCurrent();
8264 isolate->SetFatalErrorHandler(callback);
8268 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
8269 Isolate* isolate = Isolate::GetCurrent();
8270 isolate->RemoveGCPrologueCallback(
8271 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
8275 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
8276 Isolate* isolate = Isolate::GetCurrent();
8277 isolate->RemoveGCEpilogueCallback(
8278 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
8282 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8284 AllocationAction action) {
8285 Isolate* isolate = Isolate::GetCurrent();
8286 isolate->AddMemoryAllocationCallback(callback, space, action);
8290 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8291 Isolate* isolate = Isolate::GetCurrent();
8292 isolate->RemoveMemoryAllocationCallback(callback);
8296 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8299 bool V8::IsExecutionTerminating(Isolate* isolate) {
8300 if (isolate == NULL) {
8301 isolate = Isolate::GetCurrent();
8303 return isolate->IsExecutionTerminating();
8307 void V8::CancelTerminateExecution(Isolate* isolate) {
8308 isolate->CancelTerminateExecution();
8312 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8313 Isolate* isolate = Isolate::GetCurrent();
8314 isolate->VisitExternalResources(visitor);
8318 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8319 Isolate* isolate = Isolate::GetCurrent();
8320 isolate->VisitHandlesWithClassIds(visitor);
8324 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8325 PersistentHandleVisitor* visitor) {
8326 isolate->VisitHandlesWithClassIds(visitor);
8330 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8331 PersistentHandleVisitor* visitor) {
8332 isolate->VisitHandlesForPartialDependence(visitor);
8337 * A simple shell that takes a list of expressions on the
8338 * command-line and executes them.
8343 * \example process.cc