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/
20 // We reserve the V8_* prefix for macros defined in V8 public API and
21 // assume there are no name conflicts with the embedder's code.
25 // Setup for Windows DLL export/import. When building the V8 DLL the
26 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
27 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
28 // static library or building a program which uses the V8 static library neither
29 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
30 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
31 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
32 build configuration to ensure that at most one of these is set
35 #ifdef BUILDING_V8_SHARED
36 # define V8_EXPORT __declspec(dllexport)
38 # define V8_EXPORT __declspec(dllimport)
41 #endif // BUILDING_V8_SHARED
45 // Setup for Linux shared library export.
46 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
47 # ifdef BUILDING_V8_SHARED
48 # define V8_EXPORT __attribute__ ((visibility("default")))
59 * The v8 JavaScript engine.
63 class AccessorSignature;
71 class DeclaredAccessorDescriptor;
74 class FunctionTemplate;
76 class ImplementationUtilities;
83 class ObjectOperationDescriptor;
87 class RawOperationDescriptor;
100 template <class T> class Handle;
101 template <class T> class Local;
102 template <class T> class Eternal;
103 template<class T> class NonCopyablePersistentTraits;
104 template<class T> class PersistentBase;
106 class M = NonCopyablePersistentTraits<T> > class Persistent;
107 template<class T> class UniquePersistent;
108 template<class K, class V, class T> class PersistentValueMap;
109 template<class V, class T> class PersistentValueVector;
110 template<class T, class P> class WeakCallbackObject;
111 class FunctionTemplate;
112 class ObjectTemplate;
114 template<typename T> class FunctionCallbackInfo;
115 template<typename T> class PropertyCallbackInfo;
119 class DeclaredAccessorDescriptor;
120 class ObjectOperationDescriptor;
121 class RawOperationDescriptor;
122 class CallHandlerHelper;
123 class EscapableHandleScope;
124 template<typename T> class ReturnValue;
132 template<typename T> class CustomArguments;
133 class PropertyCallbackArguments;
134 class FunctionCallbackArguments;
140 * General purpose unique identifier.
144 explicit UniqueId(intptr_t data)
147 bool operator==(const UniqueId& other) const {
148 return data_ == other.data_;
151 bool operator!=(const UniqueId& other) const {
152 return data_ != other.data_;
155 bool operator<(const UniqueId& other) const {
156 return data_ < other.data_;
165 #define TYPE_CHECK(T, S) \
167 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
172 * An object reference managed by the v8 garbage collector.
174 * All objects returned from v8 have to be tracked by the garbage
175 * collector so that it knows that the objects are still alive. Also,
176 * because the garbage collector may move objects, it is unsafe to
177 * point directly to an object. Instead, all objects are stored in
178 * handles which are known by the garbage collector and updated
179 * whenever an object moves. Handles should always be passed by value
180 * (except in cases like out-parameters) and they should never be
181 * allocated on the heap.
183 * There are two types of handles: local and persistent handles.
184 * Local handles are light-weight and transient and typically used in
185 * local operations. They are managed by HandleScopes. Persistent
186 * handles can be used when storing objects across several independent
187 * operations and have to be explicitly deallocated when they're no
190 * It is safe to extract the object stored in the handle by
191 * dereferencing the handle (for instance, to extract the Object* from
192 * a Handle<Object>); the value will still be governed by a handle
193 * behind the scenes and the same rules apply to these values as to
196 template <class T> class Handle {
199 * Creates an empty handle.
201 V8_INLINE Handle() : val_(0) {}
204 * Creates a handle for the contents of the specified handle. This
205 * constructor allows you to pass handles as arguments by value and
206 * to assign between handles. However, if you try to assign between
207 * incompatible handles, for instance from a Handle<String> to a
208 * Handle<Number> it will cause a compile-time error. Assigning
209 * between compatible handles, for instance assigning a
210 * Handle<String> to a variable declared as Handle<Value>, is legal
211 * because String is a subclass of Value.
213 template <class S> V8_INLINE Handle(Handle<S> that)
214 : val_(reinterpret_cast<T*>(*that)) {
216 * This check fails when trying to convert between incompatible
217 * handles. For example, converting from a Handle<String> to a
224 * Returns true if the handle is empty.
226 V8_INLINE bool IsEmpty() const { return val_ == 0; }
229 * Sets the handle to be empty. IsEmpty() will then return true.
231 V8_INLINE void Clear() { val_ = 0; }
233 V8_INLINE T* operator->() const { return val_; }
235 V8_INLINE T* operator*() const { return val_; }
238 * Checks whether two handles are the same.
239 * Returns true if both are empty, or if the objects
240 * to which they refer are identical.
241 * The handles' references are not checked.
243 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
244 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
245 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
246 if (a == 0) return b == 0;
247 if (b == 0) return false;
251 template <class S> V8_INLINE bool operator==(
252 const PersistentBase<S>& that) const {
253 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
254 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
255 if (a == 0) return b == 0;
256 if (b == 0) return false;
261 * Checks whether two handles are different.
262 * Returns true if only one of the handles is empty, or if
263 * the objects to which they refer are different.
264 * The handles' references are not checked.
266 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
267 return !operator==(that);
270 template <class S> V8_INLINE bool operator!=(
271 const Persistent<S>& that) const {
272 return !operator==(that);
275 template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
276 #ifdef V8_ENABLE_CHECKS
277 // If we're going to perform the type check then we have to check
278 // that the handle isn't empty before doing the checked cast.
279 if (that.IsEmpty()) return Handle<T>();
281 return Handle<T>(T::Cast(*that));
284 template <class S> V8_INLINE Handle<S> As() {
285 return Handle<S>::Cast(*this);
288 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
289 return New(isolate, that.val_);
291 V8_INLINE static Handle<T> New(Isolate* isolate,
292 const PersistentBase<T>& that) {
293 return New(isolate, that.val_);
298 template<class F, class M> friend class Persistent;
299 template<class F> friend class PersistentBase;
300 template<class F> friend class Handle;
301 template<class F> friend class Local;
302 template<class F> friend class FunctionCallbackInfo;
303 template<class F> friend class PropertyCallbackInfo;
304 template<class F> friend class internal::CustomArguments;
305 friend Handle<Primitive> Undefined(Isolate* isolate);
306 friend Handle<Primitive> Null(Isolate* isolate);
307 friend Handle<Boolean> True(Isolate* isolate);
308 friend Handle<Boolean> False(Isolate* isolate);
309 friend class Context;
310 friend class HandleScope;
312 friend class Private;
315 * Creates a new handle for the specified value.
317 V8_INLINE explicit Handle(T* val) : val_(val) {}
319 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
326 * A light-weight stack-allocated object handle. All operations
327 * that return objects from within v8 return them in local handles. They
328 * are created within HandleScopes, and all local handles allocated within a
329 * handle scope are destroyed when the handle scope is destroyed. Hence it
330 * is not necessary to explicitly deallocate local handles.
332 template <class T> class Local : public Handle<T> {
335 template <class S> V8_INLINE Local(Local<S> that)
336 : Handle<T>(reinterpret_cast<T*>(*that)) {
338 * This check fails when trying to convert between incompatible
339 * handles. For example, converting from a Handle<String> to a
346 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
347 #ifdef V8_ENABLE_CHECKS
348 // If we're going to perform the type check then we have to check
349 // that the handle isn't empty before doing the checked cast.
350 if (that.IsEmpty()) return Local<T>();
352 return Local<T>(T::Cast(*that));
354 template <class S> V8_INLINE Local(Handle<S> that)
355 : Handle<T>(reinterpret_cast<T*>(*that)) {
359 template <class S> V8_INLINE Local<S> As() {
360 return Local<S>::Cast(*this);
364 * Create a local handle for the content of another handle.
365 * The referee is kept alive by the local handle even when
366 * the original handle is destroyed/disposed.
368 V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
369 V8_INLINE static Local<T> New(Isolate* isolate,
370 const PersistentBase<T>& that);
374 template<class F> friend class Eternal;
375 template<class F> friend class PersistentBase;
376 template<class F, class M> friend class Persistent;
377 template<class F> friend class Handle;
378 template<class F> friend class Local;
379 template<class F> friend class FunctionCallbackInfo;
380 template<class F> friend class PropertyCallbackInfo;
383 friend class Context;
384 template<class F> friend class internal::CustomArguments;
385 friend class HandleScope;
386 friend class EscapableHandleScope;
387 template<class F1, class F2, class F3> friend class PersistentValueMap;
388 template<class F1, class F2> friend class PersistentValueVector;
390 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
391 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
395 // Eternal handles are set-once handles that live for the life of the isolate.
396 template <class T> class Eternal {
398 V8_INLINE Eternal() : index_(kInitialValue) { }
400 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
401 Set(isolate, handle);
403 // Can only be safely called if already set.
404 V8_INLINE Local<T> Get(Isolate* isolate);
405 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
406 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
409 static const int kInitialValue = -1;
414 template<class T, class P>
415 class WeakCallbackData {
417 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
419 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
420 V8_INLINE Local<T> GetValue() const { return handle_; }
421 V8_INLINE P* GetParameter() const { return parameter_; }
424 friend class internal::GlobalHandles;
425 WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
426 : isolate_(isolate), handle_(handle), parameter_(parameter) { }
434 * An object reference that is independent of any handle scope. Where
435 * a Local handle only lives as long as the HandleScope in which it was
436 * allocated, a PersistentBase handle remains valid until it is explicitly
439 * A persistent handle contains a reference to a storage cell within
440 * the v8 engine which holds an object value and which is updated by
441 * the garbage collector whenever the object is moved. A new storage
442 * cell can be created using the constructor or PersistentBase::Reset and
443 * existing handles can be disposed using PersistentBase::Reset.
446 template <class T> class PersistentBase {
449 * If non-empty, destroy the underlying storage cell
450 * IsEmpty() will return true after this call.
452 V8_INLINE void Reset();
454 * If non-empty, destroy the underlying storage cell
455 * and create a new one with the contents of other if other is non empty
458 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
461 * If non-empty, destroy the underlying storage cell
462 * and create a new one with the contents of other if other is non empty
465 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
467 V8_INLINE bool IsEmpty() const { return val_ == 0; }
470 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
471 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
472 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
473 if (a == 0) return b == 0;
474 if (b == 0) return false;
478 template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
479 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
480 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
481 if (a == 0) return b == 0;
482 if (b == 0) return false;
487 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
488 return !operator==(that);
491 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
492 return !operator==(that);
496 * Install a finalization callback on this object.
497 * NOTE: There is no guarantee as to *when* or even *if* the callback is
498 * invoked. The invocation is performed solely on a best effort basis.
499 * As always, GC-based finalization should *not* be relied upon for any
500 * critical form of resource management!
503 V8_INLINE void SetWeak(
505 typename WeakCallbackData<T, P>::Callback callback);
507 template<typename S, typename P>
508 V8_INLINE void SetWeak(
510 typename WeakCallbackData<S, P>::Callback callback);
513 V8_INLINE P* ClearWeak();
515 // TODO(dcarney): remove this.
516 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
519 * Marks the reference to this object independent. Garbage collector is free
520 * to ignore any object groups containing this object. Weak callback for an
521 * independent handle should not assume that it will be preceded by a global
522 * GC prologue callback or followed by a global GC epilogue callback.
524 V8_INLINE void MarkIndependent();
527 * Marks the reference to this object partially dependent. Partially dependent
528 * handles only depend on other partially dependent handles and these
529 * dependencies are provided through object groups. It provides a way to build
530 * smaller object groups for young objects that represent only a subset of all
531 * external dependencies. This mark is automatically cleared after each
532 * garbage collection.
534 V8_INLINE void MarkPartiallyDependent();
536 V8_INLINE bool IsIndependent() const;
538 /** Checks if the handle holds the only reference to an object. */
539 V8_INLINE bool IsNearDeath() const;
541 /** Returns true if the handle's reference is weak. */
542 V8_INLINE bool IsWeak() const;
545 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
546 * description in v8-profiler.h for details.
548 V8_INLINE void SetWrapperClassId(uint16_t class_id);
551 * Returns the class ID previously assigned to this handle or 0 if no class ID
552 * was previously assigned.
554 V8_INLINE uint16_t WrapperClassId() const;
557 friend class Isolate;
559 template<class F> friend class Handle;
560 template<class F> friend class Local;
561 template<class F1, class F2> friend class Persistent;
562 template<class F> friend class UniquePersistent;
563 template<class F> friend class PersistentBase;
564 template<class F> friend class ReturnValue;
565 template<class F1, class F2, class F3> friend class PersistentValueMap;
566 template<class F1, class F2> friend class PersistentValueVector;
569 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
570 PersistentBase(PersistentBase& other); // NOLINT
571 void operator=(PersistentBase&);
572 V8_INLINE static T* New(Isolate* isolate, T* that);
579 * Default traits for Persistent. This class does not allow
580 * use of the copy constructor or assignment operator.
581 * At present kResetInDestructor is not set, but that will change in a future
585 class NonCopyablePersistentTraits {
587 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
588 static const bool kResetInDestructor = false;
589 template<class S, class M>
590 V8_INLINE static void Copy(const Persistent<S, M>& source,
591 NonCopyablePersistent* dest) {
592 Uncompilable<Object>();
594 // TODO(dcarney): come up with a good compile error here.
595 template<class O> V8_INLINE static void Uncompilable() {
596 TYPE_CHECK(O, Primitive);
602 * Helper class traits to allow copying and assignment of Persistent.
603 * This will clone the contents of storage cell, but not any of the flags, etc.
606 struct CopyablePersistentTraits {
607 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
608 static const bool kResetInDestructor = true;
609 template<class S, class M>
610 static V8_INLINE void Copy(const Persistent<S, M>& source,
611 CopyablePersistent* dest) {
612 // do nothing, just allow copy
618 * A PersistentBase which allows copy and assignment.
620 * Copy, assignment and destructor bevavior is controlled by the traits
623 * Note: Persistent class hierarchy is subject to future changes.
625 template <class T, class M> class Persistent : public PersistentBase<T> {
628 * A Persistent with no storage cell.
630 V8_INLINE Persistent() : PersistentBase<T>(0) { }
632 * Construct a Persistent from a Handle.
633 * When the Handle is non-empty, a new storage cell is created
634 * pointing to the same object, and no flags are set.
636 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
637 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
641 * Construct a Persistent from a Persistent.
642 * When the Persistent is non-empty, a new storage cell is created
643 * pointing to the same object, and no flags are set.
645 template <class S, class M2>
646 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
647 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
651 * The copy constructors and assignment operator create a Persistent
652 * exactly as the Persistent constructor, but the Copy function from the
653 * traits class is called, allowing the setting of flags based on the
656 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
659 template <class S, class M2>
660 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
663 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
667 template <class S, class M2>
668 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
673 * The destructor will dispose the Persistent based on the
674 * kResetInDestructor flags in the traits class. Since not calling dispose
675 * can result in a memory leak, it is recommended to always set this flag.
677 V8_INLINE ~Persistent() {
678 if (M::kResetInDestructor) this->Reset();
681 // TODO(dcarney): this is pretty useless, fix or remove
683 V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
684 #ifdef V8_ENABLE_CHECKS
685 // If we're going to perform the type check then we have to check
686 // that the handle isn't empty before doing the checked cast.
687 if (!that.IsEmpty()) T::Cast(*that);
689 return reinterpret_cast<Persistent<T>&>(that);
692 // TODO(dcarney): this is pretty useless, fix or remove
693 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
694 return Persistent<S>::Cast(*this);
697 // This will be removed.
698 V8_INLINE T* ClearAndLeak();
701 friend class Isolate;
703 template<class F> friend class Handle;
704 template<class F> friend class Local;
705 template<class F1, class F2> friend class Persistent;
706 template<class F> friend class ReturnValue;
708 template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
709 V8_INLINE T* operator*() const { return this->val_; }
710 template<class S, class M2>
711 V8_INLINE void Copy(const Persistent<S, M2>& that);
716 * A PersistentBase which has move semantics.
718 * Note: Persistent class hierarchy is subject to future changes.
721 class UniquePersistent : public PersistentBase<T> {
723 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
724 UniquePersistent* object;
729 * A UniquePersistent with no storage cell.
731 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
733 * Construct a UniquePersistent from a Handle.
734 * When the Handle is non-empty, a new storage cell is created
735 * pointing to the same object, and no flags are set.
738 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
739 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
743 * Construct a UniquePersistent from a PersistentBase.
744 * When the Persistent is non-empty, a new storage cell is created
745 * pointing to the same object, and no flags are set.
748 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
749 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
755 V8_INLINE UniquePersistent(RValue rvalue)
756 : PersistentBase<T>(rvalue.object->val_) {
757 rvalue.object->val_ = 0;
759 V8_INLINE ~UniquePersistent() { this->Reset(); }
761 * Move via assignment.
764 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
767 this->val_ = rhs.val_;
772 * Cast operator for moves.
774 V8_INLINE operator RValue() { return RValue(this); }
776 * Pass allows returning uniques from functions, etc.
778 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
781 UniquePersistent(UniquePersistent&);
782 void operator=(UniquePersistent&);
787 * A stack-allocated class that governs a number of local handles.
788 * After a handle scope has been created, all local handles will be
789 * allocated within that handle scope until either the handle scope is
790 * deleted or another handle scope is created. If there is already a
791 * handle scope and a new one is created, all allocations will take
792 * place in the new handle scope until it is deleted. After that,
793 * new handles will again be allocated in the original handle scope.
795 * After the handle scope of a local handle has been deleted the
796 * garbage collector will no longer track the object stored in the
797 * handle and may deallocate it. The behavior of accessing a handle
798 * for which the handle scope has been deleted is undefined.
800 class V8_EXPORT HandleScope {
802 HandleScope(Isolate* isolate);
807 * Counts the number of allocated handles.
809 static int NumberOfHandles(Isolate* isolate);
811 V8_INLINE Isolate* GetIsolate() const {
812 return reinterpret_cast<Isolate*>(isolate_);
816 V8_INLINE HandleScope() {}
818 void Initialize(Isolate* isolate);
820 static internal::Object** CreateHandle(internal::Isolate* isolate,
821 internal::Object* value);
824 // Uses heap_object to obtain the current Isolate.
825 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
826 internal::Object* value);
828 // Make it hard to create heap-allocated or illegal handle scopes by
829 // disallowing certain operations.
830 HandleScope(const HandleScope&);
831 void operator=(const HandleScope&);
832 void* operator new(size_t size);
833 void operator delete(void*, size_t);
835 internal::Isolate* isolate_;
836 internal::Object** prev_next_;
837 internal::Object** prev_limit_;
839 // Local::New uses CreateHandle with an Isolate* parameter.
840 template<class F> friend class Local;
842 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
843 // a HeapObject* in their shortcuts.
845 friend class Context;
850 * A HandleScope which first allocates a handle in the current scope
851 * which will be later filled with the escape value.
853 class V8_EXPORT EscapableHandleScope : public HandleScope {
855 EscapableHandleScope(Isolate* isolate);
856 V8_INLINE ~EscapableHandleScope() {}
859 * Pushes the value into the previous scope and returns a handle to it.
860 * Cannot be called twice.
863 V8_INLINE Local<T> Escape(Local<T> value) {
864 internal::Object** slot =
865 Escape(reinterpret_cast<internal::Object**>(*value));
866 return Local<T>(reinterpret_cast<T*>(slot));
870 internal::Object** Escape(internal::Object** escape_value);
872 // Make it hard to create heap-allocated or illegal handle scopes by
873 // disallowing certain operations.
874 EscapableHandleScope(const EscapableHandleScope&);
875 void operator=(const EscapableHandleScope&);
876 void* operator new(size_t size);
877 void operator delete(void*, size_t);
879 internal::Object** escape_slot_;
884 * A simple Maybe type, representing an object which may or may not have a
889 Maybe() : has_value(false) {}
890 explicit Maybe(T t) : has_value(true), value(t) {}
891 Maybe(bool has, T t) : has_value(has), value(t) {}
898 // Convenience wrapper.
900 inline Maybe<T> maybe(T t) {
905 // --- Special objects ---
909 * The superclass of values and API object templates.
911 class V8_EXPORT Data {
918 * The origin, within a file, of a script.
922 V8_INLINE ScriptOrigin(
923 Handle<Value> resource_name,
924 Handle<Integer> resource_line_offset = Handle<Integer>(),
925 Handle<Integer> resource_column_offset = Handle<Integer>(),
926 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
927 Handle<Integer> script_id = Handle<Integer>())
928 : resource_name_(resource_name),
929 resource_line_offset_(resource_line_offset),
930 resource_column_offset_(resource_column_offset),
931 resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
932 script_id_(script_id) { }
933 V8_INLINE Handle<Value> ResourceName() const;
934 V8_INLINE Handle<Integer> ResourceLineOffset() const;
935 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
936 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
937 V8_INLINE Handle<Integer> ScriptID() const;
939 Handle<Value> resource_name_;
940 Handle<Integer> resource_line_offset_;
941 Handle<Integer> resource_column_offset_;
942 Handle<Boolean> resource_is_shared_cross_origin_;
943 Handle<Integer> script_id_;
948 * A compiled JavaScript script, not yet tied to a Context.
950 class V8_EXPORT UnboundScript {
953 * Binds the script to the currently entered context.
955 Local<Script> BindToCurrentContext();
958 Handle<Value> GetScriptName();
961 * Data read from magic sourceURL comments.
963 Handle<Value> GetSourceURL();
965 * Data read from magic sourceMappingURL comments.
967 Handle<Value> GetSourceMappingURL();
970 * Returns zero based line number of the code_pos location in the script.
971 * -1 will be returned if no information available.
973 int GetLineNumber(int code_pos);
975 static const int kNoScriptId = 0;
980 * A compiled JavaScript script, tied to a Context which was active when the
981 * script was compiled.
983 class V8_EXPORT Script {
986 * A shorthand for ScriptCompiler::Compile().
988 static Local<Script> Compile(Handle<String> source,
989 ScriptOrigin* origin = NULL);
991 // To be decprecated, use the Compile above.
992 static Local<Script> Compile(Handle<String> source,
993 Handle<String> file_name);
996 * Runs the script returning the resulting value. It will be run in the
997 * context in which it was created (ScriptCompiler::CompileBound or
998 * UnboundScript::BindToGlobalContext()).
1003 * Returns the corresponding context-unbound script.
1005 Local<UnboundScript> GetUnboundScript();
1007 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1009 return GetUnboundScript()->GetId();
1015 * For compiling scripts.
1017 class V8_EXPORT ScriptCompiler {
1020 * Compilation data that the embedder can cache and pass back to speed up
1021 * future compilations. The data is produced if the CompilerOptions passed to
1022 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1023 * = true. The data to cache can then can be retrieved from
1026 struct V8_EXPORT CachedData {
1032 CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1034 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1035 // data and guarantees that it stays alive until the CachedData object is
1036 // destroyed. If the policy is BufferOwned, the given data will be deleted
1037 // (with delete[]) when the CachedData object is destroyed.
1038 CachedData(const uint8_t* data, int length,
1039 BufferPolicy buffer_policy = BufferNotOwned);
1041 // TODO(marja): Async compilation; add constructors which take a callback
1042 // which will be called when V8 no longer needs the data.
1043 const uint8_t* data;
1045 BufferPolicy buffer_policy;
1048 // Prevent copying. Not implemented.
1049 CachedData(const CachedData&);
1050 CachedData& operator=(const CachedData&);
1054 * Source code which can be then compiled to a UnboundScript or Script.
1058 // Source takes ownership of CachedData.
1059 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1060 CachedData* cached_data = NULL);
1061 V8_INLINE Source(Local<String> source_string,
1062 CachedData* cached_data = NULL);
1063 V8_INLINE ~Source();
1065 // Ownership of the CachedData or its buffers is *not* transferred to the
1066 // caller. The CachedData object is alive as long as the Source object is
1068 V8_INLINE const CachedData* GetCachedData() const;
1071 friend class ScriptCompiler;
1072 // Prevent copying. Not implemented.
1073 Source(const Source&);
1074 Source& operator=(const Source&);
1076 Local<String> source_string;
1078 // Origin information
1079 Handle<Value> resource_name;
1080 Handle<Integer> resource_line_offset;
1081 Handle<Integer> resource_column_offset;
1082 Handle<Boolean> resource_is_shared_cross_origin;
1084 // Cached data from previous compilation (if a kConsume*Cache flag is
1085 // set), or hold newly generated cache data (kProduce*Cache flags) are
1086 // set when calling a compile method.
1087 CachedData* cached_data;
1090 enum CompileOptions {
1091 kNoCompileOptions = 0,
1092 kProduceParserCache,
1093 kConsumeParserCache,
1097 // Support the previous API for a transition period.
1102 * Compiles the specified script (context-independent).
1103 * Cached data as part of the source object can be optionally produced to be
1104 * consumed later to speed up compilation of identical source scripts.
1106 * Note that when producing cached data, the source must point to NULL for
1107 * cached data. When consuming cached data, the cached data must have been
1108 * produced by the same version of V8.
1110 * \param source Script source code.
1111 * \return Compiled script object (context independent; for running it must be
1112 * bound to a context).
1114 static Local<UnboundScript> CompileUnbound(
1115 Isolate* isolate, Source* source,
1116 CompileOptions options = kNoCompileOptions);
1119 * Compiles the specified script (bound to current context).
1121 * \param source Script source code.
1122 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1123 * using pre_data speeds compilation if it's done multiple times.
1124 * Owned by caller, no references are kept when this function returns.
1125 * \return Compiled script object, bound to the context that was active
1126 * when this function was called. When run it will always use this
1129 static Local<Script> Compile(
1130 Isolate* isolate, Source* source,
1131 CompileOptions options = kNoCompileOptions);
1138 class V8_EXPORT Message {
1140 Local<String> Get() const;
1141 Local<String> GetSourceLine() const;
1144 * Returns the origin for the script from where the function causing the
1147 ScriptOrigin GetScriptOrigin() const;
1150 * Returns the resource name for the script from where the function causing
1151 * the error originates.
1153 Handle<Value> GetScriptResourceName() const;
1156 * Exception stack trace. By default stack traces are not captured for
1157 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1158 * to change this option.
1160 Handle<StackTrace> GetStackTrace() const;
1163 * Returns the number, 1-based, of the line where the error occurred.
1165 int GetLineNumber() const;
1168 * Returns the index within the script of the first character where
1169 * the error occurred.
1171 int GetStartPosition() const;
1174 * Returns the index within the script of the last character where
1175 * the error occurred.
1177 int GetEndPosition() const;
1180 * Returns the index within the line of the first character where
1181 * the error occurred.
1183 int GetStartColumn() const;
1186 * Returns the index within the line of the last character where
1187 * the error occurred.
1189 int GetEndColumn() const;
1192 * Passes on the value set by the embedder when it fed the script from which
1193 * this Message was generated to V8.
1195 bool IsSharedCrossOrigin() const;
1197 // TODO(1245381): Print to a string instead of on a FILE.
1198 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1200 static const int kNoLineNumberInfo = 0;
1201 static const int kNoColumnInfo = 0;
1202 static const int kNoScriptIdInfo = 0;
1207 * Representation of a JavaScript stack trace. The information collected is a
1208 * snapshot of the execution stack and the information remains valid after
1209 * execution continues.
1211 class V8_EXPORT StackTrace {
1214 * Flags that determine what information is placed captured for each
1215 * StackFrame when grabbing the current stack trace.
1217 enum StackTraceOptions {
1219 kColumnOffset = 1 << 1 | kLineNumber,
1220 kScriptName = 1 << 2,
1221 kFunctionName = 1 << 3,
1223 kIsConstructor = 1 << 5,
1224 kScriptNameOrSourceURL = 1 << 6,
1226 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1227 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1228 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1232 * Returns a StackFrame at a particular index.
1234 Local<StackFrame> GetFrame(uint32_t index) const;
1237 * Returns the number of StackFrames.
1239 int GetFrameCount() const;
1242 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1244 Local<Array> AsArray();
1247 * Grab a snapshot of the current JavaScript execution stack.
1249 * \param frame_limit The maximum number of stack frames we want to capture.
1250 * \param options Enumerates the set of things we will capture for each
1253 static Local<StackTrace> CurrentStackTrace(
1256 StackTraceOptions options = kOverview);
1261 * A single JavaScript stack frame.
1263 class V8_EXPORT StackFrame {
1266 * Returns the number, 1-based, of the line for the associate function call.
1267 * This method will return Message::kNoLineNumberInfo if it is unable to
1268 * retrieve the line number, or if kLineNumber was not passed as an option
1269 * when capturing the StackTrace.
1271 int GetLineNumber() const;
1274 * Returns the 1-based column offset on the line for the associated function
1276 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1277 * the column number, or if kColumnOffset was not passed as an option when
1278 * capturing the StackTrace.
1280 int GetColumn() const;
1283 * Returns the id of the script for the function for this StackFrame.
1284 * This method will return Message::kNoScriptIdInfo if it is unable to
1285 * retrieve the script id, or if kScriptId was not passed as an option when
1286 * capturing the StackTrace.
1288 int GetScriptId() const;
1291 * Returns the name of the resource that contains the script for the
1292 * function for this StackFrame.
1294 Local<String> GetScriptName() const;
1297 * Returns the name of the resource that contains the script for the
1298 * function for this StackFrame or sourceURL value if the script name
1299 * is undefined and its source ends with //# sourceURL=... string or
1300 * deprecated //@ sourceURL=... string.
1302 Local<String> GetScriptNameOrSourceURL() const;
1305 * Returns the name of the function associated with this stack frame.
1307 Local<String> GetFunctionName() const;
1310 * Returns whether or not the associated function is compiled via a call to
1313 bool IsEval() const;
1316 * Returns whether or not the associated function is called as a
1317 * constructor via "new".
1319 bool IsConstructor() const;
1326 class V8_EXPORT JSON {
1329 * Tries to parse the string |json_string| and returns it as value if
1332 * \param json_string The string to parse.
1333 * \return The corresponding value if successfully parsed.
1335 static Local<Value> Parse(Local<String> json_string);
1343 * The superclass of all JavaScript values and objects.
1345 class V8_EXPORT Value : public Data {
1348 * Returns true if this value is the undefined value. See ECMA-262
1351 V8_INLINE bool IsUndefined() const;
1354 * Returns true if this value is the null value. See ECMA-262
1357 V8_INLINE bool IsNull() const;
1360 * Returns true if this value is true.
1362 bool IsTrue() const;
1365 * Returns true if this value is false.
1367 bool IsFalse() const;
1370 * Returns true if this value is an instance of the String type.
1373 V8_INLINE bool IsString() const;
1376 * Returns true if this value is a symbol.
1377 * This is an experimental feature.
1379 bool IsSymbol() const;
1382 * Returns true if this value is a function.
1384 bool IsFunction() const;
1387 * Returns true if this value is an array.
1389 bool IsArray() const;
1392 * Returns true if this value is an object.
1394 bool IsObject() const;
1397 * Returns true if this value is boolean.
1399 bool IsBoolean() const;
1402 * Returns true if this value is a number.
1404 bool IsNumber() const;
1407 * Returns true if this value is external.
1409 bool IsExternal() const;
1412 * Returns true if this value is a 32-bit signed integer.
1414 bool IsInt32() const;
1417 * Returns true if this value is a 32-bit unsigned integer.
1419 bool IsUint32() const;
1422 * Returns true if this value is a Date.
1424 bool IsDate() const;
1427 * Returns true if this value is a Boolean object.
1429 bool IsBooleanObject() const;
1432 * Returns true if this value is a Number object.
1434 bool IsNumberObject() const;
1437 * Returns true if this value is a String object.
1439 bool IsStringObject() const;
1442 * Returns true if this value is a Symbol object.
1443 * This is an experimental feature.
1445 bool IsSymbolObject() const;
1448 * Returns true if this value is a NativeError.
1450 bool IsNativeError() const;
1453 * Returns true if this value is a RegExp.
1455 bool IsRegExp() const;
1458 * Returns true if this value is a Promise.
1459 * This is an experimental feature.
1461 bool IsPromise() const;
1464 * Returns true if this value is an ArrayBuffer.
1465 * This is an experimental feature.
1467 bool IsArrayBuffer() const;
1470 * Returns true if this value is an ArrayBufferView.
1471 * This is an experimental feature.
1473 bool IsArrayBufferView() const;
1476 * Returns true if this value is one of TypedArrays.
1477 * This is an experimental feature.
1479 bool IsTypedArray() const;
1482 * Returns true if this value is an Uint8Array.
1483 * This is an experimental feature.
1485 bool IsUint8Array() const;
1488 * Returns true if this value is an Uint8ClampedArray.
1489 * This is an experimental feature.
1491 bool IsUint8ClampedArray() const;
1494 * Returns true if this value is an Int8Array.
1495 * This is an experimental feature.
1497 bool IsInt8Array() const;
1500 * Returns true if this value is an Uint16Array.
1501 * This is an experimental feature.
1503 bool IsUint16Array() const;
1506 * Returns true if this value is an Int16Array.
1507 * This is an experimental feature.
1509 bool IsInt16Array() const;
1512 * Returns true if this value is an Uint32Array.
1513 * This is an experimental feature.
1515 bool IsUint32Array() const;
1518 * Returns true if this value is an Int32Array.
1519 * This is an experimental feature.
1521 bool IsInt32Array() const;
1524 * Returns true if this value is a Float32Array.
1525 * This is an experimental feature.
1527 bool IsFloat32Array() const;
1530 * Returns true if this value is a Float32x4Array.
1531 * This is an experimental feature.
1533 bool IsFloat32x4Array() const;
1536 * Returns true if this value is a Float64x2Array.
1537 * This is an experimental feature.
1539 bool IsFloat64x2Array() const;
1542 * Returns true if this value is a Int32x4Array.
1543 * This is an experimental feature.
1545 bool IsInt32x4Array() const;
1548 * Returns true if this value is a Float64Array.
1549 * This is an experimental feature.
1551 bool IsFloat64Array() const;
1554 * Returns true if this value is a DataView.
1555 * This is an experimental feature.
1557 bool IsDataView() const;
1559 Local<Boolean> ToBoolean() const;
1560 Local<Number> ToNumber() const;
1561 Local<String> ToString() const;
1562 Local<String> ToDetailString() const;
1563 Local<Object> ToObject() const;
1564 Local<Integer> ToInteger() const;
1565 Local<Uint32> ToUint32() const;
1566 Local<Int32> ToInt32() const;
1569 * Attempts to convert a string to an array index.
1570 * Returns an empty handle if the conversion fails.
1572 Local<Uint32> ToArrayIndex() const;
1574 bool BooleanValue() const;
1575 double NumberValue() const;
1576 int64_t IntegerValue() const;
1577 uint32_t Uint32Value() const;
1578 int32_t Int32Value() const;
1581 bool Equals(Handle<Value> that) const;
1582 bool StrictEquals(Handle<Value> that) const;
1583 bool SameValue(Handle<Value> that) const;
1585 template <class T> V8_INLINE static Value* Cast(T* value);
1588 V8_INLINE bool QuickIsUndefined() const;
1589 V8_INLINE bool QuickIsNull() const;
1590 V8_INLINE bool QuickIsString() const;
1591 bool FullIsUndefined() const;
1592 bool FullIsNull() const;
1593 bool FullIsString() const;
1598 * The superclass of primitive values. See ECMA-262 4.3.2.
1600 class V8_EXPORT Primitive : public Value { };
1604 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1607 class V8_EXPORT Boolean : public Primitive {
1610 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1615 * A JavaScript string value (ECMA-262, 4.3.17).
1617 class V8_EXPORT String : public Primitive {
1620 UNKNOWN_ENCODING = 0x1,
1621 TWO_BYTE_ENCODING = 0x0,
1622 ASCII_ENCODING = 0x4,
1623 ONE_BYTE_ENCODING = 0x4
1626 * Returns the number of characters in this string.
1631 * Returns the number of bytes in the UTF-8 encoded
1632 * representation of this string.
1634 int Utf8Length() const;
1637 * Returns whether this string is known to contain only one byte data.
1638 * Does not read the string.
1639 * False negatives are possible.
1641 bool IsOneByte() const;
1644 * Returns whether this string contain only one byte data.
1645 * Will read the entire string in some cases.
1647 bool ContainsOnlyOneByte() const;
1650 * Write the contents of the string to an external buffer.
1651 * If no arguments are given, expects the buffer to be large
1652 * enough to hold the entire string and NULL terminator. Copies
1653 * the contents of the string and the NULL terminator into the
1656 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1657 * before the end of the buffer.
1659 * Copies up to length characters into the output buffer.
1660 * Only null-terminates if there is enough space in the buffer.
1662 * \param buffer The buffer into which the string will be copied.
1663 * \param start The starting position within the string at which
1665 * \param length The number of characters to copy from the string. For
1666 * WriteUtf8 the number of bytes in the buffer.
1667 * \param nchars_ref The number of characters written, can be NULL.
1668 * \param options Various options that might affect performance of this or
1669 * subsequent operations.
1670 * \return The number of characters copied to the buffer excluding the null
1671 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1672 * including the null terminator (if written).
1676 HINT_MANY_WRITES_EXPECTED = 1,
1677 NO_NULL_TERMINATION = 2,
1678 PRESERVE_ASCII_NULL = 4,
1679 // Used by WriteUtf8 to replace orphan surrogate code units with the
1680 // unicode replacement character. Needs to be set to guarantee valid UTF-8
1682 REPLACE_INVALID_UTF8 = 8
1685 // 16-bit character codes.
1686 int Write(uint16_t* buffer,
1689 int options = NO_OPTIONS) const;
1690 // One byte characters.
1691 int WriteOneByte(uint8_t* buffer,
1694 int options = NO_OPTIONS) const;
1695 // UTF-8 encoded characters.
1696 int WriteUtf8(char* buffer,
1698 int* nchars_ref = NULL,
1699 int options = NO_OPTIONS) const;
1702 * A zero length string.
1704 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1707 * Returns true if the string is external
1709 bool IsExternal() const;
1712 * Returns true if the string is both external and ASCII
1714 bool IsExternalAscii() const;
1716 class V8_EXPORT ExternalStringResourceBase { // NOLINT
1718 virtual ~ExternalStringResourceBase() {}
1721 ExternalStringResourceBase() {}
1724 * Internally V8 will call this Dispose method when the external string
1725 * resource is no longer needed. The default implementation will use the
1726 * delete operator. This method can be overridden in subclasses to
1727 * control how allocated external string resources are disposed.
1729 virtual void Dispose() { delete this; }
1732 // Disallow copying and assigning.
1733 ExternalStringResourceBase(const ExternalStringResourceBase&);
1734 void operator=(const ExternalStringResourceBase&);
1736 friend class v8::internal::Heap;
1740 * An ExternalStringResource is a wrapper around a two-byte string
1741 * buffer that resides outside V8's heap. Implement an
1742 * ExternalStringResource to manage the life cycle of the underlying
1743 * buffer. Note that the string data must be immutable.
1745 class V8_EXPORT ExternalStringResource
1746 : public ExternalStringResourceBase {
1749 * Override the destructor to manage the life cycle of the underlying
1752 virtual ~ExternalStringResource() {}
1755 * The string data from the underlying buffer.
1757 virtual const uint16_t* data() const = 0;
1760 * The length of the string. That is, the number of two-byte characters.
1762 virtual size_t length() const = 0;
1765 ExternalStringResource() {}
1769 * An ExternalAsciiStringResource is a wrapper around an ASCII
1770 * string buffer that resides outside V8's heap. Implement an
1771 * ExternalAsciiStringResource to manage the life cycle of the
1772 * underlying buffer. Note that the string data must be immutable
1773 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1774 * UTF-8, which would require special treatment internally in the
1775 * engine and, in the case of UTF-8, do not allow efficient indexing.
1776 * Use String::New or convert to 16 bit data for non-ASCII.
1779 class V8_EXPORT ExternalAsciiStringResource
1780 : public ExternalStringResourceBase {
1783 * Override the destructor to manage the life cycle of the underlying
1786 virtual ~ExternalAsciiStringResource() {}
1787 /** The string data from the underlying buffer.*/
1788 virtual const char* data() const = 0;
1789 /** The number of ASCII characters in the string.*/
1790 virtual size_t length() const = 0;
1792 ExternalAsciiStringResource() {}
1795 typedef ExternalAsciiStringResource ExternalOneByteStringResource;
1798 * If the string is an external string, return the ExternalStringResourceBase
1799 * regardless of the encoding, otherwise return NULL. The encoding of the
1800 * string is returned in encoding_out.
1802 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1803 Encoding* encoding_out) const;
1806 * Get the ExternalStringResource for an external string. Returns
1807 * NULL if IsExternal() doesn't return true.
1809 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1812 * Get the ExternalAsciiStringResource for an external ASCII string.
1813 * Returns NULL if IsExternalAscii() doesn't return true.
1815 const ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
1817 V8_INLINE static String* Cast(v8::Value* obj);
1819 enum NewStringType {
1820 kNormalString, kInternalizedString, kUndetectableString
1823 /** Allocates a new string from UTF-8 data.*/
1824 static Local<String> NewFromUtf8(Isolate* isolate,
1826 NewStringType type = kNormalString,
1829 /** Allocates a new string from Latin-1 data.*/
1830 static Local<String> NewFromOneByte(
1832 const uint8_t* data,
1833 NewStringType type = kNormalString,
1836 /** Allocates a new string from UTF-16 data.*/
1837 static Local<String> NewFromTwoByte(
1839 const uint16_t* data,
1840 NewStringType type = kNormalString,
1844 * Creates a new string by concatenating the left and the right strings
1845 * passed in as parameters.
1847 static Local<String> Concat(Handle<String> left, Handle<String> right);
1850 * Creates a new external string using the data defined in the given
1851 * resource. When the external string is no longer live on V8's heap the
1852 * resource will be disposed by calling its Dispose method. The caller of
1853 * this function should not otherwise delete or modify the resource. Neither
1854 * should the underlying buffer be deallocated or modified except through the
1855 * destructor of the external string resource.
1857 static Local<String> NewExternal(Isolate* isolate,
1858 ExternalStringResource* resource);
1861 * Associate an external string resource with this string by transforming it
1862 * in place so that existing references to this string in the JavaScript heap
1863 * will use the external string resource. The external string resource's
1864 * character contents need to be equivalent to this string.
1865 * Returns true if the string has been changed to be an external string.
1866 * The string is not modified if the operation fails. See NewExternal for
1867 * information on the lifetime of the resource.
1869 bool MakeExternal(ExternalStringResource* resource);
1872 * Creates a new external string using the ASCII data defined in the given
1873 * resource. When the external string is no longer live on V8's heap the
1874 * resource will be disposed by calling its Dispose method. The caller of
1875 * this function should not otherwise delete or modify the resource. Neither
1876 * should the underlying buffer be deallocated or modified except through the
1877 * destructor of the external string resource.
1879 static Local<String> NewExternal(Isolate* isolate,
1880 ExternalAsciiStringResource* resource);
1883 * Associate an external string resource with this string by transforming it
1884 * in place so that existing references to this string in the JavaScript heap
1885 * will use the external string resource. The external string resource's
1886 * character contents need to be equivalent to this string.
1887 * Returns true if the string has been changed to be an external string.
1888 * The string is not modified if the operation fails. See NewExternal for
1889 * information on the lifetime of the resource.
1891 bool MakeExternal(ExternalAsciiStringResource* resource);
1894 * Returns true if this string can be made external.
1896 bool CanMakeExternal();
1899 * Converts an object to a UTF-8-encoded character array. Useful if
1900 * you want to print the object. If conversion to a string fails
1901 * (e.g. due to an exception in the toString() method of the object)
1902 * then the length() method returns 0 and the * operator returns
1905 class V8_EXPORT Utf8Value {
1907 explicit Utf8Value(Handle<v8::Value> obj);
1909 char* operator*() { return str_; }
1910 const char* operator*() const { return str_; }
1911 int length() const { return length_; }
1916 // Disallow copying and assigning.
1917 Utf8Value(const Utf8Value&);
1918 void operator=(const Utf8Value&);
1922 * Converts an object to a two-byte string.
1923 * If conversion to a string fails (eg. due to an exception in the toString()
1924 * method of the object) then the length() method returns 0 and the * operator
1927 class V8_EXPORT Value {
1929 explicit Value(Handle<v8::Value> obj);
1931 uint16_t* operator*() { return str_; }
1932 const uint16_t* operator*() const { return str_; }
1933 int length() const { return length_; }
1938 // Disallow copying and assigning.
1939 Value(const Value&);
1940 void operator=(const Value&);
1944 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
1945 Encoding encoding) const;
1946 void VerifyExternalStringResource(ExternalStringResource* val) const;
1947 static void CheckCast(v8::Value* obj);
1952 * A JavaScript symbol (ECMA-262 edition 6)
1954 * This is an experimental feature. Use at your own risk.
1956 class V8_EXPORT Symbol : public Primitive {
1958 // Returns the print name string of the symbol, or undefined if none.
1959 Local<Value> Name() const;
1961 // Create a symbol. If name is not empty, it will be used as the description.
1962 static Local<Symbol> New(
1963 Isolate *isolate, Local<String> name = Local<String>());
1965 // Access global symbol registry.
1966 // Note that symbols created this way are never collected, so
1967 // they should only be used for statically fixed properties.
1968 // Also, there is only one global name space for the names used as keys.
1969 // To minimize the potential for clashes, use qualified names as keys.
1970 static Local<Symbol> For(Isolate *isolate, Local<String> name);
1972 // Retrieve a global symbol. Similar to |For|, but using a separate
1973 // registry that is not accessible by (and cannot clash with) JavaScript code.
1974 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
1976 V8_INLINE static Symbol* Cast(v8::Value* obj);
1979 static void CheckCast(v8::Value* obj);
1986 * This is an experimental feature. Use at your own risk.
1988 class V8_EXPORT Private : public Data {
1990 // Returns the print name string of the private symbol, or undefined if none.
1991 Local<Value> Name() const;
1993 // Create a private symbol. If name is not empty, it will be the description.
1994 static Local<Private> New(
1995 Isolate *isolate, Local<String> name = Local<String>());
1997 // Retrieve a global private symbol. If a symbol with this name has not
1998 // been retrieved in the same isolate before, it is created.
1999 // Note that private symbols created this way are never collected, so
2000 // they should only be used for statically fixed properties.
2001 // Also, there is only one global name space for the names used as keys.
2002 // To minimize the potential for clashes, use qualified names as keys,
2003 // e.g., "Class#property".
2004 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
2012 * A JavaScript number value (ECMA-262, 4.3.20)
2014 class V8_EXPORT Number : public Primitive {
2016 double Value() const;
2017 static Local<Number> New(Isolate* isolate, double value);
2018 V8_INLINE static Number* Cast(v8::Value* obj);
2021 static void CheckCast(v8::Value* obj);
2026 * A JavaScript value representing a signed integer.
2028 class V8_EXPORT Integer : public Number {
2030 static Local<Integer> New(Isolate* isolate, int32_t value);
2031 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2032 int64_t Value() const;
2033 V8_INLINE static Integer* Cast(v8::Value* obj);
2036 static void CheckCast(v8::Value* obj);
2041 * A JavaScript value representing a 32-bit signed integer.
2043 class V8_EXPORT Int32 : public Integer {
2045 int32_t Value() const;
2052 * A JavaScript value representing a 32-bit unsigned integer.
2054 class V8_EXPORT Uint32 : public Integer {
2056 uint32_t Value() const;
2062 enum PropertyAttribute {
2069 enum ExternalArrayType {
2070 kExternalInt8Array = 1,
2071 kExternalUint8Array,
2072 kExternalInt16Array,
2073 kExternalUint16Array,
2074 kExternalInt32Array,
2075 kExternalInt32x4Array,
2076 kExternalUint32Array,
2077 kExternalFloat32Array,
2078 kExternalFloat32x4Array,
2079 kExternalFloat64x2Array,
2080 kExternalFloat64Array,
2081 kExternalUint8ClampedArray,
2083 // Legacy constant names
2084 kExternalByteArray = kExternalInt8Array,
2085 kExternalUnsignedByteArray = kExternalUint8Array,
2086 kExternalShortArray = kExternalInt16Array,
2087 kExternalUnsignedShortArray = kExternalUint16Array,
2088 kExternalIntArray = kExternalInt32Array,
2089 kExternalUnsignedIntArray = kExternalUint32Array,
2090 kExternalFloatArray = kExternalFloat32Array,
2091 kExternalDoubleArray = kExternalFloat64Array,
2092 kExternalPixelArray = kExternalUint8ClampedArray
2096 * Accessor[Getter|Setter] are used as callback functions when
2097 * setting|getting a particular property. See Object and ObjectTemplate's
2098 * method SetAccessor.
2100 typedef void (*AccessorGetterCallback)(
2101 Local<String> property,
2102 const PropertyCallbackInfo<Value>& info);
2105 typedef void (*AccessorSetterCallback)(
2106 Local<String> property,
2108 const PropertyCallbackInfo<void>& info);
2112 * Access control specifications.
2114 * Some accessors should be accessible across contexts. These
2115 * accessors have an explicit access control parameter which specifies
2116 * the kind of cross-context access that should be allowed.
2118 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2120 enum AccessControl {
2123 ALL_CAN_WRITE = 1 << 1,
2124 PROHIBITS_OVERWRITING = 1 << 2
2129 * A JavaScript object (ECMA-262, 4.3.3)
2131 class V8_EXPORT Object : public Value {
2133 bool Set(Handle<Value> key, Handle<Value> value);
2135 bool Set(uint32_t index, Handle<Value> value);
2137 // Sets an own property on this object bypassing interceptors and
2138 // overriding accessors or read-only properties.
2140 // Note that if the object has an interceptor the property will be set
2141 // locally, but since the interceptor takes precedence the local property
2142 // will only be returned if the interceptor doesn't return a value.
2144 // Note also that this only works for named properties.
2145 bool ForceSet(Handle<Value> key,
2146 Handle<Value> value,
2147 PropertyAttribute attribs = None);
2149 Local<Value> Get(Handle<Value> key);
2151 Local<Value> Get(uint32_t index);
2154 * Gets the property attributes of a property which can be None or
2155 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2156 * None when the property doesn't exist.
2158 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2161 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2163 Local<Value> GetOwnPropertyDescriptor(Local<String> key);
2165 bool Has(Handle<Value> key);
2167 bool Delete(Handle<Value> key);
2169 // Delete a property on this object bypassing interceptors and
2170 // ignoring dont-delete attributes.
2171 bool ForceDelete(Handle<Value> key);
2173 bool Has(uint32_t index);
2175 bool Delete(uint32_t index);
2177 bool SetAccessor(Handle<String> name,
2178 AccessorGetterCallback getter,
2179 AccessorSetterCallback setter = 0,
2180 Handle<Value> data = Handle<Value>(),
2181 AccessControl settings = DEFAULT,
2182 PropertyAttribute attribute = None);
2184 // This function is not yet stable and should not be used at this time.
2185 bool SetDeclaredAccessor(Local<String> name,
2186 Local<DeclaredAccessorDescriptor> descriptor,
2187 PropertyAttribute attribute = None,
2188 AccessControl settings = DEFAULT);
2190 void SetAccessorProperty(Local<String> name,
2191 Local<Function> getter,
2192 Handle<Function> setter = Handle<Function>(),
2193 PropertyAttribute attribute = None,
2194 AccessControl settings = DEFAULT);
2197 * Functionality for private properties.
2198 * This is an experimental feature, use at your own risk.
2199 * Note: Private properties are inherited. Do not rely on this, since it may
2202 bool HasPrivate(Handle<Private> key);
2203 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2204 bool DeletePrivate(Handle<Private> key);
2205 Local<Value> GetPrivate(Handle<Private> key);
2208 * Returns an array containing the names of the enumerable properties
2209 * of this object, including properties from prototype objects. The
2210 * array returned by this method contains the same values as would
2211 * be enumerated by a for-in statement over this object.
2213 Local<Array> GetPropertyNames();
2216 * This function has the same functionality as GetPropertyNames but
2217 * the returned array doesn't contain the names of properties from
2218 * prototype objects.
2220 Local<Array> GetOwnPropertyNames();
2223 * Get the prototype object. This does not skip objects marked to
2224 * be skipped by __proto__ and it does not consult the security
2227 Local<Value> GetPrototype();
2230 * Set the prototype object. This does not skip objects marked to
2231 * be skipped by __proto__ and it does not consult the security
2234 bool SetPrototype(Handle<Value> prototype);
2237 * Finds an instance of the given function template in the prototype
2240 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2243 * Call builtin Object.prototype.toString on this object.
2244 * This is different from Value::ToString() that may call
2245 * user-defined toString function. This one does not.
2247 Local<String> ObjectProtoToString();
2250 * Returns the name of the function invoked as a constructor for this object.
2252 Local<String> GetConstructorName();
2254 /** Gets the number of internal fields for this Object. */
2255 int InternalFieldCount();
2257 /** Same as above, but works for Persistents */
2258 V8_INLINE static int InternalFieldCount(
2259 const PersistentBase<Object>& object) {
2260 return object.val_->InternalFieldCount();
2263 /** Gets the value from an internal field. */
2264 V8_INLINE Local<Value> GetInternalField(int index);
2266 /** Sets the value in an internal field. */
2267 void SetInternalField(int index, Handle<Value> value);
2270 * Gets a 2-byte-aligned native pointer from an internal field. This field
2271 * must have been set by SetAlignedPointerInInternalField, everything else
2272 * leads to undefined behavior.
2274 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2276 /** Same as above, but works for Persistents */
2277 V8_INLINE static void* GetAlignedPointerFromInternalField(
2278 const PersistentBase<Object>& object, int index) {
2279 return object.val_->GetAlignedPointerFromInternalField(index);
2283 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2284 * a field, GetAlignedPointerFromInternalField must be used, everything else
2285 * leads to undefined behavior.
2287 void SetAlignedPointerInInternalField(int index, void* value);
2289 // Testers for local properties.
2290 bool HasOwnProperty(Handle<String> key);
2291 bool HasRealNamedProperty(Handle<String> key);
2292 bool HasRealIndexedProperty(uint32_t index);
2293 bool HasRealNamedCallbackProperty(Handle<String> key);
2296 * If result.IsEmpty() no real property was located in the prototype chain.
2297 * This means interceptors in the prototype chain are not called.
2299 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2302 * If result.IsEmpty() no real property was located on the object or
2303 * in the prototype chain.
2304 * This means interceptors in the prototype chain are not called.
2306 Local<Value> GetRealNamedProperty(Handle<String> key);
2308 /** Tests for a named lookup interceptor.*/
2309 bool HasNamedLookupInterceptor();
2311 /** Tests for an index lookup interceptor.*/
2312 bool HasIndexedLookupInterceptor();
2315 * Turns on access check on the object if the object is an instance of
2316 * a template that has access check callbacks. If an object has no
2317 * access check info, the object cannot be accessed by anyone.
2319 void TurnOnAccessCheck();
2322 * Returns the identity hash for this object. The current implementation
2323 * uses a hidden property on the object to store the identity hash.
2325 * The return value will never be 0. Also, it is not guaranteed to be
2328 int GetIdentityHash();
2331 * Access hidden properties on JavaScript objects. These properties are
2332 * hidden from the executing JavaScript and only accessible through the V8
2333 * C++ API. Hidden properties introduced by V8 internally (for example the
2334 * identity hash) are prefixed with "v8::".
2336 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2337 Local<Value> GetHiddenValue(Handle<String> key);
2338 bool DeleteHiddenValue(Handle<String> key);
2341 * Returns true if this is an instance of an api function (one
2342 * created from a function created from a function template) and has
2343 * been modified since it was created. Note that this method is
2344 * conservative and may return true for objects that haven't actually
2350 * Clone this object with a fast but shallow copy. Values will point
2351 * to the same values as the original object.
2353 Local<Object> Clone();
2356 * Returns the context in which the object was created.
2358 Local<Context> CreationContext();
2361 * Set the backing store of the indexed properties to be managed by the
2362 * embedding layer. Access to the indexed properties will follow the rules
2363 * spelled out in CanvasPixelArray.
2364 * Note: The embedding program still owns the data and needs to ensure that
2365 * the backing store is preserved while V8 has a reference.
2367 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2368 bool HasIndexedPropertiesInPixelData();
2369 uint8_t* GetIndexedPropertiesPixelData();
2370 int GetIndexedPropertiesPixelDataLength();
2373 * Set the backing store of the indexed properties to be managed by the
2374 * embedding layer. Access to the indexed properties will follow the rules
2375 * spelled out for the CanvasArray subtypes in the WebGL specification.
2376 * Note: The embedding program still owns the data and needs to ensure that
2377 * the backing store is preserved while V8 has a reference.
2379 void SetIndexedPropertiesToExternalArrayData(void* data,
2380 ExternalArrayType array_type,
2381 int number_of_elements);
2382 bool HasIndexedPropertiesInExternalArrayData();
2383 void* GetIndexedPropertiesExternalArrayData();
2384 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2385 int GetIndexedPropertiesExternalArrayDataLength();
2388 * Checks whether a callback is set by the
2389 * ObjectTemplate::SetCallAsFunctionHandler method.
2390 * When an Object is callable this method returns true.
2395 * Call an Object as a function if a callback is set by the
2396 * ObjectTemplate::SetCallAsFunctionHandler method.
2398 Local<Value> CallAsFunction(Handle<Value> recv,
2400 Handle<Value> argv[]);
2403 * Call an Object as a constructor if a callback is set by the
2404 * ObjectTemplate::SetCallAsFunctionHandler method.
2405 * Note: This method behaves like the Function::NewInstance method.
2407 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2409 static Local<Object> New(Isolate* isolate);
2411 V8_INLINE static Object* Cast(Value* obj);
2415 static void CheckCast(Value* obj);
2416 Local<Value> SlowGetInternalField(int index);
2417 void* SlowGetAlignedPointerFromInternalField(int index);
2422 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2424 class V8_EXPORT Array : public Object {
2426 uint32_t Length() const;
2429 * Clones an element at index |index|. Returns an empty
2430 * handle if cloning fails (for any reason).
2432 Local<Object> CloneElementAt(uint32_t index);
2435 * Creates a JavaScript array with the given length. If the length
2436 * is negative the returned array will have length 0.
2438 static Local<Array> New(Isolate* isolate, int length = 0);
2440 V8_INLINE static Array* Cast(Value* obj);
2443 static void CheckCast(Value* obj);
2447 template<typename T>
2450 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2451 : value_(that.value_) {
2455 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2456 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2457 // Fast primitive setters
2458 V8_INLINE void Set(bool value);
2459 V8_INLINE void Set(double i);
2460 V8_INLINE void Set(int32_t i);
2461 V8_INLINE void Set(uint32_t i);
2462 // Fast JS primitive setters
2463 V8_INLINE void SetNull();
2464 V8_INLINE void SetUndefined();
2465 V8_INLINE void SetEmptyString();
2466 // Convenience getter for Isolate
2467 V8_INLINE Isolate* GetIsolate();
2469 // Pointer setter: Uncompilable to prevent inadvertent misuse.
2470 template <typename S>
2471 V8_INLINE void Set(S* whatever);
2474 template<class F> friend class ReturnValue;
2475 template<class F> friend class FunctionCallbackInfo;
2476 template<class F> friend class PropertyCallbackInfo;
2477 template<class F, class G, class H> friend class PersistentValueMap;
2478 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2479 V8_INLINE internal::Object* GetDefaultValue();
2480 V8_INLINE explicit ReturnValue(internal::Object** slot);
2481 internal::Object** value_;
2486 * The argument information given to function call callbacks. This
2487 * class provides access to information about the context of the call,
2488 * including the receiver, the number and values of arguments, and
2489 * the holder of the function.
2491 template<typename T>
2492 class FunctionCallbackInfo {
2494 V8_INLINE int Length() const;
2495 V8_INLINE Local<Value> operator[](int i) const;
2496 V8_INLINE Local<Function> Callee() const;
2497 V8_INLINE Local<Object> This() const;
2498 V8_INLINE Local<Object> Holder() const;
2499 V8_INLINE bool IsConstructCall() const;
2500 V8_INLINE Local<Value> Data() const;
2501 V8_INLINE Isolate* GetIsolate() const;
2502 V8_INLINE ReturnValue<T> GetReturnValue() const;
2503 // This shouldn't be public, but the arm compiler needs it.
2504 static const int kArgsLength = 7;
2507 friend class internal::FunctionCallbackArguments;
2508 friend class internal::CustomArguments<FunctionCallbackInfo>;
2509 static const int kHolderIndex = 0;
2510 static const int kIsolateIndex = 1;
2511 static const int kReturnValueDefaultValueIndex = 2;
2512 static const int kReturnValueIndex = 3;
2513 static const int kDataIndex = 4;
2514 static const int kCalleeIndex = 5;
2515 static const int kContextSaveIndex = 6;
2517 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2518 internal::Object** values,
2520 bool is_construct_call);
2521 internal::Object** implicit_args_;
2522 internal::Object** values_;
2524 bool is_construct_call_;
2529 * The information passed to a property callback about the context
2530 * of the property access.
2532 template<typename T>
2533 class PropertyCallbackInfo {
2535 V8_INLINE Isolate* GetIsolate() const;
2536 V8_INLINE Local<Value> Data() const;
2537 V8_INLINE Local<Object> This() const;
2538 V8_INLINE Local<Object> Holder() const;
2539 V8_INLINE ReturnValue<T> GetReturnValue() const;
2540 // This shouldn't be public, but the arm compiler needs it.
2541 static const int kArgsLength = 6;
2544 friend class MacroAssembler;
2545 friend class internal::PropertyCallbackArguments;
2546 friend class internal::CustomArguments<PropertyCallbackInfo>;
2547 static const int kHolderIndex = 0;
2548 static const int kIsolateIndex = 1;
2549 static const int kReturnValueDefaultValueIndex = 2;
2550 static const int kReturnValueIndex = 3;
2551 static const int kDataIndex = 4;
2552 static const int kThisIndex = 5;
2554 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2555 internal::Object** args_;
2559 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2563 * A JavaScript function object (ECMA-262, 15.3).
2565 class V8_EXPORT Function : public Object {
2568 * Create a function in the current execution context
2569 * for a given FunctionCallback.
2571 static Local<Function> New(Isolate* isolate,
2572 FunctionCallback callback,
2573 Local<Value> data = Local<Value>(),
2576 Local<Object> NewInstance() const;
2577 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2578 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2579 void SetName(Handle<String> name);
2580 Handle<Value> GetName() const;
2583 * Name inferred from variable or property assignment of this function.
2584 * Used to facilitate debugging and profiling of JavaScript code written
2585 * in an OO style, where many functions are anonymous but are assigned
2586 * to object properties.
2588 Handle<Value> GetInferredName() const;
2591 * User-defined name assigned to the "displayName" property of this function.
2592 * Used to facilitate debugging and profiling of JavaScript code.
2594 Handle<Value> GetDisplayName() const;
2597 * Returns zero based line number of function body and
2598 * kLineOffsetNotFound if no information available.
2600 int GetScriptLineNumber() const;
2602 * Returns zero based column number of function body and
2603 * kLineOffsetNotFound if no information available.
2605 int GetScriptColumnNumber() const;
2608 * Tells whether this function is builtin.
2610 bool IsBuiltin() const;
2615 int ScriptId() const;
2618 * Returns the original function if this function is bound, else returns
2621 Local<Value> GetBoundFunction() const;
2623 ScriptOrigin GetScriptOrigin() const;
2624 V8_INLINE static Function* Cast(Value* obj);
2625 static const int kLineOffsetNotFound;
2629 static void CheckCast(Value* obj);
2634 * An instance of the built-in Promise constructor (ES6 draft).
2635 * This API is experimental. Only works with --harmony flag.
2637 class V8_EXPORT Promise : public Object {
2639 class V8_EXPORT Resolver : public Object {
2642 * Create a new resolver, along with an associated promise in pending state.
2644 static Local<Resolver> New(Isolate* isolate);
2647 * Extract the associated promise.
2649 Local<Promise> GetPromise();
2652 * Resolve/reject the associated promise with a given value.
2653 * Ignored if the promise is no longer pending.
2655 void Resolve(Handle<Value> value);
2656 void Reject(Handle<Value> value);
2658 V8_INLINE static Resolver* Cast(Value* obj);
2662 static void CheckCast(Value* obj);
2666 * Register a resolution/rejection handler with a promise.
2667 * The handler is given the respective resolution/rejection value as
2668 * an argument. If the promise is already resolved/rejected, the handler is
2669 * invoked at the end of turn.
2671 Local<Promise> Chain(Handle<Function> handler);
2672 Local<Promise> Catch(Handle<Function> handler);
2673 Local<Promise> Then(Handle<Function> handler);
2675 V8_INLINE static Promise* Cast(Value* obj);
2679 static void CheckCast(Value* obj);
2683 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2684 // The number of required internal fields can be defined by embedder.
2685 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2689 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2690 * This API is experimental and may change significantly.
2692 class V8_EXPORT ArrayBuffer : public Object {
2695 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2696 * The allocator is a global V8 setting. It should be set with
2697 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2699 * This API is experimental and may change significantly.
2701 class V8_EXPORT Allocator { // NOLINT
2703 virtual ~Allocator() {}
2706 * Allocate |length| bytes. Return NULL if allocation is not successful.
2707 * Memory should be initialized to zeroes.
2709 virtual void* Allocate(size_t length) = 0;
2712 * Allocate |length| bytes. Return NULL if allocation is not successful.
2713 * Memory does not have to be initialized.
2715 virtual void* AllocateUninitialized(size_t length) = 0;
2717 * Free the memory block of size |length|, pointed to by |data|.
2718 * That memory is guaranteed to be previously allocated by |Allocate|.
2720 virtual void Free(void* data, size_t length) = 0;
2724 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2725 * returns an instance of this class, populated, with a pointer to data
2728 * The Data pointer of ArrayBuffer::Contents is always allocated with
2729 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2731 * This API is experimental and may change significantly.
2733 class V8_EXPORT Contents { // NOLINT
2735 Contents() : data_(NULL), byte_length_(0) {}
2737 void* Data() const { return data_; }
2738 size_t ByteLength() const { return byte_length_; }
2742 size_t byte_length_;
2744 friend class ArrayBuffer;
2749 * Data length in bytes.
2751 size_t ByteLength() const;
2754 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2755 * Allocated memory will be owned by a created ArrayBuffer and
2756 * will be deallocated when it is garbage-collected,
2757 * unless the object is externalized.
2759 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2762 * Create a new ArrayBuffer over an existing memory block.
2763 * The created array buffer is immediately in externalized state.
2764 * The memory block will not be reclaimed when a created ArrayBuffer
2765 * is garbage-collected.
2767 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2768 size_t byte_length);
2771 * Returns true if ArrayBuffer is extrenalized, that is, does not
2772 * own its memory block.
2774 bool IsExternal() const;
2777 * Neuters this ArrayBuffer and all its views (typed arrays).
2778 * Neutering sets the byte length of the buffer and all typed arrays to zero,
2779 * preventing JavaScript from ever accessing underlying backing store.
2780 * ArrayBuffer should have been externalized.
2785 * Make this ArrayBuffer external. The pointer to underlying memory block
2786 * and byte length are returned as |Contents| structure. After ArrayBuffer
2787 * had been etxrenalized, it does no longer owns the memory block. The caller
2788 * should take steps to free memory when it is no longer needed.
2790 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2791 * that has been set with V8::SetArrayBufferAllocator.
2793 Contents Externalize();
2795 V8_INLINE static ArrayBuffer* Cast(Value* obj);
2797 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2801 static void CheckCast(Value* obj);
2805 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2806 // The number of required internal fields can be defined by embedder.
2807 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2812 * A base class for an instance of one of "views" over ArrayBuffer,
2813 * including TypedArrays and DataView (ES6 draft 15.13).
2815 * This API is experimental and may change significantly.
2817 class V8_EXPORT ArrayBufferView : public Object {
2820 * Returns underlying ArrayBuffer.
2822 Local<ArrayBuffer> Buffer();
2824 * Byte offset in |Buffer|.
2826 size_t ByteOffset();
2828 * Size of a view in bytes.
2830 size_t ByteLength();
2832 V8_INLINE static ArrayBufferView* Cast(Value* obj);
2834 static const int kInternalFieldCount =
2835 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2839 static void CheckCast(Value* obj);
2844 * A base class for an instance of TypedArray series of constructors
2845 * (ES6 draft 15.13.6).
2846 * This API is experimental and may change significantly.
2848 class V8_EXPORT TypedArray : public ArrayBufferView {
2851 * Number of elements in this typed array
2852 * (e.g. for Int16Array, |ByteLength|/2).
2856 V8_INLINE static TypedArray* Cast(Value* obj);
2860 static void CheckCast(Value* obj);
2865 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
2866 * This API is experimental and may change significantly.
2868 class V8_EXPORT Uint8Array : public TypedArray {
2870 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
2871 size_t byte_offset, size_t length);
2872 V8_INLINE static Uint8Array* Cast(Value* obj);
2876 static void CheckCast(Value* obj);
2881 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
2882 * This API is experimental and may change significantly.
2884 class V8_EXPORT Uint8ClampedArray : public TypedArray {
2886 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
2887 size_t byte_offset, size_t length);
2888 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
2891 Uint8ClampedArray();
2892 static void CheckCast(Value* obj);
2896 * An instance of Int8Array constructor (ES6 draft 15.13.6).
2897 * This API is experimental and may change significantly.
2899 class V8_EXPORT Int8Array : public TypedArray {
2901 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
2902 size_t byte_offset, size_t length);
2903 V8_INLINE static Int8Array* Cast(Value* obj);
2907 static void CheckCast(Value* obj);
2912 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
2913 * This API is experimental and may change significantly.
2915 class V8_EXPORT Uint16Array : public TypedArray {
2917 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
2918 size_t byte_offset, size_t length);
2919 V8_INLINE static Uint16Array* Cast(Value* obj);
2923 static void CheckCast(Value* obj);
2928 * An instance of Int16Array constructor (ES6 draft 15.13.6).
2929 * This API is experimental and may change significantly.
2931 class V8_EXPORT Int16Array : public TypedArray {
2933 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
2934 size_t byte_offset, size_t length);
2935 V8_INLINE static Int16Array* Cast(Value* obj);
2939 static void CheckCast(Value* obj);
2944 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
2945 * This API is experimental and may change significantly.
2947 class V8_EXPORT Uint32Array : public TypedArray {
2949 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
2950 size_t byte_offset, size_t length);
2951 V8_INLINE static Uint32Array* Cast(Value* obj);
2955 static void CheckCast(Value* obj);
2960 * An instance of Int32Array constructor (ES6 draft 15.13.6).
2961 * This API is experimental and may change significantly.
2963 class V8_EXPORT Int32Array : public TypedArray {
2965 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
2966 size_t byte_offset, size_t length);
2967 V8_INLINE static Int32Array* Cast(Value* obj);
2971 static void CheckCast(Value* obj);
2976 * An instance of Float32Array constructor (ES6 draft 15.13.6).
2977 * This API is experimental and may change significantly.
2979 class V8_EXPORT Float32Array : public TypedArray {
2981 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
2982 size_t byte_offset, size_t length);
2983 V8_INLINE static Float32Array* Cast(Value* obj);
2987 static void CheckCast(Value* obj);
2991 class V8_EXPORT Float32x4Array : public TypedArray {
2993 static Local<Float32x4Array> New(Handle<ArrayBuffer> array_buffer,
2994 size_t byte_offset, size_t length);
2995 V8_INLINE static Float32x4Array* Cast(Value* obj);
2999 static void CheckCast(Value* obj);
3003 class V8_EXPORT Float64x2Array : public TypedArray {
3005 static Local<Float64x2Array> New(Handle<ArrayBuffer> array_buffer,
3006 size_t byte_offset, size_t length);
3007 V8_INLINE static Float64x2Array* Cast(Value* obj);
3011 static void CheckCast(Value* obj);
3015 class V8_EXPORT Int32x4Array : public TypedArray {
3017 static Local<Int32x4Array> New(Handle<ArrayBuffer> array_buffer,
3018 size_t byte_offset, size_t length);
3019 V8_INLINE static Int32x4Array* Cast(Value* obj);
3023 static void CheckCast(Value* obj);
3028 * An instance of Float64Array constructor (ES6 draft 15.13.6).
3029 * This API is experimental and may change significantly.
3031 class V8_EXPORT Float64Array : public TypedArray {
3033 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
3034 size_t byte_offset, size_t length);
3035 V8_INLINE static Float64Array* Cast(Value* obj);
3039 static void CheckCast(Value* obj);
3044 * An instance of DataView constructor (ES6 draft 15.13.7).
3045 * This API is experimental and may change significantly.
3047 class V8_EXPORT DataView : public ArrayBufferView {
3049 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
3050 size_t byte_offset, size_t length);
3051 V8_INLINE static DataView* Cast(Value* obj);
3055 static void CheckCast(Value* obj);
3060 * An instance of the built-in Date constructor (ECMA-262, 15.9).
3062 class V8_EXPORT Date : public Object {
3064 static Local<Value> New(Isolate* isolate, double time);
3067 * A specialization of Value::NumberValue that is more efficient
3068 * because we know the structure of this object.
3070 double ValueOf() const;
3072 V8_INLINE static Date* Cast(v8::Value* obj);
3075 * Notification that the embedder has changed the time zone,
3076 * daylight savings time, or other date / time configuration
3077 * parameters. V8 keeps a cache of various values used for
3078 * date / time computation. This notification will reset
3079 * those cached values for the current context so that date /
3080 * time configuration changes would be reflected in the Date
3083 * This API should not be called more than needed as it will
3084 * negatively impact the performance of date operations.
3086 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
3089 static void CheckCast(v8::Value* obj);
3094 * A Number object (ECMA-262, 4.3.21).
3096 class V8_EXPORT NumberObject : public Object {
3098 static Local<Value> New(Isolate* isolate, double value);
3100 double ValueOf() const;
3102 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3105 static void CheckCast(v8::Value* obj);
3110 * A Boolean object (ECMA-262, 4.3.15).
3112 class V8_EXPORT BooleanObject : public Object {
3114 static Local<Value> New(bool value);
3116 bool ValueOf() const;
3118 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3121 static void CheckCast(v8::Value* obj);
3126 * A String object (ECMA-262, 4.3.18).
3128 class V8_EXPORT StringObject : public Object {
3130 static Local<Value> New(Handle<String> value);
3132 Local<String> ValueOf() const;
3134 V8_INLINE static StringObject* Cast(v8::Value* obj);
3137 static void CheckCast(v8::Value* obj);
3142 * A Symbol object (ECMA-262 edition 6).
3144 * This is an experimental feature. Use at your own risk.
3146 class V8_EXPORT SymbolObject : public Object {
3148 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3150 Local<Symbol> ValueOf() const;
3152 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3155 static void CheckCast(v8::Value* obj);
3160 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3162 class V8_EXPORT RegExp : public Object {
3165 * Regular expression flag bits. They can be or'ed to enable a set
3176 * Creates a regular expression from the given pattern string and
3177 * the flags bit field. May throw a JavaScript exception as
3178 * described in ECMA-262, 15.10.4.1.
3181 * RegExp::New(v8::String::New("foo"),
3182 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3183 * is equivalent to evaluating "/foo/gm".
3185 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3188 * Returns the value of the source property: a string representing
3189 * the regular expression.
3191 Local<String> GetSource() const;
3194 * Returns the flags bit field.
3196 Flags GetFlags() const;
3198 V8_INLINE static RegExp* Cast(v8::Value* obj);
3201 static void CheckCast(v8::Value* obj);
3206 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3207 * to associate C++ data structures with JavaScript objects.
3209 class V8_EXPORT External : public Value {
3211 static Local<External> New(Isolate* isolate, void* value);
3212 V8_INLINE static External* Cast(Value* obj);
3213 void* Value() const;
3215 static void CheckCast(v8::Value* obj);
3219 // --- Templates ---
3223 * The superclass of object and function templates.
3225 class V8_EXPORT Template : public Data {
3227 /** Adds a property to each instance created by this template.*/
3228 void Set(Handle<String> name, Handle<Data> value,
3229 PropertyAttribute attributes = None);
3230 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3232 void SetAccessorProperty(
3234 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3235 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3236 PropertyAttribute attribute = None,
3237 AccessControl settings = DEFAULT);
3240 * Whenever the property with the given name is accessed on objects
3241 * created from this Template the getter and setter callbacks
3242 * are called instead of getting and setting the property directly
3243 * on the JavaScript object.
3245 * \param name The name of the property for which an accessor is added.
3246 * \param getter The callback to invoke when getting the property.
3247 * \param setter The callback to invoke when setting the property.
3248 * \param data A piece of data that will be passed to the getter and setter
3249 * callbacks whenever they are invoked.
3250 * \param settings Access control settings for the accessor. This is a bit
3251 * field consisting of one of more of
3252 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3253 * The default is to not allow cross-context access.
3254 * ALL_CAN_READ means that all cross-context reads are allowed.
3255 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3256 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3257 * cross-context access.
3258 * \param attribute The attributes of the property for which an accessor
3260 * \param signature The signature describes valid receivers for the accessor
3261 * and is used to perform implicit instance checks against them. If the
3262 * receiver is incompatible (i.e. is not an instance of the constructor as
3263 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3264 * thrown and no callback is invoked.
3266 void SetNativeDataProperty(Local<String> name,
3267 AccessorGetterCallback getter,
3268 AccessorSetterCallback setter = 0,
3269 // TODO(dcarney): gcc can't handle Local below
3270 Handle<Value> data = Handle<Value>(),
3271 PropertyAttribute attribute = None,
3272 Local<AccessorSignature> signature =
3273 Local<AccessorSignature>(),
3274 AccessControl settings = DEFAULT);
3276 // This function is not yet stable and should not be used at this time.
3277 bool SetDeclaredAccessor(Local<String> name,
3278 Local<DeclaredAccessorDescriptor> descriptor,
3279 PropertyAttribute attribute = None,
3280 Local<AccessorSignature> signature =
3281 Local<AccessorSignature>(),
3282 AccessControl settings = DEFAULT);
3287 friend class ObjectTemplate;
3288 friend class FunctionTemplate;
3293 * NamedProperty[Getter|Setter] are used as interceptors on object.
3294 * See ObjectTemplate::SetNamedPropertyHandler.
3296 typedef void (*NamedPropertyGetterCallback)(
3297 Local<String> property,
3298 const PropertyCallbackInfo<Value>& info);
3302 * Returns the value if the setter intercepts the request.
3303 * Otherwise, returns an empty handle.
3305 typedef void (*NamedPropertySetterCallback)(
3306 Local<String> property,
3308 const PropertyCallbackInfo<Value>& info);
3312 * Returns a non-empty handle if the interceptor intercepts the request.
3313 * The result is an integer encoding property attributes (like v8::None,
3314 * v8::DontEnum, etc.)
3316 typedef void (*NamedPropertyQueryCallback)(
3317 Local<String> property,
3318 const PropertyCallbackInfo<Integer>& info);
3322 * Returns a non-empty handle if the deleter intercepts the request.
3323 * The return value is true if the property could be deleted and false
3326 typedef void (*NamedPropertyDeleterCallback)(
3327 Local<String> property,
3328 const PropertyCallbackInfo<Boolean>& info);
3332 * Returns an array containing the names of the properties the named
3333 * property getter intercepts.
3335 typedef void (*NamedPropertyEnumeratorCallback)(
3336 const PropertyCallbackInfo<Array>& info);
3340 * Returns the value of the property if the getter intercepts the
3341 * request. Otherwise, returns an empty handle.
3343 typedef void (*IndexedPropertyGetterCallback)(
3345 const PropertyCallbackInfo<Value>& info);
3349 * Returns the value if the setter intercepts the request.
3350 * Otherwise, returns an empty handle.
3352 typedef void (*IndexedPropertySetterCallback)(
3355 const PropertyCallbackInfo<Value>& info);
3359 * Returns a non-empty handle if the interceptor intercepts the request.
3360 * The result is an integer encoding property attributes.
3362 typedef void (*IndexedPropertyQueryCallback)(
3364 const PropertyCallbackInfo<Integer>& info);
3368 * Returns a non-empty handle if the deleter intercepts the request.
3369 * The return value is true if the property could be deleted and false
3372 typedef void (*IndexedPropertyDeleterCallback)(
3374 const PropertyCallbackInfo<Boolean>& info);
3378 * Returns an array containing the indices of the properties the
3379 * indexed property getter intercepts.
3381 typedef void (*IndexedPropertyEnumeratorCallback)(
3382 const PropertyCallbackInfo<Array>& info);
3386 * Access type specification.
3398 * Returns true if cross-context access should be allowed to the named
3399 * property with the given key on the host object.
3401 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3408 * Returns true if cross-context access should be allowed to the indexed
3409 * property with the given index on the host object.
3411 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3418 * A FunctionTemplate is used to create functions at runtime. There
3419 * can only be one function created from a FunctionTemplate in a
3420 * context. The lifetime of the created function is equal to the
3421 * lifetime of the context. So in case the embedder needs to create
3422 * temporary functions that can be collected using Scripts is
3425 * A FunctionTemplate can have properties, these properties are added to the
3426 * function object when it is created.
3428 * A FunctionTemplate has a corresponding instance template which is
3429 * used to create object instances when the function is used as a
3430 * constructor. Properties added to the instance template are added to
3431 * each object instance.
3433 * A FunctionTemplate can have a prototype template. The prototype template
3434 * is used to create the prototype object of the function.
3436 * The following example shows how to use a FunctionTemplate:
3439 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3440 * t->Set("func_property", v8::Number::New(1));
3442 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3443 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3444 * proto_t->Set("proto_const", v8::Number::New(2));
3446 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3447 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3448 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3449 * instance_t->Set("instance_property", Number::New(3));
3451 * v8::Local<v8::Function> function = t->GetFunction();
3452 * v8::Local<v8::Object> instance = function->NewInstance();
3455 * Let's use "function" as the JS variable name of the function object
3456 * and "instance" for the instance object created above. The function
3457 * and the instance will have the following properties:
3460 * func_property in function == true;
3461 * function.func_property == 1;
3463 * function.prototype.proto_method() invokes 'InvokeCallback'
3464 * function.prototype.proto_const == 2;
3466 * instance instanceof function == true;
3467 * instance.instance_accessor calls 'InstanceAccessorCallback'
3468 * instance.instance_property == 3;
3471 * A FunctionTemplate can inherit from another one by calling the
3472 * FunctionTemplate::Inherit method. The following graph illustrates
3473 * the semantics of inheritance:
3476 * FunctionTemplate Parent -> Parent() . prototype -> { }
3478 * | Inherit(Parent) | .__proto__
3480 * FunctionTemplate Child -> Child() . prototype -> { }
3483 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3484 * object of the Child() function has __proto__ pointing to the
3485 * Parent() function's prototype object. An instance of the Child
3486 * function has all properties on Parent's instance templates.
3488 * Let Parent be the FunctionTemplate initialized in the previous
3489 * section and create a Child FunctionTemplate by:
3492 * Local<FunctionTemplate> parent = t;
3493 * Local<FunctionTemplate> child = FunctionTemplate::New();
3494 * child->Inherit(parent);
3496 * Local<Function> child_function = child->GetFunction();
3497 * Local<Object> child_instance = child_function->NewInstance();
3500 * The Child function and Child instance will have the following
3504 * child_func.prototype.__proto__ == function.prototype;
3505 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3506 * child_instance.instance_property == 3;
3509 class V8_EXPORT FunctionTemplate : public Template {
3511 /** Creates a function template.*/
3512 static Local<FunctionTemplate> New(
3514 FunctionCallback callback = 0,
3515 Handle<Value> data = Handle<Value>(),
3516 Handle<Signature> signature = Handle<Signature>(),
3519 /** Returns the unique function instance in the current execution context.*/
3520 Local<Function> GetFunction();
3523 * Set the call-handler callback for a FunctionTemplate. This
3524 * callback is called whenever the function created from this
3525 * FunctionTemplate is called.
3527 void SetCallHandler(FunctionCallback callback,
3528 Handle<Value> data = Handle<Value>());
3530 /** Set the predefined length property for the FunctionTemplate. */
3531 void SetLength(int length);
3533 /** Get the InstanceTemplate. */
3534 Local<ObjectTemplate> InstanceTemplate();
3536 /** Causes the function template to inherit from a parent function template.*/
3537 void Inherit(Handle<FunctionTemplate> parent);
3540 * A PrototypeTemplate is the template used to create the prototype object
3541 * of the function created by this template.
3543 Local<ObjectTemplate> PrototypeTemplate();
3546 * Set the class name of the FunctionTemplate. This is used for
3547 * printing objects created with the function created from the
3548 * FunctionTemplate as its constructor.
3550 void SetClassName(Handle<String> name);
3553 * Determines whether the __proto__ accessor ignores instances of
3554 * the function template. If instances of the function template are
3555 * ignored, __proto__ skips all instances and instead returns the
3556 * next object in the prototype chain.
3558 * Call with a value of true to make the __proto__ accessor ignore
3559 * instances of the function template. Call with a value of false
3560 * to make the __proto__ accessor not ignore instances of the
3561 * function template. By default, instances of a function template
3564 void SetHiddenPrototype(bool value);
3567 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3568 * of functions created from this FunctionTemplate to true.
3570 void ReadOnlyPrototype();
3573 * Removes the prototype property from functions created from this
3576 void RemovePrototype();
3579 * Returns true if the given object is an instance of this function
3582 bool HasInstance(Handle<Value> object);
3586 friend class Context;
3587 friend class ObjectTemplate;
3592 * An ObjectTemplate is used to create objects at runtime.
3594 * Properties added to an ObjectTemplate are added to each object
3595 * created from the ObjectTemplate.
3597 class V8_EXPORT ObjectTemplate : public Template {
3599 /** Creates an ObjectTemplate. */
3600 static Local<ObjectTemplate> New(Isolate* isolate);
3601 // Will be deprecated soon.
3602 static Local<ObjectTemplate> New();
3604 /** Creates a new instance of this template.*/
3605 Local<Object> NewInstance();
3608 * Sets an accessor on the object template.
3610 * Whenever the property with the given name is accessed on objects
3611 * created from this ObjectTemplate the getter and setter callbacks
3612 * are called instead of getting and setting the property directly
3613 * on the JavaScript object.
3615 * \param name The name of the property for which an accessor is added.
3616 * \param getter The callback to invoke when getting the property.
3617 * \param setter The callback to invoke when setting the property.
3618 * \param data A piece of data that will be passed to the getter and setter
3619 * callbacks whenever they are invoked.
3620 * \param settings Access control settings for the accessor. This is a bit
3621 * field consisting of one of more of
3622 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3623 * The default is to not allow cross-context access.
3624 * ALL_CAN_READ means that all cross-context reads are allowed.
3625 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3626 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3627 * cross-context access.
3628 * \param attribute The attributes of the property for which an accessor
3630 * \param signature The signature describes valid receivers for the accessor
3631 * and is used to perform implicit instance checks against them. If the
3632 * receiver is incompatible (i.e. is not an instance of the constructor as
3633 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3634 * thrown and no callback is invoked.
3636 void SetAccessor(Handle<String> name,
3637 AccessorGetterCallback getter,
3638 AccessorSetterCallback setter = 0,
3639 Handle<Value> data = Handle<Value>(),
3640 AccessControl settings = DEFAULT,
3641 PropertyAttribute attribute = None,
3642 Handle<AccessorSignature> signature =
3643 Handle<AccessorSignature>());
3646 * Sets a named property handler on the object template.
3648 * Whenever a named property is accessed on objects created from
3649 * this object template, the provided callback is invoked instead of
3650 * accessing the property directly on the JavaScript object.
3652 * \param getter The callback to invoke when getting a property.
3653 * \param setter The callback to invoke when setting a property.
3654 * \param query The callback to invoke to check if a property is present,
3655 * and if present, get its attributes.
3656 * \param deleter The callback to invoke when deleting a property.
3657 * \param enumerator The callback to invoke to enumerate all the named
3658 * properties of an object.
3659 * \param data A piece of data that will be passed to the callbacks
3660 * whenever they are invoked.
3662 void SetNamedPropertyHandler(
3663 NamedPropertyGetterCallback getter,
3664 NamedPropertySetterCallback setter = 0,
3665 NamedPropertyQueryCallback query = 0,
3666 NamedPropertyDeleterCallback deleter = 0,
3667 NamedPropertyEnumeratorCallback enumerator = 0,
3668 Handle<Value> data = Handle<Value>());
3671 * Sets an indexed property handler on the object template.
3673 * Whenever an indexed property is accessed on objects created from
3674 * this object template, the provided callback is invoked instead of
3675 * accessing the property directly on the JavaScript object.
3677 * \param getter The callback to invoke when getting a property.
3678 * \param setter The callback to invoke when setting a property.
3679 * \param query The callback to invoke to check if an object has a property.
3680 * \param deleter The callback to invoke when deleting a property.
3681 * \param enumerator The callback to invoke to enumerate all the indexed
3682 * properties of an object.
3683 * \param data A piece of data that will be passed to the callbacks
3684 * whenever they are invoked.
3686 void SetIndexedPropertyHandler(
3687 IndexedPropertyGetterCallback getter,
3688 IndexedPropertySetterCallback setter = 0,
3689 IndexedPropertyQueryCallback query = 0,
3690 IndexedPropertyDeleterCallback deleter = 0,
3691 IndexedPropertyEnumeratorCallback enumerator = 0,
3692 Handle<Value> data = Handle<Value>());
3695 * Sets the callback to be used when calling instances created from
3696 * this template as a function. If no callback is set, instances
3697 * behave like normal JavaScript objects that cannot be called as a
3700 void SetCallAsFunctionHandler(FunctionCallback callback,
3701 Handle<Value> data = Handle<Value>());
3704 * Mark object instances of the template as undetectable.
3706 * In many ways, undetectable objects behave as though they are not
3707 * there. They behave like 'undefined' in conditionals and when
3708 * printed. However, properties can be accessed and called as on
3711 void MarkAsUndetectable();
3714 * Sets access check callbacks on the object template.
3716 * When accessing properties on instances of this object template,
3717 * the access check callback will be called to determine whether or
3718 * not to allow cross-context access to the properties.
3719 * The last parameter specifies whether access checks are turned
3720 * on by default on instances. If access checks are off by default,
3721 * they can be turned on on individual instances by calling
3722 * Object::TurnOnAccessCheck().
3724 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3725 IndexedSecurityCallback indexed_handler,
3726 Handle<Value> data = Handle<Value>(),
3727 bool turned_on_by_default = true);
3730 * Gets the number of internal fields for objects generated from
3733 int InternalFieldCount();
3736 * Sets the number of internal fields for objects generated from
3739 void SetInternalFieldCount(int value);
3743 static Local<ObjectTemplate> New(internal::Isolate* isolate,
3744 Handle<FunctionTemplate> constructor);
3745 friend class FunctionTemplate;
3750 * A Signature specifies which receivers and arguments are valid
3751 * parameters to a function.
3753 class V8_EXPORT Signature : public Data {
3755 static Local<Signature> New(Isolate* isolate,
3756 Handle<FunctionTemplate> receiver =
3757 Handle<FunctionTemplate>(),
3759 Handle<FunctionTemplate> argv[] = 0);
3767 * An AccessorSignature specifies which receivers are valid parameters
3768 * to an accessor callback.
3770 class V8_EXPORT AccessorSignature : public Data {
3772 static Local<AccessorSignature> New(Isolate* isolate,
3773 Handle<FunctionTemplate> receiver =
3774 Handle<FunctionTemplate>());
3777 AccessorSignature();
3781 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3783 DeclaredAccessorDescriptor();
3787 class V8_EXPORT ObjectOperationDescriptor : public Data {
3789 // This function is not yet stable and should not be used at this time.
3790 static Local<RawOperationDescriptor> NewInternalFieldDereference(
3792 int internal_field);
3794 ObjectOperationDescriptor();
3798 enum DeclaredAccessorDescriptorDataType {
3799 kDescriptorBoolType,
3800 kDescriptorInt8Type, kDescriptorUint8Type,
3801 kDescriptorInt16Type, kDescriptorUint16Type,
3802 kDescriptorInt32Type, kDescriptorUint32Type,
3803 kDescriptorFloatType, kDescriptorDoubleType
3807 class V8_EXPORT RawOperationDescriptor : public Data {
3809 Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3810 Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3811 Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3812 int16_t byte_offset);
3813 Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3814 void* compare_value);
3815 Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3817 DeclaredAccessorDescriptorDataType data_type,
3818 uint8_t bool_offset = 0);
3819 Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3821 uint8_t compare_value);
3822 Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3825 uint16_t compare_value);
3826 Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3829 uint32_t compare_value);
3832 RawOperationDescriptor();
3837 * A utility for determining the type of objects based on the template
3838 * they were constructed from.
3840 class V8_EXPORT TypeSwitch : public Data {
3842 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3843 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3844 int match(Handle<Value> value);
3850 // --- Extensions ---
3852 class V8_EXPORT ExternalAsciiStringResourceImpl
3853 : public String::ExternalAsciiStringResource {
3855 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
3856 ExternalAsciiStringResourceImpl(const char* data, size_t length)
3857 : data_(data), length_(length) {}
3858 const char* data() const { return data_; }
3859 size_t length() const { return length_; }
3869 class V8_EXPORT Extension { // NOLINT
3871 // Note that the strings passed into this constructor must live as long
3872 // as the Extension itself.
3873 Extension(const char* name,
3874 const char* source = 0,
3876 const char** deps = 0,
3877 int source_length = -1);
3878 virtual ~Extension() { }
3879 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
3880 v8::Isolate* isolate, v8::Handle<v8::String> name) {
3881 return v8::Handle<v8::FunctionTemplate>();
3884 const char* name() const { return name_; }
3885 size_t source_length() const { return source_length_; }
3886 const String::ExternalAsciiStringResource* source() const {
3888 int dependency_count() { return dep_count_; }
3889 const char** dependencies() { return deps_; }
3890 void set_auto_enable(bool value) { auto_enable_ = value; }
3891 bool auto_enable() { return auto_enable_; }
3895 size_t source_length_; // expected to initialize before source_
3896 ExternalAsciiStringResourceImpl source_;
3901 // Disallow copying and assigning.
3902 Extension(const Extension&);
3903 void operator=(const Extension&);
3907 void V8_EXPORT RegisterExtension(Extension* extension);
3912 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
3913 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
3914 V8_INLINE Handle<Boolean> True(Isolate* isolate);
3915 V8_INLINE Handle<Boolean> False(Isolate* isolate);
3919 * A set of constraints that specifies the limits of the runtime's memory use.
3920 * You must set the heap size before initializing the VM - the size cannot be
3921 * adjusted after the VM is initialized.
3923 * If you are using threads then you should hold the V8::Locker lock while
3924 * setting the stack limit and you must set a non-default stack limit separately
3927 class V8_EXPORT ResourceConstraints {
3929 ResourceConstraints();
3932 * Configures the constraints with reasonable default values based on the
3933 * capabilities of the current device the VM is running on.
3935 * \param physical_memory The total amount of physical memory on the current
3937 * \param virtual_memory_limit The amount of virtual memory on the current
3938 * device, in bytes, or zero, if there is no limit.
3939 * \param number_of_processors The number of CPUs available on the current
3942 void ConfigureDefaults(uint64_t physical_memory,
3943 uint64_t virtual_memory_limit,
3944 uint32_t number_of_processors);
3946 int max_semi_space_size() const { return max_semi_space_size_; }
3947 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
3948 int max_old_space_size() const { return max_old_space_size_; }
3949 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
3950 int max_executable_size() const { return max_executable_size_; }
3951 void set_max_executable_size(int value) { max_executable_size_ = value; }
3952 uint32_t* stack_limit() const { return stack_limit_; }
3953 // Sets an address beyond which the VM's stack may not grow.
3954 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
3955 int max_available_threads() const { return max_available_threads_; }
3956 // Set the number of threads available to V8, assuming at least 1.
3957 void set_max_available_threads(int value) {
3958 max_available_threads_ = value;
3960 size_t code_range_size() const { return code_range_size_; }
3961 void set_code_range_size(size_t value) {
3962 code_range_size_ = value;
3966 int max_semi_space_size_;
3967 int max_old_space_size_;
3968 int max_executable_size_;
3969 uint32_t* stack_limit_;
3970 int max_available_threads_;
3971 size_t code_range_size_;
3976 * Sets the given ResourceConstraints on the given Isolate.
3978 bool V8_EXPORT SetResourceConstraints(Isolate* isolate,
3979 ResourceConstraints* constraints);
3982 // --- Exceptions ---
3985 typedef void (*FatalErrorCallback)(const char* location, const char* message);
3988 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
3992 typedef void (*LogEventCallback)(const char* name, int event);
3995 * Create new error objects by calling the corresponding error object
3996 * constructor with the message.
3998 class V8_EXPORT Exception {
4000 static Local<Value> RangeError(Handle<String> message);
4001 static Local<Value> ReferenceError(Handle<String> message);
4002 static Local<Value> SyntaxError(Handle<String> message);
4003 static Local<Value> TypeError(Handle<String> message);
4004 static Local<Value> Error(Handle<String> message);
4008 // --- Counters Callbacks ---
4010 typedef int* (*CounterLookupCallback)(const char* name);
4012 typedef void* (*CreateHistogramCallback)(const char* name,
4017 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4019 // --- Memory Allocation Callback ---
4021 kObjectSpaceNewSpace = 1 << 0,
4022 kObjectSpaceOldPointerSpace = 1 << 1,
4023 kObjectSpaceOldDataSpace = 1 << 2,
4024 kObjectSpaceCodeSpace = 1 << 3,
4025 kObjectSpaceMapSpace = 1 << 4,
4026 kObjectSpaceLoSpace = 1 << 5,
4028 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
4029 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
4033 enum AllocationAction {
4034 kAllocationActionAllocate = 1 << 0,
4035 kAllocationActionFree = 1 << 1,
4036 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
4039 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
4040 AllocationAction action,
4043 // --- Leave Script Callback ---
4044 typedef void (*CallCompletedCallback)();
4046 // --- Microtask Callback ---
4047 typedef void (*MicrotaskCallback)(void* data);
4049 // --- Failed Access Check Callback ---
4050 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4054 // --- AllowCodeGenerationFromStrings callbacks ---
4057 * Callback to check if code generation from strings is allowed. See
4058 * Context::AllowCodeGenerationFromStrings.
4060 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
4062 // --- Garbage Collection Callbacks ---
4065 * Applications can register callback functions which will be called
4066 * before and after a garbage collection. Allocations are not
4067 * allowed in the callback functions, you therefore cannot manipulate
4068 * objects (set or delete properties for example) since it is possible
4069 * such operations will result in the allocation of objects.
4072 kGCTypeScavenge = 1 << 0,
4073 kGCTypeMarkSweepCompact = 1 << 1,
4074 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
4077 enum GCCallbackFlags {
4078 kNoGCCallbackFlags = 0,
4079 kGCCallbackFlagCompacted = 1 << 0,
4080 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
4081 kGCCallbackFlagForced = 1 << 2
4084 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4085 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4087 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4091 * Collection of V8 heap information.
4093 * Instances of this class can be passed to v8::V8::HeapStatistics to
4094 * get heap statistics from V8.
4096 class V8_EXPORT HeapStatistics {
4099 size_t total_heap_size() { return total_heap_size_; }
4100 size_t total_heap_size_executable() { return total_heap_size_executable_; }
4101 size_t total_physical_size() { return total_physical_size_; }
4102 size_t used_heap_size() { return used_heap_size_; }
4103 size_t heap_size_limit() { return heap_size_limit_; }
4106 size_t total_heap_size_;
4107 size_t total_heap_size_executable_;
4108 size_t total_physical_size_;
4109 size_t used_heap_size_;
4110 size_t heap_size_limit_;
4113 friend class Isolate;
4117 class RetainedObjectInfo;
4120 * Isolate represents an isolated instance of the V8 engine. V8
4121 * isolates have completely separate states. Objects from one isolate
4122 * must not be used in other isolates. When V8 is initialized a
4123 * default isolate is implicitly created and entered. The embedder
4124 * can create additional isolates and use them in parallel in multiple
4125 * threads. An isolate can be entered by at most one thread at any
4126 * given time. The Locker/Unlocker API must be used to synchronize.
4128 class V8_EXPORT Isolate {
4131 * Stack-allocated class which sets the isolate for all operations
4132 * executed within a local scope.
4134 class V8_EXPORT Scope {
4136 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4140 ~Scope() { isolate_->Exit(); }
4143 Isolate* const isolate_;
4145 // Prevent copying of Scope objects.
4146 Scope(const Scope&);
4147 Scope& operator=(const Scope&);
4152 * Assert that no Javascript code is invoked.
4154 class V8_EXPORT DisallowJavascriptExecutionScope {
4156 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4158 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4159 ~DisallowJavascriptExecutionScope();
4165 // Prevent copying of Scope objects.
4166 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4167 DisallowJavascriptExecutionScope& operator=(
4168 const DisallowJavascriptExecutionScope&);
4173 * Introduce exception to DisallowJavascriptExecutionScope.
4175 class V8_EXPORT AllowJavascriptExecutionScope {
4177 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4178 ~AllowJavascriptExecutionScope();
4181 void* internal_throws_;
4182 void* internal_assert_;
4184 // Prevent copying of Scope objects.
4185 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4186 AllowJavascriptExecutionScope& operator=(
4187 const AllowJavascriptExecutionScope&);
4191 * Do not run microtasks while this scope is active, even if microtasks are
4192 * automatically executed otherwise.
4194 class V8_EXPORT SuppressMicrotaskExecutionScope {
4196 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4197 ~SuppressMicrotaskExecutionScope();
4200 internal::Isolate* isolate_;
4202 // Prevent copying of Scope objects.
4203 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4204 SuppressMicrotaskExecutionScope& operator=(
4205 const SuppressMicrotaskExecutionScope&);
4209 * Types of garbage collections that can be requested via
4210 * RequestGarbageCollectionForTesting.
4212 enum GarbageCollectionType {
4213 kFullGarbageCollection,
4214 kMinorGarbageCollection
4218 * Features reported via the SetUseCounterCallback callback. Do not chang
4219 * assigned numbers of existing items; add new features to the end of this
4222 enum UseCounterFeature {
4224 kUseCounterFeatureCount // This enum value must be last.
4227 typedef void (*UseCounterCallback)(Isolate* isolate,
4228 UseCounterFeature feature);
4232 * Creates a new isolate. Does not change the currently entered
4235 * When an isolate is no longer used its resources should be freed
4236 * by calling Dispose(). Using the delete operator is not allowed.
4238 static Isolate* New();
4241 * Returns the entered isolate for the current thread or NULL in
4242 * case there is no current isolate.
4244 static Isolate* GetCurrent();
4247 * Methods below this point require holding a lock (using Locker) in
4248 * a multi-threaded environment.
4252 * Sets this isolate as the entered one for the current thread.
4253 * Saves the previously entered one (if any), so that it can be
4254 * restored when exiting. Re-entering an isolate is allowed.
4259 * Exits this isolate by restoring the previously entered one in the
4260 * current thread. The isolate may still stay the same, if it was
4261 * entered more than once.
4263 * Requires: this == Isolate::GetCurrent().
4268 * Disposes the isolate. The isolate must not be entered by any
4269 * thread to be disposable.
4274 * Associate embedder-specific data with the isolate. |slot| has to be
4275 * between 0 and GetNumberOfDataSlots() - 1.
4277 V8_INLINE void SetData(uint32_t slot, void* data);
4280 * Retrieve embedder-specific data from the isolate.
4281 * Returns NULL if SetData has never been called for the given |slot|.
4283 V8_INLINE void* GetData(uint32_t slot);
4286 * Returns the maximum number of available embedder data slots. Valid slots
4287 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4289 V8_INLINE static uint32_t GetNumberOfDataSlots();
4292 * Get statistics about the heap memory usage.
4294 void GetHeapStatistics(HeapStatistics* heap_statistics);
4297 * Adjusts the amount of registered external memory. Used to give V8 an
4298 * indication of the amount of externally allocated memory that is kept alive
4299 * by JavaScript objects. V8 uses this to decide when to perform global
4300 * garbage collections. Registering externally allocated memory will trigger
4301 * global garbage collections more often than it would otherwise in an attempt
4302 * to garbage collect the JavaScript objects that keep the externally
4303 * allocated memory alive.
4305 * \param change_in_bytes the change in externally allocated memory that is
4306 * kept alive by JavaScript objects.
4307 * \returns the adjusted value.
4310 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4313 * Returns heap profiler for this isolate. Will return NULL until the isolate
4316 HeapProfiler* GetHeapProfiler();
4319 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4320 * is initialized. It is the embedder's responsibility to stop all CPU
4321 * profiling activities if it has started any.
4323 CpuProfiler* GetCpuProfiler();
4325 /** Returns true if this isolate has a current context. */
4328 /** Returns the context that is on the top of the stack. */
4329 Local<Context> GetCurrentContext();
4332 * Returns the context of the calling JavaScript code. That is the
4333 * context of the top-most JavaScript frame. If there are no
4334 * JavaScript frames an empty handle is returned.
4336 Local<Context> GetCallingContext();
4338 /** Returns the last entered context. */
4339 Local<Context> GetEnteredContext();
4342 * Schedules an exception to be thrown when returning to JavaScript. When an
4343 * exception has been scheduled it is illegal to invoke any JavaScript
4344 * operation; the caller must return immediately and only after the exception
4345 * has been handled does it become legal to invoke JavaScript operations.
4347 Local<Value> ThrowException(Local<Value> exception);
4350 * Allows the host application to group objects together. If one
4351 * object in the group is alive, all objects in the group are alive.
4352 * After each garbage collection, object groups are removed. It is
4353 * intended to be used in the before-garbage-collection callback
4354 * function, for instance to simulate DOM tree connections among JS
4355 * wrapper objects. Object groups for all dependent handles need to
4356 * be provided for kGCTypeMarkSweepCompact collections, for all other
4357 * garbage collection types it is sufficient to provide object groups
4358 * for partially dependent handles only.
4360 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4364 * Allows the host application to declare implicit references from an object
4365 * group to an object. If the objects of the object group are alive, the child
4366 * object is alive too. After each garbage collection, all implicit references
4367 * are removed. It is intended to be used in the before-garbage-collection
4368 * callback function.
4370 template<typename T> void SetReferenceFromGroup(UniqueId id,
4371 const Persistent<T>& child);
4374 * Allows the host application to declare implicit references from an object
4375 * to another object. If the parent object is alive, the child object is alive
4376 * too. After each garbage collection, all implicit references are removed. It
4377 * is intended to be used in the before-garbage-collection callback function.
4379 template<typename T, typename S>
4380 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4382 typedef void (*GCPrologueCallback)(Isolate* isolate,
4384 GCCallbackFlags flags);
4385 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4387 GCCallbackFlags flags);
4390 * Enables the host application to receive a notification before a
4391 * garbage collection. Allocations are allowed in the callback function,
4392 * but the callback is not re-entrant: if the allocation inside it will
4393 * trigger the garbage collection, the callback won't be called again.
4394 * It is possible to specify the GCType filter for your callback. But it is
4395 * not possible to register the same callback function two times with
4396 * different GCType filters.
4398 void AddGCPrologueCallback(
4399 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4402 * This function removes callback which was installed by
4403 * AddGCPrologueCallback function.
4405 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4408 * Enables the host application to receive a notification after a
4409 * garbage collection. Allocations are allowed in the callback function,
4410 * but the callback is not re-entrant: if the allocation inside it will
4411 * trigger the garbage collection, the callback won't be called again.
4412 * It is possible to specify the GCType filter for your callback. But it is
4413 * not possible to register the same callback function two times with
4414 * different GCType filters.
4416 void AddGCEpilogueCallback(
4417 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4420 * This function removes callback which was installed by
4421 * AddGCEpilogueCallback function.
4423 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4426 * Request V8 to interrupt long running JavaScript code and invoke
4427 * the given |callback| passing the given |data| to it. After |callback|
4428 * returns control will be returned to the JavaScript code.
4429 * At any given moment V8 can remember only a single callback for the very
4430 * last interrupt request.
4431 * Can be called from another thread without acquiring a |Locker|.
4432 * Registered |callback| must not reenter interrupted Isolate.
4434 void RequestInterrupt(InterruptCallback callback, void* data);
4437 * Clear interrupt request created by |RequestInterrupt|.
4438 * Can be called from another thread without acquiring a |Locker|.
4440 void ClearInterrupt();
4443 * Request garbage collection in this Isolate. It is only valid to call this
4444 * function if --expose_gc was specified.
4446 * This should only be used for testing purposes and not to enforce a garbage
4447 * collection schedule. It has strong negative impact on the garbage
4448 * collection performance. Use IdleNotification() or LowMemoryNotification()
4449 * instead to influence the garbage collection schedule.
4451 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4454 * Set the callback to invoke for logging event.
4456 void SetEventLogger(LogEventCallback that);
4459 * Adds a callback to notify the host application when a script finished
4460 * running. If a script re-enters the runtime during executing, the
4461 * CallCompletedCallback is only invoked when the outer-most script
4462 * execution ends. Executing scripts inside the callback do not trigger
4463 * further callbacks.
4465 void AddCallCompletedCallback(CallCompletedCallback callback);
4468 * Removes callback that was installed by AddCallCompletedCallback.
4470 void RemoveCallCompletedCallback(CallCompletedCallback callback);
4473 * Experimental: Runs the Microtask Work Queue until empty
4474 * Any exceptions thrown by microtask callbacks are swallowed.
4476 void RunMicrotasks();
4479 * Experimental: Enqueues the callback to the Microtask Work Queue
4481 void EnqueueMicrotask(Handle<Function> microtask);
4484 * Experimental: Enqueues the callback to the Microtask Work Queue
4486 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
4489 * Experimental: Controls whether the Microtask Work Queue is automatically
4490 * run when the script call depth decrements to zero.
4492 void SetAutorunMicrotasks(bool autorun);
4495 * Experimental: Returns whether the Microtask Work Queue is automatically
4496 * run when the script call depth decrements to zero.
4498 bool WillAutorunMicrotasks() const;
4501 * Sets a callback for counting the number of times a feature of V8 is used.
4503 void SetUseCounterCallback(UseCounterCallback callback);
4506 * Enables the host application to provide a mechanism for recording
4507 * statistics counters.
4509 void SetCounterFunction(CounterLookupCallback);
4512 * Enables the host application to provide a mechanism for recording
4513 * histograms. The CreateHistogram function returns a
4514 * histogram which will later be passed to the AddHistogramSample
4517 void SetCreateHistogramFunction(CreateHistogramCallback);
4518 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4521 * Optional notification that the embedder is idle.
4522 * V8 uses the notification to reduce memory footprint.
4523 * This call can be used repeatedly if the embedder remains idle.
4524 * Returns true if the embedder should stop calling IdleNotification
4525 * until real work has been done. This indicates that V8 has done
4526 * as much cleanup as it will be able to do.
4528 * The idle_time_in_ms argument specifies the time V8 has to do reduce
4529 * the memory footprint. There is no guarantee that the actual work will be
4530 * done within the time limit.
4532 bool IdleNotification(int idle_time_in_ms);
4535 * Optional notification that the system is running low on memory.
4536 * V8 uses these notifications to attempt to free memory.
4538 void LowMemoryNotification();
4541 * Optional notification that a context has been disposed. V8 uses
4542 * these notifications to guide the GC heuristic. Returns the number
4543 * of context disposals - including this one - since the last time
4544 * V8 had a chance to clean up.
4546 int ContextDisposedNotification();
4549 template<class K, class V, class Traits> friend class PersistentValueMap;
4552 Isolate(const Isolate&);
4554 Isolate& operator=(const Isolate&);
4555 void* operator new(size_t size);
4556 void operator delete(void*, size_t);
4558 void SetObjectGroupId(internal::Object** object, UniqueId id);
4559 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4560 void SetReference(internal::Object** parent, internal::Object** child);
4561 void CollectAllGarbage(const char* gc_reason);
4564 class V8_EXPORT StartupData {
4566 enum CompressionAlgorithm {
4572 int compressed_size;
4578 * A helper class for driving V8 startup data decompression. It is based on
4579 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
4580 * for an embedder to use this class, instead, API functions can be used
4583 * For an example of the class usage, see the "shell.cc" sample application.
4585 class V8_EXPORT StartupDataDecompressor { // NOLINT
4587 StartupDataDecompressor();
4588 virtual ~StartupDataDecompressor();
4592 virtual int DecompressData(char* raw_data,
4594 const char* compressed_data,
4595 int compressed_data_size) = 0;
4603 * EntropySource is used as a callback function when v8 needs a source
4606 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4610 * ReturnAddressLocationResolver is used as a callback function when v8 is
4611 * resolving the location of a return address on the stack. Profilers that
4612 * change the return address on the stack can use this to resolve the stack
4613 * location to whereever the profiler stashed the original return address.
4615 * \param return_addr_location points to a location on stack where a machine
4616 * return address resides.
4617 * \returns either return_addr_location, or else a pointer to the profiler's
4618 * copy of the original return address.
4620 * \note the resolver function must not cause garbage collection.
4622 typedef uintptr_t (*ReturnAddressLocationResolver)(
4623 uintptr_t return_addr_location);
4627 * FunctionEntryHook is the type of the profile entry hook called at entry to
4628 * any generated function when function-level profiling is enabled.
4630 * \param function the address of the function that's being entered.
4631 * \param return_addr_location points to a location on stack where the machine
4632 * return address resides. This can be used to identify the caller of
4633 * \p function, and/or modified to divert execution when \p function exits.
4635 * \note the entry hook must not cause garbage collection.
4637 typedef void (*FunctionEntryHook)(uintptr_t function,
4638 uintptr_t return_addr_location);
4642 * A JIT code event is issued each time code is added, moved or removed.
4644 * \note removal events are not currently issued.
4646 struct JitCodeEvent {
4651 CODE_ADD_LINE_POS_INFO,
4652 CODE_START_LINE_INFO_RECORDING,
4653 CODE_END_LINE_INFO_RECORDING
4655 // Definition of the code position type. The "POSITION" type means the place
4656 // in the source code which are of interest when making stack traces to
4657 // pin-point the source location of a stack frame as close as possible.
4658 // The "STATEMENT_POSITION" means the place at the beginning of each
4659 // statement, and is used to indicate possible break locations.
4667 // Start of the instructions.
4669 // Size of the instructions.
4671 // Script info for CODE_ADDED event.
4672 Handle<UnboundScript> script;
4673 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4674 // code line information which is returned from the
4675 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4676 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4680 // Name of the object associated with the code, note that the string is not
4683 // Number of chars in str.
4687 struct line_info_t {
4692 // The position type.
4693 PositionType position_type;
4697 // Only valid for CODE_ADDED.
4700 // Only valid for CODE_ADD_LINE_POS_INFO
4701 struct line_info_t line_info;
4703 // New location of instructions. Only valid for CODE_MOVED.
4704 void* new_code_start;
4709 * Option flags passed to the SetJitCodeEventHandler function.
4711 enum JitCodeEventOptions {
4712 kJitCodeEventDefault = 0,
4713 // Generate callbacks for already existent code.
4714 kJitCodeEventEnumExisting = 1
4719 * Callback function passed to SetJitCodeEventHandler.
4721 * \param event code add, move or removal event.
4723 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4727 * Interface for iterating through all external resources in the heap.
4729 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4731 virtual ~ExternalResourceVisitor() {}
4732 virtual void VisitExternalString(Handle<String> string) {}
4737 * Interface for iterating through all the persistent handles in the heap.
4739 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4741 virtual ~PersistentHandleVisitor() {}
4742 virtual void VisitPersistentHandle(Persistent<Value>* value,
4743 uint16_t class_id) {}
4748 * Container class for static utility functions.
4750 class V8_EXPORT V8 {
4752 /** Set the callback to invoke in case of fatal errors. */
4753 static void SetFatalErrorHandler(FatalErrorCallback that);
4756 * Set the callback to invoke to check if code generation from
4757 * strings should be allowed.
4759 static void SetAllowCodeGenerationFromStringsCallback(
4760 AllowCodeGenerationFromStringsCallback that);
4763 * Set allocator to use for ArrayBuffer memory.
4764 * The allocator should be set only once. The allocator should be set
4765 * before any code tha uses ArrayBuffers is executed.
4766 * This allocator is used in all isolates.
4768 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4771 * Check if V8 is dead and therefore unusable. This is the case after
4772 * fatal errors such as out-of-memory situations.
4774 static bool IsDead();
4777 * The following 4 functions are to be used when V8 is built with
4778 * the 'compress_startup_data' flag enabled. In this case, the
4779 * embedder must decompress startup data prior to initializing V8.
4781 * This is how interaction with V8 should look like:
4782 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4783 * v8::StartupData* compressed_data =
4784 * new v8::StartupData[compressed_data_count];
4785 * v8::V8::GetCompressedStartupData(compressed_data);
4786 * ... decompress data (compressed_data can be updated in-place) ...
4787 * v8::V8::SetDecompressedStartupData(compressed_data);
4788 * ... now V8 can be initialized
4789 * ... make sure the decompressed data stays valid until V8 shutdown
4791 * A helper class StartupDataDecompressor is provided. It implements
4792 * the protocol of the interaction described above, and can be used in
4793 * most cases instead of calling these API functions directly.
4795 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4796 static int GetCompressedStartupDataCount();
4797 static void GetCompressedStartupData(StartupData* compressed_data);
4798 static void SetDecompressedStartupData(StartupData* decompressed_data);
4801 * Hand startup data to V8, in case the embedder has chosen to build
4802 * V8 with external startup data.
4805 * - By default the startup data is linked into the V8 library, in which
4806 * case this function is not meaningful.
4807 * - If this needs to be called, it needs to be called before V8
4808 * tries to make use of its built-ins.
4809 * - To avoid unnecessary copies of data, V8 will point directly into the
4810 * given data blob, so pretty please keep it around until V8 exit.
4811 * - Compression of the startup blob might be useful, but needs to
4812 * handled entirely on the embedders' side.
4813 * - The call will abort if the data is invalid.
4815 static void SetNativesDataBlob(StartupData* startup_blob);
4816 static void SetSnapshotDataBlob(StartupData* startup_blob);
4819 * Adds a message listener.
4821 * The same message listener can be added more than once and in that
4822 * case it will be called more than once for each message.
4824 * If data is specified, it will be passed to the callback when it is called.
4825 * Otherwise, the exception object will be passed to the callback instead.
4827 static bool AddMessageListener(MessageCallback that,
4828 Handle<Value> data = Handle<Value>());
4831 * Remove all message listeners from the specified callback function.
4833 static void RemoveMessageListeners(MessageCallback that);
4836 * Tells V8 to capture current stack trace when uncaught exception occurs
4837 * and report it to the message listeners. The option is off by default.
4839 static void SetCaptureStackTraceForUncaughtExceptions(
4841 int frame_limit = 10,
4842 StackTrace::StackTraceOptions options = StackTrace::kOverview);
4845 * Sets V8 flags from a string.
4847 static void SetFlagsFromString(const char* str, int length);
4850 * Sets V8 flags from the command line.
4852 static void SetFlagsFromCommandLine(int* argc,
4856 /** Get the version string. */
4857 static const char* GetVersion();
4859 /** Callback function for reporting failed access checks.*/
4860 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
4863 * Enables the host application to receive a notification before a
4864 * garbage collection. Allocations are not allowed in the
4865 * callback function, you therefore cannot manipulate objects (set
4866 * or delete properties for example) since it is possible such
4867 * operations will result in the allocation of objects. It is possible
4868 * to specify the GCType filter for your callback. But it is not possible to
4869 * register the same callback function two times with different
4872 static void AddGCPrologueCallback(
4873 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4876 * This function removes callback which was installed by
4877 * AddGCPrologueCallback function.
4879 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
4882 * Enables the host application to receive a notification after a
4883 * garbage collection. Allocations are not allowed in the
4884 * callback function, you therefore cannot manipulate objects (set
4885 * or delete properties for example) since it is possible such
4886 * operations will result in the allocation of objects. It is possible
4887 * to specify the GCType filter for your callback. But it is not possible to
4888 * register the same callback function two times with different
4891 static void AddGCEpilogueCallback(
4892 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4895 * This function removes callback which was installed by
4896 * AddGCEpilogueCallback function.
4898 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4901 * Enables the host application to provide a mechanism to be notified
4902 * and perform custom logging when V8 Allocates Executable Memory.
4904 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
4906 AllocationAction action);
4909 * Removes callback that was installed by AddMemoryAllocationCallback.
4911 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
4914 * Initializes from snapshot if possible. Otherwise, attempts to
4915 * initialize from scratch. This function is called implicitly if
4916 * you use the API without calling it first.
4918 static bool Initialize();
4921 * Allows the host application to provide a callback which can be used
4922 * as a source of entropy for random number generators.
4924 static void SetEntropySource(EntropySource source);
4927 * Allows the host application to provide a callback that allows v8 to
4928 * cooperate with a profiler that rewrites return addresses on stack.
4930 static void SetReturnAddressLocationResolver(
4931 ReturnAddressLocationResolver return_address_resolver);
4934 * Allows the host application to provide the address of a function that's
4935 * invoked on entry to every V8-generated function.
4936 * Note that \p entry_hook is invoked at the very start of each
4937 * generated function.
4939 * \param isolate the isolate to operate on.
4940 * \param entry_hook a function that will be invoked on entry to every
4941 * V8-generated function.
4942 * \returns true on success on supported platforms, false on failure.
4943 * \note Setting an entry hook can only be done very early in an isolates
4944 * lifetime, and once set, the entry hook cannot be revoked.
4946 static bool SetFunctionEntryHook(Isolate* isolate,
4947 FunctionEntryHook entry_hook);
4950 * Allows the host application to provide the address of a function that is
4951 * notified each time code is added, moved or removed.
4953 * \param options options for the JIT code event handler.
4954 * \param event_handler the JIT code event handler, which will be invoked
4955 * each time code is added, moved or removed.
4956 * \note \p event_handler won't get notified of existent code.
4957 * \note since code removal notifications are not currently issued, the
4958 * \p event_handler may get notifications of code that overlaps earlier
4959 * code notifications. This happens when code areas are reused, and the
4960 * earlier overlapping code areas should therefore be discarded.
4961 * \note the events passed to \p event_handler and the strings they point to
4962 * are not guaranteed to live past each call. The \p event_handler must
4963 * copy strings and other parameters it needs to keep around.
4964 * \note the set of events declared in JitCodeEvent::EventType is expected to
4965 * grow over time, and the JitCodeEvent structure is expected to accrue
4966 * new members. The \p event_handler function must ignore event codes
4967 * it does not recognize to maintain future compatibility.
4969 static void SetJitCodeEventHandler(JitCodeEventOptions options,
4970 JitCodeEventHandler event_handler);
4973 * Forcefully terminate the current thread of JavaScript execution
4974 * in the given isolate.
4976 * This method can be used by any thread even if that thread has not
4977 * acquired the V8 lock with a Locker object.
4979 * \param isolate The isolate in which to terminate the current JS execution.
4981 static void TerminateExecution(Isolate* isolate);
4984 * Is V8 terminating JavaScript execution.
4986 * Returns true if JavaScript execution is currently terminating
4987 * because of a call to TerminateExecution. In that case there are
4988 * still JavaScript frames on the stack and the termination
4989 * exception is still active.
4991 * \param isolate The isolate in which to check.
4993 static bool IsExecutionTerminating(Isolate* isolate = NULL);
4996 * Resume execution capability in the given isolate, whose execution
4997 * was previously forcefully terminated using TerminateExecution().
4999 * When execution is forcefully terminated using TerminateExecution(),
5000 * the isolate can not resume execution until all JavaScript frames
5001 * have propagated the uncatchable exception which is generated. This
5002 * method allows the program embedding the engine to handle the
5003 * termination event and resume execution capability, even if
5004 * JavaScript frames remain on the stack.
5006 * This method can be used by any thread even if that thread has not
5007 * acquired the V8 lock with a Locker object.
5009 * \param isolate The isolate in which to resume execution capability.
5011 static void CancelTerminateExecution(Isolate* isolate);
5014 * Releases any resources used by v8 and stops any utility threads
5015 * that may be running. Note that disposing v8 is permanent, it
5016 * cannot be reinitialized.
5018 * It should generally not be necessary to dispose v8 before exiting
5019 * a process, this should happen automatically. It is only necessary
5020 * to use if the process needs the resources taken up by v8.
5022 static bool Dispose();
5025 * Iterates through all external resources referenced from current isolate
5026 * heap. GC is not invoked prior to iterating, therefore there is no
5027 * guarantee that visited objects are still alive.
5029 static void VisitExternalResources(ExternalResourceVisitor* visitor);
5032 * Iterates through all the persistent handles in the current isolate's heap
5033 * that have class_ids.
5035 static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
5038 * Iterates through all the persistent handles in the current isolate's heap
5039 * that have class_ids and are candidates to be marked as partially dependent
5040 * handles. This will visit handles to young objects created since the last
5041 * garbage collection but is free to visit an arbitrary superset of these
5044 static void VisitHandlesForPartialDependence(
5045 Isolate* isolate, PersistentHandleVisitor* visitor);
5048 * Initialize the ICU library bundled with V8. The embedder should only
5049 * invoke this method when using the bundled ICU. Returns true on success.
5051 * If V8 was compiled with the ICU data in an external file, the location
5052 * of the data file has to be provided.
5054 static bool InitializeICU(const char* icu_data_file = NULL);
5057 * Sets the v8::Platform to use. This should be invoked before V8 is
5060 static void InitializePlatform(Platform* platform);
5063 * Clears all references to the v8::Platform. This should be invoked after
5066 static void ShutdownPlatform();
5071 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
5072 internal::Object** handle);
5073 static internal::Object** CopyPersistent(internal::Object** handle);
5074 static void DisposeGlobal(internal::Object** global_handle);
5075 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
5076 static void MakeWeak(internal::Object** global_handle,
5078 WeakCallback weak_callback);
5079 static void* ClearWeak(internal::Object** global_handle);
5080 static void Eternalize(Isolate* isolate,
5083 static Local<Value> GetEternal(Isolate* isolate, int index);
5085 template <class T> friend class Handle;
5086 template <class T> friend class Local;
5087 template <class T> friend class Eternal;
5088 template <class T> friend class PersistentBase;
5089 template <class T, class M> friend class Persistent;
5090 friend class Context;
5095 * An external exception handler.
5097 class V8_EXPORT TryCatch {
5100 * Creates a new try/catch block and registers it with v8. Note that
5101 * all TryCatch blocks should be stack allocated because the memory
5102 * location itself is compared against JavaScript try/catch blocks.
5107 * Unregisters and deletes this try/catch block.
5112 * Returns true if an exception has been caught by this try/catch block.
5114 bool HasCaught() const;
5117 * For certain types of exceptions, it makes no sense to continue execution.
5119 * If CanContinue returns false, the correct action is to perform any C++
5120 * cleanup needed and then return. If CanContinue returns false and
5121 * HasTerminated returns true, it is possible to call
5122 * CancelTerminateExecution in order to continue calling into the engine.
5124 bool CanContinue() const;
5127 * Returns true if an exception has been caught due to script execution
5130 * There is no JavaScript representation of an execution termination
5131 * exception. Such exceptions are thrown when the TerminateExecution
5132 * methods are called to terminate a long-running script.
5134 * If such an exception has been thrown, HasTerminated will return true,
5135 * indicating that it is possible to call CancelTerminateExecution in order
5136 * to continue calling into the engine.
5138 bool HasTerminated() const;
5141 * Throws the exception caught by this TryCatch in a way that avoids
5142 * it being caught again by this same TryCatch. As with ThrowException
5143 * it is illegal to execute any JavaScript operations after calling
5144 * ReThrow; the caller must return immediately to where the exception
5147 Handle<Value> ReThrow();
5150 * Returns the exception caught by this try/catch block. If no exception has
5151 * been caught an empty handle is returned.
5153 * The returned handle is valid until this TryCatch block has been destroyed.
5155 Local<Value> Exception() const;
5158 * Returns the .stack property of the thrown object. If no .stack
5159 * property is present an empty handle is returned.
5161 Local<Value> StackTrace() const;
5164 * Returns the message associated with this exception. If there is
5165 * no message associated an empty handle is returned.
5167 * The returned handle is valid until this TryCatch block has been
5170 Local<v8::Message> Message() const;
5173 * Clears any exceptions that may have been caught by this try/catch block.
5174 * After this method has been called, HasCaught() will return false. Cancels
5175 * the scheduled exception if it is caught and ReThrow() is not called before.
5177 * It is not necessary to clear a try/catch block before using it again; if
5178 * another exception is thrown the previously caught exception will just be
5179 * overwritten. However, it is often a good idea since it makes it easier
5180 * to determine which operation threw a given exception.
5185 * Set verbosity of the external exception handler.
5187 * By default, exceptions that are caught by an external exception
5188 * handler are not reported. Call SetVerbose with true on an
5189 * external exception handler to have exceptions caught by the
5190 * handler reported as if they were not caught.
5192 void SetVerbose(bool value);
5195 * Set whether or not this TryCatch should capture a Message object
5196 * which holds source information about where the exception
5197 * occurred. True by default.
5199 void SetCaptureMessage(bool value);
5202 * There are cases when the raw address of C++ TryCatch object cannot be
5203 * used for comparisons with addresses into the JS stack. The cases are:
5204 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5205 * 2) Address sanitizer allocates local C++ object in the heap when
5206 * UseAfterReturn mode is enabled.
5207 * This method returns address that can be used for comparisons with
5208 * addresses into the JS stack. When neither simulator nor ASAN's
5209 * UseAfterReturn is enabled, then the address returned will be the address
5210 * of the C++ try catch handler itself.
5212 static void* JSStackComparableAddress(v8::TryCatch* handler) {
5213 if (handler == NULL) return NULL;
5214 return handler->js_stack_comparable_address_;
5218 void ResetInternal();
5220 // Make it hard to create heap-allocated TryCatch blocks.
5221 TryCatch(const TryCatch&);
5222 void operator=(const TryCatch&);
5223 void* operator new(size_t size);
5224 void operator delete(void*, size_t);
5226 v8::internal::Isolate* isolate_;
5227 v8::TryCatch* next_;
5230 void* message_script_;
5231 void* js_stack_comparable_address_;
5232 int message_start_pos_;
5233 int message_end_pos_;
5234 bool is_verbose_ : 1;
5235 bool can_continue_ : 1;
5236 bool capture_message_ : 1;
5238 bool has_terminated_ : 1;
5240 friend class v8::internal::Isolate;
5248 * A container for extension names.
5250 class V8_EXPORT ExtensionConfiguration {
5252 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
5253 ExtensionConfiguration(int name_count, const char* names[])
5254 : name_count_(name_count), names_(names) { }
5256 const char** begin() const { return &names_[0]; }
5257 const char** end() const { return &names_[name_count_]; }
5260 const int name_count_;
5261 const char** names_;
5266 * A sandboxed execution context with its own set of built-in objects
5269 class V8_EXPORT Context {
5272 * Returns the global proxy object.
5274 * Global proxy object is a thin wrapper whose prototype points to actual
5275 * context's global object with the properties like Object, etc. This is done
5276 * that way for security reasons (for more details see
5277 * https://wiki.mozilla.org/Gecko:SplitWindow).
5279 * Please note that changes to global proxy object prototype most probably
5280 * would break VM---v8 expects only global object as a prototype of global
5283 Local<Object> Global();
5286 * Detaches the global object from its context before
5287 * the global object can be reused to create a new context.
5289 void DetachGlobal();
5292 * Creates a new context and returns a handle to the newly allocated
5295 * \param isolate The isolate in which to create the context.
5297 * \param extensions An optional extension configuration containing
5298 * the extensions to be installed in the newly created context.
5300 * \param global_template An optional object template from which the
5301 * global object for the newly created context will be created.
5303 * \param global_object An optional global object to be reused for
5304 * the newly created context. This global object must have been
5305 * created by a previous call to Context::New with the same global
5306 * template. The state of the global object will be completely reset
5307 * and only object identify will remain.
5309 static Local<Context> New(
5311 ExtensionConfiguration* extensions = NULL,
5312 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5313 Handle<Value> global_object = Handle<Value>());
5316 * Sets the security token for the context. To access an object in
5317 * another context, the security tokens must match.
5319 void SetSecurityToken(Handle<Value> token);
5321 /** Restores the security token to the default value. */
5322 void UseDefaultSecurityToken();
5324 /** Returns the security token of this context.*/
5325 Handle<Value> GetSecurityToken();
5328 * Enter this context. After entering a context, all code compiled
5329 * and run is compiled and run in this context. If another context
5330 * is already entered, this old context is saved so it can be
5331 * restored when the new context is exited.
5336 * Exit this context. Exiting the current context restores the
5337 * context that was in place when entering the current context.
5341 /** Returns an isolate associated with a current context. */
5342 v8::Isolate* GetIsolate();
5345 * Gets the embedder data with the given index, which must have been set by a
5346 * previous call to SetEmbedderData with the same index. Note that index 0
5347 * currently has a special meaning for Chrome's debugger.
5349 V8_INLINE Local<Value> GetEmbedderData(int index);
5352 * Sets the embedder data with the given index, growing the data as
5353 * needed. Note that index 0 currently has a special meaning for Chrome's
5356 void SetEmbedderData(int index, Handle<Value> value);
5359 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5360 * index, which must have bees set by a previous call to
5361 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5362 * currently has a special meaning for Chrome's debugger.
5364 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5367 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5368 * index, growing the data as needed. Note that index 0 currently has a
5369 * special meaning for Chrome's debugger.
5371 void SetAlignedPointerInEmbedderData(int index, void* value);
5374 * Control whether code generation from strings is allowed. Calling
5375 * this method with false will disable 'eval' and the 'Function'
5376 * constructor for code running in this context. If 'eval' or the
5377 * 'Function' constructor are used an exception will be thrown.
5379 * If code generation from strings is not allowed the
5380 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5381 * set before blocking the call to 'eval' or the 'Function'
5382 * constructor. If that callback returns true, the call will be
5383 * allowed, otherwise an exception will be thrown. If no callback is
5384 * set an exception will be thrown.
5386 void AllowCodeGenerationFromStrings(bool allow);
5389 * Returns true if code generation from strings is allowed for the context.
5390 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5392 bool IsCodeGenerationFromStringsAllowed();
5395 * Sets the error description for the exception that is thrown when
5396 * code generation from strings is not allowed and 'eval' or the 'Function'
5397 * constructor are called.
5399 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5402 * Stack-allocated class which sets the execution context for all
5403 * operations executed within a local scope.
5407 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5410 V8_INLINE ~Scope() { context_->Exit(); }
5413 Handle<Context> context_;
5418 friend class Script;
5419 friend class Object;
5420 friend class Function;
5422 Local<Value> SlowGetEmbedderData(int index);
5423 void* SlowGetAlignedPointerFromEmbedderData(int index);
5428 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5429 * to use any given V8 isolate, see the comments in the Isolate class. The
5430 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5431 * object pointers obtained from V8 handles while in the particular V8 isolate.
5432 * It is up to the user of V8 to ensure, perhaps with locking, that this
5433 * constraint is not violated. In addition to any other synchronization
5434 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5435 * used to signal thead switches to V8.
5437 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5438 * construction and destruction, the current thread is allowed to use the locked
5439 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5440 * any time. In other words, the scope of a v8::Locker is a critical section.
5446 * v8::Locker locker(isolate);
5447 * v8::Isolate::Scope isolate_scope(isolate);
5449 * // Code using V8 and isolate goes here.
5451 * } // Destructor called here
5454 * If you wish to stop using V8 in a thread A you can do this either by
5455 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5461 * v8::Unlocker unlocker(isolate);
5463 * // Code not using V8 goes here while V8 can run in another thread.
5465 * } // Destructor called here.
5469 * The Unlocker object is intended for use in a long-running callback from V8,
5470 * where you want to release the V8 lock for other threads to use.
5472 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5473 * given thread. This can be useful if you have code that can be called either
5474 * from code that holds the lock or from code that does not. The Unlocker is
5475 * not recursive so you can not have several Unlockers on the stack at once, and
5476 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5478 * An unlocker will unlock several lockers if it has to and reinstate the
5479 * correct depth of locking on its destruction, e.g.:
5484 * v8::Locker locker(isolate);
5485 * Isolate::Scope isolate_scope(isolate);
5488 * v8::Locker another_locker(isolate);
5489 * // V8 still locked (2 levels).
5492 * v8::Unlocker unlocker(isolate);
5496 * // V8 locked again (2 levels).
5498 * // V8 still locked (1 level).
5500 * // V8 Now no longer locked.
5503 class V8_EXPORT Unlocker {
5506 * Initialize Unlocker for a given Isolate.
5508 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5512 void Initialize(Isolate* isolate);
5514 internal::Isolate* isolate_;
5518 class V8_EXPORT Locker {
5521 * Initialize Locker for a given Isolate.
5523 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5528 * Returns whether or not the locker for a given isolate, is locked by the
5531 static bool IsLocked(Isolate* isolate);
5534 * Returns whether v8::Locker is being used by this V8 instance.
5536 static bool IsActive();
5539 void Initialize(Isolate* isolate);
5543 internal::Isolate* isolate_;
5545 static bool active_;
5547 // Disallow copying and assigning.
5548 Locker(const Locker&);
5549 void operator=(const Locker&);
5553 // --- Implementation ---
5556 namespace internal {
5558 const int kApiPointerSize = sizeof(void*); // NOLINT
5559 const int kApiIntSize = sizeof(int); // NOLINT
5560 const int kApiInt64Size = sizeof(int64_t); // NOLINT
5562 // Tag information for HeapObject.
5563 const int kHeapObjectTag = 1;
5564 const int kHeapObjectTagSize = 2;
5565 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5567 // Tag information for Smi.
5568 const int kSmiTag = 0;
5569 const int kSmiTagSize = 1;
5570 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5572 template <size_t ptr_size> struct SmiTagging;
5574 template<int kSmiShiftSize>
5575 V8_INLINE internal::Object* IntToSmi(int value) {
5576 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5577 intptr_t tagged_value =
5578 (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
5579 return reinterpret_cast<internal::Object*>(tagged_value);
5582 // Smi constants for 32-bit systems.
5583 template <> struct SmiTagging<4> {
5584 static const int kSmiShiftSize = 0;
5585 static const int kSmiValueSize = 31;
5586 V8_INLINE static int SmiToInt(const internal::Object* value) {
5587 int shift_bits = kSmiTagSize + kSmiShiftSize;
5588 // Throw away top 32 bits and shift down (requires >> to be sign extending).
5589 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5591 V8_INLINE static internal::Object* IntToSmi(int value) {
5592 return internal::IntToSmi<kSmiShiftSize>(value);
5594 V8_INLINE static bool IsValidSmi(intptr_t value) {
5595 // To be representable as an tagged small integer, the two
5596 // most-significant bits of 'value' must be either 00 or 11 due to
5597 // sign-extension. To check this we add 01 to the two
5598 // most-significant bits, and check if the most-significant bit is 0
5600 // CAUTION: The original code below:
5601 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5602 // may lead to incorrect results according to the C language spec, and
5603 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5604 // compiler may produce undefined results in case of signed integer
5605 // overflow. The computation must be done w/ unsigned ints.
5606 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5610 // Smi constants for 64-bit systems.
5611 template <> struct SmiTagging<8> {
5612 static const int kSmiShiftSize = 31;
5613 static const int kSmiValueSize = 32;
5614 V8_INLINE static int SmiToInt(const internal::Object* value) {
5615 int shift_bits = kSmiTagSize + kSmiShiftSize;
5616 // Shift down and throw away top 32 bits.
5617 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5619 V8_INLINE static internal::Object* IntToSmi(int value) {
5620 return internal::IntToSmi<kSmiShiftSize>(value);
5622 V8_INLINE static bool IsValidSmi(intptr_t value) {
5623 // To be representable as a long smi, the value must be a 32-bit integer.
5624 return (value == static_cast<int32_t>(value));
5628 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5629 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5630 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5631 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5632 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5635 * This class exports constants and functionality from within v8 that
5636 * is necessary to implement inline functions in the v8 api. Don't
5637 * depend on functions and constants defined here.
5641 // These values match non-compiler-dependent values defined within
5642 // the implementation of v8.
5643 static const int kHeapObjectMapOffset = 0;
5644 static const int kMapInstanceTypeAndBitFieldOffset =
5645 1 * kApiPointerSize + kApiIntSize;
5646 static const int kStringResourceOffset = 3 * kApiPointerSize;
5648 static const int kOddballKindOffset = 3 * kApiPointerSize;
5649 static const int kForeignAddressOffset = kApiPointerSize;
5650 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5651 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5652 static const int kContextHeaderSize = 2 * kApiPointerSize;
5653 static const int kContextEmbedderDataIndex = 108;
5654 static const int kFullStringRepresentationMask = 0x07;
5655 static const int kStringEncodingMask = 0x4;
5656 static const int kExternalTwoByteRepresentationTag = 0x02;
5657 static const int kExternalAsciiRepresentationTag = 0x06;
5659 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
5660 static const int kAmountOfExternalAllocatedMemoryOffset =
5661 4 * kApiPointerSize;
5662 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
5663 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
5664 static const int kIsolateRootsOffset =
5665 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
5667 static const int kUndefinedValueRootIndex = 5;
5668 static const int kNullValueRootIndex = 7;
5669 static const int kTrueValueRootIndex = 8;
5670 static const int kFalseValueRootIndex = 9;
5671 static const int kEmptyStringRootIndex = 176;
5673 // The external allocation limit should be below 256 MB on all architectures
5674 // to avoid that resource-constrained embedders run low on memory.
5675 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
5677 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5678 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5679 static const int kNodeStateMask = 0xf;
5680 static const int kNodeStateIsWeakValue = 2;
5681 static const int kNodeStateIsPendingValue = 3;
5682 static const int kNodeStateIsNearDeathValue = 4;
5683 static const int kNodeIsIndependentShift = 4;
5684 static const int kNodeIsPartiallyDependentShift = 5;
5686 static const int kJSObjectType = 0xc2;
5687 static const int kFirstNonstringType = 0x80;
5688 static const int kOddballType = 0x83;
5689 static const int kForeignType = 0x88;
5691 static const int kUndefinedOddballKind = 5;
5692 static const int kNullOddballKind = 3;
5694 static const uint32_t kNumIsolateDataSlots = 4;
5696 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5697 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5698 #ifdef V8_ENABLE_CHECKS
5699 CheckInitializedImpl(isolate);
5703 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
5704 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5708 V8_INLINE static int SmiValue(const internal::Object* value) {
5709 return PlatformSmiTagging::SmiToInt(value);
5712 V8_INLINE static internal::Object* IntToSmi(int value) {
5713 return PlatformSmiTagging::IntToSmi(value);
5716 V8_INLINE static bool IsValidSmi(intptr_t value) {
5717 return PlatformSmiTagging::IsValidSmi(value);
5720 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
5721 typedef internal::Object O;
5722 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5723 // Map::InstanceType is defined so that it will always be loaded into
5724 // the LS 8 bits of one 16-bit word, regardless of endianess.
5725 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
5728 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
5729 typedef internal::Object O;
5730 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5733 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5734 int representation = (instance_type & kFullStringRepresentationMask);
5735 return representation == kExternalTwoByteRepresentationTag;
5738 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5739 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5740 return *addr & static_cast<uint8_t>(1U << shift);
5743 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5744 bool value, int shift) {
5745 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5746 uint8_t mask = static_cast<uint8_t>(1 << shift);
5747 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5750 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5751 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5752 return *addr & kNodeStateMask;
5755 V8_INLINE static void UpdateNodeState(internal::Object** obj,
5757 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5758 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5761 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
5764 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
5765 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5766 *reinterpret_cast<void**>(addr) = data;
5769 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
5771 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
5772 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5773 return *reinterpret_cast<void* const*>(addr);
5776 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5778 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5779 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5782 template <typename T>
5783 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
5784 const uint8_t* addr =
5785 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
5786 return *reinterpret_cast<const T*>(addr);
5789 template <typename T>
5790 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
5791 typedef internal::Object O;
5792 typedef internal::Internals I;
5793 O* ctx = *reinterpret_cast<O* const*>(context);
5794 int embedder_data_offset = I::kContextHeaderSize +
5795 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5796 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5798 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5799 return I::ReadField<T>(embedder_data, value_offset);
5803 } // namespace internal
5807 Local<T>::Local() : Handle<T>() { }
5811 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5812 return New(isolate, that.val_);
5816 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
5817 return New(isolate, that.val_);
5821 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5822 if (that == NULL) return Handle<T>();
5824 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5825 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5826 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5831 Local<T> Local<T>::New(Isolate* isolate, T* that) {
5832 if (that == NULL) return Local<T>();
5834 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5835 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5836 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5842 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5844 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
5849 Local<T> Eternal<T>::Get(Isolate* isolate) {
5850 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
5855 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
5856 if (that == NULL) return NULL;
5857 internal::Object** p = reinterpret_cast<internal::Object**>(that);
5858 return reinterpret_cast<T*>(
5859 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
5864 template <class T, class M>
5865 template <class S, class M2>
5866 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
5869 if (that.IsEmpty()) return;
5870 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
5871 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
5872 M::Copy(that, this);
5877 bool PersistentBase<T>::IsIndependent() const {
5878 typedef internal::Internals I;
5879 if (this->IsEmpty()) return false;
5880 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5881 I::kNodeIsIndependentShift);
5886 bool PersistentBase<T>::IsNearDeath() const {
5887 typedef internal::Internals I;
5888 if (this->IsEmpty()) return false;
5889 uint8_t node_state =
5890 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
5891 return node_state == I::kNodeStateIsNearDeathValue ||
5892 node_state == I::kNodeStateIsPendingValue;
5897 bool PersistentBase<T>::IsWeak() const {
5898 typedef internal::Internals I;
5899 if (this->IsEmpty()) return false;
5900 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
5901 I::kNodeStateIsWeakValue;
5906 void PersistentBase<T>::Reset() {
5907 if (this->IsEmpty()) return;
5908 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
5915 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
5918 if (other.IsEmpty()) return;
5919 this->val_ = New(isolate, other.val_);
5925 void PersistentBase<T>::Reset(Isolate* isolate,
5926 const PersistentBase<S>& other) {
5929 if (other.IsEmpty()) return;
5930 this->val_ = New(isolate, other.val_);
5935 template <typename S, typename P>
5936 void PersistentBase<T>::SetWeak(
5938 typename WeakCallbackData<S, P>::Callback callback) {
5940 typedef typename WeakCallbackData<Value, void>::Callback Callback;
5941 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
5943 reinterpret_cast<Callback>(callback));
5948 template <typename P>
5949 void PersistentBase<T>::SetWeak(
5951 typename WeakCallbackData<T, P>::Callback callback) {
5952 SetWeak<T, P>(parameter, callback);
5957 template<typename P>
5958 P* PersistentBase<T>::ClearWeak() {
5959 return reinterpret_cast<P*>(
5960 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
5965 void PersistentBase<T>::MarkIndependent() {
5966 typedef internal::Internals I;
5967 if (this->IsEmpty()) return;
5968 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5970 I::kNodeIsIndependentShift);
5975 void PersistentBase<T>::MarkPartiallyDependent() {
5976 typedef internal::Internals I;
5977 if (this->IsEmpty()) return;
5978 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5980 I::kNodeIsPartiallyDependentShift);
5984 template <class T, class M>
5985 T* Persistent<T, M>::ClearAndLeak() {
5994 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
5995 typedef internal::Internals I;
5996 if (this->IsEmpty()) return;
5997 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5998 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5999 *reinterpret_cast<uint16_t*>(addr) = class_id;
6004 uint16_t PersistentBase<T>::WrapperClassId() const {
6005 typedef internal::Internals I;
6006 if (this->IsEmpty()) return 0;
6007 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
6008 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
6009 return *reinterpret_cast<uint16_t*>(addr);
6013 template<typename T>
6014 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
6016 template<typename T>
6017 template<typename S>
6018 void ReturnValue<T>::Set(const Persistent<S>& handle) {
6020 if (V8_UNLIKELY(handle.IsEmpty())) {
6021 *value_ = GetDefaultValue();
6023 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6027 template<typename T>
6028 template<typename S>
6029 void ReturnValue<T>::Set(const Handle<S> handle) {
6031 if (V8_UNLIKELY(handle.IsEmpty())) {
6032 *value_ = GetDefaultValue();
6034 *value_ = *reinterpret_cast<internal::Object**>(*handle);
6038 template<typename T>
6039 void ReturnValue<T>::Set(double i) {
6040 TYPE_CHECK(T, Number);
6041 Set(Number::New(GetIsolate(), i));
6044 template<typename T>
6045 void ReturnValue<T>::Set(int32_t i) {
6046 TYPE_CHECK(T, Integer);
6047 typedef internal::Internals I;
6048 if (V8_LIKELY(I::IsValidSmi(i))) {
6049 *value_ = I::IntToSmi(i);
6052 Set(Integer::New(GetIsolate(), i));
6055 template<typename T>
6056 void ReturnValue<T>::Set(uint32_t i) {
6057 TYPE_CHECK(T, Integer);
6058 // Can't simply use INT32_MAX here for whatever reason.
6059 bool fits_into_int32_t = (i & (1U << 31)) == 0;
6060 if (V8_LIKELY(fits_into_int32_t)) {
6061 Set(static_cast<int32_t>(i));
6064 Set(Integer::NewFromUnsigned(GetIsolate(), i));
6067 template<typename T>
6068 void ReturnValue<T>::Set(bool value) {
6069 TYPE_CHECK(T, Boolean);
6070 typedef internal::Internals I;
6073 root_index = I::kTrueValueRootIndex;
6075 root_index = I::kFalseValueRootIndex;
6077 *value_ = *I::GetRoot(GetIsolate(), root_index);
6080 template<typename T>
6081 void ReturnValue<T>::SetNull() {
6082 TYPE_CHECK(T, Primitive);
6083 typedef internal::Internals I;
6084 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
6087 template<typename T>
6088 void ReturnValue<T>::SetUndefined() {
6089 TYPE_CHECK(T, Primitive);
6090 typedef internal::Internals I;
6091 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
6094 template<typename T>
6095 void ReturnValue<T>::SetEmptyString() {
6096 TYPE_CHECK(T, String);
6097 typedef internal::Internals I;
6098 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
6101 template<typename T>
6102 Isolate* ReturnValue<T>::GetIsolate() {
6103 // Isolate is always the pointer below the default value on the stack.
6104 return *reinterpret_cast<Isolate**>(&value_[-2]);
6107 template<typename T>
6108 template<typename S>
6109 void ReturnValue<T>::Set(S* whatever) {
6110 // Uncompilable to prevent inadvertent misuse.
6111 TYPE_CHECK(S*, Primitive);
6114 template<typename T>
6115 internal::Object* ReturnValue<T>::GetDefaultValue() {
6116 // Default value is always the pointer below value_ on the stack.
6121 template<typename T>
6122 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6123 internal::Object** values,
6125 bool is_construct_call)
6126 : implicit_args_(implicit_args),
6129 is_construct_call_(is_construct_call) { }
6132 template<typename T>
6133 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6134 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6135 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6139 template<typename T>
6140 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6141 return Local<Function>(reinterpret_cast<Function*>(
6142 &implicit_args_[kCalleeIndex]));
6146 template<typename T>
6147 Local<Object> FunctionCallbackInfo<T>::This() const {
6148 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6152 template<typename T>
6153 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6154 return Local<Object>(reinterpret_cast<Object*>(
6155 &implicit_args_[kHolderIndex]));
6159 template<typename T>
6160 Local<Value> FunctionCallbackInfo<T>::Data() const {
6161 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6165 template<typename T>
6166 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6167 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6171 template<typename T>
6172 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6173 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6177 template<typename T>
6178 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6179 return is_construct_call_;
6183 template<typename T>
6184 int FunctionCallbackInfo<T>::Length() const {
6189 Handle<Value> ScriptOrigin::ResourceName() const {
6190 return resource_name_;
6194 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6195 return resource_line_offset_;
6199 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6200 return resource_column_offset_;
6204 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6205 return resource_is_shared_cross_origin_;
6209 Handle<Integer> ScriptOrigin::ScriptID() const {
6214 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6216 : source_string(string),
6217 resource_name(origin.ResourceName()),
6218 resource_line_offset(origin.ResourceLineOffset()),
6219 resource_column_offset(origin.ResourceColumnOffset()),
6220 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6221 cached_data(data) {}
6224 ScriptCompiler::Source::Source(Local<String> string,
6226 : source_string(string), cached_data(data) {}
6229 ScriptCompiler::Source::~Source() {
6234 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6240 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6241 return value ? True(isolate) : False(isolate);
6245 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6246 Set(v8::String::NewFromUtf8(isolate, name), value);
6250 Local<Value> Object::GetInternalField(int index) {
6251 #ifndef V8_ENABLE_CHECKS
6252 typedef internal::Object O;
6253 typedef internal::HeapObject HO;
6254 typedef internal::Internals I;
6255 O* obj = *reinterpret_cast<O**>(this);
6256 // Fast path: If the object is a plain JSObject, which is the common case, we
6257 // know where to find the internal fields and can return the value directly.
6258 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6259 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6260 O* value = I::ReadField<O*>(obj, offset);
6261 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6262 return Local<Value>(reinterpret_cast<Value*>(result));
6265 return SlowGetInternalField(index);
6269 void* Object::GetAlignedPointerFromInternalField(int index) {
6270 #ifndef V8_ENABLE_CHECKS
6271 typedef internal::Object O;
6272 typedef internal::Internals I;
6273 O* obj = *reinterpret_cast<O**>(this);
6274 // Fast path: If the object is a plain JSObject, which is the common case, we
6275 // know where to find the internal fields and can return the value directly.
6276 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6277 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6278 return I::ReadField<void*>(obj, offset);
6281 return SlowGetAlignedPointerFromInternalField(index);
6285 String* String::Cast(v8::Value* value) {
6286 #ifdef V8_ENABLE_CHECKS
6289 return static_cast<String*>(value);
6293 Local<String> String::Empty(Isolate* isolate) {
6294 typedef internal::Object* S;
6295 typedef internal::Internals I;
6296 I::CheckInitialized(isolate);
6297 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6298 return Local<String>(reinterpret_cast<String*>(slot));
6302 String::ExternalStringResource* String::GetExternalStringResource() const {
6303 typedef internal::Object O;
6304 typedef internal::Internals I;
6305 O* obj = *reinterpret_cast<O* const*>(this);
6306 String::ExternalStringResource* result;
6307 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6308 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6309 result = reinterpret_cast<String::ExternalStringResource*>(value);
6313 #ifdef V8_ENABLE_CHECKS
6314 VerifyExternalStringResource(result);
6320 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6321 String::Encoding* encoding_out) const {
6322 typedef internal::Object O;
6323 typedef internal::Internals I;
6324 O* obj = *reinterpret_cast<O* const*>(this);
6325 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6326 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6327 ExternalStringResourceBase* resource = NULL;
6328 if (type == I::kExternalAsciiRepresentationTag ||
6329 type == I::kExternalTwoByteRepresentationTag) {
6330 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6331 resource = static_cast<ExternalStringResourceBase*>(value);
6333 #ifdef V8_ENABLE_CHECKS
6334 VerifyExternalStringResourceBase(resource, *encoding_out);
6340 bool Value::IsUndefined() const {
6341 #ifdef V8_ENABLE_CHECKS
6342 return FullIsUndefined();
6344 return QuickIsUndefined();
6348 bool Value::QuickIsUndefined() const {
6349 typedef internal::Object O;
6350 typedef internal::Internals I;
6351 O* obj = *reinterpret_cast<O* const*>(this);
6352 if (!I::HasHeapObjectTag(obj)) return false;
6353 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6354 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6358 bool Value::IsNull() const {
6359 #ifdef V8_ENABLE_CHECKS
6360 return FullIsNull();
6362 return QuickIsNull();
6366 bool Value::QuickIsNull() const {
6367 typedef internal::Object O;
6368 typedef internal::Internals I;
6369 O* obj = *reinterpret_cast<O* const*>(this);
6370 if (!I::HasHeapObjectTag(obj)) return false;
6371 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6372 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6376 bool Value::IsString() const {
6377 #ifdef V8_ENABLE_CHECKS
6378 return FullIsString();
6380 return QuickIsString();
6384 bool Value::QuickIsString() const {
6385 typedef internal::Object O;
6386 typedef internal::Internals I;
6387 O* obj = *reinterpret_cast<O* const*>(this);
6388 if (!I::HasHeapObjectTag(obj)) return false;
6389 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6393 template <class T> Value* Value::Cast(T* value) {
6394 return static_cast<Value*>(value);
6398 Symbol* Symbol::Cast(v8::Value* value) {
6399 #ifdef V8_ENABLE_CHECKS
6402 return static_cast<Symbol*>(value);
6406 Number* Number::Cast(v8::Value* value) {
6407 #ifdef V8_ENABLE_CHECKS
6410 return static_cast<Number*>(value);
6414 Integer* Integer::Cast(v8::Value* value) {
6415 #ifdef V8_ENABLE_CHECKS
6418 return static_cast<Integer*>(value);
6422 Date* Date::Cast(v8::Value* value) {
6423 #ifdef V8_ENABLE_CHECKS
6426 return static_cast<Date*>(value);
6430 StringObject* StringObject::Cast(v8::Value* value) {
6431 #ifdef V8_ENABLE_CHECKS
6434 return static_cast<StringObject*>(value);
6438 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6439 #ifdef V8_ENABLE_CHECKS
6442 return static_cast<SymbolObject*>(value);
6446 NumberObject* NumberObject::Cast(v8::Value* value) {
6447 #ifdef V8_ENABLE_CHECKS
6450 return static_cast<NumberObject*>(value);
6454 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6455 #ifdef V8_ENABLE_CHECKS
6458 return static_cast<BooleanObject*>(value);
6462 RegExp* RegExp::Cast(v8::Value* value) {
6463 #ifdef V8_ENABLE_CHECKS
6466 return static_cast<RegExp*>(value);
6470 Object* Object::Cast(v8::Value* value) {
6471 #ifdef V8_ENABLE_CHECKS
6474 return static_cast<Object*>(value);
6478 Array* Array::Cast(v8::Value* value) {
6479 #ifdef V8_ENABLE_CHECKS
6482 return static_cast<Array*>(value);
6486 Promise* Promise::Cast(v8::Value* value) {
6487 #ifdef V8_ENABLE_CHECKS
6490 return static_cast<Promise*>(value);
6494 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6495 #ifdef V8_ENABLE_CHECKS
6498 return static_cast<Promise::Resolver*>(value);
6502 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6503 #ifdef V8_ENABLE_CHECKS
6506 return static_cast<ArrayBuffer*>(value);
6510 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6511 #ifdef V8_ENABLE_CHECKS
6514 return static_cast<ArrayBufferView*>(value);
6518 TypedArray* TypedArray::Cast(v8::Value* value) {
6519 #ifdef V8_ENABLE_CHECKS
6522 return static_cast<TypedArray*>(value);
6526 Uint8Array* Uint8Array::Cast(v8::Value* value) {
6527 #ifdef V8_ENABLE_CHECKS
6530 return static_cast<Uint8Array*>(value);
6534 Int8Array* Int8Array::Cast(v8::Value* value) {
6535 #ifdef V8_ENABLE_CHECKS
6538 return static_cast<Int8Array*>(value);
6542 Uint16Array* Uint16Array::Cast(v8::Value* value) {
6543 #ifdef V8_ENABLE_CHECKS
6546 return static_cast<Uint16Array*>(value);
6550 Int16Array* Int16Array::Cast(v8::Value* value) {
6551 #ifdef V8_ENABLE_CHECKS
6554 return static_cast<Int16Array*>(value);
6558 Uint32Array* Uint32Array::Cast(v8::Value* value) {
6559 #ifdef V8_ENABLE_CHECKS
6562 return static_cast<Uint32Array*>(value);
6566 Int32Array* Int32Array::Cast(v8::Value* value) {
6567 #ifdef V8_ENABLE_CHECKS
6570 return static_cast<Int32Array*>(value);
6574 Float32Array* Float32Array::Cast(v8::Value* value) {
6575 #ifdef V8_ENABLE_CHECKS
6578 return static_cast<Float32Array*>(value);
6582 Float32x4Array* Float32x4Array::Cast(v8::Value* value) {
6583 #ifdef V8_ENABLE_CHECKS
6586 return static_cast<Float32x4Array*>(value);
6590 Float64x2Array* Float64x2Array::Cast(v8::Value* value) {
6591 #ifdef V8_ENABLE_CHECKS
6594 return static_cast<Float64x2Array*>(value);
6598 Int32x4Array* Int32x4Array::Cast(v8::Value* value) {
6599 #ifdef V8_ENABLE_CHECKS
6602 return static_cast<Int32x4Array*>(value);
6606 Float64Array* Float64Array::Cast(v8::Value* value) {
6607 #ifdef V8_ENABLE_CHECKS
6610 return static_cast<Float64Array*>(value);
6614 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6615 #ifdef V8_ENABLE_CHECKS
6618 return static_cast<Uint8ClampedArray*>(value);
6622 DataView* DataView::Cast(v8::Value* value) {
6623 #ifdef V8_ENABLE_CHECKS
6626 return static_cast<DataView*>(value);
6630 Function* Function::Cast(v8::Value* value) {
6631 #ifdef V8_ENABLE_CHECKS
6634 return static_cast<Function*>(value);
6638 External* External::Cast(v8::Value* value) {
6639 #ifdef V8_ENABLE_CHECKS
6642 return static_cast<External*>(value);
6646 template<typename T>
6647 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6648 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6652 template<typename T>
6653 Local<Value> PropertyCallbackInfo<T>::Data() const {
6654 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6658 template<typename T>
6659 Local<Object> PropertyCallbackInfo<T>::This() const {
6660 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
6664 template<typename T>
6665 Local<Object> PropertyCallbackInfo<T>::Holder() const {
6666 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6670 template<typename T>
6671 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6672 return ReturnValue<T>(&args_[kReturnValueIndex]);
6676 Handle<Primitive> Undefined(Isolate* isolate) {
6677 typedef internal::Object* S;
6678 typedef internal::Internals I;
6679 I::CheckInitialized(isolate);
6680 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6681 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6685 Handle<Primitive> Null(Isolate* isolate) {
6686 typedef internal::Object* S;
6687 typedef internal::Internals I;
6688 I::CheckInitialized(isolate);
6689 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6690 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6694 Handle<Boolean> True(Isolate* isolate) {
6695 typedef internal::Object* S;
6696 typedef internal::Internals I;
6697 I::CheckInitialized(isolate);
6698 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6699 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6703 Handle<Boolean> False(Isolate* isolate) {
6704 typedef internal::Object* S;
6705 typedef internal::Internals I;
6706 I::CheckInitialized(isolate);
6707 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6708 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6712 void Isolate::SetData(uint32_t slot, void* data) {
6713 typedef internal::Internals I;
6714 I::SetEmbedderData(this, slot, data);
6718 void* Isolate::GetData(uint32_t slot) {
6719 typedef internal::Internals I;
6720 return I::GetEmbedderData(this, slot);
6724 uint32_t Isolate::GetNumberOfDataSlots() {
6725 typedef internal::Internals I;
6726 return I::kNumIsolateDataSlots;
6730 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
6731 int64_t change_in_bytes) {
6732 typedef internal::Internals I;
6733 int64_t* amount_of_external_allocated_memory =
6734 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
6735 I::kAmountOfExternalAllocatedMemoryOffset);
6736 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
6737 reinterpret_cast<int64_t*>(
6738 reinterpret_cast<uint8_t*>(this) +
6739 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
6740 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
6741 if (change_in_bytes > 0 &&
6742 amount - *amount_of_external_allocated_memory_at_last_global_gc >
6743 I::kExternalAllocationLimit) {
6744 CollectAllGarbage("external memory allocation limit reached.");
6746 *amount_of_external_allocated_memory = amount;
6748 return *amount_of_external_allocated_memory;
6752 template<typename T>
6753 void Isolate::SetObjectGroupId(const Persistent<T>& object,
6755 TYPE_CHECK(Value, T);
6756 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6760 template<typename T>
6761 void Isolate::SetReferenceFromGroup(UniqueId id,
6762 const Persistent<T>& object) {
6763 TYPE_CHECK(Value, T);
6764 SetReferenceFromGroup(id,
6765 reinterpret_cast<v8::internal::Object**>(object.val_));
6769 template<typename T, typename S>
6770 void Isolate::SetReference(const Persistent<T>& parent,
6771 const Persistent<S>& child) {
6772 TYPE_CHECK(Object, T);
6773 TYPE_CHECK(Value, S);
6774 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6775 reinterpret_cast<v8::internal::Object**>(child.val_));
6779 Local<Value> Context::GetEmbedderData(int index) {
6780 #ifndef V8_ENABLE_CHECKS
6781 typedef internal::Object O;
6782 typedef internal::HeapObject HO;
6783 typedef internal::Internals I;
6784 HO* context = *reinterpret_cast<HO**>(this);
6786 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6787 return Local<Value>(reinterpret_cast<Value*>(result));
6789 return SlowGetEmbedderData(index);
6794 void* Context::GetAlignedPointerFromEmbedderData(int index) {
6795 #ifndef V8_ENABLE_CHECKS
6796 typedef internal::Internals I;
6797 return I::ReadEmbedderData<void*>(this, index);
6799 return SlowGetAlignedPointerFromEmbedderData(index);
6806 * A simple shell that takes a list of expressions on the
6807 * command-line and executes them.
6812 * \example process.cc