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(const PersistentBase& other) = delete; // NOLINT
642 void operator=(const 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(const Global&) = delete;
849 void operator=(const 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();
1121 * For compiling scripts.
1123 class V8_EXPORT ScriptCompiler {
1126 * Compilation data that the embedder can cache and pass back to speed up
1127 * future compilations. The data is produced if the CompilerOptions passed to
1128 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1129 * = true. The data to cache can then can be retrieved from
1132 struct V8_EXPORT CachedData {
1142 buffer_policy(BufferNotOwned) {}
1144 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1145 // data and guarantees that it stays alive until the CachedData object is
1146 // destroyed. If the policy is BufferOwned, the given data will be deleted
1147 // (with delete[]) when the CachedData object is destroyed.
1148 CachedData(const uint8_t* data, int length,
1149 BufferPolicy buffer_policy = BufferNotOwned);
1151 // TODO(marja): Async compilation; add constructors which take a callback
1152 // which will be called when V8 no longer needs the data.
1153 const uint8_t* data;
1156 BufferPolicy buffer_policy;
1159 // Prevent copying. Not implemented.
1160 CachedData(const CachedData&);
1161 CachedData& operator=(const CachedData&);
1165 * Source code which can be then compiled to a UnboundScript or Script.
1169 // Source takes ownership of CachedData.
1170 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1171 CachedData* cached_data = NULL);
1172 V8_INLINE Source(Local<String> source_string,
1173 CachedData* cached_data = NULL);
1174 V8_INLINE ~Source();
1176 // Ownership of the CachedData or its buffers is *not* transferred to the
1177 // caller. The CachedData object is alive as long as the Source object is
1179 V8_INLINE const CachedData* GetCachedData() const;
1182 friend class ScriptCompiler;
1183 // Prevent copying. Not implemented.
1184 Source(const Source&);
1185 Source& operator=(const Source&);
1187 Local<String> source_string;
1189 // Origin information
1190 Local<Value> resource_name;
1191 Local<Integer> resource_line_offset;
1192 Local<Integer> resource_column_offset;
1193 ScriptOriginOptions resource_options;
1194 Local<Value> source_map_url;
1196 // Cached data from previous compilation (if a kConsume*Cache flag is
1197 // set), or hold newly generated cache data (kProduce*Cache flags) are
1198 // set when calling a compile method.
1199 CachedData* cached_data;
1203 * For streaming incomplete script data to V8. The embedder should implement a
1204 * subclass of this class.
1206 class V8_EXPORT ExternalSourceStream {
1208 virtual ~ExternalSourceStream() {}
1211 * V8 calls this to request the next chunk of data from the embedder. This
1212 * function will be called on a background thread, so it's OK to block and
1213 * wait for the data, if the embedder doesn't have data yet. Returns the
1214 * length of the data returned. When the data ends, GetMoreData should
1215 * return 0. Caller takes ownership of the data.
1217 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1218 * two data chunks, but doesn't handle multi-byte characters split between
1219 * more than two data chunks. The embedder can avoid this problem by always
1220 * returning at least 2 bytes of data.
1222 * If the embedder wants to cancel the streaming, they should make the next
1223 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1224 * probably, parsing will fail). The streaming task will return as soon as
1225 * V8 has parsed the data it received so far.
1227 virtual size_t GetMoreData(const uint8_t** src) = 0;
1230 * V8 calls this method to set a 'bookmark' at the current position in
1231 * the source stream, for the purpose of (maybe) later calling
1232 * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1233 * calls to GetMoreData should return the same data as they did when
1234 * SetBookmark was called earlier.
1236 * The embedder may return 'false' to indicate it cannot provide this
1239 virtual bool SetBookmark();
1242 * V8 calls this to return to a previously set bookmark.
1244 virtual void ResetToBookmark();
1249 * Source code which can be streamed into V8 in pieces. It will be parsed
1250 * while streaming. It can be compiled after the streaming is complete.
1251 * StreamedSource must be kept alive while the streaming task is ran (see
1252 * ScriptStreamingTask below).
1254 class V8_EXPORT StreamedSource {
1256 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1258 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1261 // Ownership of the CachedData or its buffers is *not* transferred to the
1262 // caller. The CachedData object is alive as long as the StreamedSource
1264 const CachedData* GetCachedData() const;
1266 internal::StreamedSource* impl() const { return impl_; }
1269 // Prevent copying. Not implemented.
1270 StreamedSource(const StreamedSource&);
1271 StreamedSource& operator=(const StreamedSource&);
1273 internal::StreamedSource* impl_;
1277 * A streaming task which the embedder must run on a background thread to
1278 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1280 class ScriptStreamingTask {
1282 virtual ~ScriptStreamingTask() {}
1283 virtual void Run() = 0;
1286 enum CompileOptions {
1287 kNoCompileOptions = 0,
1288 kProduceParserCache,
1289 kConsumeParserCache,
1295 * Compiles the specified script (context-independent).
1296 * Cached data as part of the source object can be optionally produced to be
1297 * consumed later to speed up compilation of identical source scripts.
1299 * Note that when producing cached data, the source must point to NULL for
1300 * cached data. When consuming cached data, the cached data must have been
1301 * produced by the same version of V8.
1303 * \param source Script source code.
1304 * \return Compiled script object (context independent; for running it must be
1305 * bound to a context).
1307 static V8_DEPRECATE_SOON("Use maybe version",
1308 Local<UnboundScript> CompileUnbound(
1309 Isolate* isolate, Source* source,
1310 CompileOptions options = kNoCompileOptions));
1311 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
1312 Isolate* isolate, Source* source,
1313 CompileOptions options = kNoCompileOptions);
1316 * Compiles the specified script (bound to current context).
1318 * \param source Script source code.
1319 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1320 * using pre_data speeds compilation if it's done multiple times.
1321 * Owned by caller, no references are kept when this function returns.
1322 * \return Compiled script object, bound to the context that was active
1323 * when this function was called. When run it will always use this
1326 static V8_DEPRECATE_SOON(
1327 "Use maybe version",
1328 Local<Script> Compile(Isolate* isolate, Source* source,
1329 CompileOptions options = kNoCompileOptions));
1330 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1331 Local<Context> context, Source* source,
1332 CompileOptions options = kNoCompileOptions);
1335 * Returns a task which streams script data into V8, or NULL if the script
1336 * cannot be streamed. The user is responsible for running the task on a
1337 * background thread and deleting it. When ran, the task starts parsing the
1338 * script, and it will request data from the StreamedSource as needed. When
1339 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1340 * can be compiled (see Compile below).
1342 * This API allows to start the streaming with as little data as possible, and
1343 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1345 static ScriptStreamingTask* StartStreamingScript(
1346 Isolate* isolate, StreamedSource* source,
1347 CompileOptions options = kNoCompileOptions);
1350 * Compiles a streamed script (bound to current context).
1352 * This can only be called after the streaming has finished
1353 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1354 * during streaming, so the embedder needs to pass the full source here.
1356 static V8_DEPRECATE_SOON(
1357 "Use maybe version",
1358 Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1359 Local<String> full_source_string,
1360 const ScriptOrigin& origin));
1361 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1362 Local<Context> context, StreamedSource* source,
1363 Local<String> full_source_string, const ScriptOrigin& origin);
1366 * Return a version tag for CachedData for the current V8 version & flags.
1368 * This value is meant only for determining whether a previously generated
1369 * CachedData instance is still valid; the tag has no other meaing.
1371 * Background: The data carried by CachedData may depend on the exact
1372 * V8 version number or currently compiler flags. This means when
1373 * persisting CachedData, the embedder must take care to not pass in
1374 * data from another V8 version, or the same version with different
1377 * The easiest way to do so is to clear the embedder's cache on any
1380 * Alternatively, this tag can be stored alongside the cached data and
1381 * compared when it is being used.
1383 static uint32_t CachedDataVersionTag();
1386 * Compile an ES6 module.
1388 * This is an experimental feature.
1390 * TODO(adamk): Script is likely the wrong return value for this;
1391 * should return some new Module type.
1393 static V8_DEPRECATE_SOON(
1394 "Use maybe version",
1395 Local<Script> CompileModule(Isolate* isolate, Source* source,
1396 CompileOptions options = kNoCompileOptions));
1397 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> CompileModule(
1398 Local<Context> context, Source* source,
1399 CompileOptions options = kNoCompileOptions);
1402 * Compile a function for a given context. This is equivalent to running
1405 * return function(args) { ... }
1408 * It is possible to specify multiple context extensions (obj in the above
1411 static V8_DEPRECATE_SOON("Use maybe version",
1412 Local<Function> CompileFunctionInContext(
1413 Isolate* isolate, Source* source,
1414 Local<Context> context, size_t arguments_count,
1415 Local<String> arguments[],
1416 size_t context_extension_count,
1417 Local<Object> context_extensions[]));
1418 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
1419 Local<Context> context, Source* source, size_t arguments_count,
1420 Local<String> arguments[], size_t context_extension_count,
1421 Local<Object> context_extensions[]);
1424 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1425 Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1432 class V8_EXPORT Message {
1434 Local<String> Get() const;
1436 V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1437 V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
1438 Local<Context> context) const;
1441 * Returns the origin for the script from where the function causing the
1444 ScriptOrigin GetScriptOrigin() const;
1447 * Returns the resource name for the script from where the function causing
1448 * the error originates.
1450 Local<Value> GetScriptResourceName() const;
1453 * Exception stack trace. By default stack traces are not captured for
1454 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1455 * to change this option.
1457 Local<StackTrace> GetStackTrace() const;
1460 * Returns the number, 1-based, of the line where the error occurred.
1462 V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1463 V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1466 * Returns the index within the script of the first character where
1467 * the error occurred.
1469 int GetStartPosition() const;
1472 * Returns the index within the script of the last character where
1473 * the error occurred.
1475 int GetEndPosition() const;
1478 * Returns the index within the line of the first character where
1479 * the error occurred.
1481 V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1482 V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1485 * Returns the index within the line of the last character where
1486 * the error occurred.
1488 V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn() const);
1489 V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1492 * Passes on the value set by the embedder when it fed the script from which
1493 * this Message was generated to V8.
1495 bool IsSharedCrossOrigin() const;
1496 bool IsOpaque() const;
1498 // TODO(1245381): Print to a string instead of on a FILE.
1499 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1501 static const int kNoLineNumberInfo = 0;
1502 static const int kNoColumnInfo = 0;
1503 static const int kNoScriptIdInfo = 0;
1508 * Representation of a JavaScript stack trace. The information collected is a
1509 * snapshot of the execution stack and the information remains valid after
1510 * execution continues.
1512 class V8_EXPORT StackTrace {
1515 * Flags that determine what information is placed captured for each
1516 * StackFrame when grabbing the current stack trace.
1518 enum StackTraceOptions {
1520 kColumnOffset = 1 << 1 | kLineNumber,
1521 kScriptName = 1 << 2,
1522 kFunctionName = 1 << 3,
1524 kIsConstructor = 1 << 5,
1525 kScriptNameOrSourceURL = 1 << 6,
1527 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1528 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1529 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1533 * Returns a StackFrame at a particular index.
1535 Local<StackFrame> GetFrame(uint32_t index) const;
1538 * Returns the number of StackFrames.
1540 int GetFrameCount() const;
1543 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1545 Local<Array> AsArray();
1548 * Grab a snapshot of the current JavaScript execution stack.
1550 * \param frame_limit The maximum number of stack frames we want to capture.
1551 * \param options Enumerates the set of things we will capture for each
1554 static Local<StackTrace> CurrentStackTrace(
1557 StackTraceOptions options = kOverview);
1562 * A single JavaScript stack frame.
1564 class V8_EXPORT StackFrame {
1567 * Returns the number, 1-based, of the line for the associate function call.
1568 * This method will return Message::kNoLineNumberInfo if it is unable to
1569 * retrieve the line number, or if kLineNumber was not passed as an option
1570 * when capturing the StackTrace.
1572 int GetLineNumber() const;
1575 * Returns the 1-based column offset on the line for the associated function
1577 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1578 * the column number, or if kColumnOffset was not passed as an option when
1579 * capturing the StackTrace.
1581 int GetColumn() const;
1584 * Returns the id of the script for the function for this StackFrame.
1585 * This method will return Message::kNoScriptIdInfo if it is unable to
1586 * retrieve the script id, or if kScriptId was not passed as an option when
1587 * capturing the StackTrace.
1589 int GetScriptId() const;
1592 * Returns the name of the resource that contains the script for the
1593 * function for this StackFrame.
1595 Local<String> GetScriptName() const;
1598 * Returns the name of the resource that contains the script for the
1599 * function for this StackFrame or sourceURL value if the script name
1600 * is undefined and its source ends with //# sourceURL=... string or
1601 * deprecated //@ sourceURL=... string.
1603 Local<String> GetScriptNameOrSourceURL() const;
1606 * Returns the name of the function associated with this stack frame.
1608 Local<String> GetFunctionName() const;
1611 * Returns whether or not the associated function is compiled via a call to
1614 bool IsEval() const;
1617 * Returns whether or not the associated function is called as a
1618 * constructor via "new".
1620 bool IsConstructor() const;
1624 // A StateTag represents a possible state of the VM.
1625 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
1628 // A RegisterState represents the current state of registers used
1629 // by the sampling profiler API.
1630 struct RegisterState {
1631 RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1632 void* pc; // Instruction pointer.
1633 void* sp; // Stack pointer.
1634 void* fp; // Frame pointer.
1638 // The output structure filled up by GetStackSample API function.
1640 size_t frames_count;
1648 class V8_EXPORT JSON {
1651 * Tries to parse the string |json_string| and returns it as value if
1654 * \param json_string The string to parse.
1655 * \return The corresponding value if successfully parsed.
1657 static V8_DEPRECATE_SOON("Use maybe version",
1658 Local<Value> Parse(Local<String> json_string));
1659 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1660 Isolate* isolate, Local<String> json_string);
1665 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1666 * but can be created without entering a v8::Context and hence shouldn't
1667 * escape to JavaScript.
1669 class V8_EXPORT NativeWeakMap : public Data {
1671 static Local<NativeWeakMap> New(Isolate* isolate);
1672 void Set(Local<Value> key, Local<Value> value);
1673 Local<Value> Get(Local<Value> key);
1674 bool Has(Local<Value> key);
1675 bool Delete(Local<Value> key);
1683 * The superclass of all JavaScript values and objects.
1685 class V8_EXPORT Value : public Data {
1688 * Returns true if this value is the undefined value. See ECMA-262
1691 V8_INLINE bool IsUndefined() const;
1694 * Returns true if this value is the null value. See ECMA-262
1697 V8_INLINE bool IsNull() const;
1700 * Returns true if this value is true.
1702 bool IsTrue() const;
1705 * Returns true if this value is false.
1707 bool IsFalse() const;
1710 * Returns true if this value is a symbol or a string.
1711 * This is an experimental feature.
1713 bool IsName() const;
1716 * Returns true if this value is an instance of the String type.
1719 V8_INLINE bool IsString() const;
1722 * Returns true if this value is a symbol.
1723 * This is an experimental feature.
1725 bool IsSymbol() const;
1728 * Returns true if this value is a function.
1730 bool IsFunction() const;
1733 * Returns true if this value is an array.
1735 bool IsArray() const;
1738 * Returns true if this value is an object.
1740 bool IsObject() const;
1743 * Returns true if this value is boolean.
1745 bool IsBoolean() const;
1748 * Returns true if this value is a number.
1750 bool IsNumber() const;
1753 * Returns true if this value is external.
1755 bool IsExternal() const;
1758 * Returns true if this value is a 32-bit signed integer.
1760 bool IsInt32() const;
1763 * Returns true if this value is a 32-bit unsigned integer.
1765 bool IsUint32() const;
1768 * Returns true if this value is a Date.
1770 bool IsDate() const;
1773 * Returns true if this value is an Arguments object.
1775 bool IsArgumentsObject() const;
1778 * Returns true if this value is a Boolean object.
1780 bool IsBooleanObject() const;
1783 * Returns true if this value is a Number object.
1785 bool IsNumberObject() const;
1788 * Returns true if this value is a String object.
1790 bool IsStringObject() const;
1793 * Returns true if this value is a Symbol object.
1794 * This is an experimental feature.
1796 bool IsSymbolObject() const;
1799 * Returns true if this value is a NativeError.
1801 bool IsNativeError() const;
1804 * Returns true if this value is a RegExp.
1806 bool IsRegExp() const;
1809 * Returns true if this value is a Generator function.
1810 * This is an experimental feature.
1812 bool IsGeneratorFunction() const;
1815 * Returns true if this value is a Generator object (iterator).
1816 * This is an experimental feature.
1818 bool IsGeneratorObject() const;
1821 * Returns true if this value is a Promise.
1822 * This is an experimental feature.
1824 bool IsPromise() const;
1827 * Returns true if this value is a Map.
1832 * Returns true if this value is a Set.
1837 * Returns true if this value is a Map Iterator.
1839 bool IsMapIterator() const;
1842 * Returns true if this value is a Set Iterator.
1844 bool IsSetIterator() const;
1847 * Returns true if this value is a WeakMap.
1849 bool IsWeakMap() const;
1852 * Returns true if this value is a WeakSet.
1854 bool IsWeakSet() const;
1857 * Returns true if this value is an ArrayBuffer.
1858 * This is an experimental feature.
1860 bool IsArrayBuffer() const;
1863 * Returns true if this value is an ArrayBufferView.
1864 * This is an experimental feature.
1866 bool IsArrayBufferView() const;
1869 * Returns true if this value is one of TypedArrays.
1870 * This is an experimental feature.
1872 bool IsTypedArray() const;
1875 * Returns true if this value is an Uint8Array.
1876 * This is an experimental feature.
1878 bool IsUint8Array() const;
1881 * Returns true if this value is an Uint8ClampedArray.
1882 * This is an experimental feature.
1884 bool IsUint8ClampedArray() const;
1887 * Returns true if this value is an Int8Array.
1888 * This is an experimental feature.
1890 bool IsInt8Array() const;
1893 * Returns true if this value is an Uint16Array.
1894 * This is an experimental feature.
1896 bool IsUint16Array() const;
1899 * Returns true if this value is an Int16Array.
1900 * This is an experimental feature.
1902 bool IsInt16Array() const;
1905 * Returns true if this value is an Uint32Array.
1906 * This is an experimental feature.
1908 bool IsUint32Array() const;
1911 * Returns true if this value is an Int32Array.
1912 * This is an experimental feature.
1914 bool IsInt32Array() const;
1917 * Returns true if this value is a Float32Array.
1918 * This is an experimental feature.
1920 bool IsFloat32Array() const;
1923 * Returns true if this value is a Float64Array.
1924 * This is an experimental feature.
1926 bool IsFloat64Array() const;
1929 * Returns true if this value is a SIMD Float32x4.
1930 * This is an experimental feature.
1932 bool IsFloat32x4() const;
1935 * Returns true if this value is a DataView.
1936 * This is an experimental feature.
1938 bool IsDataView() const;
1941 * Returns true if this value is a SharedArrayBuffer.
1942 * This is an experimental feature.
1944 bool IsSharedArrayBuffer() const;
1947 V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
1948 Local<Context> context) const;
1949 V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
1950 Local<Context> context) const;
1951 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
1952 Local<Context> context) const;
1953 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
1954 Local<Context> context) const;
1955 V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
1956 Local<Context> context) const;
1957 V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
1958 Local<Context> context) const;
1959 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
1960 Local<Context> context) const;
1961 V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
1963 V8_DEPRECATE_SOON("Use maybe version",
1964 Local<Boolean> ToBoolean(Isolate* isolate) const);
1965 V8_DEPRECATE_SOON("Use maybe version",
1966 Local<Number> ToNumber(Isolate* isolate) const);
1967 V8_DEPRECATE_SOON("Use maybe version",
1968 Local<String> ToString(Isolate* isolate) const);
1969 V8_DEPRECATE_SOON("Use maybe version",
1970 Local<String> ToDetailString(Isolate* isolate) const);
1971 V8_DEPRECATE_SOON("Use maybe version",
1972 Local<Object> ToObject(Isolate* isolate) const);
1973 V8_DEPRECATE_SOON("Use maybe version",
1974 Local<Integer> ToInteger(Isolate* isolate) const);
1975 V8_DEPRECATE_SOON("Use maybe version",
1976 Local<Uint32> ToUint32(Isolate* isolate) const);
1977 V8_DEPRECATE_SOON("Use maybe version",
1978 Local<Int32> ToInt32(Isolate* isolate) const);
1980 inline V8_DEPRECATE_SOON("Use maybe version",
1981 Local<Boolean> ToBoolean() const);
1982 inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber() const);
1983 inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
1984 inline V8_DEPRECATE_SOON("Use maybe version",
1985 Local<String> ToDetailString() const);
1986 inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
1987 inline V8_DEPRECATE_SOON("Use maybe version",
1988 Local<Integer> ToInteger() const);
1989 inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32() const);
1990 inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32() const);
1993 * Attempts to convert a string to an array index.
1994 * Returns an empty handle if the conversion fails.
1996 V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex() const);
1997 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
1998 Local<Context> context) const;
2000 V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2001 V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2002 V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2003 Local<Context> context) const;
2004 V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2005 Local<Context> context) const;
2006 V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2008 V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2009 V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2010 V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2011 V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2012 V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2015 V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2016 V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2017 Local<Value> that) const;
2018 bool StrictEquals(Local<Value> that) const;
2019 bool SameValue(Local<Value> that) const;
2021 template <class T> V8_INLINE static Value* Cast(T* value);
2024 V8_INLINE bool QuickIsUndefined() const;
2025 V8_INLINE bool QuickIsNull() const;
2026 V8_INLINE bool QuickIsString() const;
2027 bool FullIsUndefined() const;
2028 bool FullIsNull() const;
2029 bool FullIsString() const;
2034 * The superclass of primitive values. See ECMA-262 4.3.2.
2036 class V8_EXPORT Primitive : public Value { };
2040 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2043 class V8_EXPORT Boolean : public Primitive {
2046 V8_INLINE static Boolean* Cast(v8::Value* obj);
2047 V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2050 static void CheckCast(v8::Value* obj);
2055 * A superclass for symbols and strings.
2057 class V8_EXPORT Name : public Primitive {
2060 * Returns the identity hash for this object. The current implementation
2061 * uses an inline property on the object to store the identity hash.
2063 * The return value will never be 0. Also, it is not guaranteed to be
2066 int GetIdentityHash();
2068 V8_INLINE static Name* Cast(v8::Value* obj);
2070 static void CheckCast(v8::Value* obj);
2074 enum class NewStringType { kNormal, kInternalized };
2078 * A JavaScript string value (ECMA-262, 4.3.17).
2080 class V8_EXPORT String : public Name {
2082 static const int kMaxLength = (1 << 28) - 16;
2085 UNKNOWN_ENCODING = 0x1,
2086 TWO_BYTE_ENCODING = 0x0,
2087 ONE_BYTE_ENCODING = 0x4
2090 * Returns the number of characters in this string.
2095 * Returns the number of bytes in the UTF-8 encoded
2096 * representation of this string.
2098 int Utf8Length() const;
2101 * Returns whether this string is known to contain only one byte data.
2102 * Does not read the string.
2103 * False negatives are possible.
2105 bool IsOneByte() const;
2108 * Returns whether this string contain only one byte data.
2109 * Will read the entire string in some cases.
2111 bool ContainsOnlyOneByte() const;
2114 * Write the contents of the string to an external buffer.
2115 * If no arguments are given, expects the buffer to be large
2116 * enough to hold the entire string and NULL terminator. Copies
2117 * the contents of the string and the NULL terminator into the
2120 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2121 * before the end of the buffer.
2123 * Copies up to length characters into the output buffer.
2124 * Only null-terminates if there is enough space in the buffer.
2126 * \param buffer The buffer into which the string will be copied.
2127 * \param start The starting position within the string at which
2129 * \param length The number of characters to copy from the string. For
2130 * WriteUtf8 the number of bytes in the buffer.
2131 * \param nchars_ref The number of characters written, can be NULL.
2132 * \param options Various options that might affect performance of this or
2133 * subsequent operations.
2134 * \return The number of characters copied to the buffer excluding the null
2135 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2136 * including the null terminator (if written).
2140 HINT_MANY_WRITES_EXPECTED = 1,
2141 NO_NULL_TERMINATION = 2,
2142 PRESERVE_ONE_BYTE_NULL = 4,
2143 // Used by WriteUtf8 to replace orphan surrogate code units with the
2144 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2146 REPLACE_INVALID_UTF8 = 8
2149 // 16-bit character codes.
2150 int Write(uint16_t* buffer,
2153 int options = NO_OPTIONS) const;
2154 // One byte characters.
2155 int WriteOneByte(uint8_t* buffer,
2158 int options = NO_OPTIONS) const;
2159 // UTF-8 encoded characters.
2160 int WriteUtf8(char* buffer,
2162 int* nchars_ref = NULL,
2163 int options = NO_OPTIONS) const;
2166 * A zero length string.
2168 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2171 * Returns true if the string is external
2173 bool IsExternal() const;
2176 * Returns true if the string is both external and one-byte.
2178 bool IsExternalOneByte() const;
2180 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2182 virtual ~ExternalStringResourceBase() {}
2185 ExternalStringResourceBase() {}
2188 * Internally V8 will call this Dispose method when the external string
2189 * resource is no longer needed. The default implementation will use the
2190 * delete operator. This method can be overridden in subclasses to
2191 * control how allocated external string resources are disposed.
2193 virtual void Dispose() { delete this; }
2196 // Disallow copying and assigning.
2197 ExternalStringResourceBase(const ExternalStringResourceBase&);
2198 void operator=(const ExternalStringResourceBase&);
2200 friend class v8::internal::Heap;
2204 * An ExternalStringResource is a wrapper around a two-byte string
2205 * buffer that resides outside V8's heap. Implement an
2206 * ExternalStringResource to manage the life cycle of the underlying
2207 * buffer. Note that the string data must be immutable.
2209 class V8_EXPORT ExternalStringResource
2210 : public ExternalStringResourceBase {
2213 * Override the destructor to manage the life cycle of the underlying
2216 virtual ~ExternalStringResource() {}
2219 * The string data from the underlying buffer.
2221 virtual const uint16_t* data() const = 0;
2224 * The length of the string. That is, the number of two-byte characters.
2226 virtual size_t length() const = 0;
2229 ExternalStringResource() {}
2233 * An ExternalOneByteStringResource is a wrapper around an one-byte
2234 * string buffer that resides outside V8's heap. Implement an
2235 * ExternalOneByteStringResource to manage the life cycle of the
2236 * underlying buffer. Note that the string data must be immutable
2237 * and that the data must be Latin-1 and not UTF-8, which would require
2238 * special treatment internally in the engine and do not allow efficient
2239 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2242 class V8_EXPORT ExternalOneByteStringResource
2243 : public ExternalStringResourceBase {
2246 * Override the destructor to manage the life cycle of the underlying
2249 virtual ~ExternalOneByteStringResource() {}
2250 /** The string data from the underlying buffer.*/
2251 virtual const char* data() const = 0;
2252 /** The number of Latin-1 characters in the string.*/
2253 virtual size_t length() const = 0;
2255 ExternalOneByteStringResource() {}
2259 * If the string is an external string, return the ExternalStringResourceBase
2260 * regardless of the encoding, otherwise return NULL. The encoding of the
2261 * string is returned in encoding_out.
2263 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2264 Encoding* encoding_out) const;
2267 * Get the ExternalStringResource for an external string. Returns
2268 * NULL if IsExternal() doesn't return true.
2270 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2273 * Get the ExternalOneByteStringResource for an external one-byte string.
2274 * Returns NULL if IsExternalOneByte() doesn't return true.
2276 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2278 V8_INLINE static String* Cast(v8::Value* obj);
2280 // TODO(dcarney): remove with deprecation of New functions.
2281 enum NewStringType {
2282 kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2283 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2286 /** Allocates a new string from UTF-8 data.*/
2287 static V8_DEPRECATE_SOON(
2288 "Use maybe version",
2289 Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2290 NewStringType type = kNormalString,
2293 /** Allocates a new string from UTF-8 data. Only returns an empty value when
2294 * length > kMaxLength. **/
2295 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2296 Isolate* isolate, const char* data, v8::NewStringType type,
2299 /** Allocates a new string from Latin-1 data.*/
2300 static V8_DEPRECATE_SOON(
2301 "Use maybe version",
2302 Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2303 NewStringType type = kNormalString,
2306 /** Allocates a new string from Latin-1 data. Only returns an empty value
2307 * when length > kMaxLength. **/
2308 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2309 Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2312 /** Allocates a new string from UTF-16 data.*/
2313 static V8_DEPRECATE_SOON(
2314 "Use maybe version",
2315 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2316 NewStringType type = kNormalString,
2319 /** Allocates a new string from UTF-16 data. Only returns an empty value when
2320 * length > kMaxLength. **/
2321 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2322 Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2326 * Creates a new string by concatenating the left and the right strings
2327 * passed in as parameters.
2329 static Local<String> Concat(Local<String> left, Local<String> right);
2332 * Creates a new external string using the data defined in the given
2333 * resource. When the external string is no longer live on V8's heap the
2334 * resource will be disposed by calling its Dispose method. The caller of
2335 * this function should not otherwise delete or modify the resource. Neither
2336 * should the underlying buffer be deallocated or modified except through the
2337 * destructor of the external string resource.
2339 static V8_DEPRECATE_SOON(
2340 "Use maybe version",
2341 Local<String> NewExternal(Isolate* isolate,
2342 ExternalStringResource* resource));
2343 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2344 Isolate* isolate, ExternalStringResource* resource);
2347 * Associate an external string resource with this string by transforming it
2348 * in place so that existing references to this string in the JavaScript heap
2349 * will use the external string resource. The external string resource's
2350 * character contents need to be equivalent to this string.
2351 * Returns true if the string has been changed to be an external string.
2352 * The string is not modified if the operation fails. See NewExternal for
2353 * information on the lifetime of the resource.
2355 bool MakeExternal(ExternalStringResource* resource);
2358 * Creates a new external string using the one-byte data defined in the given
2359 * resource. When the external string is no longer live on V8's heap the
2360 * resource will be disposed by calling its Dispose method. The caller of
2361 * this function should not otherwise delete or modify the resource. Neither
2362 * should the underlying buffer be deallocated or modified except through the
2363 * destructor of the external string resource.
2365 static V8_DEPRECATE_SOON(
2366 "Use maybe version",
2367 Local<String> NewExternal(Isolate* isolate,
2368 ExternalOneByteStringResource* resource));
2369 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2370 Isolate* isolate, ExternalOneByteStringResource* resource);
2373 * Associate an external string resource with this string by transforming it
2374 * in place so that existing references to this string in the JavaScript heap
2375 * will use the external string resource. The external string resource's
2376 * character contents need to be equivalent to this string.
2377 * Returns true if the string has been changed to be an external string.
2378 * The string is not modified if the operation fails. See NewExternal for
2379 * information on the lifetime of the resource.
2381 bool MakeExternal(ExternalOneByteStringResource* resource);
2384 * Returns true if this string can be made external.
2386 bool CanMakeExternal();
2389 * Converts an object to a UTF-8-encoded character array. Useful if
2390 * you want to print the object. If conversion to a string fails
2391 * (e.g. due to an exception in the toString() method of the object)
2392 * then the length() method returns 0 and the * operator returns
2395 class V8_EXPORT Utf8Value {
2397 explicit Utf8Value(Local<v8::Value> obj);
2399 char* operator*() { return str_; }
2400 const char* operator*() const { return str_; }
2401 int length() const { return length_; }
2406 // Disallow copying and assigning.
2407 Utf8Value(const Utf8Value&);
2408 void operator=(const Utf8Value&);
2412 * Converts an object to a two-byte string.
2413 * If conversion to a string fails (eg. due to an exception in the toString()
2414 * method of the object) then the length() method returns 0 and the * operator
2417 class V8_EXPORT Value {
2419 explicit Value(Local<v8::Value> obj);
2421 uint16_t* operator*() { return str_; }
2422 const uint16_t* operator*() const { return str_; }
2423 int length() const { return length_; }
2428 // Disallow copying and assigning.
2429 Value(const Value&);
2430 void operator=(const Value&);
2434 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2435 Encoding encoding) const;
2436 void VerifyExternalStringResource(ExternalStringResource* val) const;
2437 static void CheckCast(v8::Value* obj);
2442 * A JavaScript symbol (ECMA-262 edition 6)
2444 * This is an experimental feature. Use at your own risk.
2446 class V8_EXPORT Symbol : public Name {
2448 // Returns the print name string of the symbol, or undefined if none.
2449 Local<Value> Name() const;
2451 // Create a symbol. If name is not empty, it will be used as the description.
2452 static Local<Symbol> New(
2453 Isolate *isolate, Local<String> name = Local<String>());
2455 // Access global symbol registry.
2456 // Note that symbols created this way are never collected, so
2457 // they should only be used for statically fixed properties.
2458 // Also, there is only one global name space for the names used as keys.
2459 // To minimize the potential for clashes, use qualified names as keys.
2460 static Local<Symbol> For(Isolate *isolate, Local<String> name);
2462 // Retrieve a global symbol. Similar to |For|, but using a separate
2463 // registry that is not accessible by (and cannot clash with) JavaScript code.
2464 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2466 // Well-known symbols
2467 static Local<Symbol> GetIterator(Isolate* isolate);
2468 static Local<Symbol> GetUnscopables(Isolate* isolate);
2469 static Local<Symbol> GetToStringTag(Isolate* isolate);
2471 V8_INLINE static Symbol* Cast(v8::Value* obj);
2475 static void CheckCast(v8::Value* obj);
2480 * A JavaScript number value (ECMA-262, 4.3.20)
2482 class V8_EXPORT Number : public Primitive {
2484 double Value() const;
2485 static Local<Number> New(Isolate* isolate, double value);
2486 V8_INLINE static Number* Cast(v8::Value* obj);
2489 static void CheckCast(v8::Value* obj);
2494 * A JavaScript value representing a signed integer.
2496 class V8_EXPORT Integer : public Number {
2498 static Local<Integer> New(Isolate* isolate, int32_t value);
2499 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2500 int64_t Value() const;
2501 V8_INLINE static Integer* Cast(v8::Value* obj);
2504 static void CheckCast(v8::Value* obj);
2509 * A JavaScript value representing a 32-bit signed integer.
2511 class V8_EXPORT Int32 : public Integer {
2513 int32_t Value() const;
2514 V8_INLINE static Int32* Cast(v8::Value* obj);
2518 static void CheckCast(v8::Value* obj);
2523 * A JavaScript value representing a 32-bit unsigned integer.
2525 class V8_EXPORT Uint32 : public Integer {
2527 uint32_t Value() const;
2528 V8_INLINE static Uint32* Cast(v8::Value* obj);
2532 static void CheckCast(v8::Value* obj);
2536 enum PropertyAttribute {
2544 * Accessor[Getter|Setter] are used as callback functions when
2545 * setting|getting a particular property. See Object and ObjectTemplate's
2546 * method SetAccessor.
2548 typedef void (*AccessorGetterCallback)(
2549 Local<String> property,
2550 const PropertyCallbackInfo<Value>& info);
2551 typedef void (*AccessorNameGetterCallback)(
2552 Local<Name> property,
2553 const PropertyCallbackInfo<Value>& info);
2556 typedef void (*AccessorSetterCallback)(
2557 Local<String> property,
2559 const PropertyCallbackInfo<void>& info);
2560 typedef void (*AccessorNameSetterCallback)(
2561 Local<Name> property,
2563 const PropertyCallbackInfo<void>& info);
2567 * Access control specifications.
2569 * Some accessors should be accessible across contexts. These
2570 * accessors have an explicit access control parameter which specifies
2571 * the kind of cross-context access that should be allowed.
2573 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2575 enum AccessControl {
2578 ALL_CAN_WRITE = 1 << 1,
2579 PROHIBITS_OVERWRITING = 1 << 2
2584 * A JavaScript object (ECMA-262, 4.3.3)
2586 class V8_EXPORT Object : public Value {
2588 V8_DEPRECATE_SOON("Use maybe version",
2589 bool Set(Local<Value> key, Local<Value> value));
2590 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
2591 Local<Value> key, Local<Value> value);
2593 V8_DEPRECATE_SOON("Use maybe version",
2594 bool Set(uint32_t index, Local<Value> value));
2595 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
2596 Local<Value> value);
2598 // Implements CreateDataProperty (ECMA-262, 7.3.4).
2600 // Defines a configurable, writable, enumerable property with the given value
2601 // on the object unless the property already exists and is not configurable
2602 // or the object is not extensible.
2604 // Returns true on success.
2605 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2607 Local<Value> value);
2608 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
2610 Local<Value> value);
2612 // Implements DefineOwnProperty.
2614 // In general, CreateDataProperty will be faster, however, does not allow
2615 // for specifying attributes.
2617 // Returns true on success.
2618 V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
2619 Local<Context> context, Local<Name> key, Local<Value> value,
2620 PropertyAttribute attributes = None);
2622 // Sets an own property on this object bypassing interceptors and
2623 // overriding accessors or read-only properties.
2625 // Note that if the object has an interceptor the property will be set
2626 // locally, but since the interceptor takes precedence the local property
2627 // will only be returned if the interceptor doesn't return a value.
2629 // Note also that this only works for named properties.
2630 V8_DEPRECATE_SOON("Use CreateDataProperty",
2631 bool ForceSet(Local<Value> key, Local<Value> value,
2632 PropertyAttribute attribs = None));
2633 V8_DEPRECATE_SOON("Use CreateDataProperty",
2634 Maybe<bool> ForceSet(Local<Context> context,
2635 Local<Value> key, Local<Value> value,
2636 PropertyAttribute attribs = None));
2638 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
2639 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2642 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2643 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2647 * Gets the property attributes of a property which can be None or
2648 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2649 * None when the property doesn't exist.
2651 V8_DEPRECATE_SOON("Use maybe version",
2652 PropertyAttribute GetPropertyAttributes(Local<Value> key));
2653 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
2654 Local<Context> context, Local<Value> key);
2657 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2659 V8_DEPRECATE_SOON("Use maybe version",
2660 Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2661 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
2662 Local<Context> context, Local<String> key);
2664 V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
2665 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2668 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
2669 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2670 Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2672 V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2673 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
2675 V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2676 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2677 Maybe<bool> Delete(Local<Context> context, uint32_t index);
2679 V8_DEPRECATE_SOON("Use maybe version",
2680 bool SetAccessor(Local<String> name,
2681 AccessorGetterCallback getter,
2682 AccessorSetterCallback setter = 0,
2683 Local<Value> data = Local<Value>(),
2684 AccessControl settings = DEFAULT,
2685 PropertyAttribute attribute = None));
2686 V8_DEPRECATE_SOON("Use maybe version",
2687 bool SetAccessor(Local<Name> name,
2688 AccessorNameGetterCallback getter,
2689 AccessorNameSetterCallback setter = 0,
2690 Local<Value> data = Local<Value>(),
2691 AccessControl settings = DEFAULT,
2692 PropertyAttribute attribute = None));
2693 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2694 Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2695 AccessorNameGetterCallback getter,
2696 AccessorNameSetterCallback setter = 0,
2697 MaybeLocal<Value> data = MaybeLocal<Value>(),
2698 AccessControl settings = DEFAULT,
2699 PropertyAttribute attribute = None);
2701 void SetAccessorProperty(Local<Name> name, Local<Function> getter,
2702 Local<Function> setter = Local<Function>(),
2703 PropertyAttribute attribute = None,
2704 AccessControl settings = DEFAULT);
2707 * Returns an array containing the names of the enumerable properties
2708 * of this object, including properties from prototype objects. The
2709 * array returned by this method contains the same values as would
2710 * be enumerated by a for-in statement over this object.
2712 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2713 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
2714 Local<Context> context);
2717 * This function has the same functionality as GetPropertyNames but
2718 * the returned array doesn't contain the names of properties from
2719 * prototype objects.
2721 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2722 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
2723 Local<Context> context);
2726 * Get the prototype object. This does not skip objects marked to
2727 * be skipped by __proto__ and it does not consult the security
2730 Local<Value> GetPrototype();
2733 * Set the prototype object. This does not skip objects marked to
2734 * be skipped by __proto__ and it does not consult the security
2737 V8_DEPRECATE_SOON("Use maybe version",
2738 bool SetPrototype(Local<Value> prototype));
2739 V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
2740 Local<Value> prototype);
2743 * Finds an instance of the given function template in the prototype
2746 Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
2749 * Call builtin Object.prototype.toString on this object.
2750 * This is different from Value::ToString() that may call
2751 * user-defined toString function. This one does not.
2753 V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2754 V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
2755 Local<Context> context);
2758 * Returns the name of the function invoked as a constructor for this object.
2760 Local<String> GetConstructorName();
2762 /** Gets the number of internal fields for this Object. */
2763 int InternalFieldCount();
2765 /** Same as above, but works for Persistents */
2766 V8_INLINE static int InternalFieldCount(
2767 const PersistentBase<Object>& object) {
2768 return object.val_->InternalFieldCount();
2771 /** Gets the value from an internal field. */
2772 V8_INLINE Local<Value> GetInternalField(int index);
2774 /** Sets the value in an internal field. */
2775 void SetInternalField(int index, Local<Value> value);
2778 * Gets a 2-byte-aligned native pointer from an internal field. This field
2779 * must have been set by SetAlignedPointerInInternalField, everything else
2780 * leads to undefined behavior.
2782 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2784 /** Same as above, but works for Persistents */
2785 V8_INLINE static void* GetAlignedPointerFromInternalField(
2786 const PersistentBase<Object>& object, int index) {
2787 return object.val_->GetAlignedPointerFromInternalField(index);
2791 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2792 * a field, GetAlignedPointerFromInternalField must be used, everything else
2793 * leads to undefined behavior.
2795 void SetAlignedPointerInInternalField(int index, void* value);
2797 // Testers for local properties.
2798 V8_DEPRECATE_SOON("Use maybe version",
2799 bool HasOwnProperty(Local<String> key));
2800 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
2802 V8_DEPRECATE_SOON("Use maybe version",
2803 bool HasRealNamedProperty(Local<String> key));
2804 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
2806 V8_DEPRECATE_SOON("Use maybe version",
2807 bool HasRealIndexedProperty(uint32_t index));
2808 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
2809 Local<Context> context, uint32_t index);
2810 V8_DEPRECATE_SOON("Use maybe version",
2811 bool HasRealNamedCallbackProperty(Local<String> key));
2812 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
2813 Local<Context> context, Local<Name> key);
2816 * If result.IsEmpty() no real property was located in the prototype chain.
2817 * This means interceptors in the prototype chain are not called.
2820 "Use maybe version",
2821 Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
2822 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
2823 Local<Context> context, Local<Name> key);
2826 * Gets the property attributes of a real property in the prototype chain,
2827 * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2828 * Interceptors in the prototype chain are not called.
2831 "Use maybe version",
2832 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2833 Local<String> key));
2834 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
2835 GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
2839 * If result.IsEmpty() no real property was located on the object or
2840 * in the prototype chain.
2841 * This means interceptors in the prototype chain are not called.
2843 V8_DEPRECATE_SOON("Use maybe version",
2844 Local<Value> GetRealNamedProperty(Local<String> key));
2845 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
2846 Local<Context> context, Local<Name> key);
2849 * Gets the property attributes of a real property which can be
2850 * None or any combination of ReadOnly, DontEnum and DontDelete.
2851 * Interceptors in the prototype chain are not called.
2853 V8_DEPRECATE_SOON("Use maybe version",
2854 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2855 Local<String> key));
2856 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2857 Local<Context> context, Local<Name> key);
2859 /** Tests for a named lookup interceptor.*/
2860 bool HasNamedLookupInterceptor();
2862 /** Tests for an index lookup interceptor.*/
2863 bool HasIndexedLookupInterceptor();
2866 * Returns the identity hash for this object. The current implementation
2867 * uses a hidden property on the object to store the identity hash.
2869 * The return value will never be 0. Also, it is not guaranteed to be
2872 int GetIdentityHash();
2875 * Access hidden properties on JavaScript objects. These properties are
2876 * hidden from the executing JavaScript and only accessible through the V8
2877 * C++ API. Hidden properties introduced by V8 internally (for example the
2878 * identity hash) are prefixed with "v8::".
2880 // TODO(dcarney): convert these to take a isolate and optionally bailout?
2881 bool SetHiddenValue(Local<String> key, Local<Value> value);
2882 Local<Value> GetHiddenValue(Local<String> key);
2883 bool DeleteHiddenValue(Local<String> key);
2886 * Clone this object with a fast but shallow copy. Values will point
2887 * to the same values as the original object.
2889 // TODO(dcarney): take an isolate and optionally bail out?
2890 Local<Object> Clone();
2893 * Returns the context in which the object was created.
2895 Local<Context> CreationContext();
2898 * Checks whether a callback is set by the
2899 * ObjectTemplate::SetCallAsFunctionHandler method.
2900 * When an Object is callable this method returns true.
2905 * Call an Object as a function if a callback is set by the
2906 * ObjectTemplate::SetCallAsFunctionHandler method.
2908 V8_DEPRECATE_SOON("Use maybe version",
2909 Local<Value> CallAsFunction(Local<Value> recv, int argc,
2910 Local<Value> argv[]));
2911 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
2914 Local<Value> argv[]);
2917 * Call an Object as a constructor if a callback is set by the
2918 * ObjectTemplate::SetCallAsFunctionHandler method.
2919 * Note: This method behaves like the Function::NewInstance method.
2921 V8_DEPRECATE_SOON("Use maybe version",
2922 Local<Value> CallAsConstructor(int argc,
2923 Local<Value> argv[]));
2924 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
2925 Local<Context> context, int argc, Local<Value> argv[]);
2928 * Return the isolate to which the Object belongs to.
2930 V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
2932 static Local<Object> New(Isolate* isolate);
2934 V8_INLINE static Object* Cast(Value* obj);
2938 static void CheckCast(Value* obj);
2939 Local<Value> SlowGetInternalField(int index);
2940 void* SlowGetAlignedPointerFromInternalField(int index);
2945 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2947 class V8_EXPORT Array : public Object {
2949 uint32_t Length() const;
2952 * Clones an element at index |index|. Returns an empty
2953 * handle if cloning fails (for any reason).
2955 V8_DEPRECATE_SOON("Use maybe version",
2956 Local<Object> CloneElementAt(uint32_t index));
2957 V8_WARN_UNUSED_RESULT MaybeLocal<Object> CloneElementAt(
2958 Local<Context> context, uint32_t index);
2961 * Creates a JavaScript array with the given length. If the length
2962 * is negative the returned array will have length 0.
2964 static Local<Array> New(Isolate* isolate, int length = 0);
2966 V8_INLINE static Array* Cast(Value* obj);
2969 static void CheckCast(Value* obj);
2974 * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
2976 class V8_EXPORT Map : public Object {
2978 size_t Size() const;
2980 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
2982 V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
2984 Local<Value> value);
2985 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
2987 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
2991 * Returns an array of length Size() * 2, where index N is the Nth key and
2992 * index N + 1 is the Nth value.
2994 Local<Array> AsArray() const;
2997 * Creates a new empty Map.
2999 static Local<Map> New(Isolate* isolate);
3002 * Creates a new Map containing the elements of array, which must be formatted
3003 * in the same manner as the array returned from AsArray().
3004 * Guaranteed to be side-effect free if the array contains no holes.
3006 static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3007 "Use mutation methods instead",
3008 MaybeLocal<Map> FromArray(Local<Context> context, Local<Array> array));
3010 V8_INLINE static Map* Cast(Value* obj);
3014 static void CheckCast(Value* obj);
3019 * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3021 class V8_EXPORT Set : public Object {
3023 size_t Size() const;
3025 V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3027 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3029 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3033 * Returns an array of the keys in this Set.
3035 Local<Array> AsArray() const;
3038 * Creates a new empty Set.
3040 static Local<Set> New(Isolate* isolate);
3043 * Creates a new Set containing the items in array.
3044 * Guaranteed to be side-effect free if the array contains no holes.
3046 static V8_WARN_UNUSED_RESULT V8_DEPRECATED(
3047 "Use mutation methods instead",
3048 MaybeLocal<Set> FromArray(Local<Context> context, Local<Array> array));
3050 V8_INLINE static Set* Cast(Value* obj);
3054 static void CheckCast(Value* obj);
3058 template<typename T>
3061 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3062 : value_(that.value_) {
3066 template <typename S>
3067 V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3068 void Set(const Persistent<S>& handle));
3069 template <typename S>
3070 V8_INLINE void Set(const Global<S>& handle);
3071 template <typename S>
3072 V8_INLINE void Set(const Local<S> handle);
3073 // Fast primitive setters
3074 V8_INLINE void Set(bool value);
3075 V8_INLINE void Set(double i);
3076 V8_INLINE void Set(int32_t i);
3077 V8_INLINE void Set(uint32_t i);
3078 // Fast JS primitive setters
3079 V8_INLINE void SetNull();
3080 V8_INLINE void SetUndefined();
3081 V8_INLINE void SetEmptyString();
3082 // Convenience getter for Isolate
3083 V8_INLINE Isolate* GetIsolate();
3085 // Pointer setter: Uncompilable to prevent inadvertent misuse.
3086 template <typename S>
3087 V8_INLINE void Set(S* whatever);
3090 template<class F> friend class ReturnValue;
3091 template<class F> friend class FunctionCallbackInfo;
3092 template<class F> friend class PropertyCallbackInfo;
3093 template <class F, class G, class H>
3094 friend class PersistentValueMapBase;
3095 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3096 V8_INLINE internal::Object* GetDefaultValue();
3097 V8_INLINE explicit ReturnValue(internal::Object** slot);
3098 internal::Object** value_;
3103 * The argument information given to function call callbacks. This
3104 * class provides access to information about the context of the call,
3105 * including the receiver, the number and values of arguments, and
3106 * the holder of the function.
3108 template<typename T>
3109 class FunctionCallbackInfo {
3111 V8_INLINE int Length() const;
3112 V8_INLINE Local<Value> operator[](int i) const;
3113 V8_INLINE Local<Function> Callee() const;
3114 V8_INLINE Local<Object> This() const;
3115 V8_INLINE Local<Object> Holder() const;
3116 V8_INLINE bool IsConstructCall() const;
3117 V8_INLINE Local<Value> Data() const;
3118 V8_INLINE Isolate* GetIsolate() const;
3119 V8_INLINE ReturnValue<T> GetReturnValue() const;
3120 // This shouldn't be public, but the arm compiler needs it.
3121 static const int kArgsLength = 7;
3124 friend class internal::FunctionCallbackArguments;
3125 friend class internal::CustomArguments<FunctionCallbackInfo>;
3126 static const int kHolderIndex = 0;
3127 static const int kIsolateIndex = 1;
3128 static const int kReturnValueDefaultValueIndex = 2;
3129 static const int kReturnValueIndex = 3;
3130 static const int kDataIndex = 4;
3131 static const int kCalleeIndex = 5;
3132 static const int kContextSaveIndex = 6;
3134 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3135 internal::Object** values,
3137 bool is_construct_call);
3138 internal::Object** implicit_args_;
3139 internal::Object** values_;
3141 int is_construct_call_;
3146 * The information passed to a property callback about the context
3147 * of the property access.
3149 template<typename T>
3150 class PropertyCallbackInfo {
3152 V8_INLINE Isolate* GetIsolate() const;
3153 V8_INLINE Local<Value> Data() const;
3154 V8_INLINE Local<Object> This() const;
3155 V8_INLINE Local<Object> Holder() const;
3156 V8_INLINE ReturnValue<T> GetReturnValue() const;
3157 // This shouldn't be public, but the arm compiler needs it.
3158 static const int kArgsLength = 6;
3161 friend class MacroAssembler;
3162 friend class internal::PropertyCallbackArguments;
3163 friend class internal::CustomArguments<PropertyCallbackInfo>;
3164 static const int kHolderIndex = 0;
3165 static const int kIsolateIndex = 1;
3166 static const int kReturnValueDefaultValueIndex = 2;
3167 static const int kReturnValueIndex = 3;
3168 static const int kDataIndex = 4;
3169 static const int kThisIndex = 5;
3171 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3172 internal::Object** args_;
3176 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3180 * A JavaScript function object (ECMA-262, 15.3).
3182 class V8_EXPORT Function : public Object {
3185 * Create a function in the current execution context
3186 * for a given FunctionCallback.
3188 static MaybeLocal<Function> New(Local<Context> context,
3189 FunctionCallback callback,
3190 Local<Value> data = Local<Value>(),
3192 static V8_DEPRECATE_SOON(
3193 "Use maybe version",
3194 Local<Function> New(Isolate* isolate, FunctionCallback callback,
3195 Local<Value> data = Local<Value>(), int length = 0));
3197 V8_DEPRECATE_SOON("Use maybe version",
3198 Local<Object> NewInstance(int argc, Local<Value> argv[])
3200 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3201 Local<Context> context, int argc, Local<Value> argv[]) const;
3203 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance() const);
3204 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
3205 Local<Context> context) const {
3206 return NewInstance(context, 0, nullptr);
3209 V8_DEPRECATE_SOON("Use maybe version",
3210 Local<Value> Call(Local<Value> recv, int argc,
3211 Local<Value> argv[]));
3212 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
3213 Local<Value> recv, int argc,
3214 Local<Value> argv[]);
3216 void SetName(Local<String> name);
3217 Local<Value> GetName() const;
3220 * Name inferred from variable or property assignment of this function.
3221 * Used to facilitate debugging and profiling of JavaScript code written
3222 * in an OO style, where many functions are anonymous but are assigned
3223 * to object properties.
3225 Local<Value> GetInferredName() const;
3228 * User-defined name assigned to the "displayName" property of this function.
3229 * Used to facilitate debugging and profiling of JavaScript code.
3231 Local<Value> GetDisplayName() const;
3234 * Returns zero based line number of function body and
3235 * kLineOffsetNotFound if no information available.
3237 int GetScriptLineNumber() const;
3239 * Returns zero based column number of function body and
3240 * kLineOffsetNotFound if no information available.
3242 int GetScriptColumnNumber() const;
3245 * Tells whether this function is builtin.
3247 bool IsBuiltin() const;
3252 int ScriptId() const;
3255 * Returns the original function if this function is bound, else returns
3258 Local<Value> GetBoundFunction() const;
3260 ScriptOrigin GetScriptOrigin() const;
3261 V8_INLINE static Function* Cast(Value* obj);
3262 static const int kLineOffsetNotFound;
3266 static void CheckCast(Value* obj);
3271 * An instance of the built-in Promise constructor (ES6 draft).
3272 * This API is experimental. Only works with --harmony flag.
3274 class V8_EXPORT Promise : public Object {
3276 class V8_EXPORT Resolver : public Object {
3279 * Create a new resolver, along with an associated promise in pending state.
3281 static V8_DEPRECATE_SOON("Use maybe version",
3282 Local<Resolver> New(Isolate* isolate));
3283 static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
3284 Local<Context> context);
3287 * Extract the associated promise.
3289 Local<Promise> GetPromise();
3292 * Resolve/reject the associated promise with a given value.
3293 * Ignored if the promise is no longer pending.
3295 V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3296 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3297 Maybe<bool> Resolve(Local<Context> context, Local<Value> value);
3299 V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3300 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3301 Maybe<bool> Reject(Local<Context> context, Local<Value> value);
3303 V8_INLINE static Resolver* Cast(Value* obj);
3307 static void CheckCast(Value* obj);
3311 * Register a resolution/rejection handler with a promise.
3312 * The handler is given the respective resolution/rejection value as
3313 * an argument. If the promise is already resolved/rejected, the handler is
3314 * invoked at the end of turn.
3316 V8_DEPRECATE_SOON("Use maybe version",
3317 Local<Promise> Chain(Local<Function> handler));
3318 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Chain(Local<Context> context,
3319 Local<Function> handler);
3321 V8_DEPRECATE_SOON("Use maybe version",
3322 Local<Promise> Catch(Local<Function> handler));
3323 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
3324 Local<Function> handler);
3326 V8_DEPRECATE_SOON("Use maybe version",
3327 Local<Promise> Then(Local<Function> handler));
3328 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
3329 Local<Function> handler);
3332 * Returns true if the promise has at least one derived promise, and
3333 * therefore resolve/reject handlers (including default handler).
3337 V8_INLINE static Promise* Cast(Value* obj);
3341 static void CheckCast(Value* obj);
3345 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3346 // The number of required internal fields can be defined by embedder.
3347 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3351 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
3355 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3356 * This API is experimental and may change significantly.
3358 class V8_EXPORT ArrayBuffer : public Object {
3361 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3362 * The allocator is a global V8 setting. It has to be set via
3363 * Isolate::CreateParams.
3365 * This API is experimental and may change significantly.
3367 class V8_EXPORT Allocator { // NOLINT
3369 virtual ~Allocator() {}
3372 * Allocate |length| bytes. Return NULL if allocation is not successful.
3373 * Memory should be initialized to zeroes.
3375 virtual void* Allocate(size_t length) = 0;
3378 * Allocate |length| bytes. Return NULL if allocation is not successful.
3379 * Memory does not have to be initialized.
3381 virtual void* AllocateUninitialized(size_t length) = 0;
3383 * Free the memory block of size |length|, pointed to by |data|.
3384 * That memory is guaranteed to be previously allocated by |Allocate|.
3386 virtual void Free(void* data, size_t length) = 0;
3390 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3391 * returns an instance of this class, populated, with a pointer to data
3394 * The Data pointer of ArrayBuffer::Contents is always allocated with
3395 * Allocator::Allocate that is set via Isolate::CreateParams.
3397 * This API is experimental and may change significantly.
3399 class V8_EXPORT Contents { // NOLINT
3401 Contents() : data_(NULL), byte_length_(0) {}
3403 void* Data() const { return data_; }
3404 size_t ByteLength() const { return byte_length_; }
3408 size_t byte_length_;
3410 friend class ArrayBuffer;
3415 * Data length in bytes.
3417 size_t ByteLength() const;
3420 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3421 * Allocated memory will be owned by a created ArrayBuffer and
3422 * will be deallocated when it is garbage-collected,
3423 * unless the object is externalized.
3425 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3428 * Create a new ArrayBuffer over an existing memory block.
3429 * The created array buffer is by default immediately in externalized state.
3430 * The memory block will not be reclaimed when a created ArrayBuffer
3431 * is garbage-collected.
3433 static Local<ArrayBuffer> New(
3434 Isolate* isolate, void* data, size_t byte_length,
3435 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3438 * Returns true if ArrayBuffer is externalized, that is, does not
3439 * own its memory block.
3441 bool IsExternal() const;
3444 * Returns true if this ArrayBuffer may be neutered.
3446 bool IsNeuterable() const;
3449 * Neuters this ArrayBuffer and all its views (typed arrays).
3450 * Neutering sets the byte length of the buffer and all typed arrays to zero,
3451 * preventing JavaScript from ever accessing underlying backing store.
3452 * ArrayBuffer should have been externalized and must be neuterable.
3457 * Make this ArrayBuffer external. The pointer to underlying memory block
3458 * and byte length are returned as |Contents| structure. After ArrayBuffer
3459 * had been etxrenalized, it does no longer owns the memory block. The caller
3460 * should take steps to free memory when it is no longer needed.
3462 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3463 * that has been set via Isolate::CreateParams.
3465 Contents Externalize();
3468 * Get a pointer to the ArrayBuffer's underlying memory block without
3469 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3470 * will become invalid as soon as the ArrayBuffer became garbage collected.
3472 * The embedder should make sure to hold a strong reference to the
3473 * ArrayBuffer while accessing this pointer.
3475 * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3477 Contents GetContents();
3479 V8_INLINE static ArrayBuffer* Cast(Value* obj);
3481 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3485 static void CheckCast(Value* obj);
3489 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3490 // The number of required internal fields can be defined by embedder.
3491 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3496 * A base class for an instance of one of "views" over ArrayBuffer,
3497 * including TypedArrays and DataView (ES6 draft 15.13).
3499 * This API is experimental and may change significantly.
3501 class V8_EXPORT ArrayBufferView : public Object {
3504 * Returns underlying ArrayBuffer.
3506 Local<ArrayBuffer> Buffer();
3508 * Byte offset in |Buffer|.
3510 size_t ByteOffset();
3512 * Size of a view in bytes.
3514 size_t ByteLength();
3517 * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3518 * memory without additional overhead that calling ArrayBufferView::Buffer
3521 * Will write at most min(|byte_length|, ByteLength) bytes starting at
3522 * ByteOffset of the underling buffer to the memory starting at |dest|.
3523 * Returns the number of bytes actually written.
3525 size_t CopyContents(void* dest, size_t byte_length);
3528 * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3531 bool HasBuffer() const;
3533 V8_INLINE static ArrayBufferView* Cast(Value* obj);
3535 static const int kInternalFieldCount =
3536 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
3540 static void CheckCast(Value* obj);
3545 * A base class for an instance of TypedArray series of constructors
3546 * (ES6 draft 15.13.6).
3547 * This API is experimental and may change significantly.
3549 class V8_EXPORT TypedArray : public ArrayBufferView {
3552 * Number of elements in this typed array
3553 * (e.g. for Int16Array, |ByteLength|/2).
3557 V8_INLINE static TypedArray* Cast(Value* obj);
3561 static void CheckCast(Value* obj);
3566 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3567 * This API is experimental and may change significantly.
3569 class V8_EXPORT Uint8Array : public TypedArray {
3571 static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
3572 size_t byte_offset, size_t length);
3573 static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3574 size_t byte_offset, size_t length);
3575 V8_INLINE static Uint8Array* Cast(Value* obj);
3579 static void CheckCast(Value* obj);
3584 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3585 * This API is experimental and may change significantly.
3587 class V8_EXPORT Uint8ClampedArray : public TypedArray {
3589 static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
3590 size_t byte_offset, size_t length);
3591 static Local<Uint8ClampedArray> New(
3592 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
3594 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3597 Uint8ClampedArray();
3598 static void CheckCast(Value* obj);
3602 * An instance of Int8Array constructor (ES6 draft 15.13.6).
3603 * This API is experimental and may change significantly.
3605 class V8_EXPORT Int8Array : public TypedArray {
3607 static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
3608 size_t byte_offset, size_t length);
3609 static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3610 size_t byte_offset, size_t length);
3611 V8_INLINE static Int8Array* Cast(Value* obj);
3615 static void CheckCast(Value* obj);
3620 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3621 * This API is experimental and may change significantly.
3623 class V8_EXPORT Uint16Array : public TypedArray {
3625 static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
3626 size_t byte_offset, size_t length);
3627 static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3628 size_t byte_offset, size_t length);
3629 V8_INLINE static Uint16Array* Cast(Value* obj);
3633 static void CheckCast(Value* obj);
3638 * An instance of Int16Array constructor (ES6 draft 15.13.6).
3639 * This API is experimental and may change significantly.
3641 class V8_EXPORT Int16Array : public TypedArray {
3643 static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
3644 size_t byte_offset, size_t length);
3645 static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3646 size_t byte_offset, size_t length);
3647 V8_INLINE static Int16Array* Cast(Value* obj);
3651 static void CheckCast(Value* obj);
3656 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3657 * This API is experimental and may change significantly.
3659 class V8_EXPORT Uint32Array : public TypedArray {
3661 static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
3662 size_t byte_offset, size_t length);
3663 static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3664 size_t byte_offset, size_t length);
3665 V8_INLINE static Uint32Array* Cast(Value* obj);
3669 static void CheckCast(Value* obj);
3674 * An instance of Int32Array constructor (ES6 draft 15.13.6).
3675 * This API is experimental and may change significantly.
3677 class V8_EXPORT Int32Array : public TypedArray {
3679 static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
3680 size_t byte_offset, size_t length);
3681 static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3682 size_t byte_offset, size_t length);
3683 V8_INLINE static Int32Array* Cast(Value* obj);
3687 static void CheckCast(Value* obj);
3692 * An instance of Float32Array constructor (ES6 draft 15.13.6).
3693 * This API is experimental and may change significantly.
3695 class V8_EXPORT Float32Array : public TypedArray {
3697 static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
3698 size_t byte_offset, size_t length);
3699 static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3700 size_t byte_offset, size_t length);
3701 V8_INLINE static Float32Array* Cast(Value* obj);
3705 static void CheckCast(Value* obj);
3710 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3711 * This API is experimental and may change significantly.
3713 class V8_EXPORT Float64Array : public TypedArray {
3715 static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
3716 size_t byte_offset, size_t length);
3717 static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3718 size_t byte_offset, size_t length);
3719 V8_INLINE static Float64Array* Cast(Value* obj);
3723 static void CheckCast(Value* obj);
3728 * An instance of DataView constructor (ES6 draft 15.13.7).
3729 * This API is experimental and may change significantly.
3731 class V8_EXPORT DataView : public ArrayBufferView {
3733 static Local<DataView> New(Local<ArrayBuffer> array_buffer,
3734 size_t byte_offset, size_t length);
3735 static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
3736 size_t byte_offset, size_t length);
3737 V8_INLINE static DataView* Cast(Value* obj);
3741 static void CheckCast(Value* obj);
3746 * An instance of the built-in SharedArrayBuffer constructor.
3747 * This API is experimental and may change significantly.
3749 class V8_EXPORT SharedArrayBuffer : public Object {
3752 * The contents of an |SharedArrayBuffer|. Externalization of
3753 * |SharedArrayBuffer| returns an instance of this class, populated, with a
3754 * pointer to data and byte length.
3756 * The Data pointer of SharedArrayBuffer::Contents is always allocated with
3757 * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
3758 * v8::Isolate::CreateParams::array_buffer_allocator.
3760 * This API is experimental and may change significantly.
3762 class V8_EXPORT Contents { // NOLINT
3764 Contents() : data_(NULL), byte_length_(0) {}
3766 void* Data() const { return data_; }
3767 size_t ByteLength() const { return byte_length_; }
3771 size_t byte_length_;
3773 friend class SharedArrayBuffer;
3778 * Data length in bytes.
3780 size_t ByteLength() const;
3783 * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
3784 * Allocated memory will be owned by a created SharedArrayBuffer and
3785 * will be deallocated when it is garbage-collected,
3786 * unless the object is externalized.
3788 static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
3791 * Create a new SharedArrayBuffer over an existing memory block. The created
3792 * array buffer is immediately in externalized state unless otherwise
3793 * specified. The memory block will not be reclaimed when a created
3794 * SharedArrayBuffer is garbage-collected.
3796 static Local<SharedArrayBuffer> New(
3797 Isolate* isolate, void* data, size_t byte_length,
3798 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
3801 * Returns true if SharedArrayBuffer is externalized, that is, does not
3802 * own its memory block.
3804 bool IsExternal() const;
3807 * Make this SharedArrayBuffer external. The pointer to underlying memory
3808 * block and byte length are returned as |Contents| structure. After
3809 * SharedArrayBuffer had been etxrenalized, it does no longer owns the memory
3810 * block. The caller should take steps to free memory when it is no longer
3813 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3814 * by the allocator specified in
3815 * v8::Isolate::CreateParams::array_buffer_allocator.
3818 Contents Externalize();
3821 * Get a pointer to the ArrayBuffer's underlying memory block without
3822 * externalizing it. If the ArrayBuffer is not externalized, this pointer
3823 * will become invalid as soon as the ArrayBuffer became garbage collected.
3825 * The embedder should make sure to hold a strong reference to the
3826 * ArrayBuffer while accessing this pointer.
3828 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3829 * by the allocator specified in
3830 * v8::Isolate::CreateParams::array_buffer_allocator.
3832 Contents GetContents();
3834 V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
3836 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
3839 SharedArrayBuffer();
3840 static void CheckCast(Value* obj);
3845 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3847 class V8_EXPORT Date : public Object {
3849 static V8_DEPRECATE_SOON("Use maybe version.",
3850 Local<Value> New(Isolate* isolate, double time));
3851 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
3855 * A specialization of Value::NumberValue that is more efficient
3856 * because we know the structure of this object.
3858 double ValueOf() const;
3860 V8_INLINE static Date* Cast(v8::Value* obj);
3863 * Notification that the embedder has changed the time zone,
3864 * daylight savings time, or other date / time configuration
3865 * parameters. V8 keeps a cache of various values used for
3866 * date / time computation. This notification will reset
3867 * those cached values for the current context so that date /
3868 * time configuration changes would be reflected in the Date
3871 * This API should not be called more than needed as it will
3872 * negatively impact the performance of date operations.
3874 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3877 static void CheckCast(v8::Value* obj);
3882 * A Number object (ECMA-262, 4.3.21).
3884 class V8_EXPORT NumberObject : public Object {
3886 static Local<Value> New(Isolate* isolate, double value);
3888 double ValueOf() const;
3890 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3893 static void CheckCast(v8::Value* obj);
3898 * A Boolean object (ECMA-262, 4.3.15).
3900 class V8_EXPORT BooleanObject : public Object {
3902 static Local<Value> New(bool value);
3904 bool ValueOf() const;
3906 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3909 static void CheckCast(v8::Value* obj);
3914 * A String object (ECMA-262, 4.3.18).
3916 class V8_EXPORT StringObject : public Object {
3918 static Local<Value> New(Local<String> value);
3920 Local<String> ValueOf() const;
3922 V8_INLINE static StringObject* Cast(v8::Value* obj);
3925 static void CheckCast(v8::Value* obj);
3930 * A Symbol object (ECMA-262 edition 6).
3932 * This is an experimental feature. Use at your own risk.
3934 class V8_EXPORT SymbolObject : public Object {
3936 static Local<Value> New(Isolate* isolate, Local<Symbol> value);
3938 Local<Symbol> ValueOf() const;
3940 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3943 static void CheckCast(v8::Value* obj);
3948 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3950 class V8_EXPORT RegExp : public Object {
3953 * Regular expression flag bits. They can be or'ed to enable a set
3964 * Creates a regular expression from the given pattern string and
3965 * the flags bit field. May throw a JavaScript exception as
3966 * described in ECMA-262, 15.10.4.1.
3969 * RegExp::New(v8::String::New("foo"),
3970 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3971 * is equivalent to evaluating "/foo/gm".
3973 static V8_DEPRECATE_SOON("Use maybe version",
3974 Local<RegExp> New(Local<String> pattern,
3976 static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
3977 Local<String> pattern,
3981 * Returns the value of the source property: a string representing
3982 * the regular expression.
3984 Local<String> GetSource() const;
3987 * Returns the flags bit field.
3989 Flags GetFlags() const;
3991 V8_INLINE static RegExp* Cast(v8::Value* obj);
3994 static void CheckCast(v8::Value* obj);
3999 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
4000 * to associate C++ data structures with JavaScript objects.
4002 class V8_EXPORT External : public Value {
4004 static Local<External> New(Isolate* isolate, void* value);
4005 V8_INLINE static External* Cast(Value* obj);
4006 void* Value() const;
4008 static void CheckCast(v8::Value* obj);
4012 // --- Templates ---
4016 * The superclass of object and function templates.
4018 class V8_EXPORT Template : public Data {
4020 /** Adds a property to each instance created by this template.*/
4021 void Set(Local<Name> name, Local<Data> value,
4022 PropertyAttribute attributes = None);
4023 V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
4025 void SetAccessorProperty(
4027 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
4028 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
4029 PropertyAttribute attribute = None,
4030 AccessControl settings = DEFAULT);
4033 * Whenever the property with the given name is accessed on objects
4034 * created from this Template the getter and setter callbacks
4035 * are called instead of getting and setting the property directly
4036 * on the JavaScript object.
4038 * \param name The name of the property for which an accessor is added.
4039 * \param getter The callback to invoke when getting the property.
4040 * \param setter The callback to invoke when setting the property.
4041 * \param data A piece of data that will be passed to the getter and setter
4042 * callbacks whenever they are invoked.
4043 * \param settings Access control settings for the accessor. This is a bit
4044 * field consisting of one of more of
4045 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4046 * The default is to not allow cross-context access.
4047 * ALL_CAN_READ means that all cross-context reads are allowed.
4048 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4049 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4050 * cross-context access.
4051 * \param attribute The attributes of the property for which an accessor
4053 * \param signature The signature describes valid receivers for the accessor
4054 * and is used to perform implicit instance checks against them. If the
4055 * receiver is incompatible (i.e. is not an instance of the constructor as
4056 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4057 * thrown and no callback is invoked.
4059 void SetNativeDataProperty(
4060 Local<String> name, AccessorGetterCallback getter,
4061 AccessorSetterCallback setter = 0,
4062 // TODO(dcarney): gcc can't handle Local below
4063 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4064 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4065 AccessControl settings = DEFAULT);
4066 void SetNativeDataProperty(
4067 Local<Name> name, AccessorNameGetterCallback getter,
4068 AccessorNameSetterCallback setter = 0,
4069 // TODO(dcarney): gcc can't handle Local below
4070 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4071 Local<AccessorSignature> signature = Local<AccessorSignature>(),
4072 AccessControl settings = DEFAULT);
4077 friend class ObjectTemplate;
4078 friend class FunctionTemplate;
4083 * NamedProperty[Getter|Setter] are used as interceptors on object.
4084 * See ObjectTemplate::SetNamedPropertyHandler.
4086 typedef void (*NamedPropertyGetterCallback)(
4087 Local<String> property,
4088 const PropertyCallbackInfo<Value>& info);
4092 * Returns the value if the setter intercepts the request.
4093 * Otherwise, returns an empty handle.
4095 typedef void (*NamedPropertySetterCallback)(
4096 Local<String> property,
4098 const PropertyCallbackInfo<Value>& info);
4102 * Returns a non-empty handle if the interceptor intercepts the request.
4103 * The result is an integer encoding property attributes (like v8::None,
4104 * v8::DontEnum, etc.)
4106 typedef void (*NamedPropertyQueryCallback)(
4107 Local<String> property,
4108 const PropertyCallbackInfo<Integer>& info);
4112 * Returns a non-empty handle if the deleter intercepts the request.
4113 * The return value is true if the property could be deleted and false
4116 typedef void (*NamedPropertyDeleterCallback)(
4117 Local<String> property,
4118 const PropertyCallbackInfo<Boolean>& info);
4122 * Returns an array containing the names of the properties the named
4123 * property getter intercepts.
4125 typedef void (*NamedPropertyEnumeratorCallback)(
4126 const PropertyCallbackInfo<Array>& info);
4129 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
4130 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
4132 * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
4133 * See ObjectTemplate::SetNamedPropertyHandler.
4135 typedef void (*GenericNamedPropertyGetterCallback)(
4136 Local<Name> property, const PropertyCallbackInfo<Value>& info);
4140 * Returns the value if the setter intercepts the request.
4141 * Otherwise, returns an empty handle.
4143 typedef void (*GenericNamedPropertySetterCallback)(
4144 Local<Name> property, Local<Value> value,
4145 const PropertyCallbackInfo<Value>& info);
4149 * Returns a non-empty handle if the interceptor intercepts the request.
4150 * The result is an integer encoding property attributes (like v8::None,
4151 * v8::DontEnum, etc.)
4153 typedef void (*GenericNamedPropertyQueryCallback)(
4154 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4158 * Returns a non-empty handle if the deleter intercepts the request.
4159 * The return value is true if the property could be deleted and false
4162 typedef void (*GenericNamedPropertyDeleterCallback)(
4163 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4167 * Returns an array containing the names of the properties the named
4168 * property getter intercepts.
4170 typedef void (*GenericNamedPropertyEnumeratorCallback)(
4171 const PropertyCallbackInfo<Array>& info);
4175 * Returns the value of the property if the getter intercepts the
4176 * request. Otherwise, returns an empty handle.
4178 typedef void (*IndexedPropertyGetterCallback)(
4180 const PropertyCallbackInfo<Value>& info);
4184 * Returns the value if the setter intercepts the request.
4185 * Otherwise, returns an empty handle.
4187 typedef void (*IndexedPropertySetterCallback)(
4190 const PropertyCallbackInfo<Value>& info);
4194 * Returns a non-empty handle if the interceptor intercepts the request.
4195 * The result is an integer encoding property attributes.
4197 typedef void (*IndexedPropertyQueryCallback)(
4199 const PropertyCallbackInfo<Integer>& info);
4203 * Returns a non-empty handle if the deleter intercepts the request.
4204 * The return value is true if the property could be deleted and false
4207 typedef void (*IndexedPropertyDeleterCallback)(
4209 const PropertyCallbackInfo<Boolean>& info);
4213 * Returns an array containing the indices of the properties the
4214 * indexed property getter intercepts.
4216 typedef void (*IndexedPropertyEnumeratorCallback)(
4217 const PropertyCallbackInfo<Array>& info);
4221 * Access type specification.
4233 * Returns true if cross-context access should be allowed to the named
4234 * property with the given key on the host object.
4236 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4243 * Returns true if cross-context access should be allowed to the indexed
4244 * property with the given index on the host object.
4246 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4253 * A FunctionTemplate is used to create functions at runtime. There
4254 * can only be one function created from a FunctionTemplate in a
4255 * context. The lifetime of the created function is equal to the
4256 * lifetime of the context. So in case the embedder needs to create
4257 * temporary functions that can be collected using Scripts is
4260 * Any modification of a FunctionTemplate after first instantiation will trigger
4263 * A FunctionTemplate can have properties, these properties are added to the
4264 * function object when it is created.
4266 * A FunctionTemplate has a corresponding instance template which is
4267 * used to create object instances when the function is used as a
4268 * constructor. Properties added to the instance template are added to
4269 * each object instance.
4271 * A FunctionTemplate can have a prototype template. The prototype template
4272 * is used to create the prototype object of the function.
4274 * The following example shows how to use a FunctionTemplate:
4277 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4278 * t->Set("func_property", v8::Number::New(1));
4280 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4281 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4282 * proto_t->Set("proto_const", v8::Number::New(2));
4284 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4285 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4286 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4287 * instance_t->Set("instance_property", Number::New(3));
4289 * v8::Local<v8::Function> function = t->GetFunction();
4290 * v8::Local<v8::Object> instance = function->NewInstance();
4293 * Let's use "function" as the JS variable name of the function object
4294 * and "instance" for the instance object created above. The function
4295 * and the instance will have the following properties:
4298 * func_property in function == true;
4299 * function.func_property == 1;
4301 * function.prototype.proto_method() invokes 'InvokeCallback'
4302 * function.prototype.proto_const == 2;
4304 * instance instanceof function == true;
4305 * instance.instance_accessor calls 'InstanceAccessorCallback'
4306 * instance.instance_property == 3;
4309 * A FunctionTemplate can inherit from another one by calling the
4310 * FunctionTemplate::Inherit method. The following graph illustrates
4311 * the semantics of inheritance:
4314 * FunctionTemplate Parent -> Parent() . prototype -> { }
4316 * | Inherit(Parent) | .__proto__
4318 * FunctionTemplate Child -> Child() . prototype -> { }
4321 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4322 * object of the Child() function has __proto__ pointing to the
4323 * Parent() function's prototype object. An instance of the Child
4324 * function has all properties on Parent's instance templates.
4326 * Let Parent be the FunctionTemplate initialized in the previous
4327 * section and create a Child FunctionTemplate by:
4330 * Local<FunctionTemplate> parent = t;
4331 * Local<FunctionTemplate> child = FunctionTemplate::New();
4332 * child->Inherit(parent);
4334 * Local<Function> child_function = child->GetFunction();
4335 * Local<Object> child_instance = child_function->NewInstance();
4338 * The Child function and Child instance will have the following
4342 * child_func.prototype.__proto__ == function.prototype;
4343 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
4344 * child_instance.instance_property == 3;
4347 class V8_EXPORT FunctionTemplate : public Template {
4349 /** Creates a function template.*/
4350 static Local<FunctionTemplate> New(
4351 Isolate* isolate, FunctionCallback callback = 0,
4352 Local<Value> data = Local<Value>(),
4353 Local<Signature> signature = Local<Signature>(), int length = 0);
4355 /** Returns the unique function instance in the current execution context.*/
4356 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4357 V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
4358 Local<Context> context);
4361 * Set the call-handler callback for a FunctionTemplate. This
4362 * callback is called whenever the function created from this
4363 * FunctionTemplate is called.
4365 void SetCallHandler(FunctionCallback callback,
4366 Local<Value> data = Local<Value>());
4368 /** Set the predefined length property for the FunctionTemplate. */
4369 void SetLength(int length);
4371 /** Get the InstanceTemplate. */
4372 Local<ObjectTemplate> InstanceTemplate();
4374 /** Causes the function template to inherit from a parent function template.*/
4375 void Inherit(Local<FunctionTemplate> parent);
4378 * A PrototypeTemplate is the template used to create the prototype object
4379 * of the function created by this template.
4381 Local<ObjectTemplate> PrototypeTemplate();
4384 * Set the class name of the FunctionTemplate. This is used for
4385 * printing objects created with the function created from the
4386 * FunctionTemplate as its constructor.
4388 void SetClassName(Local<String> name);
4392 * When set to true, no access check will be performed on the receiver of a
4393 * function call. Currently defaults to true, but this is subject to change.
4395 void SetAcceptAnyReceiver(bool value);
4398 * Determines whether the __proto__ accessor ignores instances of
4399 * the function template. If instances of the function template are
4400 * ignored, __proto__ skips all instances and instead returns the
4401 * next object in the prototype chain.
4403 * Call with a value of true to make the __proto__ accessor ignore
4404 * instances of the function template. Call with a value of false
4405 * to make the __proto__ accessor not ignore instances of the
4406 * function template. By default, instances of a function template
4409 void SetHiddenPrototype(bool value);
4412 * Sets the ReadOnly flag in the attributes of the 'prototype' property
4413 * of functions created from this FunctionTemplate to true.
4415 void ReadOnlyPrototype();
4418 * Removes the prototype property from functions created from this
4421 void RemovePrototype();
4424 * Returns true if the given object is an instance of this function
4427 bool HasInstance(Local<Value> object);
4431 friend class Context;
4432 friend class ObjectTemplate;
4436 enum class PropertyHandlerFlags {
4438 // See ALL_CAN_READ above.
4440 // Will not call into interceptor for properties on the receiver or prototype
4441 // chain. Currently only valid for named interceptors.
4442 kNonMasking = 1 << 1,
4443 // Will not call into interceptor for symbol lookup. Only meaningful for
4444 // named interceptors.
4445 kOnlyInterceptStrings = 1 << 2,
4449 struct NamedPropertyHandlerConfiguration {
4450 NamedPropertyHandlerConfiguration(
4451 /** Note: getter is required **/
4452 GenericNamedPropertyGetterCallback getter = 0,
4453 GenericNamedPropertySetterCallback setter = 0,
4454 GenericNamedPropertyQueryCallback query = 0,
4455 GenericNamedPropertyDeleterCallback deleter = 0,
4456 GenericNamedPropertyEnumeratorCallback enumerator = 0,
4457 Local<Value> data = Local<Value>(),
4458 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4463 enumerator(enumerator),
4467 GenericNamedPropertyGetterCallback getter;
4468 GenericNamedPropertySetterCallback setter;
4469 GenericNamedPropertyQueryCallback query;
4470 GenericNamedPropertyDeleterCallback deleter;
4471 GenericNamedPropertyEnumeratorCallback enumerator;
4473 PropertyHandlerFlags flags;
4477 struct IndexedPropertyHandlerConfiguration {
4478 IndexedPropertyHandlerConfiguration(
4479 /** Note: getter is required **/
4480 IndexedPropertyGetterCallback getter = 0,
4481 IndexedPropertySetterCallback setter = 0,
4482 IndexedPropertyQueryCallback query = 0,
4483 IndexedPropertyDeleterCallback deleter = 0,
4484 IndexedPropertyEnumeratorCallback enumerator = 0,
4485 Local<Value> data = Local<Value>(),
4486 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
4491 enumerator(enumerator),
4495 IndexedPropertyGetterCallback getter;
4496 IndexedPropertySetterCallback setter;
4497 IndexedPropertyQueryCallback query;
4498 IndexedPropertyDeleterCallback deleter;
4499 IndexedPropertyEnumeratorCallback enumerator;
4501 PropertyHandlerFlags flags;
4506 * An ObjectTemplate is used to create objects at runtime.
4508 * Properties added to an ObjectTemplate are added to each object
4509 * created from the ObjectTemplate.
4511 class V8_EXPORT ObjectTemplate : public Template {
4513 /** Creates an ObjectTemplate. */
4514 static Local<ObjectTemplate> New(
4516 Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
4517 static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4519 /** Creates a new instance of this template.*/
4520 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4521 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
4524 * Sets an accessor on the object template.
4526 * Whenever the property with the given name is accessed on objects
4527 * created from this ObjectTemplate the getter and setter callbacks
4528 * are called instead of getting and setting the property directly
4529 * on the JavaScript object.
4531 * \param name The name of the property for which an accessor is added.
4532 * \param getter The callback to invoke when getting the property.
4533 * \param setter The callback to invoke when setting the property.
4534 * \param data A piece of data that will be passed to the getter and setter
4535 * callbacks whenever they are invoked.
4536 * \param settings Access control settings for the accessor. This is a bit
4537 * field consisting of one of more of
4538 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4539 * The default is to not allow cross-context access.
4540 * ALL_CAN_READ means that all cross-context reads are allowed.
4541 * ALL_CAN_WRITE means that all cross-context writes are allowed.
4542 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4543 * cross-context access.
4544 * \param attribute The attributes of the property for which an accessor
4546 * \param signature The signature describes valid receivers for the accessor
4547 * and is used to perform implicit instance checks against them. If the
4548 * receiver is incompatible (i.e. is not an instance of the constructor as
4549 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4550 * thrown and no callback is invoked.
4553 Local<String> name, AccessorGetterCallback getter,
4554 AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4555 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4556 Local<AccessorSignature> signature = Local<AccessorSignature>());
4558 Local<Name> name, AccessorNameGetterCallback getter,
4559 AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4560 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4561 Local<AccessorSignature> signature = Local<AccessorSignature>());
4564 * Sets a named property handler on the object template.
4566 * Whenever a property whose name is a string is accessed on objects created
4567 * from this object template, the provided callback is invoked instead of
4568 * accessing the property directly on the JavaScript object.
4570 * Note that new code should use the second version that can intercept
4571 * symbol-named properties as well as string-named properties.
4573 * \param getter The callback to invoke when getting a property.
4574 * \param setter The callback to invoke when setting a property.
4575 * \param query The callback to invoke to check if a property is present,
4576 * and if present, get its attributes.
4577 * \param deleter The callback to invoke when deleting a property.
4578 * \param enumerator The callback to invoke to enumerate all the named
4579 * properties of an object.
4580 * \param data A piece of data that will be passed to the callbacks
4581 * whenever they are invoked.
4583 // TODO(dcarney): deprecate
4584 void SetNamedPropertyHandler(NamedPropertyGetterCallback getter,
4585 NamedPropertySetterCallback setter = 0,
4586 NamedPropertyQueryCallback query = 0,
4587 NamedPropertyDeleterCallback deleter = 0,
4588 NamedPropertyEnumeratorCallback enumerator = 0,
4589 Local<Value> data = Local<Value>());
4590 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4593 * Sets an indexed property handler on the object template.
4595 * Whenever an indexed property is accessed on objects created from
4596 * this object template, the provided callback is invoked instead of
4597 * accessing the property directly on the JavaScript object.
4599 * \param getter The callback to invoke when getting a property.
4600 * \param setter The callback to invoke when setting a property.
4601 * \param query The callback to invoke to check if an object has a property.
4602 * \param deleter The callback to invoke when deleting a property.
4603 * \param enumerator The callback to invoke to enumerate all the indexed
4604 * properties of an object.
4605 * \param data A piece of data that will be passed to the callbacks
4606 * whenever they are invoked.
4608 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
4609 // TODO(dcarney): deprecate
4610 void SetIndexedPropertyHandler(
4611 IndexedPropertyGetterCallback getter,
4612 IndexedPropertySetterCallback setter = 0,
4613 IndexedPropertyQueryCallback query = 0,
4614 IndexedPropertyDeleterCallback deleter = 0,
4615 IndexedPropertyEnumeratorCallback enumerator = 0,
4616 Local<Value> data = Local<Value>()) {
4617 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
4618 deleter, enumerator, data));
4621 * Sets the callback to be used when calling instances created from
4622 * this template as a function. If no callback is set, instances
4623 * behave like normal JavaScript objects that cannot be called as a
4626 void SetCallAsFunctionHandler(FunctionCallback callback,
4627 Local<Value> data = Local<Value>());
4630 * Mark object instances of the template as undetectable.
4632 * In many ways, undetectable objects behave as though they are not
4633 * there. They behave like 'undefined' in conditionals and when
4634 * printed. However, properties can be accessed and called as on
4637 void MarkAsUndetectable();
4640 * Sets access check callbacks on the object template and enables
4643 * When accessing properties on instances of this object template,
4644 * the access check callback will be called to determine whether or
4645 * not to allow cross-context access to the properties.
4647 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
4648 IndexedSecurityCallback indexed_handler,
4649 Local<Value> data = Local<Value>());
4652 * Gets the number of internal fields for objects generated from
4655 int InternalFieldCount();
4658 * Sets the number of internal fields for objects generated from
4661 void SetInternalFieldCount(int value);
4665 static Local<ObjectTemplate> New(internal::Isolate* isolate,
4666 Local<FunctionTemplate> constructor);
4667 friend class FunctionTemplate;
4672 * A Signature specifies which receiver is valid for a function.
4674 class V8_EXPORT Signature : public Data {
4676 static Local<Signature> New(
4678 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4686 * An AccessorSignature specifies which receivers are valid parameters
4687 * to an accessor callback.
4689 class V8_EXPORT AccessorSignature : public Data {
4691 static Local<AccessorSignature> New(
4693 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
4696 AccessorSignature();
4701 * A utility for determining the type of objects based on the template
4702 * they were constructed from.
4704 class V8_EXPORT TypeSwitch : public Data {
4706 static Local<TypeSwitch> New(Local<FunctionTemplate> type);
4707 static Local<TypeSwitch> New(int argc, Local<FunctionTemplate> types[]);
4708 int match(Local<Value> value);
4715 // --- Extensions ---
4717 class V8_EXPORT ExternalOneByteStringResourceImpl
4718 : public String::ExternalOneByteStringResource {
4720 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4721 ExternalOneByteStringResourceImpl(const char* data, size_t length)
4722 : data_(data), length_(length) {}
4723 const char* data() const { return data_; }
4724 size_t length() const { return length_; }
4734 class V8_EXPORT Extension { // NOLINT
4736 // Note that the strings passed into this constructor must live as long
4737 // as the Extension itself.
4738 Extension(const char* name,
4739 const char* source = 0,
4741 const char** deps = 0,
4742 int source_length = -1);
4743 virtual ~Extension() { }
4744 virtual v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
4745 v8::Isolate* isolate, v8::Local<v8::String> name) {
4746 return v8::Local<v8::FunctionTemplate>();
4749 const char* name() const { return name_; }
4750 size_t source_length() const { return source_length_; }
4751 const String::ExternalOneByteStringResource* source() const {
4753 int dependency_count() { return dep_count_; }
4754 const char** dependencies() { return deps_; }
4755 void set_auto_enable(bool value) { auto_enable_ = value; }
4756 bool auto_enable() { return auto_enable_; }
4760 size_t source_length_; // expected to initialize before source_
4761 ExternalOneByteStringResourceImpl source_;
4766 // Disallow copying and assigning.
4767 Extension(const Extension&);
4768 void operator=(const Extension&);
4772 void V8_EXPORT RegisterExtension(Extension* extension);
4777 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
4778 V8_INLINE Local<Primitive> Null(Isolate* isolate);
4779 V8_INLINE Local<Boolean> True(Isolate* isolate);
4780 V8_INLINE Local<Boolean> False(Isolate* isolate);
4784 * A set of constraints that specifies the limits of the runtime's memory use.
4785 * You must set the heap size before initializing the VM - the size cannot be
4786 * adjusted after the VM is initialized.
4788 * If you are using threads then you should hold the V8::Locker lock while
4789 * setting the stack limit and you must set a non-default stack limit separately
4792 class V8_EXPORT ResourceConstraints {
4794 ResourceConstraints();
4797 * Configures the constraints with reasonable default values based on the
4798 * capabilities of the current device the VM is running on.
4800 * \param physical_memory The total amount of physical memory on the current
4802 * \param virtual_memory_limit The amount of virtual memory on the current
4803 * device, in bytes, or zero, if there is no limit.
4805 void ConfigureDefaults(uint64_t physical_memory,
4806 uint64_t virtual_memory_limit);
4808 int max_semi_space_size() const { return max_semi_space_size_; }
4809 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4810 int max_old_space_size() const { return max_old_space_size_; }
4811 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4812 int max_executable_size() const { return max_executable_size_; }
4813 void set_max_executable_size(int value) { max_executable_size_ = value; }
4814 uint32_t* stack_limit() const { return stack_limit_; }
4815 // Sets an address beyond which the VM's stack may not grow.
4816 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4817 size_t code_range_size() const { return code_range_size_; }
4818 void set_code_range_size(size_t value) {
4819 code_range_size_ = value;
4823 int max_semi_space_size_;
4824 int max_old_space_size_;
4825 int max_executable_size_;
4826 uint32_t* stack_limit_;
4827 size_t code_range_size_;
4831 // --- Exceptions ---
4834 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4837 typedef void (*MessageCallback)(Local<Message> message, Local<Value> error);
4841 typedef void (*LogEventCallback)(const char* name, int event);
4844 * Create new error objects by calling the corresponding error object
4845 * constructor with the message.
4847 class V8_EXPORT Exception {
4849 static Local<Value> RangeError(Local<String> message);
4850 static Local<Value> ReferenceError(Local<String> message);
4851 static Local<Value> SyntaxError(Local<String> message);
4852 static Local<Value> TypeError(Local<String> message);
4853 static Local<Value> Error(Local<String> message);
4856 * Creates an error message for the given exception.
4857 * Will try to reconstruct the original stack trace from the exception value,
4858 * or capture the current stack trace if not available.
4860 static Local<Message> CreateMessage(Local<Value> exception);
4863 * Returns the original stack trace that was captured at the creation time
4864 * of a given exception, or an empty handle if not available.
4866 static Local<StackTrace> GetStackTrace(Local<Value> exception);
4870 // --- Counters Callbacks ---
4872 typedef int* (*CounterLookupCallback)(const char* name);
4874 typedef void* (*CreateHistogramCallback)(const char* name,
4879 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4881 // --- Memory Allocation Callback ---
4883 kObjectSpaceNewSpace = 1 << 0,
4884 kObjectSpaceOldSpace = 1 << 1,
4885 kObjectSpaceCodeSpace = 1 << 2,
4886 kObjectSpaceMapSpace = 1 << 3,
4887 kObjectSpaceLoSpace = 1 << 4,
4888 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldSpace |
4889 kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4893 enum AllocationAction {
4894 kAllocationActionAllocate = 1 << 0,
4895 kAllocationActionFree = 1 << 1,
4896 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4899 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4900 AllocationAction action,
4903 // --- Leave Script Callback ---
4904 typedef void (*CallCompletedCallback)();
4906 // --- Promise Reject Callback ---
4907 enum PromiseRejectEvent {
4908 kPromiseRejectWithNoHandler = 0,
4909 kPromiseHandlerAddedAfterReject = 1
4912 class PromiseRejectMessage {
4914 PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
4915 Local<Value> value, Local<StackTrace> stack_trace)
4916 : promise_(promise),
4919 stack_trace_(stack_trace) {}
4921 V8_INLINE Local<Promise> GetPromise() const { return promise_; }
4922 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4923 V8_INLINE Local<Value> GetValue() const { return value_; }
4925 // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4926 V8_INLINE Local<StackTrace> GetStackTrace() const { return stack_trace_; }
4929 Local<Promise> promise_;
4930 PromiseRejectEvent event_;
4931 Local<Value> value_;
4932 Local<StackTrace> stack_trace_;
4935 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
4937 // --- Microtask Callback ---
4938 typedef void (*MicrotaskCallback)(void* data);
4940 // --- Failed Access Check Callback ---
4941 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4945 // --- AllowCodeGenerationFromStrings callbacks ---
4948 * Callback to check if code generation from strings is allowed. See
4949 * Context::AllowCodeGenerationFromStrings.
4951 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4953 // --- Garbage Collection Callbacks ---
4956 * Applications can register callback functions which will be called
4957 * before and after a garbage collection. Allocations are not
4958 * allowed in the callback functions, you therefore cannot manipulate
4959 * objects (set or delete properties for example) since it is possible
4960 * such operations will result in the allocation of objects.
4963 kGCTypeScavenge = 1 << 0,
4964 kGCTypeMarkSweepCompact = 1 << 1,
4965 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4968 enum GCCallbackFlags {
4969 kNoGCCallbackFlags = 0,
4970 kGCCallbackFlagCompacted = 1 << 0,
4971 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4972 kGCCallbackFlagForced = 1 << 2
4975 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4976 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4978 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4982 * Collection of V8 heap information.
4984 * Instances of this class can be passed to v8::V8::HeapStatistics to
4985 * get heap statistics from V8.
4987 class V8_EXPORT HeapStatistics {
4990 size_t total_heap_size() { return total_heap_size_; }
4991 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4992 size_t total_physical_size() { return total_physical_size_; }
4993 size_t total_available_size() { return total_available_size_; }
4994 size_t used_heap_size() { return used_heap_size_; }
4995 size_t heap_size_limit() { return heap_size_limit_; }
4998 size_t total_heap_size_;
4999 size_t total_heap_size_executable_;
5000 size_t total_physical_size_;
5001 size_t total_available_size_;
5002 size_t used_heap_size_;
5003 size_t heap_size_limit_;
5006 friend class Isolate;
5010 class V8_EXPORT HeapSpaceStatistics {
5012 HeapSpaceStatistics();
5013 const char* space_name() { return space_name_; }
5014 size_t space_size() { return space_size_; }
5015 size_t space_used_size() { return space_used_size_; }
5016 size_t space_available_size() { return space_available_size_; }
5017 size_t physical_space_size() { return physical_space_size_; }
5020 const char* space_name_;
5022 size_t space_used_size_;
5023 size_t space_available_size_;
5024 size_t physical_space_size_;
5026 friend class Isolate;
5030 class V8_EXPORT HeapObjectStatistics {
5032 HeapObjectStatistics();
5033 const char* object_type() { return object_type_; }
5034 const char* object_sub_type() { return object_sub_type_; }
5035 size_t object_count() { return object_count_; }
5036 size_t object_size() { return object_size_; }
5039 const char* object_type_;
5040 const char* object_sub_type_;
5041 size_t object_count_;
5042 size_t object_size_;
5044 friend class Isolate;
5048 class RetainedObjectInfo;
5052 * FunctionEntryHook is the type of the profile entry hook called at entry to
5053 * any generated function when function-level profiling is enabled.
5055 * \param function the address of the function that's being entered.
5056 * \param return_addr_location points to a location on stack where the machine
5057 * return address resides. This can be used to identify the caller of
5058 * \p function, and/or modified to divert execution when \p function exits.
5060 * \note the entry hook must not cause garbage collection.
5062 typedef void (*FunctionEntryHook)(uintptr_t function,
5063 uintptr_t return_addr_location);
5066 * A JIT code event is issued each time code is added, moved or removed.
5068 * \note removal events are not currently issued.
5070 struct JitCodeEvent {
5075 CODE_ADD_LINE_POS_INFO,
5076 CODE_START_LINE_INFO_RECORDING,
5077 CODE_END_LINE_INFO_RECORDING
5079 // Definition of the code position type. The "POSITION" type means the place
5080 // in the source code which are of interest when making stack traces to
5081 // pin-point the source location of a stack frame as close as possible.
5082 // The "STATEMENT_POSITION" means the place at the beginning of each
5083 // statement, and is used to indicate possible break locations.
5084 enum PositionType { POSITION, STATEMENT_POSITION };
5088 // Start of the instructions.
5090 // Size of the instructions.
5092 // Script info for CODE_ADDED event.
5093 Local<UnboundScript> script;
5094 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
5095 // code line information which is returned from the
5096 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
5097 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
5101 // Name of the object associated with the code, note that the string is not
5104 // Number of chars in str.
5108 struct line_info_t {
5113 // The position type.
5114 PositionType position_type;
5118 // Only valid for CODE_ADDED.
5121 // Only valid for CODE_ADD_LINE_POS_INFO
5122 struct line_info_t line_info;
5124 // New location of instructions. Only valid for CODE_MOVED.
5125 void* new_code_start;
5130 * Option flags passed to the SetJitCodeEventHandler function.
5132 enum JitCodeEventOptions {
5133 kJitCodeEventDefault = 0,
5134 // Generate callbacks for already existent code.
5135 kJitCodeEventEnumExisting = 1
5140 * Callback function passed to SetJitCodeEventHandler.
5142 * \param event code add, move or removal event.
5144 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
5148 * Interface for iterating through all external resources in the heap.
5150 class V8_EXPORT ExternalResourceVisitor { // NOLINT
5152 virtual ~ExternalResourceVisitor() {}
5153 virtual void VisitExternalString(Local<String> string) {}
5158 * Interface for iterating through all the persistent handles in the heap.
5160 class V8_EXPORT PersistentHandleVisitor { // NOLINT
5162 virtual ~PersistentHandleVisitor() {}
5163 virtual void VisitPersistentHandle(Persistent<Value>* value,
5164 uint16_t class_id) {}
5169 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
5170 * completely separate states. Objects from one isolate must not be used in
5171 * other isolates. The embedder can create multiple isolates and use them in
5172 * parallel in multiple threads. An isolate can be entered by at most one
5173 * thread at any given time. The Locker/Unlocker API must be used to
5176 class V8_EXPORT Isolate {
5179 * Initial configuration parameters for a new Isolate.
5181 struct CreateParams {
5184 code_event_handler(NULL),
5185 snapshot_blob(NULL),
5186 counter_lookup_callback(NULL),
5187 create_histogram_callback(NULL),
5188 add_histogram_sample_callback(NULL),
5189 array_buffer_allocator(NULL) {}
5192 * The optional entry_hook allows the host application to provide the
5193 * address of a function that's invoked on entry to every V8-generated
5194 * function. Note that entry_hook is invoked at the very start of each
5195 * generated function. Furthermore, if an entry_hook is given, V8 will
5196 * always run without a context snapshot.
5198 FunctionEntryHook entry_hook;
5201 * Allows the host application to provide the address of a function that is
5202 * notified each time code is added, moved or removed.
5204 JitCodeEventHandler code_event_handler;
5207 * ResourceConstraints to use for the new Isolate.
5209 ResourceConstraints constraints;
5212 * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5214 StartupData* snapshot_blob;
5218 * Enables the host application to provide a mechanism for recording
5219 * statistics counters.
5221 CounterLookupCallback counter_lookup_callback;
5224 * Enables the host application to provide a mechanism for recording
5225 * histograms. The CreateHistogram function returns a
5226 * histogram which will later be passed to the AddHistogramSample
5229 CreateHistogramCallback create_histogram_callback;
5230 AddHistogramSampleCallback add_histogram_sample_callback;
5233 * The ArrayBuffer::Allocator to use for allocating and freeing the backing
5234 * store of ArrayBuffers.
5236 ArrayBuffer::Allocator* array_buffer_allocator;
5241 * Stack-allocated class which sets the isolate for all operations
5242 * executed within a local scope.
5244 class V8_EXPORT Scope {
5246 explicit Scope(Isolate* isolate) : isolate_(isolate) {
5250 ~Scope() { isolate_->Exit(); }
5253 Isolate* const isolate_;
5255 // Prevent copying of Scope objects.
5256 Scope(const Scope&);
5257 Scope& operator=(const Scope&);
5262 * Assert that no Javascript code is invoked.
5264 class V8_EXPORT DisallowJavascriptExecutionScope {
5266 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
5268 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
5269 ~DisallowJavascriptExecutionScope();
5275 // Prevent copying of Scope objects.
5276 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5277 DisallowJavascriptExecutionScope& operator=(
5278 const DisallowJavascriptExecutionScope&);
5283 * Introduce exception to DisallowJavascriptExecutionScope.
5285 class V8_EXPORT AllowJavascriptExecutionScope {
5287 explicit AllowJavascriptExecutionScope(Isolate* isolate);
5288 ~AllowJavascriptExecutionScope();
5291 void* internal_throws_;
5292 void* internal_assert_;
5294 // Prevent copying of Scope objects.
5295 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5296 AllowJavascriptExecutionScope& operator=(
5297 const AllowJavascriptExecutionScope&);
5301 * Do not run microtasks while this scope is active, even if microtasks are
5302 * automatically executed otherwise.
5304 class V8_EXPORT SuppressMicrotaskExecutionScope {
5306 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
5307 ~SuppressMicrotaskExecutionScope();
5310 internal::Isolate* isolate_;
5312 // Prevent copying of Scope objects.
5313 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5314 SuppressMicrotaskExecutionScope& operator=(
5315 const SuppressMicrotaskExecutionScope&);
5319 * Types of garbage collections that can be requested via
5320 * RequestGarbageCollectionForTesting.
5322 enum GarbageCollectionType {
5323 kFullGarbageCollection,
5324 kMinorGarbageCollection
5328 * Features reported via the SetUseCounterCallback callback. Do not change
5329 * assigned numbers of existing items; add new features to the end of this
5332 enum UseCounterFeature {
5336 kMarkDequeOverflow = 3,
5337 kStoreBufferOverflow = 4,
5338 kSlotsBufferOverflow = 5,
5341 kUseCounterFeatureCount // This enum value must be last.
5344 typedef void (*UseCounterCallback)(Isolate* isolate,
5345 UseCounterFeature feature);
5349 * Creates a new isolate. Does not change the currently entered
5352 * When an isolate is no longer used its resources should be freed
5353 * by calling Dispose(). Using the delete operator is not allowed.
5355 * V8::Initialize() must have run prior to this.
5357 static Isolate* New(const CreateParams& params);
5360 * Returns the entered isolate for the current thread or NULL in
5361 * case there is no current isolate.
5363 * This method must not be invoked before V8::Initialize() was invoked.
5365 static Isolate* GetCurrent();
5368 * Methods below this point require holding a lock (using Locker) in
5369 * a multi-threaded environment.
5373 * Sets this isolate as the entered one for the current thread.
5374 * Saves the previously entered one (if any), so that it can be
5375 * restored when exiting. Re-entering an isolate is allowed.
5380 * Exits this isolate by restoring the previously entered one in the
5381 * current thread. The isolate may still stay the same, if it was
5382 * entered more than once.
5384 * Requires: this == Isolate::GetCurrent().
5389 * Disposes the isolate. The isolate must not be entered by any
5390 * thread to be disposable.
5395 * Associate embedder-specific data with the isolate. |slot| has to be
5396 * between 0 and GetNumberOfDataSlots() - 1.
5398 V8_INLINE void SetData(uint32_t slot, void* data);
5401 * Retrieve embedder-specific data from the isolate.
5402 * Returns NULL if SetData has never been called for the given |slot|.
5404 V8_INLINE void* GetData(uint32_t slot);
5407 * Returns the maximum number of available embedder data slots. Valid slots
5408 * are in the range of 0 - GetNumberOfDataSlots() - 1.
5410 V8_INLINE static uint32_t GetNumberOfDataSlots();
5413 * Get statistics about the heap memory usage.
5415 void GetHeapStatistics(HeapStatistics* heap_statistics);
5418 * Returns the number of spaces in the heap.
5420 size_t NumberOfHeapSpaces();
5423 * Get the memory usage of a space in the heap.
5425 * \param space_statistics The HeapSpaceStatistics object to fill in
5427 * \param index The index of the space to get statistics from, which ranges
5428 * from 0 to NumberOfHeapSpaces() - 1.
5429 * \returns true on success.
5431 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
5435 * Returns the number of types of objects tracked in the heap at GC.
5437 size_t NumberOfTrackedHeapObjectTypes();
5440 * Get statistics about objects in the heap.
5442 * \param object_statistics The HeapObjectStatistics object to fill in
5443 * statistics of objects of given type, which were live in the previous GC.
5444 * \param type_index The index of the type of object to fill details about,
5445 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
5446 * \returns true on success.
5448 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
5452 * Get a call stack sample from the isolate.
5453 * \param state Execution state.
5454 * \param frames Caller allocated buffer to store stack frames.
5455 * \param frames_limit Maximum number of frames to capture. The buffer must
5456 * be large enough to hold the number of frames.
5457 * \param sample_info The sample info is filled up by the function
5458 * provides number of actual captured stack frames and
5459 * the current VM state.
5460 * \note GetStackSample should only be called when the JS thread is paused or
5461 * interrupted. Otherwise the behavior is undefined.
5463 void GetStackSample(const RegisterState& state, void** frames,
5464 size_t frames_limit, SampleInfo* sample_info);
5467 * Adjusts the amount of registered external memory. Used to give V8 an
5468 * indication of the amount of externally allocated memory that is kept alive
5469 * by JavaScript objects. V8 uses this to decide when to perform global
5470 * garbage collections. Registering externally allocated memory will trigger
5471 * global garbage collections more often than it would otherwise in an attempt
5472 * to garbage collect the JavaScript objects that keep the externally
5473 * allocated memory alive.
5475 * \param change_in_bytes the change in externally allocated memory that is
5476 * kept alive by JavaScript objects.
5477 * \returns the adjusted value.
5480 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5483 * Returns heap profiler for this isolate. Will return NULL until the isolate
5486 HeapProfiler* GetHeapProfiler();
5489 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5490 * is initialized. It is the embedder's responsibility to stop all CPU
5491 * profiling activities if it has started any.
5493 CpuProfiler* GetCpuProfiler();
5495 /** Returns true if this isolate has a current context. */
5498 /** Returns the context that is on the top of the stack. */
5499 Local<Context> GetCurrentContext();
5502 * Returns the context of the calling JavaScript code. That is the
5503 * context of the top-most JavaScript frame. If there are no
5504 * JavaScript frames an empty handle is returned.
5506 Local<Context> GetCallingContext();
5508 /** Returns the last entered context. */
5509 Local<Context> GetEnteredContext();
5512 * Schedules an exception to be thrown when returning to JavaScript. When an
5513 * exception has been scheduled it is illegal to invoke any JavaScript
5514 * operation; the caller must return immediately and only after the exception
5515 * has been handled does it become legal to invoke JavaScript operations.
5517 Local<Value> ThrowException(Local<Value> exception);
5520 * Allows the host application to group objects together. If one
5521 * object in the group is alive, all objects in the group are alive.
5522 * After each garbage collection, object groups are removed. It is
5523 * intended to be used in the before-garbage-collection callback
5524 * function, for instance to simulate DOM tree connections among JS
5525 * wrapper objects. Object groups for all dependent handles need to
5526 * be provided for kGCTypeMarkSweepCompact collections, for all other
5527 * garbage collection types it is sufficient to provide object groups
5528 * for partially dependent handles only.
5530 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5534 * Allows the host application to declare implicit references from an object
5535 * group to an object. If the objects of the object group are alive, the child
5536 * object is alive too. After each garbage collection, all implicit references
5537 * are removed. It is intended to be used in the before-garbage-collection
5538 * callback function.
5540 template<typename T> void SetReferenceFromGroup(UniqueId id,
5541 const Persistent<T>& child);
5544 * Allows the host application to declare implicit references from an object
5545 * to another object. If the parent object is alive, the child object is alive
5546 * too. After each garbage collection, all implicit references are removed. It
5547 * is intended to be used in the before-garbage-collection callback function.
5549 template<typename T, typename S>
5550 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5552 typedef void (*GCPrologueCallback)(Isolate* isolate,
5554 GCCallbackFlags flags);
5555 typedef void (*GCEpilogueCallback)(Isolate* isolate,
5557 GCCallbackFlags flags);
5560 * Enables the host application to receive a notification before a
5561 * garbage collection. Allocations are allowed in the callback function,
5562 * but the callback is not re-entrant: if the allocation inside it will
5563 * trigger the garbage collection, the callback won't be called again.
5564 * It is possible to specify the GCType filter for your callback. But it is
5565 * not possible to register the same callback function two times with
5566 * different GCType filters.
5568 void AddGCPrologueCallback(
5569 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5572 * This function removes callback which was installed by
5573 * AddGCPrologueCallback function.
5575 void RemoveGCPrologueCallback(GCPrologueCallback callback);
5578 * Enables the host application to receive a notification after a
5579 * garbage collection. Allocations are allowed in the callback function,
5580 * but the callback is not re-entrant: if the allocation inside it will
5581 * trigger the garbage collection, the callback won't be called again.
5582 * It is possible to specify the GCType filter for your callback. But it is
5583 * not possible to register the same callback function two times with
5584 * different GCType filters.
5586 void AddGCEpilogueCallback(
5587 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5590 * This function removes callback which was installed by
5591 * AddGCEpilogueCallback function.
5593 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
5597 * Forcefully terminate the current thread of JavaScript execution
5598 * in the given isolate.
5600 * This method can be used by any thread even if that thread has not
5601 * acquired the V8 lock with a Locker object.
5603 void TerminateExecution();
5606 * Is V8 terminating JavaScript execution.
5608 * Returns true if JavaScript execution is currently terminating
5609 * because of a call to TerminateExecution. In that case there are
5610 * still JavaScript frames on the stack and the termination
5611 * exception is still active.
5613 bool IsExecutionTerminating();
5616 * Resume execution capability in the given isolate, whose execution
5617 * was previously forcefully terminated using TerminateExecution().
5619 * When execution is forcefully terminated using TerminateExecution(),
5620 * the isolate can not resume execution until all JavaScript frames
5621 * have propagated the uncatchable exception which is generated. This
5622 * method allows the program embedding the engine to handle the
5623 * termination event and resume execution capability, even if
5624 * JavaScript frames remain on the stack.
5626 * This method can be used by any thread even if that thread has not
5627 * acquired the V8 lock with a Locker object.
5629 void CancelTerminateExecution();
5632 * Request V8 to interrupt long running JavaScript code and invoke
5633 * the given |callback| passing the given |data| to it. After |callback|
5634 * returns control will be returned to the JavaScript code.
5635 * There may be a number of interrupt requests in flight.
5636 * Can be called from another thread without acquiring a |Locker|.
5637 * Registered |callback| must not reenter interrupted Isolate.
5639 void RequestInterrupt(InterruptCallback callback, void* data);
5642 * Request garbage collection in this Isolate. It is only valid to call this
5643 * function if --expose_gc was specified.
5645 * This should only be used for testing purposes and not to enforce a garbage
5646 * collection schedule. It has strong negative impact on the garbage
5647 * collection performance. Use IdleNotificationDeadline() or
5648 * LowMemoryNotification() instead to influence the garbage collection
5651 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
5654 * Set the callback to invoke for logging event.
5656 void SetEventLogger(LogEventCallback that);
5659 * Adds a callback to notify the host application when a script finished
5660 * running. If a script re-enters the runtime during executing, the
5661 * CallCompletedCallback is only invoked when the outer-most script
5662 * execution ends. Executing scripts inside the callback do not trigger
5663 * further callbacks.
5665 void AddCallCompletedCallback(CallCompletedCallback callback);
5668 * Removes callback that was installed by AddCallCompletedCallback.
5670 void RemoveCallCompletedCallback(CallCompletedCallback callback);
5674 * Set callback to notify about promise reject with no handler, or
5675 * revocation of such a previous notification once the handler is added.
5677 void SetPromiseRejectCallback(PromiseRejectCallback callback);
5680 * Experimental: Runs the Microtask Work Queue until empty
5681 * Any exceptions thrown by microtask callbacks are swallowed.
5683 void RunMicrotasks();
5686 * Experimental: Enqueues the callback to the Microtask Work Queue
5688 void EnqueueMicrotask(Local<Function> microtask);
5691 * Experimental: Enqueues the callback to the Microtask Work Queue
5693 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5696 * Experimental: Controls whether the Microtask Work Queue is automatically
5697 * run when the script call depth decrements to zero.
5699 void SetAutorunMicrotasks(bool autorun);
5702 * Experimental: Returns whether the Microtask Work Queue is automatically
5703 * run when the script call depth decrements to zero.
5705 bool WillAutorunMicrotasks() const;
5708 * Sets a callback for counting the number of times a feature of V8 is used.
5710 void SetUseCounterCallback(UseCounterCallback callback);
5713 * Enables the host application to provide a mechanism for recording
5714 * statistics counters.
5716 void SetCounterFunction(CounterLookupCallback);
5719 * Enables the host application to provide a mechanism for recording
5720 * histograms. The CreateHistogram function returns a
5721 * histogram which will later be passed to the AddHistogramSample
5724 void SetCreateHistogramFunction(CreateHistogramCallback);
5725 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
5728 * Optional notification that the embedder is idle.
5729 * V8 uses the notification to perform garbage collection.
5730 * This call can be used repeatedly if the embedder remains idle.
5731 * Returns true if the embedder should stop calling IdleNotificationDeadline
5732 * until real work has been done. This indicates that V8 has done
5733 * as much cleanup as it will be able to do.
5735 * The deadline_in_seconds argument specifies the deadline V8 has to finish
5736 * garbage collection work. deadline_in_seconds is compared with
5737 * MonotonicallyIncreasingTime() and should be based on the same timebase as
5738 * that function. There is no guarantee that the actual work will be done
5739 * within the time limit.
5741 bool IdleNotificationDeadline(double deadline_in_seconds);
5743 V8_DEPRECATE_SOON("use IdleNotificationDeadline()",
5744 bool IdleNotification(int idle_time_in_ms));
5747 * Optional notification that the system is running low on memory.
5748 * V8 uses these notifications to attempt to free memory.
5750 void LowMemoryNotification();
5753 * Optional notification that a context has been disposed. V8 uses
5754 * these notifications to guide the GC heuristic. Returns the number
5755 * of context disposals - including this one - since the last time
5756 * V8 had a chance to clean up.
5758 * The optional parameter |dependant_context| specifies whether the disposed
5759 * context was depending on state from other contexts or not.
5761 int ContextDisposedNotification(bool dependant_context = true);
5764 * Allows the host application to provide the address of a function that is
5765 * notified each time code is added, moved or removed.
5767 * \param options options for the JIT code event handler.
5768 * \param event_handler the JIT code event handler, which will be invoked
5769 * each time code is added, moved or removed.
5770 * \note \p event_handler won't get notified of existent code.
5771 * \note since code removal notifications are not currently issued, the
5772 * \p event_handler may get notifications of code that overlaps earlier
5773 * code notifications. This happens when code areas are reused, and the
5774 * earlier overlapping code areas should therefore be discarded.
5775 * \note the events passed to \p event_handler and the strings they point to
5776 * are not guaranteed to live past each call. The \p event_handler must
5777 * copy strings and other parameters it needs to keep around.
5778 * \note the set of events declared in JitCodeEvent::EventType is expected to
5779 * grow over time, and the JitCodeEvent structure is expected to accrue
5780 * new members. The \p event_handler function must ignore event codes
5781 * it does not recognize to maintain future compatibility.
5782 * \note Use Isolate::CreateParams to get events for code executed during
5785 void SetJitCodeEventHandler(JitCodeEventOptions options,
5786 JitCodeEventHandler event_handler);
5789 * Modifies the stack limit for this Isolate.
5791 * \param stack_limit An address beyond which the Vm's stack may not grow.
5793 * \note If you are using threads then you should hold the V8::Locker lock
5794 * while setting the stack limit and you must set a non-default stack
5795 * limit separately for each thread.
5797 void SetStackLimit(uintptr_t stack_limit);
5800 * Returns a memory range that can potentially contain jitted code.
5802 * On Win64, embedders are advised to install function table callbacks for
5803 * these ranges, as default SEH won't be able to unwind through jitted code.
5805 * The first page of the code range is reserved for the embedder and is
5806 * committed, writable, and executable.
5808 * Might be empty on other platforms.
5810 * https://code.google.com/p/v8/issues/detail?id=3598
5812 void GetCodeRange(void** start, size_t* length_in_bytes);
5814 /** Set the callback to invoke in case of fatal errors. */
5815 void SetFatalErrorHandler(FatalErrorCallback that);
5818 * Set the callback to invoke to check if code generation from
5819 * strings should be allowed.
5821 void SetAllowCodeGenerationFromStringsCallback(
5822 AllowCodeGenerationFromStringsCallback callback);
5825 * Check if V8 is dead and therefore unusable. This is the case after
5826 * fatal errors such as out-of-memory situations.
5831 * Adds a message listener.
5833 * The same message listener can be added more than once and in that
5834 * case it will be called more than once for each message.
5836 * If data is specified, it will be passed to the callback when it is called.
5837 * Otherwise, the exception object will be passed to the callback instead.
5839 bool AddMessageListener(MessageCallback that,
5840 Local<Value> data = Local<Value>());
5843 * Remove all message listeners from the specified callback function.
5845 void RemoveMessageListeners(MessageCallback that);
5847 /** Callback function for reporting failed access checks.*/
5848 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
5851 * Tells V8 to capture current stack trace when uncaught exception occurs
5852 * and report it to the message listeners. The option is off by default.
5854 void SetCaptureStackTraceForUncaughtExceptions(
5855 bool capture, int frame_limit = 10,
5856 StackTrace::StackTraceOptions options = StackTrace::kOverview);
5859 * Enables the host application to provide a mechanism to be notified
5860 * and perform custom logging when V8 Allocates Executable Memory.
5862 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5863 ObjectSpace space, AllocationAction action);
5866 * Removes callback that was installed by AddMemoryAllocationCallback.
5868 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
5871 * Iterates through all external resources referenced from current isolate
5872 * heap. GC is not invoked prior to iterating, therefore there is no
5873 * guarantee that visited objects are still alive.
5875 void VisitExternalResources(ExternalResourceVisitor* visitor);
5878 * Iterates through all the persistent handles in the current isolate's heap
5879 * that have class_ids.
5881 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5884 * Iterates through all the persistent handles in the current isolate's heap
5885 * that have class_ids and are candidates to be marked as partially dependent
5886 * handles. This will visit handles to young objects created since the last
5887 * garbage collection but is free to visit an arbitrary superset of these
5890 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
5893 template <class K, class V, class Traits>
5894 friend class PersistentValueMapBase;
5897 Isolate(const Isolate&);
5899 Isolate& operator=(const Isolate&);
5900 void* operator new(size_t size);
5901 void operator delete(void*, size_t);
5903 void SetObjectGroupId(internal::Object** object, UniqueId id);
5904 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5905 void SetReference(internal::Object** parent, internal::Object** child);
5906 void CollectAllGarbage(const char* gc_reason);
5909 class V8_EXPORT StartupData {
5917 * EntropySource is used as a callback function when v8 needs a source
5920 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5924 * ReturnAddressLocationResolver is used as a callback function when v8 is
5925 * resolving the location of a return address on the stack. Profilers that
5926 * change the return address on the stack can use this to resolve the stack
5927 * location to whereever the profiler stashed the original return address.
5929 * \param return_addr_location points to a location on stack where a machine
5930 * return address resides.
5931 * \returns either return_addr_location, or else a pointer to the profiler's
5932 * copy of the original return address.
5934 * \note the resolver function must not cause garbage collection.
5936 typedef uintptr_t (*ReturnAddressLocationResolver)(
5937 uintptr_t return_addr_location);
5941 * Container class for static utility functions.
5943 class V8_EXPORT V8 {
5945 /** Set the callback to invoke in case of fatal errors. */
5946 V8_INLINE static V8_DEPRECATE_SOON(
5947 "Use isolate version",
5948 void SetFatalErrorHandler(FatalErrorCallback that));
5951 * Set the callback to invoke to check if code generation from
5952 * strings should be allowed.
5954 V8_INLINE static V8_DEPRECATE_SOON(
5955 "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
5956 AllowCodeGenerationFromStringsCallback that));
5959 * Check if V8 is dead and therefore unusable. This is the case after
5960 * fatal errors such as out-of-memory situations.
5962 V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
5965 * Hand startup data to V8, in case the embedder has chosen to build
5966 * V8 with external startup data.
5969 * - By default the startup data is linked into the V8 library, in which
5970 * case this function is not meaningful.
5971 * - If this needs to be called, it needs to be called before V8
5972 * tries to make use of its built-ins.
5973 * - To avoid unnecessary copies of data, V8 will point directly into the
5974 * given data blob, so pretty please keep it around until V8 exit.
5975 * - Compression of the startup blob might be useful, but needs to
5976 * handled entirely on the embedders' side.
5977 * - The call will abort if the data is invalid.
5979 static void SetNativesDataBlob(StartupData* startup_blob);
5980 static void SetSnapshotDataBlob(StartupData* startup_blob);
5983 * Create a new isolate and context for the purpose of capturing a snapshot
5984 * Returns { NULL, 0 } on failure.
5985 * The caller owns the data array in the return value.
5987 static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
5990 * Adds a message listener.
5992 * The same message listener can be added more than once and in that
5993 * case it will be called more than once for each message.
5995 * If data is specified, it will be passed to the callback when it is called.
5996 * Otherwise, the exception object will be passed to the callback instead.
5998 V8_INLINE static V8_DEPRECATE_SOON(
5999 "Use isolate version",
6000 bool AddMessageListener(MessageCallback that,
6001 Local<Value> data = Local<Value>()));
6004 * Remove all message listeners from the specified callback function.
6006 V8_INLINE static V8_DEPRECATE_SOON(
6007 "Use isolate version", void RemoveMessageListeners(MessageCallback that));
6010 * Tells V8 to capture current stack trace when uncaught exception occurs
6011 * and report it to the message listeners. The option is off by default.
6013 V8_INLINE static V8_DEPRECATE_SOON(
6014 "Use isolate version",
6015 void SetCaptureStackTraceForUncaughtExceptions(
6016 bool capture, int frame_limit = 10,
6017 StackTrace::StackTraceOptions options = StackTrace::kOverview));
6020 * Sets V8 flags from a string.
6022 static void SetFlagsFromString(const char* str, int length);
6025 * Sets V8 flags from the command line.
6027 static void SetFlagsFromCommandLine(int* argc,
6031 /** Get the version string. */
6032 static const char* GetVersion();
6034 /** Callback function for reporting failed access checks.*/
6035 V8_INLINE static V8_DEPRECATE_SOON(
6036 "Use isolate version",
6037 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
6040 * Enables the host application to receive a notification before a
6041 * garbage collection. Allocations are not allowed in the
6042 * callback function, you therefore cannot manipulate objects (set
6043 * or delete properties for example) since it is possible such
6044 * operations will result in the allocation of objects. It is possible
6045 * to specify the GCType filter for your callback. But it is not possible to
6046 * register the same callback function two times with different
6049 static V8_DEPRECATE_SOON(
6050 "Use isolate version",
6051 void AddGCPrologueCallback(GCPrologueCallback callback,
6052 GCType gc_type_filter = kGCTypeAll));
6055 * This function removes callback which was installed by
6056 * AddGCPrologueCallback function.
6058 V8_INLINE static V8_DEPRECATE_SOON(
6059 "Use isolate version",
6060 void RemoveGCPrologueCallback(GCPrologueCallback callback));
6063 * Enables the host application to receive a notification after a
6064 * garbage collection. Allocations are not allowed in the
6065 * callback function, you therefore cannot manipulate objects (set
6066 * or delete properties for example) since it is possible such
6067 * operations will result in the allocation of objects. It is possible
6068 * to specify the GCType filter for your callback. But it is not possible to
6069 * register the same callback function two times with different
6072 static V8_DEPRECATE_SOON(
6073 "Use isolate version",
6074 void AddGCEpilogueCallback(GCEpilogueCallback callback,
6075 GCType gc_type_filter = kGCTypeAll));
6078 * This function removes callback which was installed by
6079 * AddGCEpilogueCallback function.
6081 V8_INLINE static V8_DEPRECATE_SOON(
6082 "Use isolate version",
6083 void RemoveGCEpilogueCallback(GCEpilogueCallback callback));
6086 * Enables the host application to provide a mechanism to be notified
6087 * and perform custom logging when V8 Allocates Executable Memory.
6089 V8_INLINE static V8_DEPRECATE_SOON(
6090 "Use isolate version",
6091 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
6093 AllocationAction action));
6096 * Removes callback that was installed by AddMemoryAllocationCallback.
6098 V8_INLINE static V8_DEPRECATE_SOON(
6099 "Use isolate version",
6100 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
6103 * Initializes V8. This function needs to be called before the first Isolate
6104 * is created. It always returns true.
6106 static bool Initialize();
6109 * Allows the host application to provide a callback which can be used
6110 * as a source of entropy for random number generators.
6112 static void SetEntropySource(EntropySource source);
6115 * Allows the host application to provide a callback that allows v8 to
6116 * cooperate with a profiler that rewrites return addresses on stack.
6118 static void SetReturnAddressLocationResolver(
6119 ReturnAddressLocationResolver return_address_resolver);
6122 * Forcefully terminate the current thread of JavaScript execution
6123 * in the given isolate.
6125 * This method can be used by any thread even if that thread has not
6126 * acquired the V8 lock with a Locker object.
6128 * \param isolate The isolate in which to terminate the current JS execution.
6130 V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
6131 void TerminateExecution(Isolate* isolate));
6134 * Is V8 terminating JavaScript execution.
6136 * Returns true if JavaScript execution is currently terminating
6137 * because of a call to TerminateExecution. In that case there are
6138 * still JavaScript frames on the stack and the termination
6139 * exception is still active.
6141 * \param isolate The isolate in which to check.
6143 V8_INLINE static V8_DEPRECATE_SOON(
6144 "Use isolate version",
6145 bool IsExecutionTerminating(Isolate* isolate = NULL));
6148 * Resume execution capability in the given isolate, whose execution
6149 * was previously forcefully terminated using TerminateExecution().
6151 * When execution is forcefully terminated using TerminateExecution(),
6152 * the isolate can not resume execution until all JavaScript frames
6153 * have propagated the uncatchable exception which is generated. This
6154 * method allows the program embedding the engine to handle the
6155 * termination event and resume execution capability, even if
6156 * JavaScript frames remain on the stack.
6158 * This method can be used by any thread even if that thread has not
6159 * acquired the V8 lock with a Locker object.
6161 * \param isolate The isolate in which to resume execution capability.
6163 V8_INLINE static V8_DEPRECATE_SOON(
6164 "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
6167 * Releases any resources used by v8 and stops any utility threads
6168 * that may be running. Note that disposing v8 is permanent, it
6169 * cannot be reinitialized.
6171 * It should generally not be necessary to dispose v8 before exiting
6172 * a process, this should happen automatically. It is only necessary
6173 * to use if the process needs the resources taken up by v8.
6175 static bool Dispose();
6178 * Iterates through all external resources referenced from current isolate
6179 * heap. GC is not invoked prior to iterating, therefore there is no
6180 * guarantee that visited objects are still alive.
6182 V8_INLINE static V8_DEPRECATE_SOON(
6183 "Use isoalte version",
6184 void VisitExternalResources(ExternalResourceVisitor* visitor));
6187 * Iterates through all the persistent handles in the current isolate's heap
6188 * that have class_ids.
6190 V8_INLINE static V8_DEPRECATE_SOON(
6191 "Use isolate version",
6192 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
6195 * Iterates through all the persistent handles in isolate's heap that have
6198 V8_INLINE static V8_DEPRECATE_SOON(
6199 "Use isolate version",
6200 void VisitHandlesWithClassIds(Isolate* isolate,
6201 PersistentHandleVisitor* visitor));
6204 * Iterates through all the persistent handles in the current isolate's heap
6205 * that have class_ids and are candidates to be marked as partially dependent
6206 * handles. This will visit handles to young objects created since the last
6207 * garbage collection but is free to visit an arbitrary superset of these
6210 V8_INLINE static V8_DEPRECATE_SOON(
6211 "Use isolate version",
6212 void VisitHandlesForPartialDependence(Isolate* isolate,
6213 PersistentHandleVisitor* visitor));
6216 * Initialize the ICU library bundled with V8. The embedder should only
6217 * invoke this method when using the bundled ICU. Returns true on success.
6219 * If V8 was compiled with the ICU data in an external file, the location
6220 * of the data file has to be provided.
6222 static bool InitializeICU(const char* icu_data_file = NULL);
6225 * Sets the v8::Platform to use. This should be invoked before V8 is
6228 static void InitializePlatform(Platform* platform);
6231 * Clears all references to the v8::Platform. This should be invoked after
6234 static void ShutdownPlatform();
6239 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6240 internal::Object** handle);
6241 static internal::Object** CopyPersistent(internal::Object** handle);
6242 static void DisposeGlobal(internal::Object** global_handle);
6243 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6244 static void MakeWeak(internal::Object** global_handle, void* data,
6245 WeakCallback weak_callback);
6246 static void MakeWeak(internal::Object** global_handle, void* data,
6247 WeakCallbackInfo<void>::Callback weak_callback,
6248 WeakCallbackType type);
6249 static void MakeWeak(internal::Object** global_handle, void* data,
6251 int internal_field_index1,
6253 int internal_field_index2,
6254 WeakCallbackInfo<void>::Callback weak_callback);
6255 static void* ClearWeak(internal::Object** global_handle);
6256 static void Eternalize(Isolate* isolate,
6259 static Local<Value> GetEternal(Isolate* isolate, int index);
6261 static void FromJustIsNothing();
6262 static void ToLocalEmpty();
6263 static void InternalFieldOutOfBounds(int index);
6264 template <class T> friend class Local;
6266 friend class MaybeLocal;
6270 friend class WeakCallbackInfo;
6271 template <class T> friend class Eternal;
6272 template <class T> friend class PersistentBase;
6273 template <class T, class M> friend class Persistent;
6274 friend class Context;
6279 * A simple Maybe type, representing an object which may or may not have a
6280 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6282 * If an API method returns a Maybe<>, the API method can potentially fail
6283 * either because an exception is thrown, or because an exception is pending,
6284 * e.g. because a previous API call threw an exception that hasn't been caught
6285 * yet, or because a TerminateExecution exception was thrown. In that case, a
6286 * "Nothing" value is returned.
6291 V8_INLINE bool IsNothing() const { return !has_value; }
6292 V8_INLINE bool IsJust() const { return has_value; }
6294 // Will crash if the Maybe<> is nothing.
6295 V8_INLINE T FromJust() const {
6296 if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
6300 V8_INLINE T FromMaybe(const T& default_value) const {
6301 return has_value ? value : default_value;
6304 V8_INLINE bool operator==(const Maybe& other) const {
6305 return (IsJust() == other.IsJust()) &&
6306 (!IsJust() || FromJust() == other.FromJust());
6309 V8_INLINE bool operator!=(const Maybe& other) const {
6310 return !operator==(other);
6314 Maybe() : has_value(false) {}
6315 explicit Maybe(const T& t) : has_value(true), value(t) {}
6321 friend Maybe<U> Nothing();
6323 friend Maybe<U> Just(const U& u);
6328 inline Maybe<T> Nothing() {
6334 inline Maybe<T> Just(const T& t) {
6340 * An external exception handler.
6342 class V8_EXPORT TryCatch {
6345 * Creates a new try/catch block and registers it with v8. Note that
6346 * all TryCatch blocks should be stack allocated because the memory
6347 * location itself is compared against JavaScript try/catch blocks.
6349 V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6352 * Creates a new try/catch block and registers it with v8. Note that
6353 * all TryCatch blocks should be stack allocated because the memory
6354 * location itself is compared against JavaScript try/catch blocks.
6356 TryCatch(Isolate* isolate);
6359 * Unregisters and deletes this try/catch block.
6364 * Returns true if an exception has been caught by this try/catch block.
6366 bool HasCaught() const;
6369 * For certain types of exceptions, it makes no sense to continue execution.
6371 * If CanContinue returns false, the correct action is to perform any C++
6372 * cleanup needed and then return. If CanContinue returns false and
6373 * HasTerminated returns true, it is possible to call
6374 * CancelTerminateExecution in order to continue calling into the engine.
6376 bool CanContinue() const;
6379 * Returns true if an exception has been caught due to script execution
6382 * There is no JavaScript representation of an execution termination
6383 * exception. Such exceptions are thrown when the TerminateExecution
6384 * methods are called to terminate a long-running script.
6386 * If such an exception has been thrown, HasTerminated will return true,
6387 * indicating that it is possible to call CancelTerminateExecution in order
6388 * to continue calling into the engine.
6390 bool HasTerminated() const;
6393 * Throws the exception caught by this TryCatch in a way that avoids
6394 * it being caught again by this same TryCatch. As with ThrowException
6395 * it is illegal to execute any JavaScript operations after calling
6396 * ReThrow; the caller must return immediately to where the exception
6399 Local<Value> ReThrow();
6402 * Returns the exception caught by this try/catch block. If no exception has
6403 * been caught an empty handle is returned.
6405 * The returned handle is valid until this TryCatch block has been destroyed.
6407 Local<Value> Exception() const;
6410 * Returns the .stack property of the thrown object. If no .stack
6411 * property is present an empty handle is returned.
6413 V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
6414 V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
6415 Local<Context> context) const;
6418 * Returns the message associated with this exception. If there is
6419 * no message associated an empty handle is returned.
6421 * The returned handle is valid until this TryCatch block has been
6424 Local<v8::Message> Message() const;
6427 * Clears any exceptions that may have been caught by this try/catch block.
6428 * After this method has been called, HasCaught() will return false. Cancels
6429 * the scheduled exception if it is caught and ReThrow() is not called before.
6431 * It is not necessary to clear a try/catch block before using it again; if
6432 * another exception is thrown the previously caught exception will just be
6433 * overwritten. However, it is often a good idea since it makes it easier
6434 * to determine which operation threw a given exception.
6439 * Set verbosity of the external exception handler.
6441 * By default, exceptions that are caught by an external exception
6442 * handler are not reported. Call SetVerbose with true on an
6443 * external exception handler to have exceptions caught by the
6444 * handler reported as if they were not caught.
6446 void SetVerbose(bool value);
6449 * Set whether or not this TryCatch should capture a Message object
6450 * which holds source information about where the exception
6451 * occurred. True by default.
6453 void SetCaptureMessage(bool value);
6456 * There are cases when the raw address of C++ TryCatch object cannot be
6457 * used for comparisons with addresses into the JS stack. The cases are:
6458 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6459 * 2) Address sanitizer allocates local C++ object in the heap when
6460 * UseAfterReturn mode is enabled.
6461 * This method returns address that can be used for comparisons with
6462 * addresses into the JS stack. When neither simulator nor ASAN's
6463 * UseAfterReturn is enabled, then the address returned will be the address
6464 * of the C++ try catch handler itself.
6466 static void* JSStackComparableAddress(v8::TryCatch* handler) {
6467 if (handler == NULL) return NULL;
6468 return handler->js_stack_comparable_address_;
6472 void ResetInternal();
6474 // Make it hard to create heap-allocated TryCatch blocks.
6475 TryCatch(const TryCatch&);
6476 void operator=(const TryCatch&);
6477 void* operator new(size_t size);
6478 void operator delete(void*, size_t);
6480 v8::internal::Isolate* isolate_;
6481 v8::TryCatch* next_;
6484 void* js_stack_comparable_address_;
6485 bool is_verbose_ : 1;
6486 bool can_continue_ : 1;
6487 bool capture_message_ : 1;
6489 bool has_terminated_ : 1;
6491 friend class v8::internal::Isolate;
6499 * A container for extension names.
6501 class V8_EXPORT ExtensionConfiguration {
6503 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6504 ExtensionConfiguration(int name_count, const char* names[])
6505 : name_count_(name_count), names_(names) { }
6507 const char** begin() const { return &names_[0]; }
6508 const char** end() const { return &names_[name_count_]; }
6511 const int name_count_;
6512 const char** names_;
6517 * A sandboxed execution context with its own set of built-in objects
6520 class V8_EXPORT Context {
6523 * Returns the global proxy object.
6525 * Global proxy object is a thin wrapper whose prototype points to actual
6526 * context's global object with the properties like Object, etc. This is done
6527 * that way for security reasons (for more details see
6528 * https://wiki.mozilla.org/Gecko:SplitWindow).
6530 * Please note that changes to global proxy object prototype most probably
6531 * would break VM---v8 expects only global object as a prototype of global
6534 Local<Object> Global();
6537 * Detaches the global object from its context before
6538 * the global object can be reused to create a new context.
6540 void DetachGlobal();
6543 * Creates a new context and returns a handle to the newly allocated
6546 * \param isolate The isolate in which to create the context.
6548 * \param extensions An optional extension configuration containing
6549 * the extensions to be installed in the newly created context.
6551 * \param global_template An optional object template from which the
6552 * global object for the newly created context will be created.
6554 * \param global_object An optional global object to be reused for
6555 * the newly created context. This global object must have been
6556 * created by a previous call to Context::New with the same global
6557 * template. The state of the global object will be completely reset
6558 * and only object identify will remain.
6560 static Local<Context> New(
6561 Isolate* isolate, ExtensionConfiguration* extensions = NULL,
6562 Local<ObjectTemplate> global_template = Local<ObjectTemplate>(),
6563 Local<Value> global_object = Local<Value>());
6566 * Sets the security token for the context. To access an object in
6567 * another context, the security tokens must match.
6569 void SetSecurityToken(Local<Value> token);
6571 /** Restores the security token to the default value. */
6572 void UseDefaultSecurityToken();
6574 /** Returns the security token of this context.*/
6575 Local<Value> GetSecurityToken();
6578 * Enter this context. After entering a context, all code compiled
6579 * and run is compiled and run in this context. If another context
6580 * is already entered, this old context is saved so it can be
6581 * restored when the new context is exited.
6586 * Exit this context. Exiting the current context restores the
6587 * context that was in place when entering the current context.
6591 /** Returns an isolate associated with a current context. */
6592 v8::Isolate* GetIsolate();
6595 * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6596 * The value is propagated to the scripts compiled in given Context and
6597 * can be used for filtering scripts.
6599 enum EmbedderDataFields { kDebugIdIndex = 0 };
6602 * Gets the embedder data with the given index, which must have been set by a
6603 * previous call to SetEmbedderData with the same index. Note that index 0
6604 * currently has a special meaning for Chrome's debugger.
6606 V8_INLINE Local<Value> GetEmbedderData(int index);
6609 * Gets the exports object used by V8 extras. Extra natives get a reference
6610 * to this object and can use it to export functionality.
6612 Local<Object> GetExtrasExportsObject();
6615 * Sets the embedder data with the given index, growing the data as
6616 * needed. Note that index 0 currently has a special meaning for Chrome's
6619 void SetEmbedderData(int index, Local<Value> value);
6622 * Gets a 2-byte-aligned native pointer from the embedder data with the given
6623 * index, which must have bees set by a previous call to
6624 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6625 * currently has a special meaning for Chrome's debugger.
6627 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
6630 * Sets a 2-byte-aligned native pointer in the embedder data with the given
6631 * index, growing the data as needed. Note that index 0 currently has a
6632 * special meaning for Chrome's debugger.
6634 void SetAlignedPointerInEmbedderData(int index, void* value);
6637 * Control whether code generation from strings is allowed. Calling
6638 * this method with false will disable 'eval' and the 'Function'
6639 * constructor for code running in this context. If 'eval' or the
6640 * 'Function' constructor are used an exception will be thrown.
6642 * If code generation from strings is not allowed the
6643 * V8::AllowCodeGenerationFromStrings callback will be invoked if
6644 * set before blocking the call to 'eval' or the 'Function'
6645 * constructor. If that callback returns true, the call will be
6646 * allowed, otherwise an exception will be thrown. If no callback is
6647 * set an exception will be thrown.
6649 void AllowCodeGenerationFromStrings(bool allow);
6652 * Returns true if code generation from strings is allowed for the context.
6653 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6655 bool IsCodeGenerationFromStringsAllowed();
6658 * Sets the error description for the exception that is thrown when
6659 * code generation from strings is not allowed and 'eval' or the 'Function'
6660 * constructor are called.
6662 void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
6665 * Stack-allocated class which sets the execution context for all
6666 * operations executed within a local scope.
6670 explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
6673 V8_INLINE ~Scope() { context_->Exit(); }
6676 Local<Context> context_;
6681 friend class Script;
6682 friend class Object;
6683 friend class Function;
6685 Local<Value> SlowGetEmbedderData(int index);
6686 void* SlowGetAlignedPointerFromEmbedderData(int index);
6691 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6692 * to use any given V8 isolate, see the comments in the Isolate class. The
6693 * definition of 'using a V8 isolate' includes accessing handles or holding onto
6694 * object pointers obtained from V8 handles while in the particular V8 isolate.
6695 * It is up to the user of V8 to ensure, perhaps with locking, that this
6696 * constraint is not violated. In addition to any other synchronization
6697 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6698 * used to signal thead switches to V8.
6700 * v8::Locker is a scoped lock object. While it's active, i.e. between its
6701 * construction and destruction, the current thread is allowed to use the locked
6702 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6703 * any time. In other words, the scope of a v8::Locker is a critical section.
6709 * v8::Locker locker(isolate);
6710 * v8::Isolate::Scope isolate_scope(isolate);
6712 * // Code using V8 and isolate goes here.
6714 * } // Destructor called here
6717 * If you wish to stop using V8 in a thread A you can do this either by
6718 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6724 * v8::Unlocker unlocker(isolate);
6726 * // Code not using V8 goes here while V8 can run in another thread.
6728 * } // Destructor called here.
6732 * The Unlocker object is intended for use in a long-running callback from V8,
6733 * where you want to release the V8 lock for other threads to use.
6735 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6736 * given thread. This can be useful if you have code that can be called either
6737 * from code that holds the lock or from code that does not. The Unlocker is
6738 * not recursive so you can not have several Unlockers on the stack at once, and
6739 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6741 * An unlocker will unlock several lockers if it has to and reinstate the
6742 * correct depth of locking on its destruction, e.g.:
6747 * v8::Locker locker(isolate);
6748 * Isolate::Scope isolate_scope(isolate);
6751 * v8::Locker another_locker(isolate);
6752 * // V8 still locked (2 levels).
6755 * v8::Unlocker unlocker(isolate);
6759 * // V8 locked again (2 levels).
6761 * // V8 still locked (1 level).
6763 * // V8 Now no longer locked.
6766 class V8_EXPORT Unlocker {
6769 * Initialize Unlocker for a given Isolate.
6771 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6775 void Initialize(Isolate* isolate);
6777 internal::Isolate* isolate_;
6781 class V8_EXPORT Locker {
6784 * Initialize Locker for a given Isolate.
6786 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6791 * Returns whether or not the locker for a given isolate, is locked by the
6794 static bool IsLocked(Isolate* isolate);
6797 * Returns whether v8::Locker is being used by this V8 instance.
6799 static bool IsActive();
6802 void Initialize(Isolate* isolate);
6806 internal::Isolate* isolate_;
6808 // Disallow copying and assigning.
6809 Locker(const Locker&);
6810 void operator=(const Locker&);
6814 // --- Implementation ---
6817 namespace internal {
6819 const int kApiPointerSize = sizeof(void*); // NOLINT
6820 const int kApiIntSize = sizeof(int); // NOLINT
6821 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6823 // Tag information for HeapObject.
6824 const int kHeapObjectTag = 1;
6825 const int kHeapObjectTagSize = 2;
6826 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6828 // Tag information for Smi.
6829 const int kSmiTag = 0;
6830 const int kSmiTagSize = 1;
6831 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6833 template <size_t ptr_size> struct SmiTagging;
6835 template<int kSmiShiftSize>
6836 V8_INLINE internal::Object* IntToSmi(int value) {
6837 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6838 uintptr_t tagged_value =
6839 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6840 return reinterpret_cast<internal::Object*>(tagged_value);
6843 // Smi constants for 32-bit systems.
6844 template <> struct SmiTagging<4> {
6845 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6846 static int SmiShiftSize() { return kSmiShiftSize; }
6847 static int SmiValueSize() { return kSmiValueSize; }
6848 V8_INLINE static int SmiToInt(const internal::Object* value) {
6849 int shift_bits = kSmiTagSize + kSmiShiftSize;
6850 // Throw away top 32 bits and shift down (requires >> to be sign extending).
6851 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6853 V8_INLINE static internal::Object* IntToSmi(int value) {
6854 return internal::IntToSmi<kSmiShiftSize>(value);
6856 V8_INLINE static bool IsValidSmi(intptr_t value) {
6857 // To be representable as an tagged small integer, the two
6858 // most-significant bits of 'value' must be either 00 or 11 due to
6859 // sign-extension. To check this we add 01 to the two
6860 // most-significant bits, and check if the most-significant bit is 0
6862 // CAUTION: The original code below:
6863 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6864 // may lead to incorrect results according to the C language spec, and
6865 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6866 // compiler may produce undefined results in case of signed integer
6867 // overflow. The computation must be done w/ unsigned ints.
6868 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6872 // Smi constants for 64-bit systems.
6873 template <> struct SmiTagging<8> {
6874 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6875 static int SmiShiftSize() { return kSmiShiftSize; }
6876 static int SmiValueSize() { return kSmiValueSize; }
6877 V8_INLINE static int SmiToInt(const internal::Object* value) {
6878 int shift_bits = kSmiTagSize + kSmiShiftSize;
6879 // Shift down and throw away top 32 bits.
6880 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6882 V8_INLINE static internal::Object* IntToSmi(int value) {
6883 return internal::IntToSmi<kSmiShiftSize>(value);
6885 V8_INLINE static bool IsValidSmi(intptr_t value) {
6886 // To be representable as a long smi, the value must be a 32-bit integer.
6887 return (value == static_cast<int32_t>(value));
6891 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
6892 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
6893 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
6894 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6895 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6898 * This class exports constants and functionality from within v8 that
6899 * is necessary to implement inline functions in the v8 api. Don't
6900 * depend on functions and constants defined here.
6904 // These values match non-compiler-dependent values defined within
6905 // the implementation of v8.
6906 static const int kHeapObjectMapOffset = 0;
6907 static const int kMapInstanceTypeAndBitFieldOffset =
6908 1 * kApiPointerSize + kApiIntSize;
6909 static const int kStringResourceOffset = 3 * kApiPointerSize;
6911 static const int kOddballKindOffset = 3 * kApiPointerSize;
6912 static const int kForeignAddressOffset = kApiPointerSize;
6913 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6914 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6915 static const int kContextHeaderSize = 2 * kApiPointerSize;
6916 static const int kContextEmbedderDataIndex = 82;
6917 static const int kFullStringRepresentationMask = 0x07;
6918 static const int kStringEncodingMask = 0x4;
6919 static const int kExternalTwoByteRepresentationTag = 0x02;
6920 static const int kExternalOneByteRepresentationTag = 0x06;
6922 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
6923 static const int kAmountOfExternalAllocatedMemoryOffset =
6924 4 * kApiPointerSize;
6925 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
6926 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
6927 static const int kIsolateRootsOffset =
6928 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
6930 static const int kUndefinedValueRootIndex = 5;
6931 static const int kNullValueRootIndex = 7;
6932 static const int kTrueValueRootIndex = 8;
6933 static const int kFalseValueRootIndex = 9;
6934 static const int kEmptyStringRootIndex = 10;
6936 // The external allocation limit should be below 256 MB on all architectures
6937 // to avoid that resource-constrained embedders run low on memory.
6938 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6940 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6941 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6942 static const int kNodeStateMask = 0x7;
6943 static const int kNodeStateIsWeakValue = 2;
6944 static const int kNodeStateIsPendingValue = 3;
6945 static const int kNodeStateIsNearDeathValue = 4;
6946 static const int kNodeIsIndependentShift = 3;
6947 static const int kNodeIsPartiallyDependentShift = 4;
6949 static const int kJSObjectType = 0xb6;
6950 static const int kFirstNonstringType = 0x80;
6951 static const int kOddballType = 0x83;
6952 static const int kForeignType = 0x87;
6954 static const int kUndefinedOddballKind = 5;
6955 static const int kNullOddballKind = 3;
6957 static const uint32_t kNumIsolateDataSlots = 4;
6959 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
6960 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
6961 #ifdef V8_ENABLE_CHECKS
6962 CheckInitializedImpl(isolate);
6966 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
6967 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
6971 V8_INLINE static int SmiValue(const internal::Object* value) {
6972 return PlatformSmiTagging::SmiToInt(value);
6975 V8_INLINE static internal::Object* IntToSmi(int value) {
6976 return PlatformSmiTagging::IntToSmi(value);
6979 V8_INLINE static bool IsValidSmi(intptr_t value) {
6980 return PlatformSmiTagging::IsValidSmi(value);
6983 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
6984 typedef internal::Object O;
6985 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
6986 // Map::InstanceType is defined so that it will always be loaded into
6987 // the LS 8 bits of one 16-bit word, regardless of endianess.
6988 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
6991 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
6992 typedef internal::Object O;
6993 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
6996 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
6997 int representation = (instance_type & kFullStringRepresentationMask);
6998 return representation == kExternalTwoByteRepresentationTag;
7001 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
7002 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7003 return *addr & static_cast<uint8_t>(1U << shift);
7006 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
7007 bool value, int shift) {
7008 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7009 uint8_t mask = static_cast<uint8_t>(1U << shift);
7010 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
7013 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
7014 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7015 return *addr & kNodeStateMask;
7018 V8_INLINE static void UpdateNodeState(internal::Object** obj,
7020 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7021 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
7024 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
7027 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
7028 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7029 *reinterpret_cast<void**>(addr) = data;
7032 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
7034 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
7035 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
7036 return *reinterpret_cast<void* const*>(addr);
7039 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
7041 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
7042 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
7045 template <typename T>
7046 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
7047 const uint8_t* addr =
7048 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
7049 return *reinterpret_cast<const T*>(addr);
7052 template <typename T>
7053 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
7054 typedef internal::Object O;
7055 typedef internal::Internals I;
7056 O* ctx = *reinterpret_cast<O* const*>(context);
7057 int embedder_data_offset = I::kContextHeaderSize +
7058 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
7059 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
7061 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
7062 return I::ReadField<T>(embedder_data, value_offset);
7066 } // namespace internal
7070 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
7071 return New(isolate, that.val_);
7075 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
7076 return New(isolate, that.val_);
7081 Local<T> Local<T>::New(Isolate* isolate, T* that) {
7082 if (that == NULL) return Local<T>();
7084 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
7085 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
7086 reinterpret_cast<internal::Isolate*>(isolate), *p)));
7092 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
7094 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
7099 Local<T> Eternal<T>::Get(Isolate* isolate) {
7100 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
7105 Local<T> MaybeLocal<T>::ToLocalChecked() {
7106 if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
7107 return Local<T>(val_);
7112 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
7113 #ifdef V8_ENABLE_CHECKS
7114 if (index < 0 || index >= kInternalFieldsInWeakCallback) {
7115 V8::InternalFieldOutOfBounds(index);
7118 return internal_fields_[index];
7123 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
7124 if (that == NULL) return NULL;
7125 internal::Object** p = reinterpret_cast<internal::Object**>(that);
7126 return reinterpret_cast<T*>(
7127 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
7132 template <class T, class M>
7133 template <class S, class M2>
7134 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
7137 if (that.IsEmpty()) return;
7138 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
7139 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
7140 M::Copy(that, this);
7145 bool PersistentBase<T>::IsIndependent() const {
7146 typedef internal::Internals I;
7147 if (this->IsEmpty()) return false;
7148 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7149 I::kNodeIsIndependentShift);
7154 bool PersistentBase<T>::IsNearDeath() const {
7155 typedef internal::Internals I;
7156 if (this->IsEmpty()) return false;
7157 uint8_t node_state =
7158 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
7159 return node_state == I::kNodeStateIsNearDeathValue ||
7160 node_state == I::kNodeStateIsPendingValue;
7165 bool PersistentBase<T>::IsWeak() const {
7166 typedef internal::Internals I;
7167 if (this->IsEmpty()) return false;
7168 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
7169 I::kNodeStateIsWeakValue;
7174 void PersistentBase<T>::Reset() {
7175 if (this->IsEmpty()) return;
7176 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
7183 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
7186 if (other.IsEmpty()) return;
7187 this->val_ = New(isolate, other.val_);
7193 void PersistentBase<T>::Reset(Isolate* isolate,
7194 const PersistentBase<S>& other) {
7197 if (other.IsEmpty()) return;
7198 this->val_ = New(isolate, other.val_);
7203 template <typename S, typename P>
7204 void PersistentBase<T>::SetWeak(
7206 typename WeakCallbackData<S, P>::Callback callback) {
7208 typedef typename WeakCallbackData<Value, void>::Callback Callback;
7209 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7210 reinterpret_cast<Callback>(callback));
7215 template <typename P>
7216 void PersistentBase<T>::SetWeak(
7218 typename WeakCallbackData<T, P>::Callback callback) {
7219 SetWeak<T, P>(parameter, callback);
7224 template <typename P>
7225 void PersistentBase<T>::SetPhantom(
7226 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7227 int internal_field_index1, int internal_field_index2) {
7228 typedef typename WeakCallbackInfo<void>::Callback Callback;
7229 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7230 internal_field_index1, internal_field_index2,
7231 reinterpret_cast<Callback>(callback));
7236 template <typename P>
7237 V8_INLINE void PersistentBase<T>::SetWeak(
7238 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7239 WeakCallbackType type) {
7240 typedef typename WeakCallbackInfo<void>::Callback Callback;
7241 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7242 reinterpret_cast<Callback>(callback), type);
7247 template <typename P>
7248 P* PersistentBase<T>::ClearWeak() {
7249 return reinterpret_cast<P*>(
7250 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7255 void PersistentBase<T>::MarkIndependent() {
7256 typedef internal::Internals I;
7257 if (this->IsEmpty()) return;
7258 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7260 I::kNodeIsIndependentShift);
7265 void PersistentBase<T>::MarkPartiallyDependent() {
7266 typedef internal::Internals I;
7267 if (this->IsEmpty()) return;
7268 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7270 I::kNodeIsPartiallyDependentShift);
7275 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7276 typedef internal::Internals I;
7277 if (this->IsEmpty()) return;
7278 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7279 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7280 *reinterpret_cast<uint16_t*>(addr) = class_id;
7285 uint16_t PersistentBase<T>::WrapperClassId() const {
7286 typedef internal::Internals I;
7287 if (this->IsEmpty()) return 0;
7288 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7289 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7290 return *reinterpret_cast<uint16_t*>(addr);
7294 template<typename T>
7295 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7297 template<typename T>
7298 template<typename S>
7299 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7301 if (V8_UNLIKELY(handle.IsEmpty())) {
7302 *value_ = GetDefaultValue();
7304 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7308 template <typename T>
7309 template <typename S>
7310 void ReturnValue<T>::Set(const Global<S>& handle) {
7312 if (V8_UNLIKELY(handle.IsEmpty())) {
7313 *value_ = GetDefaultValue();
7315 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7319 template <typename T>
7320 template <typename S>
7321 void ReturnValue<T>::Set(const Local<S> handle) {
7323 if (V8_UNLIKELY(handle.IsEmpty())) {
7324 *value_ = GetDefaultValue();
7326 *value_ = *reinterpret_cast<internal::Object**>(*handle);
7330 template<typename T>
7331 void ReturnValue<T>::Set(double i) {
7332 TYPE_CHECK(T, Number);
7333 Set(Number::New(GetIsolate(), i));
7336 template<typename T>
7337 void ReturnValue<T>::Set(int32_t i) {
7338 TYPE_CHECK(T, Integer);
7339 typedef internal::Internals I;
7340 if (V8_LIKELY(I::IsValidSmi(i))) {
7341 *value_ = I::IntToSmi(i);
7344 Set(Integer::New(GetIsolate(), i));
7347 template<typename T>
7348 void ReturnValue<T>::Set(uint32_t i) {
7349 TYPE_CHECK(T, Integer);
7350 // Can't simply use INT32_MAX here for whatever reason.
7351 bool fits_into_int32_t = (i & (1U << 31)) == 0;
7352 if (V8_LIKELY(fits_into_int32_t)) {
7353 Set(static_cast<int32_t>(i));
7356 Set(Integer::NewFromUnsigned(GetIsolate(), i));
7359 template<typename T>
7360 void ReturnValue<T>::Set(bool value) {
7361 TYPE_CHECK(T, Boolean);
7362 typedef internal::Internals I;
7365 root_index = I::kTrueValueRootIndex;
7367 root_index = I::kFalseValueRootIndex;
7369 *value_ = *I::GetRoot(GetIsolate(), root_index);
7372 template<typename T>
7373 void ReturnValue<T>::SetNull() {
7374 TYPE_CHECK(T, Primitive);
7375 typedef internal::Internals I;
7376 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
7379 template<typename T>
7380 void ReturnValue<T>::SetUndefined() {
7381 TYPE_CHECK(T, Primitive);
7382 typedef internal::Internals I;
7383 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
7386 template<typename T>
7387 void ReturnValue<T>::SetEmptyString() {
7388 TYPE_CHECK(T, String);
7389 typedef internal::Internals I;
7390 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
7393 template<typename T>
7394 Isolate* ReturnValue<T>::GetIsolate() {
7395 // Isolate is always the pointer below the default value on the stack.
7396 return *reinterpret_cast<Isolate**>(&value_[-2]);
7399 template<typename T>
7400 template<typename S>
7401 void ReturnValue<T>::Set(S* whatever) {
7402 // Uncompilable to prevent inadvertent misuse.
7403 TYPE_CHECK(S*, Primitive);
7406 template<typename T>
7407 internal::Object* ReturnValue<T>::GetDefaultValue() {
7408 // Default value is always the pointer below value_ on the stack.
7413 template<typename T>
7414 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
7415 internal::Object** values,
7417 bool is_construct_call)
7418 : implicit_args_(implicit_args),
7421 is_construct_call_(is_construct_call) { }
7424 template<typename T>
7425 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
7426 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7427 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7431 template<typename T>
7432 Local<Function> FunctionCallbackInfo<T>::Callee() const {
7433 return Local<Function>(reinterpret_cast<Function*>(
7434 &implicit_args_[kCalleeIndex]));
7438 template<typename T>
7439 Local<Object> FunctionCallbackInfo<T>::This() const {
7440 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7444 template<typename T>
7445 Local<Object> FunctionCallbackInfo<T>::Holder() const {
7446 return Local<Object>(reinterpret_cast<Object*>(
7447 &implicit_args_[kHolderIndex]));
7451 template<typename T>
7452 Local<Value> FunctionCallbackInfo<T>::Data() const {
7453 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7457 template<typename T>
7458 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
7459 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7463 template<typename T>
7464 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
7465 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
7469 template<typename T>
7470 bool FunctionCallbackInfo<T>::IsConstructCall() const {
7471 return is_construct_call_ & 0x1;
7475 template<typename T>
7476 int FunctionCallbackInfo<T>::Length() const {
7480 ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
7481 Local<Integer> resource_line_offset,
7482 Local<Integer> resource_column_offset,
7483 Local<Boolean> resource_is_shared_cross_origin,
7484 Local<Integer> script_id,
7485 Local<Boolean> resource_is_embedder_debug_script,
7486 Local<Value> source_map_url,
7487 Local<Boolean> resource_is_opaque)
7488 : resource_name_(resource_name),
7489 resource_line_offset_(resource_line_offset),
7490 resource_column_offset_(resource_column_offset),
7491 options_(!resource_is_embedder_debug_script.IsEmpty() &&
7492 resource_is_embedder_debug_script->IsTrue(),
7493 !resource_is_shared_cross_origin.IsEmpty() &&
7494 resource_is_shared_cross_origin->IsTrue(),
7495 !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue()),
7496 script_id_(script_id),
7497 source_map_url_(source_map_url) {}
7499 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
7502 Local<Integer> ScriptOrigin::ResourceLineOffset() const {
7503 return resource_line_offset_;
7507 Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
7508 return resource_column_offset_;
7512 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
7515 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7518 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
7520 : source_string(string),
7521 resource_name(origin.ResourceName()),
7522 resource_line_offset(origin.ResourceLineOffset()),
7523 resource_column_offset(origin.ResourceColumnOffset()),
7524 resource_options(origin.Options()),
7525 source_map_url(origin.SourceMapUrl()),
7526 cached_data(data) {}
7529 ScriptCompiler::Source::Source(Local<String> string,
7531 : source_string(string), cached_data(data) {}
7534 ScriptCompiler::Source::~Source() {
7539 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
7545 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
7546 return value ? True(isolate) : False(isolate);
7550 void Template::Set(Isolate* isolate, const char* name, v8::Local<Data> value) {
7551 Set(v8::String::NewFromUtf8(isolate, name, NewStringType::kNormal)
7557 Local<Value> Object::GetInternalField(int index) {
7558 #ifndef V8_ENABLE_CHECKS
7559 typedef internal::Object O;
7560 typedef internal::HeapObject HO;
7561 typedef internal::Internals I;
7562 O* obj = *reinterpret_cast<O**>(this);
7563 // Fast path: If the object is a plain JSObject, which is the common case, we
7564 // know where to find the internal fields and can return the value directly.
7565 if (I::GetInstanceType(obj) == I::kJSObjectType) {
7566 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7567 O* value = I::ReadField<O*>(obj, offset);
7568 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7569 return Local<Value>(reinterpret_cast<Value*>(result));
7572 return SlowGetInternalField(index);
7576 void* Object::GetAlignedPointerFromInternalField(int index) {
7577 #ifndef V8_ENABLE_CHECKS
7578 typedef internal::Object O;
7579 typedef internal::Internals I;
7580 O* obj = *reinterpret_cast<O**>(this);
7581 // Fast path: If the object is a plain JSObject, which is the common case, we
7582 // know where to find the internal fields and can return the value directly.
7583 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
7584 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7585 return I::ReadField<void*>(obj, offset);
7588 return SlowGetAlignedPointerFromInternalField(index);
7592 String* String::Cast(v8::Value* value) {
7593 #ifdef V8_ENABLE_CHECKS
7596 return static_cast<String*>(value);
7600 Local<String> String::Empty(Isolate* isolate) {
7601 typedef internal::Object* S;
7602 typedef internal::Internals I;
7603 I::CheckInitialized(isolate);
7604 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7605 return Local<String>(reinterpret_cast<String*>(slot));
7609 String::ExternalStringResource* String::GetExternalStringResource() const {
7610 typedef internal::Object O;
7611 typedef internal::Internals I;
7612 O* obj = *reinterpret_cast<O* const*>(this);
7613 String::ExternalStringResource* result;
7614 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
7615 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7616 result = reinterpret_cast<String::ExternalStringResource*>(value);
7620 #ifdef V8_ENABLE_CHECKS
7621 VerifyExternalStringResource(result);
7627 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
7628 String::Encoding* encoding_out) const {
7629 typedef internal::Object O;
7630 typedef internal::Internals I;
7631 O* obj = *reinterpret_cast<O* const*>(this);
7632 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
7633 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7634 ExternalStringResourceBase* resource = NULL;
7635 if (type == I::kExternalOneByteRepresentationTag ||
7636 type == I::kExternalTwoByteRepresentationTag) {
7637 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7638 resource = static_cast<ExternalStringResourceBase*>(value);
7640 #ifdef V8_ENABLE_CHECKS
7641 VerifyExternalStringResourceBase(resource, *encoding_out);
7647 bool Value::IsUndefined() const {
7648 #ifdef V8_ENABLE_CHECKS
7649 return FullIsUndefined();
7651 return QuickIsUndefined();
7655 bool Value::QuickIsUndefined() const {
7656 typedef internal::Object O;
7657 typedef internal::Internals I;
7658 O* obj = *reinterpret_cast<O* const*>(this);
7659 if (!I::HasHeapObjectTag(obj)) return false;
7660 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7661 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
7665 bool Value::IsNull() const {
7666 #ifdef V8_ENABLE_CHECKS
7667 return FullIsNull();
7669 return QuickIsNull();
7673 bool Value::QuickIsNull() const {
7674 typedef internal::Object O;
7675 typedef internal::Internals I;
7676 O* obj = *reinterpret_cast<O* const*>(this);
7677 if (!I::HasHeapObjectTag(obj)) return false;
7678 if (I::GetInstanceType(obj) != I::kOddballType) return false;
7679 return (I::GetOddballKind(obj) == I::kNullOddballKind);
7683 bool Value::IsString() const {
7684 #ifdef V8_ENABLE_CHECKS
7685 return FullIsString();
7687 return QuickIsString();
7691 bool Value::QuickIsString() const {
7692 typedef internal::Object O;
7693 typedef internal::Internals I;
7694 O* obj = *reinterpret_cast<O* const*>(this);
7695 if (!I::HasHeapObjectTag(obj)) return false;
7696 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
7700 template <class T> Value* Value::Cast(T* value) {
7701 return static_cast<Value*>(value);
7705 Local<Boolean> Value::ToBoolean() const {
7706 return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
7707 .FromMaybe(Local<Boolean>());
7711 Local<Number> Value::ToNumber() const {
7712 return ToNumber(Isolate::GetCurrent()->GetCurrentContext())
7713 .FromMaybe(Local<Number>());
7717 Local<String> Value::ToString() const {
7718 return ToString(Isolate::GetCurrent()->GetCurrentContext())
7719 .FromMaybe(Local<String>());
7723 Local<String> Value::ToDetailString() const {
7724 return ToDetailString(Isolate::GetCurrent()->GetCurrentContext())
7725 .FromMaybe(Local<String>());
7729 Local<Object> Value::ToObject() const {
7730 return ToObject(Isolate::GetCurrent()->GetCurrentContext())
7731 .FromMaybe(Local<Object>());
7735 Local<Integer> Value::ToInteger() const {
7736 return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
7737 .FromMaybe(Local<Integer>());
7741 Local<Uint32> Value::ToUint32() const {
7742 return ToUint32(Isolate::GetCurrent()->GetCurrentContext())
7743 .FromMaybe(Local<Uint32>());
7747 Local<Int32> Value::ToInt32() const {
7748 return ToInt32(Isolate::GetCurrent()->GetCurrentContext())
7749 .FromMaybe(Local<Int32>());
7753 Boolean* Boolean::Cast(v8::Value* value) {
7754 #ifdef V8_ENABLE_CHECKS
7757 return static_cast<Boolean*>(value);
7761 Name* Name::Cast(v8::Value* value) {
7762 #ifdef V8_ENABLE_CHECKS
7765 return static_cast<Name*>(value);
7769 Symbol* Symbol::Cast(v8::Value* value) {
7770 #ifdef V8_ENABLE_CHECKS
7773 return static_cast<Symbol*>(value);
7777 Number* Number::Cast(v8::Value* value) {
7778 #ifdef V8_ENABLE_CHECKS
7781 return static_cast<Number*>(value);
7785 Integer* Integer::Cast(v8::Value* value) {
7786 #ifdef V8_ENABLE_CHECKS
7789 return static_cast<Integer*>(value);
7793 Int32* Int32::Cast(v8::Value* value) {
7794 #ifdef V8_ENABLE_CHECKS
7797 return static_cast<Int32*>(value);
7801 Uint32* Uint32::Cast(v8::Value* value) {
7802 #ifdef V8_ENABLE_CHECKS
7805 return static_cast<Uint32*>(value);
7809 Date* Date::Cast(v8::Value* value) {
7810 #ifdef V8_ENABLE_CHECKS
7813 return static_cast<Date*>(value);
7817 StringObject* StringObject::Cast(v8::Value* value) {
7818 #ifdef V8_ENABLE_CHECKS
7821 return static_cast<StringObject*>(value);
7825 SymbolObject* SymbolObject::Cast(v8::Value* value) {
7826 #ifdef V8_ENABLE_CHECKS
7829 return static_cast<SymbolObject*>(value);
7833 NumberObject* NumberObject::Cast(v8::Value* value) {
7834 #ifdef V8_ENABLE_CHECKS
7837 return static_cast<NumberObject*>(value);
7841 BooleanObject* BooleanObject::Cast(v8::Value* value) {
7842 #ifdef V8_ENABLE_CHECKS
7845 return static_cast<BooleanObject*>(value);
7849 RegExp* RegExp::Cast(v8::Value* value) {
7850 #ifdef V8_ENABLE_CHECKS
7853 return static_cast<RegExp*>(value);
7857 Object* Object::Cast(v8::Value* value) {
7858 #ifdef V8_ENABLE_CHECKS
7861 return static_cast<Object*>(value);
7865 Array* Array::Cast(v8::Value* value) {
7866 #ifdef V8_ENABLE_CHECKS
7869 return static_cast<Array*>(value);
7873 Map* Map::Cast(v8::Value* value) {
7874 #ifdef V8_ENABLE_CHECKS
7877 return static_cast<Map*>(value);
7881 Set* Set::Cast(v8::Value* value) {
7882 #ifdef V8_ENABLE_CHECKS
7885 return static_cast<Set*>(value);
7889 Promise* Promise::Cast(v8::Value* value) {
7890 #ifdef V8_ENABLE_CHECKS
7893 return static_cast<Promise*>(value);
7897 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
7898 #ifdef V8_ENABLE_CHECKS
7901 return static_cast<Promise::Resolver*>(value);
7905 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
7906 #ifdef V8_ENABLE_CHECKS
7909 return static_cast<ArrayBuffer*>(value);
7913 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
7914 #ifdef V8_ENABLE_CHECKS
7917 return static_cast<ArrayBufferView*>(value);
7921 TypedArray* TypedArray::Cast(v8::Value* value) {
7922 #ifdef V8_ENABLE_CHECKS
7925 return static_cast<TypedArray*>(value);
7929 Uint8Array* Uint8Array::Cast(v8::Value* value) {
7930 #ifdef V8_ENABLE_CHECKS
7933 return static_cast<Uint8Array*>(value);
7937 Int8Array* Int8Array::Cast(v8::Value* value) {
7938 #ifdef V8_ENABLE_CHECKS
7941 return static_cast<Int8Array*>(value);
7945 Uint16Array* Uint16Array::Cast(v8::Value* value) {
7946 #ifdef V8_ENABLE_CHECKS
7949 return static_cast<Uint16Array*>(value);
7953 Int16Array* Int16Array::Cast(v8::Value* value) {
7954 #ifdef V8_ENABLE_CHECKS
7957 return static_cast<Int16Array*>(value);
7961 Uint32Array* Uint32Array::Cast(v8::Value* value) {
7962 #ifdef V8_ENABLE_CHECKS
7965 return static_cast<Uint32Array*>(value);
7969 Int32Array* Int32Array::Cast(v8::Value* value) {
7970 #ifdef V8_ENABLE_CHECKS
7973 return static_cast<Int32Array*>(value);
7977 Float32Array* Float32Array::Cast(v8::Value* value) {
7978 #ifdef V8_ENABLE_CHECKS
7981 return static_cast<Float32Array*>(value);
7985 Float64Array* Float64Array::Cast(v8::Value* value) {
7986 #ifdef V8_ENABLE_CHECKS
7989 return static_cast<Float64Array*>(value);
7993 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
7994 #ifdef V8_ENABLE_CHECKS
7997 return static_cast<Uint8ClampedArray*>(value);
8001 DataView* DataView::Cast(v8::Value* value) {
8002 #ifdef V8_ENABLE_CHECKS
8005 return static_cast<DataView*>(value);
8009 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
8010 #ifdef V8_ENABLE_CHECKS
8013 return static_cast<SharedArrayBuffer*>(value);
8017 Function* Function::Cast(v8::Value* value) {
8018 #ifdef V8_ENABLE_CHECKS
8021 return static_cast<Function*>(value);
8025 External* External::Cast(v8::Value* value) {
8026 #ifdef V8_ENABLE_CHECKS
8029 return static_cast<External*>(value);
8033 template<typename T>
8034 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
8035 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
8039 template<typename T>
8040 Local<Value> PropertyCallbackInfo<T>::Data() const {
8041 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
8045 template<typename T>
8046 Local<Object> PropertyCallbackInfo<T>::This() const {
8047 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
8051 template<typename T>
8052 Local<Object> PropertyCallbackInfo<T>::Holder() const {
8053 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
8057 template<typename T>
8058 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
8059 return ReturnValue<T>(&args_[kReturnValueIndex]);
8063 Local<Primitive> Undefined(Isolate* isolate) {
8064 typedef internal::Object* S;
8065 typedef internal::Internals I;
8066 I::CheckInitialized(isolate);
8067 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
8068 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8072 Local<Primitive> Null(Isolate* isolate) {
8073 typedef internal::Object* S;
8074 typedef internal::Internals I;
8075 I::CheckInitialized(isolate);
8076 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
8077 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8081 Local<Boolean> True(Isolate* isolate) {
8082 typedef internal::Object* S;
8083 typedef internal::Internals I;
8084 I::CheckInitialized(isolate);
8085 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
8086 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8090 Local<Boolean> False(Isolate* isolate) {
8091 typedef internal::Object* S;
8092 typedef internal::Internals I;
8093 I::CheckInitialized(isolate);
8094 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
8095 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8099 void Isolate::SetData(uint32_t slot, void* data) {
8100 typedef internal::Internals I;
8101 I::SetEmbedderData(this, slot, data);
8105 void* Isolate::GetData(uint32_t slot) {
8106 typedef internal::Internals I;
8107 return I::GetEmbedderData(this, slot);
8111 uint32_t Isolate::GetNumberOfDataSlots() {
8112 typedef internal::Internals I;
8113 return I::kNumIsolateDataSlots;
8117 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
8118 int64_t change_in_bytes) {
8119 typedef internal::Internals I;
8120 int64_t* amount_of_external_allocated_memory =
8121 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
8122 I::kAmountOfExternalAllocatedMemoryOffset);
8123 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
8124 reinterpret_cast<int64_t*>(
8125 reinterpret_cast<uint8_t*>(this) +
8126 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
8127 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
8128 if (change_in_bytes > 0 &&
8129 amount - *amount_of_external_allocated_memory_at_last_global_gc >
8130 I::kExternalAllocationLimit) {
8131 CollectAllGarbage("external memory allocation limit reached.");
8133 *amount_of_external_allocated_memory = amount;
8134 return *amount_of_external_allocated_memory;
8138 template<typename T>
8139 void Isolate::SetObjectGroupId(const Persistent<T>& object,
8141 TYPE_CHECK(Value, T);
8142 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
8146 template<typename T>
8147 void Isolate::SetReferenceFromGroup(UniqueId id,
8148 const Persistent<T>& object) {
8149 TYPE_CHECK(Value, T);
8150 SetReferenceFromGroup(id,
8151 reinterpret_cast<v8::internal::Object**>(object.val_));
8155 template<typename T, typename S>
8156 void Isolate::SetReference(const Persistent<T>& parent,
8157 const Persistent<S>& child) {
8158 TYPE_CHECK(Object, T);
8159 TYPE_CHECK(Value, S);
8160 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
8161 reinterpret_cast<v8::internal::Object**>(child.val_));
8165 Local<Value> Context::GetEmbedderData(int index) {
8166 #ifndef V8_ENABLE_CHECKS
8167 typedef internal::Object O;
8168 typedef internal::HeapObject HO;
8169 typedef internal::Internals I;
8170 HO* context = *reinterpret_cast<HO**>(this);
8172 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
8173 return Local<Value>(reinterpret_cast<Value*>(result));
8175 return SlowGetEmbedderData(index);
8180 void* Context::GetAlignedPointerFromEmbedderData(int index) {
8181 #ifndef V8_ENABLE_CHECKS
8182 typedef internal::Internals I;
8183 return I::ReadEmbedderData<void*>(this, index);
8185 return SlowGetAlignedPointerFromEmbedderData(index);
8190 void V8::SetAllowCodeGenerationFromStringsCallback(
8191 AllowCodeGenerationFromStringsCallback callback) {
8192 Isolate* isolate = Isolate::GetCurrent();
8193 isolate->SetAllowCodeGenerationFromStringsCallback(callback);
8198 Isolate* isolate = Isolate::GetCurrent();
8199 return isolate->IsDead();
8203 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
8204 Isolate* isolate = Isolate::GetCurrent();
8205 return isolate->AddMessageListener(that, data);
8209 void V8::RemoveMessageListeners(MessageCallback that) {
8210 Isolate* isolate = Isolate::GetCurrent();
8211 isolate->RemoveMessageListeners(that);
8215 void V8::SetFailedAccessCheckCallbackFunction(
8216 FailedAccessCheckCallback callback) {
8217 Isolate* isolate = Isolate::GetCurrent();
8218 isolate->SetFailedAccessCheckCallbackFunction(callback);
8222 void V8::SetCaptureStackTraceForUncaughtExceptions(
8223 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8224 Isolate* isolate = Isolate::GetCurrent();
8225 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8230 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
8231 Isolate* isolate = Isolate::GetCurrent();
8232 isolate->SetFatalErrorHandler(callback);
8236 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
8237 Isolate* isolate = Isolate::GetCurrent();
8238 isolate->RemoveGCPrologueCallback(
8239 reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
8243 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
8244 Isolate* isolate = Isolate::GetCurrent();
8245 isolate->RemoveGCEpilogueCallback(
8246 reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
8250 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8252 AllocationAction action) {
8253 Isolate* isolate = Isolate::GetCurrent();
8254 isolate->AddMemoryAllocationCallback(callback, space, action);
8258 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8259 Isolate* isolate = Isolate::GetCurrent();
8260 isolate->RemoveMemoryAllocationCallback(callback);
8264 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8267 bool V8::IsExecutionTerminating(Isolate* isolate) {
8268 if (isolate == NULL) {
8269 isolate = Isolate::GetCurrent();
8271 return isolate->IsExecutionTerminating();
8275 void V8::CancelTerminateExecution(Isolate* isolate) {
8276 isolate->CancelTerminateExecution();
8280 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8281 Isolate* isolate = Isolate::GetCurrent();
8282 isolate->VisitExternalResources(visitor);
8286 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8287 Isolate* isolate = Isolate::GetCurrent();
8288 isolate->VisitHandlesWithClassIds(visitor);
8292 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8293 PersistentHandleVisitor* visitor) {
8294 isolate->VisitHandlesWithClassIds(visitor);
8298 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8299 PersistentHandleVisitor* visitor) {
8300 isolate->VisitHandlesForPartialDependence(visitor);
8305 * A simple shell that takes a list of expressions on the
8306 * command-line and executes them.
8311 * \example process.cc