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.
4
5 /** \mainpage V8 API Reference Guide
6 *
7 * V8 is Google's open source JavaScript engine.
8 *
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
11 *
12 * For other documentation see http://code.google.com/apis/v8/
13 */
14
15 #ifndef V8_H_
16 #define V8_H_
17
18 #include "v8stdint.h"
19
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.
22
23 #ifdef V8_OS_WIN
24
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
33 #endif
34
35 #ifdef BUILDING_V8_SHARED
36 # define V8_EXPORT __declspec(dllexport)
37 #elif USING_V8_SHARED
38 # define V8_EXPORT __declspec(dllimport)
39 #else
40 # define V8_EXPORT
41 #endif // BUILDING_V8_SHARED
42
43 #else // V8_OS_WIN
44
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")))
49 # else
50 # define V8_EXPORT
51 # endif
52 #else
53 # define V8_EXPORT
54 #endif
55
56 #endif // V8_OS_WIN
57
58 /**
59 * The v8 JavaScript engine.
60 */
61 namespace v8 {
62
63 class AccessorSignature;
64 class Array;
65 class Boolean;
66 class BooleanObject;
67 class Context;
68 class CpuProfiler;
69 class Data;
70 class Date;
71 class DeclaredAccessorDescriptor;
72 class External;
73 class Function;
74 class FunctionTemplate;
75 class HeapProfiler;
76 class ImplementationUtilities;
77 class Int32;
78 class Integer;
79 class Isolate;
80 class Number;
81 class NumberObject;
82 class Object;
83 class ObjectOperationDescriptor;
84 class ObjectTemplate;
85 class Platform;
86 class Primitive;
87 class RawOperationDescriptor;
88 class Script;
89 class Signature;
90 class StackFrame;
91 class StackTrace;
92 class String;
93 class StringObject;
94 class Symbol;
95 class SymbolObject;
96 class Private;
97 class Uint32;
98 class Utils;
99 class Value;
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;
105 template<class T,
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;
113 class Data;
114 template<typename T> class FunctionCallbackInfo;
115 template<typename T> class PropertyCallbackInfo;
116 class StackTrace;
117 class StackFrame;
118 class Isolate;
119 class DeclaredAccessorDescriptor;
120 class ObjectOperationDescriptor;
121 class RawOperationDescriptor;
122 class CallHandlerHelper;
123 class EscapableHandleScope;
124 template<typename T> class ReturnValue;
125
126 namespace internal {
127 class Arguments;
128 class Heap;
129 class HeapObject;
130 class Isolate;
131 class Object;
132 template<typename T> class CustomArguments;
133 class PropertyCallbackArguments;
134 class FunctionCallbackArguments;
135 class GlobalHandles;
136 }
137
138
139 /**
140 * General purpose unique identifier.
141 */
142 class UniqueId {
143 public:
UniqueId(intptr_t data)144 explicit UniqueId(intptr_t data)
145 : data_(data) {}
146
147 bool operator==(const UniqueId& other) const {
148 return data_ == other.data_;
149 }
150
151 bool operator!=(const UniqueId& other) const {
152 return data_ != other.data_;
153 }
154
155 bool operator<(const UniqueId& other) const {
156 return data_ < other.data_;
157 }
158
159 private:
160 intptr_t data_;
161 };
162
163 // --- Handles ---
164
165 #define TYPE_CHECK(T, S) \
166 while (false) { \
167 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
168 }
169
170
171 /**
172 * An object reference managed by the v8 garbage collector.
173 *
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.
182 *
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
188 * longer used.
189 *
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
194 * their handles.
195 */
196 template <class T> class Handle {
197 public:
198 /**
199 * Creates an empty handle.
200 */
Handle()201 V8_INLINE Handle() : val_(0) {}
202
203 /**
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.
212 */
Handle(Handle<S> that)213 template <class S> V8_INLINE Handle(Handle<S> that)
214 : val_(reinterpret_cast<T*>(*that)) {
215 /**
216 * This check fails when trying to convert between incompatible
217 * handles. For example, converting from a Handle<String> to a
218 * Handle<Number>.
219 */
220 TYPE_CHECK(T, S);
221 }
222
223 /**
224 * Returns true if the handle is empty.
225 */
IsEmpty()226 V8_INLINE bool IsEmpty() const { return val_ == 0; }
227
228 /**
229 * Sets the handle to be empty. IsEmpty() will then return true.
230 */
Clear()231 V8_INLINE void Clear() { val_ = 0; }
232
233 V8_INLINE T* operator->() const { return val_; }
234
235 V8_INLINE T* operator*() const { return val_; }
236
237 /**
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.
242 */
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;
248 return *a == *b;
249 }
250
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;
257 return *a == *b;
258 }
259
260 /**
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.
265 */
266 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
267 return !operator==(that);
268 }
269
270 template <class S> V8_INLINE bool operator!=(
271 const Persistent<S>& that) const {
272 return !operator==(that);
273 }
274
Cast(Handle<S> 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>();
280 #endif
281 return Handle<T>(T::Cast(*that));
282 }
283
As()284 template <class S> V8_INLINE Handle<S> As() {
285 return Handle<S>::Cast(*this);
286 }
287
New(Isolate * isolate,Handle<T> that)288 V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
289 return New(isolate, that.val_);
290 }
New(Isolate * isolate,const PersistentBase<T> & that)291 V8_INLINE static Handle<T> New(Isolate* isolate,
292 const PersistentBase<T>& that) {
293 return New(isolate, that.val_);
294 }
295
296 private:
297 friend class Utils;
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;
311 friend class Object;
312 friend class Private;
313
314 /**
315 * Creates a new handle for the specified value.
316 */
Handle(T * val)317 V8_INLINE explicit Handle(T* val) : val_(val) {}
318
319 V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
320
321 T* val_;
322 };
323
324
325 /**
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.
331 */
332 template <class T> class Local : public Handle<T> {
333 public:
334 V8_INLINE Local();
Local(Local<S> that)335 template <class S> V8_INLINE Local(Local<S> that)
336 : Handle<T>(reinterpret_cast<T*>(*that)) {
337 /**
338 * This check fails when trying to convert between incompatible
339 * handles. For example, converting from a Handle<String> to a
340 * Handle<Number>.
341 */
342 TYPE_CHECK(T, S);
343 }
344
345
Cast(Local<S> that)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>();
351 #endif
352 return Local<T>(T::Cast(*that));
353 }
Local(Handle<S> that)354 template <class S> V8_INLINE Local(Handle<S> that)
355 : Handle<T>(reinterpret_cast<T*>(*that)) {
356 TYPE_CHECK(T, S);
357 }
358
As()359 template <class S> V8_INLINE Local<S> As() {
360 return Local<S>::Cast(*this);
361 }
362
363 /**
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.
367 */
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);
371
372 private:
373 friend class Utils;
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;
381 friend class String;
382 friend class Object;
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;
389
Local(S * that)390 template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
391 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
392 };
393
394
395 // Eternal handles are set-once handles that live for the life of the isolate.
396 template <class T> class Eternal {
397 public:
Eternal()398 V8_INLINE Eternal() : index_(kInitialValue) { }
399 template<class S>
Eternal(Isolate * isolate,Local<S> handle)400 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
401 Set(isolate, handle);
402 }
403 // Can only be safely called if already set.
404 V8_INLINE Local<T> Get(Isolate* isolate);
IsEmpty()405 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
406 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
407
408 private:
409 static const int kInitialValue = -1;
410 int index_;
411 };
412
413
414 template<class T, class P>
415 class WeakCallbackData {
416 public:
417 typedef void (*Callback)(const WeakCallbackData<T, P>& data);
418
GetIsolate()419 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
GetValue()420 V8_INLINE Local<T> GetValue() const { return handle_; }
GetParameter()421 V8_INLINE P* GetParameter() const { return parameter_; }
422
423 private:
424 friend class internal::GlobalHandles;
WeakCallbackData(Isolate * isolate,Local<T> handle,P * parameter)425 WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
426 : isolate_(isolate), handle_(handle), parameter_(parameter) { }
427 Isolate* isolate_;
428 Local<T> handle_;
429 P* parameter_;
430 };
431
432
433 /**
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
437 * disposed.
438 *
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.
444 *
445 */
446 template <class T> class PersistentBase {
447 public:
448 /**
449 * If non-empty, destroy the underlying storage cell
450 * IsEmpty() will return true after this call.
451 */
452 V8_INLINE void Reset();
453 /**
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
456 */
457 template <class S>
458 V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
459
460 /**
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
463 */
464 template <class S>
465 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
466
IsEmpty()467 V8_INLINE bool IsEmpty() const { return val_ == 0; }
468
469 template <class S>
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;
475 return *a == *b;
476 }
477
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;
483 return *a == *b;
484 }
485
486 template <class S>
487 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
488 return !operator==(that);
489 }
490
491 template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
492 return !operator==(that);
493 }
494
495 /**
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!
501 */
502 template<typename P>
503 V8_INLINE void SetWeak(
504 P* parameter,
505 typename WeakCallbackData<T, P>::Callback callback);
506
507 template<typename S, typename P>
508 V8_INLINE void SetWeak(
509 P* parameter,
510 typename WeakCallbackData<S, P>::Callback callback);
511
512 template<typename P>
513 V8_INLINE P* ClearWeak();
514
515 // TODO(dcarney): remove this.
ClearWeak()516 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
517
518 /**
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.
523 */
524 V8_INLINE void MarkIndependent();
525
526 /**
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.
533 */
534 V8_INLINE void MarkPartiallyDependent();
535
536 V8_INLINE bool IsIndependent() const;
537
538 /** Checks if the handle holds the only reference to an object. */
539 V8_INLINE bool IsNearDeath() const;
540
541 /** Returns true if the handle's reference is weak. */
542 V8_INLINE bool IsWeak() const;
543
544 /**
545 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
546 * description in v8-profiler.h for details.
547 */
548 V8_INLINE void SetWrapperClassId(uint16_t class_id);
549
550 /**
551 * Returns the class ID previously assigned to this handle or 0 if no class ID
552 * was previously assigned.
553 */
554 V8_INLINE uint16_t WrapperClassId() const;
555
556 private:
557 friend class Isolate;
558 friend class Utils;
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;
567 friend class Object;
568
PersistentBase(T * val)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);
573
574 T* val_;
575 };
576
577
578 /**
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
582 * version.
583 */
584 template<class T>
585 class NonCopyablePersistentTraits {
586 public:
587 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
588 static const bool kResetInDestructor = false;
589 template<class S, class M>
Copy(const Persistent<S,M> & source,NonCopyablePersistent * dest)590 V8_INLINE static void Copy(const Persistent<S, M>& source,
591 NonCopyablePersistent* dest) {
592 Uncompilable<Object>();
593 }
594 // TODO(dcarney): come up with a good compile error here.
Uncompilable()595 template<class O> V8_INLINE static void Uncompilable() {
596 TYPE_CHECK(O, Primitive);
597 }
598 };
599
600
601 /**
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.
604 */
605 template<class T>
606 struct CopyablePersistentTraits {
607 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
608 static const bool kResetInDestructor = true;
609 template<class S, class M>
CopyCopyablePersistentTraits610 static V8_INLINE void Copy(const Persistent<S, M>& source,
611 CopyablePersistent* dest) {
612 // do nothing, just allow copy
613 }
614 };
615
616
617 /**
618 * A PersistentBase which allows copy and assignment.
619 *
620 * Copy, assignment and destructor bevavior is controlled by the traits
621 * class M.
622 *
623 * Note: Persistent class hierarchy is subject to future changes.
624 */
625 template <class T, class M> class Persistent : public PersistentBase<T> {
626 public:
627 /**
628 * A Persistent with no storage cell.
629 */
Persistent()630 V8_INLINE Persistent() : PersistentBase<T>(0) { }
631 /**
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.
635 */
Persistent(Isolate * isolate,Handle<S> that)636 template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
637 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
638 TYPE_CHECK(T, S);
639 }
640 /**
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.
644 */
645 template <class S, class M2>
Persistent(Isolate * isolate,const Persistent<S,M2> & that)646 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
647 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
648 TYPE_CHECK(T, S);
649 }
650 /**
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
654 * copied Persistent.
655 */
Persistent(const Persistent & that)656 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
657 Copy(that);
658 }
659 template <class S, class M2>
Persistent(const Persistent<S,M2> & that)660 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
661 Copy(that);
662 }
663 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
664 Copy(that);
665 return *this;
666 }
667 template <class S, class M2>
668 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
669 Copy(that);
670 return *this;
671 }
672 /**
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.
676 */
~Persistent()677 V8_INLINE ~Persistent() {
678 if (M::kResetInDestructor) this->Reset();
679 }
680
681 // TODO(dcarney): this is pretty useless, fix or remove
682 template <class S>
Cast(Persistent<S> & that)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);
688 #endif
689 return reinterpret_cast<Persistent<T>&>(that);
690 }
691
692 // TODO(dcarney): this is pretty useless, fix or remove
As()693 template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
694 return Persistent<S>::Cast(*this);
695 }
696
697 // This will be removed.
698 V8_INLINE T* ClearAndLeak();
699
700 private:
701 friend class Isolate;
702 friend class Utils;
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;
707
Persistent(S * that)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);
712 };
713
714
715 /**
716 * A PersistentBase which has move semantics.
717 *
718 * Note: Persistent class hierarchy is subject to future changes.
719 */
720 template<class T>
721 class UniquePersistent : public PersistentBase<T> {
722 struct RValue {
RValueRValue723 V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
724 UniquePersistent* object;
725 };
726
727 public:
728 /**
729 * A UniquePersistent with no storage cell.
730 */
UniquePersistent()731 V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
732 /**
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.
736 */
737 template <class S>
UniquePersistent(Isolate * isolate,Handle<S> that)738 V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
739 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
740 TYPE_CHECK(T, S);
741 }
742 /**
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.
746 */
747 template <class S>
UniquePersistent(Isolate * isolate,const PersistentBase<S> & that)748 V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
749 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
750 TYPE_CHECK(T, S);
751 }
752 /**
753 * Move constructor.
754 */
UniquePersistent(RValue rvalue)755 V8_INLINE UniquePersistent(RValue rvalue)
756 : PersistentBase<T>(rvalue.object->val_) {
757 rvalue.object->val_ = 0;
758 }
~UniquePersistent()759 V8_INLINE ~UniquePersistent() { this->Reset(); }
760 /**
761 * Move via assignment.
762 */
763 template<class S>
764 V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
765 TYPE_CHECK(T, S);
766 this->Reset();
767 this->val_ = rhs.val_;
768 rhs.val_ = 0;
769 return *this;
770 }
771 /**
772 * Cast operator for moves.
773 */
RValue()774 V8_INLINE operator RValue() { return RValue(this); }
775 /**
776 * Pass allows returning uniques from functions, etc.
777 */
Pass()778 UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
779
780 private:
781 UniquePersistent(UniquePersistent&);
782 void operator=(UniquePersistent&);
783 };
784
785
786 /**
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.
794 *
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.
799 */
800 class V8_EXPORT HandleScope {
801 public:
802 HandleScope(Isolate* isolate);
803
804 ~HandleScope();
805
806 /**
807 * Counts the number of allocated handles.
808 */
809 static int NumberOfHandles(Isolate* isolate);
810
GetIsolate()811 V8_INLINE Isolate* GetIsolate() const {
812 return reinterpret_cast<Isolate*>(isolate_);
813 }
814
815 protected:
HandleScope()816 V8_INLINE HandleScope() {}
817
818 void Initialize(Isolate* isolate);
819
820 static internal::Object** CreateHandle(internal::Isolate* isolate,
821 internal::Object* value);
822
823 private:
824 // Uses heap_object to obtain the current Isolate.
825 static internal::Object** CreateHandle(internal::HeapObject* heap_object,
826 internal::Object* value);
827
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);
834
835 internal::Isolate* isolate_;
836 internal::Object** prev_next_;
837 internal::Object** prev_limit_;
838
839 // Local::New uses CreateHandle with an Isolate* parameter.
840 template<class F> friend class Local;
841
842 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
843 // a HeapObject* in their shortcuts.
844 friend class Object;
845 friend class Context;
846 };
847
848
849 /**
850 * A HandleScope which first allocates a handle in the current scope
851 * which will be later filled with the escape value.
852 */
853 class V8_EXPORT EscapableHandleScope : public HandleScope {
854 public:
855 EscapableHandleScope(Isolate* isolate);
~EscapableHandleScope()856 V8_INLINE ~EscapableHandleScope() {}
857
858 /**
859 * Pushes the value into the previous scope and returns a handle to it.
860 * Cannot be called twice.
861 */
862 template <class T>
Escape(Local<T> value)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));
867 }
868
869 private:
870 internal::Object** Escape(internal::Object** escape_value);
871
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);
878
879 internal::Object** escape_slot_;
880 };
881
882
883 /**
884 * A simple Maybe type, representing an object which may or may not have a
885 * value.
886 */
887 template<class T>
888 struct Maybe {
MaybeMaybe889 Maybe() : has_value(false) {}
MaybeMaybe890 explicit Maybe(T t) : has_value(true), value(t) {}
MaybeMaybe891 Maybe(bool has, T t) : has_value(has), value(t) {}
892
893 bool has_value;
894 T value;
895 };
896
897
898 // --- Special objects ---
899
900
901 /**
902 * The superclass of values and API object templates.
903 */
904 class V8_EXPORT Data {
905 private:
906 Data();
907 };
908
909
910 /**
911 * The origin, within a file, of a script.
912 */
913 class ScriptOrigin {
914 public:
915 V8_INLINE ScriptOrigin(
916 Handle<Value> resource_name,
917 Handle<Integer> resource_line_offset = Handle<Integer>(),
918 Handle<Integer> resource_column_offset = Handle<Integer>(),
919 Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>())
resource_name_(resource_name)920 : resource_name_(resource_name),
921 resource_line_offset_(resource_line_offset),
922 resource_column_offset_(resource_column_offset),
923 resource_is_shared_cross_origin_(resource_is_shared_cross_origin) { }
924 V8_INLINE Handle<Value> ResourceName() const;
925 V8_INLINE Handle<Integer> ResourceLineOffset() const;
926 V8_INLINE Handle<Integer> ResourceColumnOffset() const;
927 V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
928 private:
929 Handle<Value> resource_name_;
930 Handle<Integer> resource_line_offset_;
931 Handle<Integer> resource_column_offset_;
932 Handle<Boolean> resource_is_shared_cross_origin_;
933 };
934
935
936 /**
937 * A compiled JavaScript script, not yet tied to a Context.
938 */
939 class V8_EXPORT UnboundScript {
940 public:
941 /**
942 * Binds the script to the currently entered context.
943 */
944 Local<Script> BindToCurrentContext();
945
946 int GetId();
947 Handle<Value> GetScriptName();
948
949 /**
950 * Returns zero based line number of the code_pos location in the script.
951 * -1 will be returned if no information available.
952 */
953 int GetLineNumber(int code_pos);
954
955 static const int kNoScriptId = 0;
956 };
957
958
959 /**
960 * A compiled JavaScript script, tied to a Context which was active when the
961 * script was compiled.
962 */
963 class V8_EXPORT Script {
964 public:
965 /**
966 * A shorthand for ScriptCompiler::Compile().
967 */
968 static Local<Script> Compile(Handle<String> source,
969 ScriptOrigin* origin = NULL);
970
971 // To be decprecated, use the Compile above.
972 static Local<Script> Compile(Handle<String> source,
973 Handle<String> file_name);
974
975 /**
976 * Runs the script returning the resulting value. It will be run in the
977 * context in which it was created (ScriptCompiler::CompileBound or
978 * UnboundScript::BindToGlobalContext()).
979 */
980 Local<Value> Run();
981
982 /**
983 * Returns the corresponding context-unbound script.
984 */
985 Local<UnboundScript> GetUnboundScript();
986
987 V8_DEPRECATED("Use GetUnboundScript()->GetId()",
GetId()988 int GetId()) {
989 return GetUnboundScript()->GetId();
990 }
991 };
992
993
994 /**
995 * For compiling scripts.
996 */
997 class V8_EXPORT ScriptCompiler {
998 public:
999 /**
1000 * Compilation data that the embedder can cache and pass back to speed up
1001 * future compilations. The data is produced if the CompilerOptions passed to
1002 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1003 * = true. The data to cache can then can be retrieved from
1004 * UnboundScript.
1005 */
1006 struct V8_EXPORT CachedData {
1007 enum BufferPolicy {
1008 BufferNotOwned,
1009 BufferOwned
1010 };
1011
CachedDataCachedData1012 CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
1013
1014 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1015 // data and guarantees that it stays alive until the CachedData object is
1016 // destroyed. If the policy is BufferOwned, the given data will be deleted
1017 // (with delete[]) when the CachedData object is destroyed.
1018 CachedData(const uint8_t* data, int length,
1019 BufferPolicy buffer_policy = BufferNotOwned);
1020 ~CachedData();
1021 // TODO(marja): Async compilation; add constructors which take a callback
1022 // which will be called when V8 no longer needs the data.
1023 const uint8_t* data;
1024 int length;
1025 BufferPolicy buffer_policy;
1026
1027 private:
1028 // Prevent copying. Not implemented.
1029 CachedData(const CachedData&);
1030 CachedData& operator=(const CachedData&);
1031 };
1032
1033 /**
1034 * Source code which can be then compiled to a UnboundScript or Script.
1035 */
1036 class Source {
1037 public:
1038 // Source takes ownership of CachedData.
1039 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1040 CachedData* cached_data = NULL);
1041 V8_INLINE Source(Local<String> source_string,
1042 CachedData* cached_data = NULL);
1043 V8_INLINE ~Source();
1044
1045 // Ownership of the CachedData or its buffers is *not* transferred to the
1046 // caller. The CachedData object is alive as long as the Source object is
1047 // alive.
1048 V8_INLINE const CachedData* GetCachedData() const;
1049
1050 private:
1051 friend class ScriptCompiler;
1052 // Prevent copying. Not implemented.
1053 Source(const Source&);
1054 Source& operator=(const Source&);
1055
1056 Local<String> source_string;
1057
1058 // Origin information
1059 Handle<Value> resource_name;
1060 Handle<Integer> resource_line_offset;
1061 Handle<Integer> resource_column_offset;
1062 Handle<Boolean> resource_is_shared_cross_origin;
1063
1064 // Cached data from previous compilation (if any), or generated during
1065 // compilation (if the generate_cached_data flag is passed to
1066 // ScriptCompiler).
1067 CachedData* cached_data;
1068 };
1069
1070 enum CompileOptions {
1071 kNoCompileOptions,
1072 kProduceDataToCache = 1 << 0
1073 };
1074
1075 /**
1076 * Compiles the specified script (context-independent).
1077 *
1078 * \param source Script source code.
1079 * \return Compiled script object (context independent; for running it must be
1080 * bound to a context).
1081 */
1082 static Local<UnboundScript> CompileUnbound(
1083 Isolate* isolate, Source* source,
1084 CompileOptions options = kNoCompileOptions);
1085
1086 /**
1087 * Compiles the specified script (bound to current context).
1088 *
1089 * \param source Script source code.
1090 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1091 * using pre_data speeds compilation if it's done multiple times.
1092 * Owned by caller, no references are kept when this function returns.
1093 * \return Compiled script object, bound to the context that was active
1094 * when this function was called. When run it will always use this
1095 * context.
1096 */
1097 static Local<Script> Compile(
1098 Isolate* isolate, Source* source,
1099 CompileOptions options = kNoCompileOptions);
1100 };
1101
1102
1103 /**
1104 * An error message.
1105 */
1106 class V8_EXPORT Message {
1107 public:
1108 Local<String> Get() const;
1109 Local<String> GetSourceLine() const;
1110
1111 /**
1112 * Returns the resource name for the script from where the function causing
1113 * the error originates.
1114 */
1115 Handle<Value> GetScriptResourceName() const;
1116
1117 /**
1118 * Exception stack trace. By default stack traces are not captured for
1119 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1120 * to change this option.
1121 */
1122 Handle<StackTrace> GetStackTrace() const;
1123
1124 /**
1125 * Returns the number, 1-based, of the line where the error occurred.
1126 */
1127 int GetLineNumber() const;
1128
1129 /**
1130 * Returns the index within the script of the first character where
1131 * the error occurred.
1132 */
1133 int GetStartPosition() const;
1134
1135 /**
1136 * Returns the index within the script of the last character where
1137 * the error occurred.
1138 */
1139 int GetEndPosition() const;
1140
1141 /**
1142 * Returns the index within the line of the first character where
1143 * the error occurred.
1144 */
1145 int GetStartColumn() const;
1146
1147 /**
1148 * Returns the index within the line of the last character where
1149 * the error occurred.
1150 */
1151 int GetEndColumn() const;
1152
1153 /**
1154 * Passes on the value set by the embedder when it fed the script from which
1155 * this Message was generated to V8.
1156 */
1157 bool IsSharedCrossOrigin() const;
1158
1159 // TODO(1245381): Print to a string instead of on a FILE.
1160 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1161
1162 static const int kNoLineNumberInfo = 0;
1163 static const int kNoColumnInfo = 0;
1164 static const int kNoScriptIdInfo = 0;
1165 };
1166
1167
1168 /**
1169 * Representation of a JavaScript stack trace. The information collected is a
1170 * snapshot of the execution stack and the information remains valid after
1171 * execution continues.
1172 */
1173 class V8_EXPORT StackTrace {
1174 public:
1175 /**
1176 * Flags that determine what information is placed captured for each
1177 * StackFrame when grabbing the current stack trace.
1178 */
1179 enum StackTraceOptions {
1180 kLineNumber = 1,
1181 kColumnOffset = 1 << 1 | kLineNumber,
1182 kScriptName = 1 << 2,
1183 kFunctionName = 1 << 3,
1184 kIsEval = 1 << 4,
1185 kIsConstructor = 1 << 5,
1186 kScriptNameOrSourceURL = 1 << 6,
1187 kScriptId = 1 << 7,
1188 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1189 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1190 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1191 };
1192
1193 /**
1194 * Returns a StackFrame at a particular index.
1195 */
1196 Local<StackFrame> GetFrame(uint32_t index) const;
1197
1198 /**
1199 * Returns the number of StackFrames.
1200 */
1201 int GetFrameCount() const;
1202
1203 /**
1204 * Returns StackTrace as a v8::Array that contains StackFrame objects.
1205 */
1206 Local<Array> AsArray();
1207
1208 /**
1209 * Grab a snapshot of the current JavaScript execution stack.
1210 *
1211 * \param frame_limit The maximum number of stack frames we want to capture.
1212 * \param options Enumerates the set of things we will capture for each
1213 * StackFrame.
1214 */
1215 static Local<StackTrace> CurrentStackTrace(
1216 Isolate* isolate,
1217 int frame_limit,
1218 StackTraceOptions options = kOverview);
1219 };
1220
1221
1222 /**
1223 * A single JavaScript stack frame.
1224 */
1225 class V8_EXPORT StackFrame {
1226 public:
1227 /**
1228 * Returns the number, 1-based, of the line for the associate function call.
1229 * This method will return Message::kNoLineNumberInfo if it is unable to
1230 * retrieve the line number, or if kLineNumber was not passed as an option
1231 * when capturing the StackTrace.
1232 */
1233 int GetLineNumber() const;
1234
1235 /**
1236 * Returns the 1-based column offset on the line for the associated function
1237 * call.
1238 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1239 * the column number, or if kColumnOffset was not passed as an option when
1240 * capturing the StackTrace.
1241 */
1242 int GetColumn() const;
1243
1244 /**
1245 * Returns the id of the script for the function for this StackFrame.
1246 * This method will return Message::kNoScriptIdInfo if it is unable to
1247 * retrieve the script id, or if kScriptId was not passed as an option when
1248 * capturing the StackTrace.
1249 */
1250 int GetScriptId() const;
1251
1252 /**
1253 * Returns the name of the resource that contains the script for the
1254 * function for this StackFrame.
1255 */
1256 Local<String> GetScriptName() const;
1257
1258 /**
1259 * Returns the name of the resource that contains the script for the
1260 * function for this StackFrame or sourceURL value if the script name
1261 * is undefined and its source ends with //# sourceURL=... string or
1262 * deprecated //@ sourceURL=... string.
1263 */
1264 Local<String> GetScriptNameOrSourceURL() const;
1265
1266 /**
1267 * Returns the name of the function associated with this stack frame.
1268 */
1269 Local<String> GetFunctionName() const;
1270
1271 /**
1272 * Returns whether or not the associated function is compiled via a call to
1273 * eval().
1274 */
1275 bool IsEval() const;
1276
1277 /**
1278 * Returns whether or not the associated function is called as a
1279 * constructor via "new".
1280 */
1281 bool IsConstructor() const;
1282 };
1283
1284
1285 /**
1286 * A JSON Parser.
1287 */
1288 class V8_EXPORT JSON {
1289 public:
1290 /**
1291 * Tries to parse the string |json_string| and returns it as value if
1292 * successful.
1293 *
1294 * \param json_string The string to parse.
1295 * \return The corresponding value if successfully parsed.
1296 */
1297 static Local<Value> Parse(Local<String> json_string);
1298 };
1299
1300
1301 // --- Value ---
1302
1303
1304 /**
1305 * The superclass of all JavaScript values and objects.
1306 */
1307 class V8_EXPORT Value : public Data {
1308 public:
1309 /**
1310 * Returns true if this value is the undefined value. See ECMA-262
1311 * 4.3.10.
1312 */
1313 V8_INLINE bool IsUndefined() const;
1314
1315 /**
1316 * Returns true if this value is the null value. See ECMA-262
1317 * 4.3.11.
1318 */
1319 V8_INLINE bool IsNull() const;
1320
1321 /**
1322 * Returns true if this value is true.
1323 */
1324 bool IsTrue() const;
1325
1326 /**
1327 * Returns true if this value is false.
1328 */
1329 bool IsFalse() const;
1330
1331 /**
1332 * Returns true if this value is an instance of the String type.
1333 * See ECMA-262 8.4.
1334 */
1335 V8_INLINE bool IsString() const;
1336
1337 /**
1338 * Returns true if this value is a symbol.
1339 * This is an experimental feature.
1340 */
1341 bool IsSymbol() const;
1342
1343 /**
1344 * Returns true if this value is a function.
1345 */
1346 bool IsFunction() const;
1347
1348 /**
1349 * Returns true if this value is an array.
1350 */
1351 bool IsArray() const;
1352
1353 /**
1354 * Returns true if this value is an object.
1355 */
1356 bool IsObject() const;
1357
1358 /**
1359 * Returns true if this value is boolean.
1360 */
1361 bool IsBoolean() const;
1362
1363 /**
1364 * Returns true if this value is a number.
1365 */
1366 bool IsNumber() const;
1367
1368 /**
1369 * Returns true if this value is external.
1370 */
1371 bool IsExternal() const;
1372
1373 /**
1374 * Returns true if this value is a 32-bit signed integer.
1375 */
1376 bool IsInt32() const;
1377
1378 /**
1379 * Returns true if this value is a 32-bit unsigned integer.
1380 */
1381 bool IsUint32() const;
1382
1383 /**
1384 * Returns true if this value is a Date.
1385 */
1386 bool IsDate() const;
1387
1388 /**
1389 * Returns true if this value is a Boolean object.
1390 */
1391 bool IsBooleanObject() const;
1392
1393 /**
1394 * Returns true if this value is a Number object.
1395 */
1396 bool IsNumberObject() const;
1397
1398 /**
1399 * Returns true if this value is a String object.
1400 */
1401 bool IsStringObject() const;
1402
1403 /**
1404 * Returns true if this value is a Symbol object.
1405 * This is an experimental feature.
1406 */
1407 bool IsSymbolObject() const;
1408
1409 /**
1410 * Returns true if this value is a NativeError.
1411 */
1412 bool IsNativeError() const;
1413
1414 /**
1415 * Returns true if this value is a RegExp.
1416 */
1417 bool IsRegExp() const;
1418
1419 /**
1420 * Returns true if this value is a Promise.
1421 * This is an experimental feature.
1422 */
1423 bool IsPromise() const;
1424
1425 /**
1426 * Returns true if this value is an ArrayBuffer.
1427 * This is an experimental feature.
1428 */
1429 bool IsArrayBuffer() const;
1430
1431 /**
1432 * Returns true if this value is an ArrayBufferView.
1433 * This is an experimental feature.
1434 */
1435 bool IsArrayBufferView() const;
1436
1437 /**
1438 * Returns true if this value is one of TypedArrays.
1439 * This is an experimental feature.
1440 */
1441 bool IsTypedArray() const;
1442
1443 /**
1444 * Returns true if this value is an Uint8Array.
1445 * This is an experimental feature.
1446 */
1447 bool IsUint8Array() const;
1448
1449 /**
1450 * Returns true if this value is an Uint8ClampedArray.
1451 * This is an experimental feature.
1452 */
1453 bool IsUint8ClampedArray() const;
1454
1455 /**
1456 * Returns true if this value is an Int8Array.
1457 * This is an experimental feature.
1458 */
1459 bool IsInt8Array() const;
1460
1461 /**
1462 * Returns true if this value is an Uint16Array.
1463 * This is an experimental feature.
1464 */
1465 bool IsUint16Array() const;
1466
1467 /**
1468 * Returns true if this value is an Int16Array.
1469 * This is an experimental feature.
1470 */
1471 bool IsInt16Array() const;
1472
1473 /**
1474 * Returns true if this value is an Uint32Array.
1475 * This is an experimental feature.
1476 */
1477 bool IsUint32Array() const;
1478
1479 /**
1480 * Returns true if this value is an Int32Array.
1481 * This is an experimental feature.
1482 */
1483 bool IsInt32Array() const;
1484
1485 /**
1486 * Returns true if this value is a Float32Array.
1487 * This is an experimental feature.
1488 */
1489 bool IsFloat32Array() const;
1490
1491 /**
1492 * Returns true if this value is a Float64Array.
1493 * This is an experimental feature.
1494 */
1495 bool IsFloat64Array() const;
1496
1497 /**
1498 * Returns true if this value is a DataView.
1499 * This is an experimental feature.
1500 */
1501 bool IsDataView() const;
1502
1503 Local<Boolean> ToBoolean() const;
1504 Local<Number> ToNumber() const;
1505 Local<String> ToString() const;
1506 Local<String> ToDetailString() const;
1507 Local<Object> ToObject() const;
1508 Local<Integer> ToInteger() const;
1509 Local<Uint32> ToUint32() const;
1510 Local<Int32> ToInt32() const;
1511
1512 /**
1513 * Attempts to convert a string to an array index.
1514 * Returns an empty handle if the conversion fails.
1515 */
1516 Local<Uint32> ToArrayIndex() const;
1517
1518 bool BooleanValue() const;
1519 double NumberValue() const;
1520 int64_t IntegerValue() const;
1521 uint32_t Uint32Value() const;
1522 int32_t Int32Value() const;
1523
1524 /** JS == */
1525 bool Equals(Handle<Value> that) const;
1526 bool StrictEquals(Handle<Value> that) const;
1527 bool SameValue(Handle<Value> that) const;
1528
1529 template <class T> V8_INLINE static Value* Cast(T* value);
1530
1531 private:
1532 V8_INLINE bool QuickIsUndefined() const;
1533 V8_INLINE bool QuickIsNull() const;
1534 V8_INLINE bool QuickIsString() const;
1535 bool FullIsUndefined() const;
1536 bool FullIsNull() const;
1537 bool FullIsString() const;
1538 };
1539
1540
1541 /**
1542 * The superclass of primitive values. See ECMA-262 4.3.2.
1543 */
1544 class V8_EXPORT Primitive : public Value { };
1545
1546
1547 /**
1548 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
1549 * or false value.
1550 */
1551 class V8_EXPORT Boolean : public Primitive {
1552 public:
1553 bool Value() const;
1554 V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
1555 };
1556
1557
1558 /**
1559 * A JavaScript string value (ECMA-262, 4.3.17).
1560 */
1561 class V8_EXPORT String : public Primitive {
1562 public:
1563 enum Encoding {
1564 UNKNOWN_ENCODING = 0x1,
1565 TWO_BYTE_ENCODING = 0x0,
1566 ASCII_ENCODING = 0x4,
1567 ONE_BYTE_ENCODING = 0x4
1568 };
1569 /**
1570 * Returns the number of characters in this string.
1571 */
1572 int Length() const;
1573
1574 /**
1575 * Returns the number of bytes in the UTF-8 encoded
1576 * representation of this string.
1577 */
1578 int Utf8Length() const;
1579
1580 /**
1581 * Returns whether this string is known to contain only one byte data.
1582 * Does not read the string.
1583 * False negatives are possible.
1584 */
1585 bool IsOneByte() const;
1586
1587 /**
1588 * Returns whether this string contain only one byte data.
1589 * Will read the entire string in some cases.
1590 */
1591 bool ContainsOnlyOneByte() const;
1592
1593 /**
1594 * Write the contents of the string to an external buffer.
1595 * If no arguments are given, expects the buffer to be large
1596 * enough to hold the entire string and NULL terminator. Copies
1597 * the contents of the string and the NULL terminator into the
1598 * buffer.
1599 *
1600 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
1601 * before the end of the buffer.
1602 *
1603 * Copies up to length characters into the output buffer.
1604 * Only null-terminates if there is enough space in the buffer.
1605 *
1606 * \param buffer The buffer into which the string will be copied.
1607 * \param start The starting position within the string at which
1608 * copying begins.
1609 * \param length The number of characters to copy from the string. For
1610 * WriteUtf8 the number of bytes in the buffer.
1611 * \param nchars_ref The number of characters written, can be NULL.
1612 * \param options Various options that might affect performance of this or
1613 * subsequent operations.
1614 * \return The number of characters copied to the buffer excluding the null
1615 * terminator. For WriteUtf8: The number of bytes copied to the buffer
1616 * including the null terminator (if written).
1617 */
1618 enum WriteOptions {
1619 NO_OPTIONS = 0,
1620 HINT_MANY_WRITES_EXPECTED = 1,
1621 NO_NULL_TERMINATION = 2,
1622 PRESERVE_ASCII_NULL = 4,
1623 // Used by WriteUtf8 to replace orphan surrogate code units with the
1624 // unicode replacement character. Needs to be set to guarantee valid UTF-8
1625 // output.
1626 REPLACE_INVALID_UTF8 = 8
1627 };
1628
1629 // 16-bit character codes.
1630 int Write(uint16_t* buffer,
1631 int start = 0,
1632 int length = -1,
1633 int options = NO_OPTIONS) const;
1634 // One byte characters.
1635 int WriteOneByte(uint8_t* buffer,
1636 int start = 0,
1637 int length = -1,
1638 int options = NO_OPTIONS) const;
1639 // UTF-8 encoded characters.
1640 int WriteUtf8(char* buffer,
1641 int length = -1,
1642 int* nchars_ref = NULL,
1643 int options = NO_OPTIONS) const;
1644
1645 /**
1646 * A zero length string.
1647 */
1648 V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
1649
1650 /**
1651 * Returns true if the string is external
1652 */
1653 bool IsExternal() const;
1654
1655 /**
1656 * Returns true if the string is both external and ASCII
1657 */
1658 bool IsExternalAscii() const;
1659
1660 class V8_EXPORT ExternalStringResourceBase { // NOLINT
1661 public:
~ExternalStringResourceBase()1662 virtual ~ExternalStringResourceBase() {}
1663
1664 protected:
ExternalStringResourceBase()1665 ExternalStringResourceBase() {}
1666
1667 /**
1668 * Internally V8 will call this Dispose method when the external string
1669 * resource is no longer needed. The default implementation will use the
1670 * delete operator. This method can be overridden in subclasses to
1671 * control how allocated external string resources are disposed.
1672 */
Dispose()1673 virtual void Dispose() { delete this; }
1674
1675 private:
1676 // Disallow copying and assigning.
1677 ExternalStringResourceBase(const ExternalStringResourceBase&);
1678 void operator=(const ExternalStringResourceBase&);
1679
1680 friend class v8::internal::Heap;
1681 };
1682
1683 /**
1684 * An ExternalStringResource is a wrapper around a two-byte string
1685 * buffer that resides outside V8's heap. Implement an
1686 * ExternalStringResource to manage the life cycle of the underlying
1687 * buffer. Note that the string data must be immutable.
1688 */
1689 class V8_EXPORT ExternalStringResource
1690 : public ExternalStringResourceBase {
1691 public:
1692 /**
1693 * Override the destructor to manage the life cycle of the underlying
1694 * buffer.
1695 */
~ExternalStringResource()1696 virtual ~ExternalStringResource() {}
1697
1698 /**
1699 * The string data from the underlying buffer.
1700 */
1701 virtual const uint16_t* data() const = 0;
1702
1703 /**
1704 * The length of the string. That is, the number of two-byte characters.
1705 */
1706 virtual size_t length() const = 0;
1707
1708 protected:
ExternalStringResource()1709 ExternalStringResource() {}
1710 };
1711
1712 /**
1713 * An ExternalAsciiStringResource is a wrapper around an ASCII
1714 * string buffer that resides outside V8's heap. Implement an
1715 * ExternalAsciiStringResource to manage the life cycle of the
1716 * underlying buffer. Note that the string data must be immutable
1717 * and that the data must be strict (7-bit) ASCII, not Latin-1 or
1718 * UTF-8, which would require special treatment internally in the
1719 * engine and, in the case of UTF-8, do not allow efficient indexing.
1720 * Use String::New or convert to 16 bit data for non-ASCII.
1721 */
1722
1723 class V8_EXPORT ExternalAsciiStringResource
1724 : public ExternalStringResourceBase {
1725 public:
1726 /**
1727 * Override the destructor to manage the life cycle of the underlying
1728 * buffer.
1729 */
~ExternalAsciiStringResource()1730 virtual ~ExternalAsciiStringResource() {}
1731 /** The string data from the underlying buffer.*/
1732 virtual const char* data() const = 0;
1733 /** The number of ASCII characters in the string.*/
1734 virtual size_t length() const = 0;
1735 protected:
ExternalAsciiStringResource()1736 ExternalAsciiStringResource() {}
1737 };
1738
1739 typedef ExternalAsciiStringResource ExternalOneByteStringResource;
1740
1741 /**
1742 * If the string is an external string, return the ExternalStringResourceBase
1743 * regardless of the encoding, otherwise return NULL. The encoding of the
1744 * string is returned in encoding_out.
1745 */
1746 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
1747 Encoding* encoding_out) const;
1748
1749 /**
1750 * Get the ExternalStringResource for an external string. Returns
1751 * NULL if IsExternal() doesn't return true.
1752 */
1753 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
1754
1755 /**
1756 * Get the ExternalAsciiStringResource for an external ASCII string.
1757 * Returns NULL if IsExternalAscii() doesn't return true.
1758 */
1759 const ExternalAsciiStringResource* GetExternalAsciiStringResource() const;
1760
1761 V8_INLINE static String* Cast(v8::Value* obj);
1762
1763 enum NewStringType {
1764 kNormalString, kInternalizedString, kUndetectableString
1765 };
1766
1767 /** Allocates a new string from UTF-8 data.*/
1768 static Local<String> NewFromUtf8(Isolate* isolate,
1769 const char* data,
1770 NewStringType type = kNormalString,
1771 int length = -1);
1772
1773 /** Allocates a new string from Latin-1 data.*/
1774 static Local<String> NewFromOneByte(
1775 Isolate* isolate,
1776 const uint8_t* data,
1777 NewStringType type = kNormalString,
1778 int length = -1);
1779
1780 /** Allocates a new string from UTF-16 data.*/
1781 static Local<String> NewFromTwoByte(
1782 Isolate* isolate,
1783 const uint16_t* data,
1784 NewStringType type = kNormalString,
1785 int length = -1);
1786
1787 /**
1788 * Creates a new string by concatenating the left and the right strings
1789 * passed in as parameters.
1790 */
1791 static Local<String> Concat(Handle<String> left, Handle<String> right);
1792
1793 /**
1794 * Creates a new external string using the data defined in the given
1795 * resource. When the external string is no longer live on V8's heap the
1796 * resource will be disposed by calling its Dispose method. The caller of
1797 * this function should not otherwise delete or modify the resource. Neither
1798 * should the underlying buffer be deallocated or modified except through the
1799 * destructor of the external string resource.
1800 */
1801 static Local<String> NewExternal(Isolate* isolate,
1802 ExternalStringResource* resource);
1803
1804 /**
1805 * Associate an external string resource with this string by transforming it
1806 * in place so that existing references to this string in the JavaScript heap
1807 * will use the external string resource. The external string resource's
1808 * character contents need to be equivalent to this string.
1809 * Returns true if the string has been changed to be an external string.
1810 * The string is not modified if the operation fails. See NewExternal for
1811 * information on the lifetime of the resource.
1812 */
1813 bool MakeExternal(ExternalStringResource* resource);
1814
1815 /**
1816 * Creates a new external string using the ASCII data defined in the given
1817 * resource. When the external string is no longer live on V8's heap the
1818 * resource will be disposed by calling its Dispose method. The caller of
1819 * this function should not otherwise delete or modify the resource. Neither
1820 * should the underlying buffer be deallocated or modified except through the
1821 * destructor of the external string resource.
1822 */
1823 static Local<String> NewExternal(Isolate* isolate,
1824 ExternalAsciiStringResource* resource);
1825
1826 /**
1827 * Associate an external string resource with this string by transforming it
1828 * in place so that existing references to this string in the JavaScript heap
1829 * will use the external string resource. The external string resource's
1830 * character contents need to be equivalent to this string.
1831 * Returns true if the string has been changed to be an external string.
1832 * The string is not modified if the operation fails. See NewExternal for
1833 * information on the lifetime of the resource.
1834 */
1835 bool MakeExternal(ExternalAsciiStringResource* resource);
1836
1837 /**
1838 * Returns true if this string can be made external.
1839 */
1840 bool CanMakeExternal();
1841
1842 /**
1843 * Converts an object to a UTF-8-encoded character array. Useful if
1844 * you want to print the object. If conversion to a string fails
1845 * (e.g. due to an exception in the toString() method of the object)
1846 * then the length() method returns 0 and the * operator returns
1847 * NULL.
1848 */
1849 class V8_EXPORT Utf8Value {
1850 public:
1851 explicit Utf8Value(Handle<v8::Value> obj);
1852 ~Utf8Value();
1853 char* operator*() { return str_; }
1854 const char* operator*() const { return str_; }
length()1855 int length() const { return length_; }
1856 private:
1857 char* str_;
1858 int length_;
1859
1860 // Disallow copying and assigning.
1861 Utf8Value(const Utf8Value&);
1862 void operator=(const Utf8Value&);
1863 };
1864
1865 /**
1866 * Converts an object to a two-byte string.
1867 * If conversion to a string fails (eg. due to an exception in the toString()
1868 * method of the object) then the length() method returns 0 and the * operator
1869 * returns NULL.
1870 */
1871 class V8_EXPORT Value {
1872 public:
1873 explicit Value(Handle<v8::Value> obj);
1874 ~Value();
1875 uint16_t* operator*() { return str_; }
1876 const uint16_t* operator*() const { return str_; }
length()1877 int length() const { return length_; }
1878 private:
1879 uint16_t* str_;
1880 int length_;
1881
1882 // Disallow copying and assigning.
1883 Value(const Value&);
1884 void operator=(const Value&);
1885 };
1886
1887 private:
1888 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
1889 Encoding encoding) const;
1890 void VerifyExternalStringResource(ExternalStringResource* val) const;
1891 static void CheckCast(v8::Value* obj);
1892 };
1893
1894
1895 /**
1896 * A JavaScript symbol (ECMA-262 edition 6)
1897 *
1898 * This is an experimental feature. Use at your own risk.
1899 */
1900 class V8_EXPORT Symbol : public Primitive {
1901 public:
1902 // Returns the print name string of the symbol, or undefined if none.
1903 Local<Value> Name() const;
1904
1905 // Create a symbol. If name is not empty, it will be used as the description.
1906 static Local<Symbol> New(
1907 Isolate *isolate, Local<String> name = Local<String>());
1908
1909 // Access global symbol registry.
1910 // Note that symbols created this way are never collected, so
1911 // they should only be used for statically fixed properties.
1912 // Also, there is only one global name space for the names used as keys.
1913 // To minimize the potential for clashes, use qualified names as keys.
1914 static Local<Symbol> For(Isolate *isolate, Local<String> name);
1915
1916 // Retrieve a global symbol. Similar to |For|, but using a separate
1917 // registry that is not accessible by (and cannot clash with) JavaScript code.
1918 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
1919
1920 V8_INLINE static Symbol* Cast(v8::Value* obj);
1921 private:
1922 Symbol();
1923 static void CheckCast(v8::Value* obj);
1924 };
1925
1926
1927 /**
1928 * A private symbol
1929 *
1930 * This is an experimental feature. Use at your own risk.
1931 */
1932 class V8_EXPORT Private : public Data {
1933 public:
1934 // Returns the print name string of the private symbol, or undefined if none.
1935 Local<Value> Name() const;
1936
1937 // Create a private symbol. If name is not empty, it will be the description.
1938 static Local<Private> New(
1939 Isolate *isolate, Local<String> name = Local<String>());
1940
1941 // Retrieve a global private symbol. If a symbol with this name has not
1942 // been retrieved in the same isolate before, it is created.
1943 // Note that private symbols created this way are never collected, so
1944 // they should only be used for statically fixed properties.
1945 // Also, there is only one global name space for the names used as keys.
1946 // To minimize the potential for clashes, use qualified names as keys,
1947 // e.g., "Class#property".
1948 static Local<Private> ForApi(Isolate *isolate, Local<String> name);
1949
1950 private:
1951 Private();
1952 };
1953
1954
1955 /**
1956 * A JavaScript number value (ECMA-262, 4.3.20)
1957 */
1958 class V8_EXPORT Number : public Primitive {
1959 public:
1960 double Value() const;
1961 static Local<Number> New(Isolate* isolate, double value);
1962 V8_INLINE static Number* Cast(v8::Value* obj);
1963 private:
1964 Number();
1965 static void CheckCast(v8::Value* obj);
1966 };
1967
1968
1969 /**
1970 * A JavaScript value representing a signed integer.
1971 */
1972 class V8_EXPORT Integer : public Number {
1973 public:
1974 static Local<Integer> New(Isolate* isolate, int32_t value);
1975 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
1976 int64_t Value() const;
1977 V8_INLINE static Integer* Cast(v8::Value* obj);
1978 private:
1979 Integer();
1980 static void CheckCast(v8::Value* obj);
1981 };
1982
1983
1984 /**
1985 * A JavaScript value representing a 32-bit signed integer.
1986 */
1987 class V8_EXPORT Int32 : public Integer {
1988 public:
1989 int32_t Value() const;
1990 private:
1991 Int32();
1992 };
1993
1994
1995 /**
1996 * A JavaScript value representing a 32-bit unsigned integer.
1997 */
1998 class V8_EXPORT Uint32 : public Integer {
1999 public:
2000 uint32_t Value() const;
2001 private:
2002 Uint32();
2003 };
2004
2005
2006 enum PropertyAttribute {
2007 None = 0,
2008 ReadOnly = 1 << 0,
2009 DontEnum = 1 << 1,
2010 DontDelete = 1 << 2
2011 };
2012
2013 enum ExternalArrayType {
2014 kExternalInt8Array = 1,
2015 kExternalUint8Array,
2016 kExternalInt16Array,
2017 kExternalUint16Array,
2018 kExternalInt32Array,
2019 kExternalUint32Array,
2020 kExternalFloat32Array,
2021 kExternalFloat64Array,
2022 kExternalUint8ClampedArray,
2023
2024 // Legacy constant names
2025 kExternalByteArray = kExternalInt8Array,
2026 kExternalUnsignedByteArray = kExternalUint8Array,
2027 kExternalShortArray = kExternalInt16Array,
2028 kExternalUnsignedShortArray = kExternalUint16Array,
2029 kExternalIntArray = kExternalInt32Array,
2030 kExternalUnsignedIntArray = kExternalUint32Array,
2031 kExternalFloatArray = kExternalFloat32Array,
2032 kExternalDoubleArray = kExternalFloat64Array,
2033 kExternalPixelArray = kExternalUint8ClampedArray
2034 };
2035
2036 /**
2037 * Accessor[Getter|Setter] are used as callback functions when
2038 * setting|getting a particular property. See Object and ObjectTemplate's
2039 * method SetAccessor.
2040 */
2041 typedef void (*AccessorGetterCallback)(
2042 Local<String> property,
2043 const PropertyCallbackInfo<Value>& info);
2044
2045
2046 typedef void (*AccessorSetterCallback)(
2047 Local<String> property,
2048 Local<Value> value,
2049 const PropertyCallbackInfo<void>& info);
2050
2051
2052 /**
2053 * Access control specifications.
2054 *
2055 * Some accessors should be accessible across contexts. These
2056 * accessors have an explicit access control parameter which specifies
2057 * the kind of cross-context access that should be allowed.
2058 *
2059 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2060 */
2061 enum AccessControl {
2062 DEFAULT = 0,
2063 ALL_CAN_READ = 1,
2064 ALL_CAN_WRITE = 1 << 1,
2065 PROHIBITS_OVERWRITING = 1 << 2
2066 };
2067
2068
2069 /**
2070 * A JavaScript object (ECMA-262, 4.3.3)
2071 */
2072 class V8_EXPORT Object : public Value {
2073 public:
2074 bool Set(Handle<Value> key,
2075 Handle<Value> value,
2076 PropertyAttribute attribs = None);
2077
2078 bool Set(uint32_t index, Handle<Value> value);
2079
2080 // Sets an own property on this object bypassing interceptors and
2081 // overriding accessors or read-only properties.
2082 //
2083 // Note that if the object has an interceptor the property will be set
2084 // locally, but since the interceptor takes precedence the local property
2085 // will only be returned if the interceptor doesn't return a value.
2086 //
2087 // Note also that this only works for named properties.
2088 bool ForceSet(Handle<Value> key,
2089 Handle<Value> value,
2090 PropertyAttribute attribs = None);
2091
2092 Local<Value> Get(Handle<Value> key);
2093
2094 Local<Value> Get(uint32_t index);
2095
2096 /**
2097 * Gets the property attributes of a property which can be None or
2098 * any combination of ReadOnly, DontEnum and DontDelete. Returns
2099 * None when the property doesn't exist.
2100 */
2101 PropertyAttribute GetPropertyAttributes(Handle<Value> key);
2102
2103 bool Has(Handle<Value> key);
2104
2105 bool Delete(Handle<Value> key);
2106
2107 // Delete a property on this object bypassing interceptors and
2108 // ignoring dont-delete attributes.
2109 bool ForceDelete(Handle<Value> key);
2110
2111 bool Has(uint32_t index);
2112
2113 bool Delete(uint32_t index);
2114
2115 bool SetAccessor(Handle<String> name,
2116 AccessorGetterCallback getter,
2117 AccessorSetterCallback setter = 0,
2118 Handle<Value> data = Handle<Value>(),
2119 AccessControl settings = DEFAULT,
2120 PropertyAttribute attribute = None);
2121
2122 // This function is not yet stable and should not be used at this time.
2123 bool SetDeclaredAccessor(Local<String> name,
2124 Local<DeclaredAccessorDescriptor> descriptor,
2125 PropertyAttribute attribute = None,
2126 AccessControl settings = DEFAULT);
2127
2128 void SetAccessorProperty(Local<String> name,
2129 Local<Function> getter,
2130 Handle<Function> setter = Handle<Function>(),
2131 PropertyAttribute attribute = None,
2132 AccessControl settings = DEFAULT);
2133
2134 /**
2135 * Functionality for private properties.
2136 * This is an experimental feature, use at your own risk.
2137 * Note: Private properties are inherited. Do not rely on this, since it may
2138 * change.
2139 */
2140 bool HasPrivate(Handle<Private> key);
2141 bool SetPrivate(Handle<Private> key, Handle<Value> value);
2142 bool DeletePrivate(Handle<Private> key);
2143 Local<Value> GetPrivate(Handle<Private> key);
2144
2145 /**
2146 * Returns an array containing the names of the enumerable properties
2147 * of this object, including properties from prototype objects. The
2148 * array returned by this method contains the same values as would
2149 * be enumerated by a for-in statement over this object.
2150 */
2151 Local<Array> GetPropertyNames();
2152
2153 /**
2154 * This function has the same functionality as GetPropertyNames but
2155 * the returned array doesn't contain the names of properties from
2156 * prototype objects.
2157 */
2158 Local<Array> GetOwnPropertyNames();
2159
2160 /**
2161 * Get the prototype object. This does not skip objects marked to
2162 * be skipped by __proto__ and it does not consult the security
2163 * handler.
2164 */
2165 Local<Value> GetPrototype();
2166
2167 /**
2168 * Set the prototype object. This does not skip objects marked to
2169 * be skipped by __proto__ and it does not consult the security
2170 * handler.
2171 */
2172 bool SetPrototype(Handle<Value> prototype);
2173
2174 /**
2175 * Finds an instance of the given function template in the prototype
2176 * chain.
2177 */
2178 Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
2179
2180 /**
2181 * Call builtin Object.prototype.toString on this object.
2182 * This is different from Value::ToString() that may call
2183 * user-defined toString function. This one does not.
2184 */
2185 Local<String> ObjectProtoToString();
2186
2187 /**
2188 * Returns the function invoked as a constructor for this object.
2189 * May be the null value.
2190 */
2191 Local<Value> GetConstructor();
2192
2193 /**
2194 * Returns the name of the function invoked as a constructor for this object.
2195 */
2196 Local<String> GetConstructorName();
2197
2198 /** Gets the number of internal fields for this Object. */
2199 int InternalFieldCount();
2200
2201 /** Same as above, but works for Persistents */
InternalFieldCount(const PersistentBase<Object> & object)2202 V8_INLINE static int InternalFieldCount(
2203 const PersistentBase<Object>& object) {
2204 return object.val_->InternalFieldCount();
2205 }
2206
2207 /** Gets the value from an internal field. */
2208 V8_INLINE Local<Value> GetInternalField(int index);
2209
2210 /** Sets the value in an internal field. */
2211 void SetInternalField(int index, Handle<Value> value);
2212
2213 /**
2214 * Gets a 2-byte-aligned native pointer from an internal field. This field
2215 * must have been set by SetAlignedPointerInInternalField, everything else
2216 * leads to undefined behavior.
2217 */
2218 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
2219
2220 /** Same as above, but works for Persistents */
GetAlignedPointerFromInternalField(const PersistentBase<Object> & object,int index)2221 V8_INLINE static void* GetAlignedPointerFromInternalField(
2222 const PersistentBase<Object>& object, int index) {
2223 return object.val_->GetAlignedPointerFromInternalField(index);
2224 }
2225
2226 /**
2227 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2228 * a field, GetAlignedPointerFromInternalField must be used, everything else
2229 * leads to undefined behavior.
2230 */
2231 void SetAlignedPointerInInternalField(int index, void* value);
2232
2233 // Testers for local properties.
2234 bool HasOwnProperty(Handle<String> key);
2235 bool HasRealNamedProperty(Handle<String> key);
2236 bool HasRealIndexedProperty(uint32_t index);
2237 bool HasRealNamedCallbackProperty(Handle<String> key);
2238
2239 /**
2240 * If result.IsEmpty() no real property was located in the prototype chain.
2241 * This means interceptors in the prototype chain are not called.
2242 */
2243 Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
2244
2245 /**
2246 * If result.IsEmpty() no real property was located on the object or
2247 * in the prototype chain.
2248 * This means interceptors in the prototype chain are not called.
2249 */
2250 Local<Value> GetRealNamedProperty(Handle<String> key);
2251
2252 /** Tests for a named lookup interceptor.*/
2253 bool HasNamedLookupInterceptor();
2254
2255 /** Tests for an index lookup interceptor.*/
2256 bool HasIndexedLookupInterceptor();
2257
2258 /**
2259 * Turns on access check on the object if the object is an instance of
2260 * a template that has access check callbacks. If an object has no
2261 * access check info, the object cannot be accessed by anyone.
2262 */
2263 void TurnOnAccessCheck();
2264
2265 /**
2266 * Returns the identity hash for this object. The current implementation
2267 * uses a hidden property on the object to store the identity hash.
2268 *
2269 * The return value will never be 0. Also, it is not guaranteed to be
2270 * unique.
2271 */
2272 int GetIdentityHash();
2273
2274 /**
2275 * Access hidden properties on JavaScript objects. These properties are
2276 * hidden from the executing JavaScript and only accessible through the V8
2277 * C++ API. Hidden properties introduced by V8 internally (for example the
2278 * identity hash) are prefixed with "v8::".
2279 */
2280 bool SetHiddenValue(Handle<String> key, Handle<Value> value);
2281 Local<Value> GetHiddenValue(Handle<String> key);
2282 bool DeleteHiddenValue(Handle<String> key);
2283
2284 /**
2285 * Returns true if this is an instance of an api function (one
2286 * created from a function created from a function template) and has
2287 * been modified since it was created. Note that this method is
2288 * conservative and may return true for objects that haven't actually
2289 * been modified.
2290 */
2291 bool IsDirty();
2292
2293 /**
2294 * Clone this object with a fast but shallow copy. Values will point
2295 * to the same values as the original object.
2296 */
2297 Local<Object> Clone();
2298
2299 /**
2300 * Returns the context in which the object was created.
2301 */
2302 Local<Context> CreationContext();
2303
2304 /**
2305 * Set the backing store of the indexed properties to be managed by the
2306 * embedding layer. Access to the indexed properties will follow the rules
2307 * spelled out in CanvasPixelArray.
2308 * Note: The embedding program still owns the data and needs to ensure that
2309 * the backing store is preserved while V8 has a reference.
2310 */
2311 void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
2312 bool HasIndexedPropertiesInPixelData();
2313 uint8_t* GetIndexedPropertiesPixelData();
2314 int GetIndexedPropertiesPixelDataLength();
2315
2316 /**
2317 * Set the backing store of the indexed properties to be managed by the
2318 * embedding layer. Access to the indexed properties will follow the rules
2319 * spelled out for the CanvasArray subtypes in the WebGL specification.
2320 * Note: The embedding program still owns the data and needs to ensure that
2321 * the backing store is preserved while V8 has a reference.
2322 */
2323 void SetIndexedPropertiesToExternalArrayData(void* data,
2324 ExternalArrayType array_type,
2325 int number_of_elements);
2326 bool HasIndexedPropertiesInExternalArrayData();
2327 void* GetIndexedPropertiesExternalArrayData();
2328 ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
2329 int GetIndexedPropertiesExternalArrayDataLength();
2330
2331 /**
2332 * Checks whether a callback is set by the
2333 * ObjectTemplate::SetCallAsFunctionHandler method.
2334 * When an Object is callable this method returns true.
2335 */
2336 bool IsCallable();
2337
2338 /**
2339 * Call an Object as a function if a callback is set by the
2340 * ObjectTemplate::SetCallAsFunctionHandler method.
2341 */
2342 Local<Value> CallAsFunction(Handle<Value> recv,
2343 int argc,
2344 Handle<Value> argv[]);
2345
2346 /**
2347 * Call an Object as a constructor if a callback is set by the
2348 * ObjectTemplate::SetCallAsFunctionHandler method.
2349 * Note: This method behaves like the Function::NewInstance method.
2350 */
2351 Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
2352
2353 static Local<Object> New(Isolate* isolate);
2354
2355 V8_INLINE static Object* Cast(Value* obj);
2356
2357 private:
2358 Object();
2359 static void CheckCast(Value* obj);
2360 Local<Value> SlowGetInternalField(int index);
2361 void* SlowGetAlignedPointerFromInternalField(int index);
2362 };
2363
2364
2365 /**
2366 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2367 */
2368 class V8_EXPORT Array : public Object {
2369 public:
2370 uint32_t Length() const;
2371
2372 /**
2373 * Clones an element at index |index|. Returns an empty
2374 * handle if cloning fails (for any reason).
2375 */
2376 Local<Object> CloneElementAt(uint32_t index);
2377
2378 /**
2379 * Creates a JavaScript array with the given length. If the length
2380 * is negative the returned array will have length 0.
2381 */
2382 static Local<Array> New(Isolate* isolate, int length = 0);
2383
2384 V8_INLINE static Array* Cast(Value* obj);
2385 private:
2386 Array();
2387 static void CheckCast(Value* obj);
2388 };
2389
2390
2391 template<typename T>
2392 class ReturnValue {
2393 public:
ReturnValue(const ReturnValue<S> & that)2394 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
2395 : value_(that.value_) {
2396 TYPE_CHECK(T, S);
2397 }
2398 // Handle setters
2399 template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
2400 template <typename S> V8_INLINE void Set(const Handle<S> handle);
2401 // Fast primitive setters
2402 V8_INLINE void Set(bool value);
2403 V8_INLINE void Set(double i);
2404 V8_INLINE void Set(int32_t i);
2405 V8_INLINE void Set(uint32_t i);
2406 // Fast JS primitive setters
2407 V8_INLINE void SetNull();
2408 V8_INLINE void SetUndefined();
2409 V8_INLINE void SetEmptyString();
2410 // Convenience getter for Isolate
2411 V8_INLINE Isolate* GetIsolate();
2412
2413 // Pointer setter: Uncompilable to prevent inadvertent misuse.
2414 template <typename S>
2415 V8_INLINE void Set(S* whatever);
2416
2417 private:
2418 template<class F> friend class ReturnValue;
2419 template<class F> friend class FunctionCallbackInfo;
2420 template<class F> friend class PropertyCallbackInfo;
2421 template<class F, class G, class H> friend class PersistentValueMap;
SetInternal(internal::Object * value)2422 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
2423 V8_INLINE internal::Object* GetDefaultValue();
2424 V8_INLINE explicit ReturnValue(internal::Object** slot);
2425 internal::Object** value_;
2426 };
2427
2428
2429 /**
2430 * The argument information given to function call callbacks. This
2431 * class provides access to information about the context of the call,
2432 * including the receiver, the number and values of arguments, and
2433 * the holder of the function.
2434 */
2435 template<typename T>
2436 class FunctionCallbackInfo {
2437 public:
2438 V8_INLINE int Length() const;
2439 V8_INLINE Local<Value> operator[](int i) const;
2440 V8_INLINE Local<Function> Callee() const;
2441 V8_INLINE Local<Object> This() const;
2442 V8_INLINE Local<Object> Holder() const;
2443 V8_INLINE bool IsConstructCall() const;
2444 V8_INLINE Local<Value> Data() const;
2445 V8_INLINE Isolate* GetIsolate() const;
2446 V8_INLINE ReturnValue<T> GetReturnValue() const;
2447 // This shouldn't be public, but the arm compiler needs it.
2448 static const int kArgsLength = 7;
2449
2450 protected:
2451 friend class internal::FunctionCallbackArguments;
2452 friend class internal::CustomArguments<FunctionCallbackInfo>;
2453 static const int kHolderIndex = 0;
2454 static const int kIsolateIndex = 1;
2455 static const int kReturnValueDefaultValueIndex = 2;
2456 static const int kReturnValueIndex = 3;
2457 static const int kDataIndex = 4;
2458 static const int kCalleeIndex = 5;
2459 static const int kContextSaveIndex = 6;
2460
2461 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
2462 internal::Object** values,
2463 int length,
2464 bool is_construct_call);
2465 internal::Object** implicit_args_;
2466 internal::Object** values_;
2467 int length_;
2468 bool is_construct_call_;
2469 };
2470
2471
2472 /**
2473 * The information passed to a property callback about the context
2474 * of the property access.
2475 */
2476 template<typename T>
2477 class PropertyCallbackInfo {
2478 public:
2479 V8_INLINE Isolate* GetIsolate() const;
2480 V8_INLINE Local<Value> Data() const;
2481 V8_INLINE Local<Object> This() const;
2482 V8_INLINE Local<Object> Holder() const;
2483 V8_INLINE ReturnValue<T> GetReturnValue() const;
2484 // This shouldn't be public, but the arm compiler needs it.
2485 static const int kArgsLength = 6;
2486
2487 protected:
2488 friend class MacroAssembler;
2489 friend class internal::PropertyCallbackArguments;
2490 friend class internal::CustomArguments<PropertyCallbackInfo>;
2491 static const int kHolderIndex = 0;
2492 static const int kIsolateIndex = 1;
2493 static const int kReturnValueDefaultValueIndex = 2;
2494 static const int kReturnValueIndex = 3;
2495 static const int kDataIndex = 4;
2496 static const int kThisIndex = 5;
2497
PropertyCallbackInfo(internal::Object ** args)2498 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
2499 internal::Object** args_;
2500 };
2501
2502
2503 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
2504
2505
2506 /**
2507 * A JavaScript function object (ECMA-262, 15.3).
2508 */
2509 class V8_EXPORT Function : public Object {
2510 public:
2511 /**
2512 * Create a function in the current execution context
2513 * for a given FunctionCallback.
2514 */
2515 static Local<Function> New(Isolate* isolate,
2516 FunctionCallback callback,
2517 Local<Value> data = Local<Value>(),
2518 int length = 0);
2519
2520 Local<Object> NewInstance() const;
2521 Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
2522 Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
2523 void SetName(Handle<String> name);
2524 Handle<Value> GetName() const;
2525
2526 /**
2527 * Name inferred from variable or property assignment of this function.
2528 * Used to facilitate debugging and profiling of JavaScript code written
2529 * in an OO style, where many functions are anonymous but are assigned
2530 * to object properties.
2531 */
2532 Handle<Value> GetInferredName() const;
2533
2534 /**
2535 * User-defined name assigned to the "displayName" property of this function.
2536 * Used to facilitate debugging and profiling of JavaScript code.
2537 */
2538 Handle<Value> GetDisplayName() const;
2539
2540 /**
2541 * Returns zero based line number of function body and
2542 * kLineOffsetNotFound if no information available.
2543 */
2544 int GetScriptLineNumber() const;
2545 /**
2546 * Returns zero based column number of function body and
2547 * kLineOffsetNotFound if no information available.
2548 */
2549 int GetScriptColumnNumber() const;
2550
2551 /**
2552 * Tells whether this function is builtin.
2553 */
2554 bool IsBuiltin() const;
2555
2556 /**
2557 * Returns scriptId.
2558 */
2559 int ScriptId() const;
2560
2561 /**
2562 * Returns the original function if this function is bound, else returns
2563 * v8::Undefined.
2564 */
2565 Local<Value> GetBoundFunction() const;
2566
2567 ScriptOrigin GetScriptOrigin() const;
2568 V8_INLINE static Function* Cast(Value* obj);
2569 static const int kLineOffsetNotFound;
2570
2571 private:
2572 Function();
2573 static void CheckCast(Value* obj);
2574 };
2575
2576
2577 /**
2578 * An instance of the built-in Promise constructor (ES6 draft).
2579 * This API is experimental. Only works with --harmony flag.
2580 */
2581 class V8_EXPORT Promise : public Object {
2582 public:
2583 class V8_EXPORT Resolver : public Object {
2584 public:
2585 /**
2586 * Create a new resolver, along with an associated promise in pending state.
2587 */
2588 static Local<Resolver> New(Isolate* isolate);
2589
2590 /**
2591 * Extract the associated promise.
2592 */
2593 Local<Promise> GetPromise();
2594
2595 /**
2596 * Resolve/reject the associated promise with a given value.
2597 * Ignored if the promise is no longer pending.
2598 */
2599 void Resolve(Handle<Value> value);
2600 void Reject(Handle<Value> value);
2601
2602 V8_INLINE static Resolver* Cast(Value* obj);
2603
2604 private:
2605 Resolver();
2606 static void CheckCast(Value* obj);
2607 };
2608
2609 /**
2610 * Register a resolution/rejection handler with a promise.
2611 * The handler is given the respective resolution/rejection value as
2612 * an argument. If the promise is already resolved/rejected, the handler is
2613 * invoked at the end of turn.
2614 */
2615 Local<Promise> Chain(Handle<Function> handler);
2616 Local<Promise> Catch(Handle<Function> handler);
2617 Local<Promise> Then(Handle<Function> handler);
2618
2619 V8_INLINE static Promise* Cast(Value* obj);
2620
2621 private:
2622 Promise();
2623 static void CheckCast(Value* obj);
2624 };
2625
2626
2627 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
2628 // The number of required internal fields can be defined by embedder.
2629 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
2630 #endif
2631
2632 /**
2633 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
2634 * This API is experimental and may change significantly.
2635 */
2636 class V8_EXPORT ArrayBuffer : public Object {
2637 public:
2638 /**
2639 * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
2640 * The allocator is a global V8 setting. It should be set with
2641 * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
2642 *
2643 * This API is experimental and may change significantly.
2644 */
2645 class V8_EXPORT Allocator { // NOLINT
2646 public:
~Allocator()2647 virtual ~Allocator() {}
2648
2649 /**
2650 * Allocate |length| bytes. Return NULL if allocation is not successful.
2651 * Memory should be initialized to zeroes.
2652 */
2653 virtual void* Allocate(size_t length) = 0;
2654
2655 /**
2656 * Allocate |length| bytes. Return NULL if allocation is not successful.
2657 * Memory does not have to be initialized.
2658 */
2659 virtual void* AllocateUninitialized(size_t length) = 0;
2660 /**
2661 * Free the memory block of size |length|, pointed to by |data|.
2662 * That memory is guaranteed to be previously allocated by |Allocate|.
2663 */
2664 virtual void Free(void* data, size_t length) = 0;
2665 };
2666
2667 /**
2668 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
2669 * returns an instance of this class, populated, with a pointer to data
2670 * and byte length.
2671 *
2672 * The Data pointer of ArrayBuffer::Contents is always allocated with
2673 * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
2674 *
2675 * This API is experimental and may change significantly.
2676 */
2677 class V8_EXPORT Contents { // NOLINT
2678 public:
Contents()2679 Contents() : data_(NULL), byte_length_(0) {}
2680
Data()2681 void* Data() const { return data_; }
ByteLength()2682 size_t ByteLength() const { return byte_length_; }
2683
2684 private:
2685 void* data_;
2686 size_t byte_length_;
2687
2688 friend class ArrayBuffer;
2689 };
2690
2691
2692 /**
2693 * Data length in bytes.
2694 */
2695 size_t ByteLength() const;
2696
2697 /**
2698 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
2699 * Allocated memory will be owned by a created ArrayBuffer and
2700 * will be deallocated when it is garbage-collected,
2701 * unless the object is externalized.
2702 */
2703 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
2704
2705 /**
2706 * Create a new ArrayBuffer over an existing memory block.
2707 * The created array buffer is immediately in externalized state.
2708 * The memory block will not be reclaimed when a created ArrayBuffer
2709 * is garbage-collected.
2710 */
2711 static Local<ArrayBuffer> New(Isolate* isolate, void* data,
2712 size_t byte_length);
2713
2714 /**
2715 * Returns true if ArrayBuffer is extrenalized, that is, does not
2716 * own its memory block.
2717 */
2718 bool IsExternal() const;
2719
2720 /**
2721 * Neuters this ArrayBuffer and all its views (typed arrays).
2722 * Neutering sets the byte length of the buffer and all typed arrays to zero,
2723 * preventing JavaScript from ever accessing underlying backing store.
2724 * ArrayBuffer should have been externalized.
2725 */
2726 void Neuter();
2727
2728 /**
2729 * Make this ArrayBuffer external. The pointer to underlying memory block
2730 * and byte length are returned as |Contents| structure. After ArrayBuffer
2731 * had been etxrenalized, it does no longer owns the memory block. The caller
2732 * should take steps to free memory when it is no longer needed.
2733 *
2734 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
2735 * that has been set with V8::SetArrayBufferAllocator.
2736 */
2737 Contents Externalize();
2738
2739 V8_INLINE static ArrayBuffer* Cast(Value* obj);
2740
2741 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
2742
2743 private:
2744 ArrayBuffer();
2745 static void CheckCast(Value* obj);
2746 };
2747
2748
2749 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
2750 // The number of required internal fields can be defined by embedder.
2751 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
2752 #endif
2753
2754
2755 /**
2756 * A base class for an instance of one of "views" over ArrayBuffer,
2757 * including TypedArrays and DataView (ES6 draft 15.13).
2758 *
2759 * This API is experimental and may change significantly.
2760 */
2761 class V8_EXPORT ArrayBufferView : public Object {
2762 public:
2763 /**
2764 * Returns underlying ArrayBuffer.
2765 */
2766 Local<ArrayBuffer> Buffer();
2767 /**
2768 * Byte offset in |Buffer|.
2769 */
2770 size_t ByteOffset();
2771 /**
2772 * Size of a view in bytes.
2773 */
2774 size_t ByteLength();
2775
2776 V8_INLINE static ArrayBufferView* Cast(Value* obj);
2777
2778 static const int kInternalFieldCount =
2779 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
2780
2781 private:
2782 ArrayBufferView();
2783 static void CheckCast(Value* obj);
2784 };
2785
2786
2787 /**
2788 * A base class for an instance of TypedArray series of constructors
2789 * (ES6 draft 15.13.6).
2790 * This API is experimental and may change significantly.
2791 */
2792 class V8_EXPORT TypedArray : public ArrayBufferView {
2793 public:
2794 /**
2795 * Number of elements in this typed array
2796 * (e.g. for Int16Array, |ByteLength|/2).
2797 */
2798 size_t Length();
2799
2800 V8_INLINE static TypedArray* Cast(Value* obj);
2801
2802 private:
2803 TypedArray();
2804 static void CheckCast(Value* obj);
2805 };
2806
2807
2808 /**
2809 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
2810 * This API is experimental and may change significantly.
2811 */
2812 class V8_EXPORT Uint8Array : public TypedArray {
2813 public:
2814 static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
2815 size_t byte_offset, size_t length);
2816 V8_INLINE static Uint8Array* Cast(Value* obj);
2817
2818 private:
2819 Uint8Array();
2820 static void CheckCast(Value* obj);
2821 };
2822
2823
2824 /**
2825 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
2826 * This API is experimental and may change significantly.
2827 */
2828 class V8_EXPORT Uint8ClampedArray : public TypedArray {
2829 public:
2830 static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
2831 size_t byte_offset, size_t length);
2832 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
2833
2834 private:
2835 Uint8ClampedArray();
2836 static void CheckCast(Value* obj);
2837 };
2838
2839 /**
2840 * An instance of Int8Array constructor (ES6 draft 15.13.6).
2841 * This API is experimental and may change significantly.
2842 */
2843 class V8_EXPORT Int8Array : public TypedArray {
2844 public:
2845 static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
2846 size_t byte_offset, size_t length);
2847 V8_INLINE static Int8Array* Cast(Value* obj);
2848
2849 private:
2850 Int8Array();
2851 static void CheckCast(Value* obj);
2852 };
2853
2854
2855 /**
2856 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
2857 * This API is experimental and may change significantly.
2858 */
2859 class V8_EXPORT Uint16Array : public TypedArray {
2860 public:
2861 static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
2862 size_t byte_offset, size_t length);
2863 V8_INLINE static Uint16Array* Cast(Value* obj);
2864
2865 private:
2866 Uint16Array();
2867 static void CheckCast(Value* obj);
2868 };
2869
2870
2871 /**
2872 * An instance of Int16Array constructor (ES6 draft 15.13.6).
2873 * This API is experimental and may change significantly.
2874 */
2875 class V8_EXPORT Int16Array : public TypedArray {
2876 public:
2877 static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
2878 size_t byte_offset, size_t length);
2879 V8_INLINE static Int16Array* Cast(Value* obj);
2880
2881 private:
2882 Int16Array();
2883 static void CheckCast(Value* obj);
2884 };
2885
2886
2887 /**
2888 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
2889 * This API is experimental and may change significantly.
2890 */
2891 class V8_EXPORT Uint32Array : public TypedArray {
2892 public:
2893 static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
2894 size_t byte_offset, size_t length);
2895 V8_INLINE static Uint32Array* Cast(Value* obj);
2896
2897 private:
2898 Uint32Array();
2899 static void CheckCast(Value* obj);
2900 };
2901
2902
2903 /**
2904 * An instance of Int32Array constructor (ES6 draft 15.13.6).
2905 * This API is experimental and may change significantly.
2906 */
2907 class V8_EXPORT Int32Array : public TypedArray {
2908 public:
2909 static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
2910 size_t byte_offset, size_t length);
2911 V8_INLINE static Int32Array* Cast(Value* obj);
2912
2913 private:
2914 Int32Array();
2915 static void CheckCast(Value* obj);
2916 };
2917
2918
2919 /**
2920 * An instance of Float32Array constructor (ES6 draft 15.13.6).
2921 * This API is experimental and may change significantly.
2922 */
2923 class V8_EXPORT Float32Array : public TypedArray {
2924 public:
2925 static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
2926 size_t byte_offset, size_t length);
2927 V8_INLINE static Float32Array* Cast(Value* obj);
2928
2929 private:
2930 Float32Array();
2931 static void CheckCast(Value* obj);
2932 };
2933
2934
2935 /**
2936 * An instance of Float64Array constructor (ES6 draft 15.13.6).
2937 * This API is experimental and may change significantly.
2938 */
2939 class V8_EXPORT Float64Array : public TypedArray {
2940 public:
2941 static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
2942 size_t byte_offset, size_t length);
2943 V8_INLINE static Float64Array* Cast(Value* obj);
2944
2945 private:
2946 Float64Array();
2947 static void CheckCast(Value* obj);
2948 };
2949
2950
2951 /**
2952 * An instance of DataView constructor (ES6 draft 15.13.7).
2953 * This API is experimental and may change significantly.
2954 */
2955 class V8_EXPORT DataView : public ArrayBufferView {
2956 public:
2957 static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
2958 size_t byte_offset, size_t length);
2959 V8_INLINE static DataView* Cast(Value* obj);
2960
2961 private:
2962 DataView();
2963 static void CheckCast(Value* obj);
2964 };
2965
2966
2967 /**
2968 * An instance of the built-in Date constructor (ECMA-262, 15.9).
2969 */
2970 class V8_EXPORT Date : public Object {
2971 public:
2972 static Local<Value> New(Isolate* isolate, double time);
2973
2974 /**
2975 * A specialization of Value::NumberValue that is more efficient
2976 * because we know the structure of this object.
2977 */
2978 double ValueOf() const;
2979
2980 V8_INLINE static Date* Cast(v8::Value* obj);
2981
2982 /**
2983 * Notification that the embedder has changed the time zone,
2984 * daylight savings time, or other date / time configuration
2985 * parameters. V8 keeps a cache of various values used for
2986 * date / time computation. This notification will reset
2987 * those cached values for the current context so that date /
2988 * time configuration changes would be reflected in the Date
2989 * object.
2990 *
2991 * This API should not be called more than needed as it will
2992 * negatively impact the performance of date operations.
2993 */
2994 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
2995
2996 private:
2997 static void CheckCast(v8::Value* obj);
2998 };
2999
3000
3001 /**
3002 * A Number object (ECMA-262, 4.3.21).
3003 */
3004 class V8_EXPORT NumberObject : public Object {
3005 public:
3006 static Local<Value> New(Isolate* isolate, double value);
3007
3008 double ValueOf() const;
3009
3010 V8_INLINE static NumberObject* Cast(v8::Value* obj);
3011
3012 private:
3013 static void CheckCast(v8::Value* obj);
3014 };
3015
3016
3017 /**
3018 * A Boolean object (ECMA-262, 4.3.15).
3019 */
3020 class V8_EXPORT BooleanObject : public Object {
3021 public:
3022 static Local<Value> New(bool value);
3023
3024 bool ValueOf() const;
3025
3026 V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3027
3028 private:
3029 static void CheckCast(v8::Value* obj);
3030 };
3031
3032
3033 /**
3034 * A String object (ECMA-262, 4.3.18).
3035 */
3036 class V8_EXPORT StringObject : public Object {
3037 public:
3038 static Local<Value> New(Handle<String> value);
3039
3040 Local<String> ValueOf() const;
3041
3042 V8_INLINE static StringObject* Cast(v8::Value* obj);
3043
3044 private:
3045 static void CheckCast(v8::Value* obj);
3046 };
3047
3048
3049 /**
3050 * A Symbol object (ECMA-262 edition 6).
3051 *
3052 * This is an experimental feature. Use at your own risk.
3053 */
3054 class V8_EXPORT SymbolObject : public Object {
3055 public:
3056 static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
3057
3058 Local<Symbol> ValueOf() const;
3059
3060 V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3061
3062 private:
3063 static void CheckCast(v8::Value* obj);
3064 };
3065
3066
3067 /**
3068 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3069 */
3070 class V8_EXPORT RegExp : public Object {
3071 public:
3072 /**
3073 * Regular expression flag bits. They can be or'ed to enable a set
3074 * of flags.
3075 */
3076 enum Flags {
3077 kNone = 0,
3078 kGlobal = 1,
3079 kIgnoreCase = 2,
3080 kMultiline = 4
3081 };
3082
3083 /**
3084 * Creates a regular expression from the given pattern string and
3085 * the flags bit field. May throw a JavaScript exception as
3086 * described in ECMA-262, 15.10.4.1.
3087 *
3088 * For example,
3089 * RegExp::New(v8::String::New("foo"),
3090 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3091 * is equivalent to evaluating "/foo/gm".
3092 */
3093 static Local<RegExp> New(Handle<String> pattern, Flags flags);
3094
3095 /**
3096 * Returns the value of the source property: a string representing
3097 * the regular expression.
3098 */
3099 Local<String> GetSource() const;
3100
3101 /**
3102 * Returns the flags bit field.
3103 */
3104 Flags GetFlags() const;
3105
3106 V8_INLINE static RegExp* Cast(v8::Value* obj);
3107
3108 private:
3109 static void CheckCast(v8::Value* obj);
3110 };
3111
3112
3113 /**
3114 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3115 * to associate C++ data structures with JavaScript objects.
3116 */
3117 class V8_EXPORT External : public Value {
3118 public:
3119 static Local<External> New(Isolate* isolate, void* value);
3120 V8_INLINE static External* Cast(Value* obj);
3121 void* Value() const;
3122 private:
3123 static void CheckCast(v8::Value* obj);
3124 };
3125
3126
3127 // --- Templates ---
3128
3129
3130 /**
3131 * The superclass of object and function templates.
3132 */
3133 class V8_EXPORT Template : public Data {
3134 public:
3135 /** Adds a property to each instance created by this template.*/
3136 void Set(Handle<String> name, Handle<Data> value,
3137 PropertyAttribute attributes = None);
3138 V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
3139
3140 void SetAccessorProperty(
3141 Local<String> name,
3142 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
3143 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
3144 PropertyAttribute attribute = None,
3145 AccessControl settings = DEFAULT);
3146
3147 /**
3148 * Whenever the property with the given name is accessed on objects
3149 * created from this Template the getter and setter callbacks
3150 * are called instead of getting and setting the property directly
3151 * on the JavaScript object.
3152 *
3153 * \param name The name of the property for which an accessor is added.
3154 * \param getter The callback to invoke when getting the property.
3155 * \param setter The callback to invoke when setting the property.
3156 * \param data A piece of data that will be passed to the getter and setter
3157 * callbacks whenever they are invoked.
3158 * \param settings Access control settings for the accessor. This is a bit
3159 * field consisting of one of more of
3160 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3161 * The default is to not allow cross-context access.
3162 * ALL_CAN_READ means that all cross-context reads are allowed.
3163 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3164 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3165 * cross-context access.
3166 * \param attribute The attributes of the property for which an accessor
3167 * is added.
3168 * \param signature The signature describes valid receivers for the accessor
3169 * and is used to perform implicit instance checks against them. If the
3170 * receiver is incompatible (i.e. is not an instance of the constructor as
3171 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3172 * thrown and no callback is invoked.
3173 */
3174 void SetNativeDataProperty(Local<String> name,
3175 AccessorGetterCallback getter,
3176 AccessorSetterCallback setter = 0,
3177 // TODO(dcarney): gcc can't handle Local below
3178 Handle<Value> data = Handle<Value>(),
3179 PropertyAttribute attribute = None,
3180 Local<AccessorSignature> signature =
3181 Local<AccessorSignature>(),
3182 AccessControl settings = DEFAULT);
3183
3184 // This function is not yet stable and should not be used at this time.
3185 bool SetDeclaredAccessor(Local<String> name,
3186 Local<DeclaredAccessorDescriptor> descriptor,
3187 PropertyAttribute attribute = None,
3188 Local<AccessorSignature> signature =
3189 Local<AccessorSignature>(),
3190 AccessControl settings = DEFAULT);
3191
3192 private:
3193 Template();
3194
3195 friend class ObjectTemplate;
3196 friend class FunctionTemplate;
3197 };
3198
3199
3200 /**
3201 * NamedProperty[Getter|Setter] are used as interceptors on object.
3202 * See ObjectTemplate::SetNamedPropertyHandler.
3203 */
3204 typedef void (*NamedPropertyGetterCallback)(
3205 Local<String> property,
3206 const PropertyCallbackInfo<Value>& info);
3207
3208
3209 /**
3210 * Returns the value if the setter intercepts the request.
3211 * Otherwise, returns an empty handle.
3212 */
3213 typedef void (*NamedPropertySetterCallback)(
3214 Local<String> property,
3215 Local<Value> value,
3216 const PropertyCallbackInfo<Value>& info);
3217
3218
3219 /**
3220 * Returns a non-empty handle if the interceptor intercepts the request.
3221 * The result is an integer encoding property attributes (like v8::None,
3222 * v8::DontEnum, etc.)
3223 */
3224 typedef void (*NamedPropertyQueryCallback)(
3225 Local<String> property,
3226 const PropertyCallbackInfo<Integer>& info);
3227
3228
3229 /**
3230 * Returns a non-empty handle if the deleter intercepts the request.
3231 * The return value is true if the property could be deleted and false
3232 * otherwise.
3233 */
3234 typedef void (*NamedPropertyDeleterCallback)(
3235 Local<String> property,
3236 const PropertyCallbackInfo<Boolean>& info);
3237
3238
3239 /**
3240 * Returns an array containing the names of the properties the named
3241 * property getter intercepts.
3242 */
3243 typedef void (*NamedPropertyEnumeratorCallback)(
3244 const PropertyCallbackInfo<Array>& info);
3245
3246
3247 /**
3248 * Returns the value of the property if the getter intercepts the
3249 * request. Otherwise, returns an empty handle.
3250 */
3251 typedef void (*IndexedPropertyGetterCallback)(
3252 uint32_t index,
3253 const PropertyCallbackInfo<Value>& info);
3254
3255
3256 /**
3257 * Returns the value if the setter intercepts the request.
3258 * Otherwise, returns an empty handle.
3259 */
3260 typedef void (*IndexedPropertySetterCallback)(
3261 uint32_t index,
3262 Local<Value> value,
3263 const PropertyCallbackInfo<Value>& info);
3264
3265
3266 /**
3267 * Returns a non-empty handle if the interceptor intercepts the request.
3268 * The result is an integer encoding property attributes.
3269 */
3270 typedef void (*IndexedPropertyQueryCallback)(
3271 uint32_t index,
3272 const PropertyCallbackInfo<Integer>& info);
3273
3274
3275 /**
3276 * Returns a non-empty handle if the deleter intercepts the request.
3277 * The return value is true if the property could be deleted and false
3278 * otherwise.
3279 */
3280 typedef void (*IndexedPropertyDeleterCallback)(
3281 uint32_t index,
3282 const PropertyCallbackInfo<Boolean>& info);
3283
3284
3285 /**
3286 * Returns an array containing the indices of the properties the
3287 * indexed property getter intercepts.
3288 */
3289 typedef void (*IndexedPropertyEnumeratorCallback)(
3290 const PropertyCallbackInfo<Array>& info);
3291
3292
3293 /**
3294 * Access type specification.
3295 */
3296 enum AccessType {
3297 ACCESS_GET,
3298 ACCESS_SET,
3299 ACCESS_HAS,
3300 ACCESS_DELETE,
3301 ACCESS_KEYS
3302 };
3303
3304
3305 /**
3306 * Returns true if cross-context access should be allowed to the named
3307 * property with the given key on the host object.
3308 */
3309 typedef bool (*NamedSecurityCallback)(Local<Object> host,
3310 Local<Value> key,
3311 AccessType type,
3312 Local<Value> data);
3313
3314
3315 /**
3316 * Returns true if cross-context access should be allowed to the indexed
3317 * property with the given index on the host object.
3318 */
3319 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
3320 uint32_t index,
3321 AccessType type,
3322 Local<Value> data);
3323
3324
3325 /**
3326 * A FunctionTemplate is used to create functions at runtime. There
3327 * can only be one function created from a FunctionTemplate in a
3328 * context. The lifetime of the created function is equal to the
3329 * lifetime of the context. So in case the embedder needs to create
3330 * temporary functions that can be collected using Scripts is
3331 * preferred.
3332 *
3333 * A FunctionTemplate can have properties, these properties are added to the
3334 * function object when it is created.
3335 *
3336 * A FunctionTemplate has a corresponding instance template which is
3337 * used to create object instances when the function is used as a
3338 * constructor. Properties added to the instance template are added to
3339 * each object instance.
3340 *
3341 * A FunctionTemplate can have a prototype template. The prototype template
3342 * is used to create the prototype object of the function.
3343 *
3344 * The following example shows how to use a FunctionTemplate:
3345 *
3346 * \code
3347 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
3348 * t->Set("func_property", v8::Number::New(1));
3349 *
3350 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
3351 * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
3352 * proto_t->Set("proto_const", v8::Number::New(2));
3353 *
3354 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
3355 * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
3356 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
3357 * instance_t->Set("instance_property", Number::New(3));
3358 *
3359 * v8::Local<v8::Function> function = t->GetFunction();
3360 * v8::Local<v8::Object> instance = function->NewInstance();
3361 * \endcode
3362 *
3363 * Let's use "function" as the JS variable name of the function object
3364 * and "instance" for the instance object created above. The function
3365 * and the instance will have the following properties:
3366 *
3367 * \code
3368 * func_property in function == true;
3369 * function.func_property == 1;
3370 *
3371 * function.prototype.proto_method() invokes 'InvokeCallback'
3372 * function.prototype.proto_const == 2;
3373 *
3374 * instance instanceof function == true;
3375 * instance.instance_accessor calls 'InstanceAccessorCallback'
3376 * instance.instance_property == 3;
3377 * \endcode
3378 *
3379 * A FunctionTemplate can inherit from another one by calling the
3380 * FunctionTemplate::Inherit method. The following graph illustrates
3381 * the semantics of inheritance:
3382 *
3383 * \code
3384 * FunctionTemplate Parent -> Parent() . prototype -> { }
3385 * ^ ^
3386 * | Inherit(Parent) | .__proto__
3387 * | |
3388 * FunctionTemplate Child -> Child() . prototype -> { }
3389 * \endcode
3390 *
3391 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
3392 * object of the Child() function has __proto__ pointing to the
3393 * Parent() function's prototype object. An instance of the Child
3394 * function has all properties on Parent's instance templates.
3395 *
3396 * Let Parent be the FunctionTemplate initialized in the previous
3397 * section and create a Child FunctionTemplate by:
3398 *
3399 * \code
3400 * Local<FunctionTemplate> parent = t;
3401 * Local<FunctionTemplate> child = FunctionTemplate::New();
3402 * child->Inherit(parent);
3403 *
3404 * Local<Function> child_function = child->GetFunction();
3405 * Local<Object> child_instance = child_function->NewInstance();
3406 * \endcode
3407 *
3408 * The Child function and Child instance will have the following
3409 * properties:
3410 *
3411 * \code
3412 * child_func.prototype.__proto__ == function.prototype;
3413 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
3414 * child_instance.instance_property == 3;
3415 * \endcode
3416 */
3417 class V8_EXPORT FunctionTemplate : public Template {
3418 public:
3419 /** Creates a function template.*/
3420 static Local<FunctionTemplate> New(
3421 Isolate* isolate,
3422 FunctionCallback callback = 0,
3423 Handle<Value> data = Handle<Value>(),
3424 Handle<Signature> signature = Handle<Signature>(),
3425 int length = 0);
3426
3427 /** Returns the unique function instance in the current execution context.*/
3428 Local<Function> GetFunction();
3429
3430 /**
3431 * Set the call-handler callback for a FunctionTemplate. This
3432 * callback is called whenever the function created from this
3433 * FunctionTemplate is called.
3434 */
3435 void SetCallHandler(FunctionCallback callback,
3436 Handle<Value> data = Handle<Value>());
3437
3438 /** Set the predefined length property for the FunctionTemplate. */
3439 void SetLength(int length);
3440
3441 /** Get the InstanceTemplate. */
3442 Local<ObjectTemplate> InstanceTemplate();
3443
3444 /** Causes the function template to inherit from a parent function template.*/
3445 void Inherit(Handle<FunctionTemplate> parent);
3446
3447 /**
3448 * A PrototypeTemplate is the template used to create the prototype object
3449 * of the function created by this template.
3450 */
3451 Local<ObjectTemplate> PrototypeTemplate();
3452
3453 /**
3454 * Set the class name of the FunctionTemplate. This is used for
3455 * printing objects created with the function created from the
3456 * FunctionTemplate as its constructor.
3457 */
3458 void SetClassName(Handle<String> name);
3459
3460 /**
3461 * Determines whether the __proto__ accessor ignores instances of
3462 * the function template. If instances of the function template are
3463 * ignored, __proto__ skips all instances and instead returns the
3464 * next object in the prototype chain.
3465 *
3466 * Call with a value of true to make the __proto__ accessor ignore
3467 * instances of the function template. Call with a value of false
3468 * to make the __proto__ accessor not ignore instances of the
3469 * function template. By default, instances of a function template
3470 * are not ignored.
3471 */
3472 void SetHiddenPrototype(bool value);
3473
3474 /**
3475 * Sets the ReadOnly flag in the attributes of the 'prototype' property
3476 * of functions created from this FunctionTemplate to true.
3477 */
3478 void ReadOnlyPrototype();
3479
3480 /**
3481 * Removes the prototype property from functions created from this
3482 * FunctionTemplate.
3483 */
3484 void RemovePrototype();
3485
3486 /**
3487 * Returns true if the given object is an instance of this function
3488 * template.
3489 */
3490 bool HasInstance(Handle<Value> object);
3491
3492 private:
3493 FunctionTemplate();
3494 friend class Context;
3495 friend class ObjectTemplate;
3496 };
3497
3498
3499 /**
3500 * An ObjectTemplate is used to create objects at runtime.
3501 *
3502 * Properties added to an ObjectTemplate are added to each object
3503 * created from the ObjectTemplate.
3504 */
3505 class V8_EXPORT ObjectTemplate : public Template {
3506 public:
3507 /** Creates an ObjectTemplate. */
3508 static Local<ObjectTemplate> New(Isolate* isolate);
3509 // Will be deprecated soon.
3510 static Local<ObjectTemplate> New();
3511
3512 /** Creates a new instance of this template.*/
3513 Local<Object> NewInstance();
3514
3515 /**
3516 * Sets an accessor on the object template.
3517 *
3518 * Whenever the property with the given name is accessed on objects
3519 * created from this ObjectTemplate the getter and setter callbacks
3520 * are called instead of getting and setting the property directly
3521 * on the JavaScript object.
3522 *
3523 * \param name The name of the property for which an accessor is added.
3524 * \param getter The callback to invoke when getting the property.
3525 * \param setter The callback to invoke when setting the property.
3526 * \param data A piece of data that will be passed to the getter and setter
3527 * callbacks whenever they are invoked.
3528 * \param settings Access control settings for the accessor. This is a bit
3529 * field consisting of one of more of
3530 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
3531 * The default is to not allow cross-context access.
3532 * ALL_CAN_READ means that all cross-context reads are allowed.
3533 * ALL_CAN_WRITE means that all cross-context writes are allowed.
3534 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
3535 * cross-context access.
3536 * \param attribute The attributes of the property for which an accessor
3537 * is added.
3538 * \param signature The signature describes valid receivers for the accessor
3539 * and is used to perform implicit instance checks against them. If the
3540 * receiver is incompatible (i.e. is not an instance of the constructor as
3541 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
3542 * thrown and no callback is invoked.
3543 */
3544 void SetAccessor(Handle<String> name,
3545 AccessorGetterCallback getter,
3546 AccessorSetterCallback setter = 0,
3547 Handle<Value> data = Handle<Value>(),
3548 AccessControl settings = DEFAULT,
3549 PropertyAttribute attribute = None,
3550 Handle<AccessorSignature> signature =
3551 Handle<AccessorSignature>());
3552
3553 /**
3554 * Sets a named property handler on the object template.
3555 *
3556 * Whenever a named property is accessed on objects created from
3557 * this object template, the provided callback is invoked instead of
3558 * accessing the property directly on the JavaScript object.
3559 *
3560 * \param getter The callback to invoke when getting a property.
3561 * \param setter The callback to invoke when setting a property.
3562 * \param query The callback to invoke to check if a property is present,
3563 * and if present, get its attributes.
3564 * \param deleter The callback to invoke when deleting a property.
3565 * \param enumerator The callback to invoke to enumerate all the named
3566 * properties of an object.
3567 * \param data A piece of data that will be passed to the callbacks
3568 * whenever they are invoked.
3569 */
3570 void SetNamedPropertyHandler(
3571 NamedPropertyGetterCallback getter,
3572 NamedPropertySetterCallback setter = 0,
3573 NamedPropertyQueryCallback query = 0,
3574 NamedPropertyDeleterCallback deleter = 0,
3575 NamedPropertyEnumeratorCallback enumerator = 0,
3576 Handle<Value> data = Handle<Value>());
3577
3578 /**
3579 * Sets an indexed property handler on the object template.
3580 *
3581 * Whenever an indexed property is accessed on objects created from
3582 * this object template, the provided callback is invoked instead of
3583 * accessing the property directly on the JavaScript object.
3584 *
3585 * \param getter The callback to invoke when getting a property.
3586 * \param setter The callback to invoke when setting a property.
3587 * \param query The callback to invoke to check if an object has a property.
3588 * \param deleter The callback to invoke when deleting a property.
3589 * \param enumerator The callback to invoke to enumerate all the indexed
3590 * properties of an object.
3591 * \param data A piece of data that will be passed to the callbacks
3592 * whenever they are invoked.
3593 */
3594 void SetIndexedPropertyHandler(
3595 IndexedPropertyGetterCallback getter,
3596 IndexedPropertySetterCallback setter = 0,
3597 IndexedPropertyQueryCallback query = 0,
3598 IndexedPropertyDeleterCallback deleter = 0,
3599 IndexedPropertyEnumeratorCallback enumerator = 0,
3600 Handle<Value> data = Handle<Value>());
3601
3602 /**
3603 * Sets the callback to be used when calling instances created from
3604 * this template as a function. If no callback is set, instances
3605 * behave like normal JavaScript objects that cannot be called as a
3606 * function.
3607 */
3608 void SetCallAsFunctionHandler(FunctionCallback callback,
3609 Handle<Value> data = Handle<Value>());
3610
3611 /**
3612 * Mark object instances of the template as undetectable.
3613 *
3614 * In many ways, undetectable objects behave as though they are not
3615 * there. They behave like 'undefined' in conditionals and when
3616 * printed. However, properties can be accessed and called as on
3617 * normal objects.
3618 */
3619 void MarkAsUndetectable();
3620
3621 /**
3622 * Sets access check callbacks on the object template.
3623 *
3624 * When accessing properties on instances of this object template,
3625 * the access check callback will be called to determine whether or
3626 * not to allow cross-context access to the properties.
3627 * The last parameter specifies whether access checks are turned
3628 * on by default on instances. If access checks are off by default,
3629 * they can be turned on on individual instances by calling
3630 * Object::TurnOnAccessCheck().
3631 */
3632 void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
3633 IndexedSecurityCallback indexed_handler,
3634 Handle<Value> data = Handle<Value>(),
3635 bool turned_on_by_default = true);
3636
3637 /**
3638 * Gets the number of internal fields for objects generated from
3639 * this template.
3640 */
3641 int InternalFieldCount();
3642
3643 /**
3644 * Sets the number of internal fields for objects generated from
3645 * this template.
3646 */
3647 void SetInternalFieldCount(int value);
3648
3649 private:
3650 ObjectTemplate();
3651 static Local<ObjectTemplate> New(internal::Isolate* isolate,
3652 Handle<FunctionTemplate> constructor);
3653 friend class FunctionTemplate;
3654 };
3655
3656
3657 /**
3658 * A Signature specifies which receivers and arguments are valid
3659 * parameters to a function.
3660 */
3661 class V8_EXPORT Signature : public Data {
3662 public:
3663 static Local<Signature> New(Isolate* isolate,
3664 Handle<FunctionTemplate> receiver =
3665 Handle<FunctionTemplate>(),
3666 int argc = 0,
3667 Handle<FunctionTemplate> argv[] = 0);
3668
3669 private:
3670 Signature();
3671 };
3672
3673
3674 /**
3675 * An AccessorSignature specifies which receivers are valid parameters
3676 * to an accessor callback.
3677 */
3678 class V8_EXPORT AccessorSignature : public Data {
3679 public:
3680 static Local<AccessorSignature> New(Isolate* isolate,
3681 Handle<FunctionTemplate> receiver =
3682 Handle<FunctionTemplate>());
3683
3684 private:
3685 AccessorSignature();
3686 };
3687
3688
3689 class V8_EXPORT DeclaredAccessorDescriptor : public Data {
3690 private:
3691 DeclaredAccessorDescriptor();
3692 };
3693
3694
3695 class V8_EXPORT ObjectOperationDescriptor : public Data {
3696 public:
3697 // This function is not yet stable and should not be used at this time.
3698 static Local<RawOperationDescriptor> NewInternalFieldDereference(
3699 Isolate* isolate,
3700 int internal_field);
3701 private:
3702 ObjectOperationDescriptor();
3703 };
3704
3705
3706 enum DeclaredAccessorDescriptorDataType {
3707 kDescriptorBoolType,
3708 kDescriptorInt8Type, kDescriptorUint8Type,
3709 kDescriptorInt16Type, kDescriptorUint16Type,
3710 kDescriptorInt32Type, kDescriptorUint32Type,
3711 kDescriptorFloatType, kDescriptorDoubleType
3712 };
3713
3714
3715 class V8_EXPORT RawOperationDescriptor : public Data {
3716 public:
3717 Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
3718 Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
3719 Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
3720 int16_t byte_offset);
3721 Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
3722 void* compare_value);
3723 Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
3724 Isolate* isolate,
3725 DeclaredAccessorDescriptorDataType data_type,
3726 uint8_t bool_offset = 0);
3727 Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
3728 uint8_t bitmask,
3729 uint8_t compare_value);
3730 Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
3731 Isolate* isolate,
3732 uint16_t bitmask,
3733 uint16_t compare_value);
3734 Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
3735 Isolate* isolate,
3736 uint32_t bitmask,
3737 uint32_t compare_value);
3738
3739 private:
3740 RawOperationDescriptor();
3741 };
3742
3743
3744 /**
3745 * A utility for determining the type of objects based on the template
3746 * they were constructed from.
3747 */
3748 class V8_EXPORT TypeSwitch : public Data {
3749 public:
3750 static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
3751 static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
3752 int match(Handle<Value> value);
3753 private:
3754 TypeSwitch();
3755 };
3756
3757
3758 // --- Extensions ---
3759
3760 class V8_EXPORT ExternalAsciiStringResourceImpl
3761 : public String::ExternalAsciiStringResource {
3762 public:
ExternalAsciiStringResourceImpl()3763 ExternalAsciiStringResourceImpl() : data_(0), length_(0) {}
ExternalAsciiStringResourceImpl(const char * data,size_t length)3764 ExternalAsciiStringResourceImpl(const char* data, size_t length)
3765 : data_(data), length_(length) {}
data()3766 const char* data() const { return data_; }
length()3767 size_t length() const { return length_; }
3768
3769 private:
3770 const char* data_;
3771 size_t length_;
3772 };
3773
3774 /**
3775 * Ignore
3776 */
3777 class V8_EXPORT Extension { // NOLINT
3778 public:
3779 // Note that the strings passed into this constructor must live as long
3780 // as the Extension itself.
3781 Extension(const char* name,
3782 const char* source = 0,
3783 int dep_count = 0,
3784 const char** deps = 0,
3785 int source_length = -1);
~Extension()3786 virtual ~Extension() { }
GetNativeFunctionTemplate(v8::Isolate * isolate,v8::Handle<v8::String> name)3787 virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
3788 v8::Isolate* isolate, v8::Handle<v8::String> name) {
3789 return v8::Handle<v8::FunctionTemplate>();
3790 }
3791
name()3792 const char* name() const { return name_; }
source_length()3793 size_t source_length() const { return source_length_; }
source()3794 const String::ExternalAsciiStringResource* source() const {
3795 return &source_; }
dependency_count()3796 int dependency_count() { return dep_count_; }
dependencies()3797 const char** dependencies() { return deps_; }
set_auto_enable(bool value)3798 void set_auto_enable(bool value) { auto_enable_ = value; }
auto_enable()3799 bool auto_enable() { return auto_enable_; }
3800
3801 private:
3802 const char* name_;
3803 size_t source_length_; // expected to initialize before source_
3804 ExternalAsciiStringResourceImpl source_;
3805 int dep_count_;
3806 const char** deps_;
3807 bool auto_enable_;
3808
3809 // Disallow copying and assigning.
3810 Extension(const Extension&);
3811 void operator=(const Extension&);
3812 };
3813
3814
3815 void V8_EXPORT RegisterExtension(Extension* extension);
3816
3817
3818 // --- Statics ---
3819
3820 V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
3821 V8_INLINE Handle<Primitive> Null(Isolate* isolate);
3822 V8_INLINE Handle<Boolean> True(Isolate* isolate);
3823 V8_INLINE Handle<Boolean> False(Isolate* isolate);
3824
3825
3826 /**
3827 * A set of constraints that specifies the limits of the runtime's memory use.
3828 * You must set the heap size before initializing the VM - the size cannot be
3829 * adjusted after the VM is initialized.
3830 *
3831 * If you are using threads then you should hold the V8::Locker lock while
3832 * setting the stack limit and you must set a non-default stack limit separately
3833 * for each thread.
3834 */
3835 class V8_EXPORT ResourceConstraints {
3836 public:
3837 ResourceConstraints();
3838
3839 /**
3840 * Configures the constraints with reasonable default values based on the
3841 * capabilities of the current device the VM is running on.
3842 *
3843 * \param physical_memory The total amount of physical memory on the current
3844 * device, in bytes.
3845 * \param virtual_memory_limit The amount of virtual memory on the current
3846 * device, in bytes, or zero, if there is no limit.
3847 * \param number_of_processors The number of CPUs available on the current
3848 * device.
3849 */
3850 void ConfigureDefaults(uint64_t physical_memory,
3851 uint64_t virtual_memory_limit,
3852 uint32_t number_of_processors);
3853
max_semi_space_size()3854 int max_semi_space_size() const { return max_semi_space_size_; }
set_max_semi_space_size(int value)3855 void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
max_old_space_size()3856 int max_old_space_size() const { return max_old_space_size_; }
set_max_old_space_size(int value)3857 void set_max_old_space_size(int value) { max_old_space_size_ = value; }
max_executable_size()3858 int max_executable_size() const { return max_executable_size_; }
set_max_executable_size(int value)3859 void set_max_executable_size(int value) { max_executable_size_ = value; }
stack_limit()3860 uint32_t* stack_limit() const { return stack_limit_; }
3861 // Sets an address beyond which the VM's stack may not grow.
set_stack_limit(uint32_t * value)3862 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
max_available_threads()3863 int max_available_threads() const { return max_available_threads_; }
3864 // Set the number of threads available to V8, assuming at least 1.
set_max_available_threads(int value)3865 void set_max_available_threads(int value) {
3866 max_available_threads_ = value;
3867 }
code_range_size()3868 size_t code_range_size() const { return code_range_size_; }
set_code_range_size(size_t value)3869 void set_code_range_size(size_t value) {
3870 code_range_size_ = value;
3871 }
3872
3873 private:
3874 int max_semi_space_size_;
3875 int max_old_space_size_;
3876 int max_executable_size_;
3877 uint32_t* stack_limit_;
3878 int max_available_threads_;
3879 size_t code_range_size_;
3880 };
3881
3882
3883 /**
3884 * Sets the given ResourceConstraints on the given Isolate.
3885 */
3886 bool V8_EXPORT SetResourceConstraints(Isolate* isolate,
3887 ResourceConstraints* constraints);
3888
3889
3890 // --- Exceptions ---
3891
3892
3893 typedef void (*FatalErrorCallback)(const char* location, const char* message);
3894
3895
3896 typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
3897
3898 // --- Tracing ---
3899
3900 typedef void (*LogEventCallback)(const char* name, int event);
3901
3902 /**
3903 * Create new error objects by calling the corresponding error object
3904 * constructor with the message.
3905 */
3906 class V8_EXPORT Exception {
3907 public:
3908 static Local<Value> RangeError(Handle<String> message);
3909 static Local<Value> ReferenceError(Handle<String> message);
3910 static Local<Value> SyntaxError(Handle<String> message);
3911 static Local<Value> TypeError(Handle<String> message);
3912 static Local<Value> Error(Handle<String> message);
3913 };
3914
3915
3916 // --- Counters Callbacks ---
3917
3918 typedef int* (*CounterLookupCallback)(const char* name);
3919
3920 typedef void* (*CreateHistogramCallback)(const char* name,
3921 int min,
3922 int max,
3923 size_t buckets);
3924
3925 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
3926
3927 // --- Memory Allocation Callback ---
3928 enum ObjectSpace {
3929 kObjectSpaceNewSpace = 1 << 0,
3930 kObjectSpaceOldPointerSpace = 1 << 1,
3931 kObjectSpaceOldDataSpace = 1 << 2,
3932 kObjectSpaceCodeSpace = 1 << 3,
3933 kObjectSpaceMapSpace = 1 << 4,
3934 kObjectSpaceLoSpace = 1 << 5,
3935
3936 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
3937 kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
3938 kObjectSpaceLoSpace
3939 };
3940
3941 enum AllocationAction {
3942 kAllocationActionAllocate = 1 << 0,
3943 kAllocationActionFree = 1 << 1,
3944 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
3945 };
3946
3947 typedef void (*MemoryAllocationCallback)(ObjectSpace space,
3948 AllocationAction action,
3949 int size);
3950
3951 // --- Leave Script Callback ---
3952 typedef void (*CallCompletedCallback)();
3953
3954 // --- Microtask Callback ---
3955 typedef void (*MicrotaskCallback)(void* data);
3956
3957 // --- Failed Access Check Callback ---
3958 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
3959 AccessType type,
3960 Local<Value> data);
3961
3962 // --- AllowCodeGenerationFromStrings callbacks ---
3963
3964 /**
3965 * Callback to check if code generation from strings is allowed. See
3966 * Context::AllowCodeGenerationFromStrings.
3967 */
3968 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
3969
3970 // --- Garbage Collection Callbacks ---
3971
3972 /**
3973 * Applications can register callback functions which will be called
3974 * before and after a garbage collection. Allocations are not
3975 * allowed in the callback functions, you therefore cannot manipulate
3976 * objects (set or delete properties for example) since it is possible
3977 * such operations will result in the allocation of objects.
3978 */
3979 enum GCType {
3980 kGCTypeScavenge = 1 << 0,
3981 kGCTypeMarkSweepCompact = 1 << 1,
3982 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
3983 };
3984
3985 enum GCCallbackFlags {
3986 kNoGCCallbackFlags = 0,
3987 kGCCallbackFlagCompacted = 1 << 0,
3988 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
3989 kGCCallbackFlagForced = 1 << 2
3990 };
3991
3992 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
3993 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
3994
3995 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
3996
3997
3998 /**
3999 * Collection of V8 heap information.
4000 *
4001 * Instances of this class can be passed to v8::V8::HeapStatistics to
4002 * get heap statistics from V8.
4003 */
4004 class V8_EXPORT HeapStatistics {
4005 public:
4006 HeapStatistics();
total_heap_size()4007 size_t total_heap_size() { return total_heap_size_; }
total_heap_size_executable()4008 size_t total_heap_size_executable() { return total_heap_size_executable_; }
total_physical_size()4009 size_t total_physical_size() { return total_physical_size_; }
used_heap_size()4010 size_t used_heap_size() { return used_heap_size_; }
heap_size_limit()4011 size_t heap_size_limit() { return heap_size_limit_; }
4012
4013 private:
4014 size_t total_heap_size_;
4015 size_t total_heap_size_executable_;
4016 size_t total_physical_size_;
4017 size_t used_heap_size_;
4018 size_t heap_size_limit_;
4019
4020 friend class V8;
4021 friend class Isolate;
4022 };
4023
4024
4025 class RetainedObjectInfo;
4026
4027 /**
4028 * Isolate represents an isolated instance of the V8 engine. V8
4029 * isolates have completely separate states. Objects from one isolate
4030 * must not be used in other isolates. When V8 is initialized a
4031 * default isolate is implicitly created and entered. The embedder
4032 * can create additional isolates and use them in parallel in multiple
4033 * threads. An isolate can be entered by at most one thread at any
4034 * given time. The Locker/Unlocker API must be used to synchronize.
4035 */
4036 class V8_EXPORT Isolate {
4037 public:
4038 /**
4039 * Stack-allocated class which sets the isolate for all operations
4040 * executed within a local scope.
4041 */
4042 class V8_EXPORT Scope {
4043 public:
Scope(Isolate * isolate)4044 explicit Scope(Isolate* isolate) : isolate_(isolate) {
4045 isolate->Enter();
4046 }
4047
~Scope()4048 ~Scope() { isolate_->Exit(); }
4049
4050 private:
4051 Isolate* const isolate_;
4052
4053 // Prevent copying of Scope objects.
4054 Scope(const Scope&);
4055 Scope& operator=(const Scope&);
4056 };
4057
4058
4059 /**
4060 * Assert that no Javascript code is invoked.
4061 */
4062 class V8_EXPORT DisallowJavascriptExecutionScope {
4063 public:
4064 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
4065
4066 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
4067 ~DisallowJavascriptExecutionScope();
4068
4069 private:
4070 bool on_failure_;
4071 void* internal_;
4072
4073 // Prevent copying of Scope objects.
4074 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
4075 DisallowJavascriptExecutionScope& operator=(
4076 const DisallowJavascriptExecutionScope&);
4077 };
4078
4079
4080 /**
4081 * Introduce exception to DisallowJavascriptExecutionScope.
4082 */
4083 class V8_EXPORT AllowJavascriptExecutionScope {
4084 public:
4085 explicit AllowJavascriptExecutionScope(Isolate* isolate);
4086 ~AllowJavascriptExecutionScope();
4087
4088 private:
4089 void* internal_throws_;
4090 void* internal_assert_;
4091
4092 // Prevent copying of Scope objects.
4093 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
4094 AllowJavascriptExecutionScope& operator=(
4095 const AllowJavascriptExecutionScope&);
4096 };
4097
4098 /**
4099 * Do not run microtasks while this scope is active, even if microtasks are
4100 * automatically executed otherwise.
4101 */
4102 class V8_EXPORT SuppressMicrotaskExecutionScope {
4103 public:
4104 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
4105 ~SuppressMicrotaskExecutionScope();
4106
4107 private:
4108 internal::Isolate* isolate_;
4109
4110 // Prevent copying of Scope objects.
4111 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
4112 SuppressMicrotaskExecutionScope& operator=(
4113 const SuppressMicrotaskExecutionScope&);
4114 };
4115
4116 /**
4117 * Types of garbage collections that can be requested via
4118 * RequestGarbageCollectionForTesting.
4119 */
4120 enum GarbageCollectionType {
4121 kFullGarbageCollection,
4122 kMinorGarbageCollection
4123 };
4124
4125 /**
4126 * Creates a new isolate. Does not change the currently entered
4127 * isolate.
4128 *
4129 * When an isolate is no longer used its resources should be freed
4130 * by calling Dispose(). Using the delete operator is not allowed.
4131 */
4132 static Isolate* New();
4133
4134 /**
4135 * Returns the entered isolate for the current thread or NULL in
4136 * case there is no current isolate.
4137 */
4138 static Isolate* GetCurrent();
4139
4140 /**
4141 * Methods below this point require holding a lock (using Locker) in
4142 * a multi-threaded environment.
4143 */
4144
4145 /**
4146 * Sets this isolate as the entered one for the current thread.
4147 * Saves the previously entered one (if any), so that it can be
4148 * restored when exiting. Re-entering an isolate is allowed.
4149 */
4150 void Enter();
4151
4152 /**
4153 * Exits this isolate by restoring the previously entered one in the
4154 * current thread. The isolate may still stay the same, if it was
4155 * entered more than once.
4156 *
4157 * Requires: this == Isolate::GetCurrent().
4158 */
4159 void Exit();
4160
4161 /**
4162 * Disposes the isolate. The isolate must not be entered by any
4163 * thread to be disposable.
4164 */
4165 void Dispose();
4166
4167 /**
4168 * Associate embedder-specific data with the isolate. |slot| has to be
4169 * between 0 and GetNumberOfDataSlots() - 1.
4170 */
4171 V8_INLINE void SetData(uint32_t slot, void* data);
4172
4173 /**
4174 * Retrieve embedder-specific data from the isolate.
4175 * Returns NULL if SetData has never been called for the given |slot|.
4176 */
4177 V8_INLINE void* GetData(uint32_t slot);
4178
4179 /**
4180 * Returns the maximum number of available embedder data slots. Valid slots
4181 * are in the range of 0 - GetNumberOfDataSlots() - 1.
4182 */
4183 V8_INLINE static uint32_t GetNumberOfDataSlots();
4184
4185 /**
4186 * Get statistics about the heap memory usage.
4187 */
4188 void GetHeapStatistics(HeapStatistics* heap_statistics);
4189
4190 /**
4191 * Adjusts the amount of registered external memory. Used to give V8 an
4192 * indication of the amount of externally allocated memory that is kept alive
4193 * by JavaScript objects. V8 uses this to decide when to perform global
4194 * garbage collections. Registering externally allocated memory will trigger
4195 * global garbage collections more often than it would otherwise in an attempt
4196 * to garbage collect the JavaScript objects that keep the externally
4197 * allocated memory alive.
4198 *
4199 * \param change_in_bytes the change in externally allocated memory that is
4200 * kept alive by JavaScript objects.
4201 * \returns the adjusted value.
4202 */
4203 V8_INLINE int64_t
4204 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
4205
4206 /**
4207 * Returns heap profiler for this isolate. Will return NULL until the isolate
4208 * is initialized.
4209 */
4210 HeapProfiler* GetHeapProfiler();
4211
4212 /**
4213 * Returns CPU profiler for this isolate. Will return NULL unless the isolate
4214 * is initialized. It is the embedder's responsibility to stop all CPU
4215 * profiling activities if it has started any.
4216 */
4217 CpuProfiler* GetCpuProfiler();
4218
4219 /** Returns true if this isolate has a current context. */
4220 bool InContext();
4221
4222 /** Returns the context that is on the top of the stack. */
4223 Local<Context> GetCurrentContext();
4224
4225 /**
4226 * Returns the context of the calling JavaScript code. That is the
4227 * context of the top-most JavaScript frame. If there are no
4228 * JavaScript frames an empty handle is returned.
4229 */
4230 Local<Context> GetCallingContext();
4231
4232 /** Returns the last entered context. */
4233 Local<Context> GetEnteredContext();
4234
4235 /**
4236 * Schedules an exception to be thrown when returning to JavaScript. When an
4237 * exception has been scheduled it is illegal to invoke any JavaScript
4238 * operation; the caller must return immediately and only after the exception
4239 * has been handled does it become legal to invoke JavaScript operations.
4240 */
4241 Local<Value> ThrowException(Local<Value> exception);
4242
4243 /**
4244 * Allows the host application to group objects together. If one
4245 * object in the group is alive, all objects in the group are alive.
4246 * After each garbage collection, object groups are removed. It is
4247 * intended to be used in the before-garbage-collection callback
4248 * function, for instance to simulate DOM tree connections among JS
4249 * wrapper objects. Object groups for all dependent handles need to
4250 * be provided for kGCTypeMarkSweepCompact collections, for all other
4251 * garbage collection types it is sufficient to provide object groups
4252 * for partially dependent handles only.
4253 */
4254 template<typename T> void SetObjectGroupId(const Persistent<T>& object,
4255 UniqueId id);
4256
4257 /**
4258 * Allows the host application to declare implicit references from an object
4259 * group to an object. If the objects of the object group are alive, the child
4260 * object is alive too. After each garbage collection, all implicit references
4261 * are removed. It is intended to be used in the before-garbage-collection
4262 * callback function.
4263 */
4264 template<typename T> void SetReferenceFromGroup(UniqueId id,
4265 const Persistent<T>& child);
4266
4267 /**
4268 * Allows the host application to declare implicit references from an object
4269 * to another object. If the parent object is alive, the child object is alive
4270 * too. After each garbage collection, all implicit references are removed. It
4271 * is intended to be used in the before-garbage-collection callback function.
4272 */
4273 template<typename T, typename S>
4274 void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
4275
4276 typedef void (*GCPrologueCallback)(Isolate* isolate,
4277 GCType type,
4278 GCCallbackFlags flags);
4279 typedef void (*GCEpilogueCallback)(Isolate* isolate,
4280 GCType type,
4281 GCCallbackFlags flags);
4282
4283 /**
4284 * Enables the host application to receive a notification before a
4285 * garbage collection. Allocations are allowed in the callback function,
4286 * but the callback is not re-entrant: if the allocation inside it will
4287 * trigger the garbage collection, the callback won't be called again.
4288 * It is possible to specify the GCType filter for your callback. But it is
4289 * not possible to register the same callback function two times with
4290 * different GCType filters.
4291 */
4292 void AddGCPrologueCallback(
4293 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4294
4295 /**
4296 * This function removes callback which was installed by
4297 * AddGCPrologueCallback function.
4298 */
4299 void RemoveGCPrologueCallback(GCPrologueCallback callback);
4300
4301 /**
4302 * Enables the host application to receive a notification after a
4303 * garbage collection. Allocations are allowed in the callback function,
4304 * but the callback is not re-entrant: if the allocation inside it will
4305 * trigger the garbage collection, the callback won't be called again.
4306 * It is possible to specify the GCType filter for your callback. But it is
4307 * not possible to register the same callback function two times with
4308 * different GCType filters.
4309 */
4310 void AddGCEpilogueCallback(
4311 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4312
4313 /**
4314 * This function removes callback which was installed by
4315 * AddGCEpilogueCallback function.
4316 */
4317 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4318
4319 /**
4320 * Request V8 to interrupt long running JavaScript code and invoke
4321 * the given |callback| passing the given |data| to it. After |callback|
4322 * returns control will be returned to the JavaScript code.
4323 * At any given moment V8 can remember only a single callback for the very
4324 * last interrupt request.
4325 * Can be called from another thread without acquiring a |Locker|.
4326 * Registered |callback| must not reenter interrupted Isolate.
4327 */
4328 void RequestInterrupt(InterruptCallback callback, void* data);
4329
4330 /**
4331 * Clear interrupt request created by |RequestInterrupt|.
4332 * Can be called from another thread without acquiring a |Locker|.
4333 */
4334 void ClearInterrupt();
4335
4336 /**
4337 * Request garbage collection in this Isolate. It is only valid to call this
4338 * function if --expose_gc was specified.
4339 *
4340 * This should only be used for testing purposes and not to enforce a garbage
4341 * collection schedule. It has strong negative impact on the garbage
4342 * collection performance. Use IdleNotification() or LowMemoryNotification()
4343 * instead to influence the garbage collection schedule.
4344 */
4345 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
4346
4347 /**
4348 * Set the callback to invoke for logging event.
4349 */
4350 void SetEventLogger(LogEventCallback that);
4351
4352 /**
4353 * Adds a callback to notify the host application when a script finished
4354 * running. If a script re-enters the runtime during executing, the
4355 * CallCompletedCallback is only invoked when the outer-most script
4356 * execution ends. Executing scripts inside the callback do not trigger
4357 * further callbacks.
4358 */
4359 void AddCallCompletedCallback(CallCompletedCallback callback);
4360
4361 /**
4362 * Removes callback that was installed by AddCallCompletedCallback.
4363 */
4364 void RemoveCallCompletedCallback(CallCompletedCallback callback);
4365
4366 /**
4367 * Experimental: Runs the Microtask Work Queue until empty
4368 * Any exceptions thrown by microtask callbacks are swallowed.
4369 */
4370 void RunMicrotasks();
4371
4372 /**
4373 * Experimental: Enqueues the callback to the Microtask Work Queue
4374 */
4375 void EnqueueMicrotask(Handle<Function> microtask);
4376
4377 /**
4378 * Experimental: Enqueues the callback to the Microtask Work Queue
4379 */
4380 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
4381
4382 /**
4383 * Experimental: Controls whether the Microtask Work Queue is automatically
4384 * run when the script call depth decrements to zero.
4385 */
4386 void SetAutorunMicrotasks(bool autorun);
4387
4388 /**
4389 * Experimental: Returns whether the Microtask Work Queue is automatically
4390 * run when the script call depth decrements to zero.
4391 */
4392 bool WillAutorunMicrotasks() const;
4393
4394 /**
4395 * Enables the host application to provide a mechanism for recording
4396 * statistics counters.
4397 */
4398 void SetCounterFunction(CounterLookupCallback);
4399
4400 /**
4401 * Enables the host application to provide a mechanism for recording
4402 * histograms. The CreateHistogram function returns a
4403 * histogram which will later be passed to the AddHistogramSample
4404 * function.
4405 */
4406 void SetCreateHistogramFunction(CreateHistogramCallback);
4407 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4408
4409 private:
4410 template<class K, class V, class Traits> friend class PersistentValueMap;
4411
4412 Isolate();
4413 Isolate(const Isolate&);
4414 ~Isolate();
4415 Isolate& operator=(const Isolate&);
4416 void* operator new(size_t size);
4417 void operator delete(void*, size_t);
4418
4419 void SetObjectGroupId(internal::Object** object, UniqueId id);
4420 void SetReferenceFromGroup(UniqueId id, internal::Object** object);
4421 void SetReference(internal::Object** parent, internal::Object** child);
4422 void CollectAllGarbage(const char* gc_reason);
4423 };
4424
4425 class V8_EXPORT StartupData {
4426 public:
4427 enum CompressionAlgorithm {
4428 kUncompressed,
4429 kBZip2
4430 };
4431
4432 const char* data;
4433 int compressed_size;
4434 int raw_size;
4435 };
4436
4437
4438 /**
4439 * A helper class for driving V8 startup data decompression. It is based on
4440 * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
4441 * for an embedder to use this class, instead, API functions can be used
4442 * directly.
4443 *
4444 * For an example of the class usage, see the "shell.cc" sample application.
4445 */
4446 class V8_EXPORT StartupDataDecompressor { // NOLINT
4447 public:
4448 StartupDataDecompressor();
4449 virtual ~StartupDataDecompressor();
4450 int Decompress();
4451
4452 protected:
4453 virtual int DecompressData(char* raw_data,
4454 int* raw_data_size,
4455 const char* compressed_data,
4456 int compressed_data_size) = 0;
4457
4458 private:
4459 char** raw_data;
4460 };
4461
4462
4463 /**
4464 * EntropySource is used as a callback function when v8 needs a source
4465 * of entropy.
4466 */
4467 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
4468
4469
4470 /**
4471 * ReturnAddressLocationResolver is used as a callback function when v8 is
4472 * resolving the location of a return address on the stack. Profilers that
4473 * change the return address on the stack can use this to resolve the stack
4474 * location to whereever the profiler stashed the original return address.
4475 *
4476 * \param return_addr_location points to a location on stack where a machine
4477 * return address resides.
4478 * \returns either return_addr_location, or else a pointer to the profiler's
4479 * copy of the original return address.
4480 *
4481 * \note the resolver function must not cause garbage collection.
4482 */
4483 typedef uintptr_t (*ReturnAddressLocationResolver)(
4484 uintptr_t return_addr_location);
4485
4486
4487 /**
4488 * FunctionEntryHook is the type of the profile entry hook called at entry to
4489 * any generated function when function-level profiling is enabled.
4490 *
4491 * \param function the address of the function that's being entered.
4492 * \param return_addr_location points to a location on stack where the machine
4493 * return address resides. This can be used to identify the caller of
4494 * \p function, and/or modified to divert execution when \p function exits.
4495 *
4496 * \note the entry hook must not cause garbage collection.
4497 */
4498 typedef void (*FunctionEntryHook)(uintptr_t function,
4499 uintptr_t return_addr_location);
4500
4501
4502 /**
4503 * A JIT code event is issued each time code is added, moved or removed.
4504 *
4505 * \note removal events are not currently issued.
4506 */
4507 struct JitCodeEvent {
4508 enum EventType {
4509 CODE_ADDED,
4510 CODE_MOVED,
4511 CODE_REMOVED,
4512 CODE_ADD_LINE_POS_INFO,
4513 CODE_START_LINE_INFO_RECORDING,
4514 CODE_END_LINE_INFO_RECORDING
4515 };
4516 // Definition of the code position type. The "POSITION" type means the place
4517 // in the source code which are of interest when making stack traces to
4518 // pin-point the source location of a stack frame as close as possible.
4519 // The "STATEMENT_POSITION" means the place at the beginning of each
4520 // statement, and is used to indicate possible break locations.
4521 enum PositionType {
4522 POSITION,
4523 STATEMENT_POSITION
4524 };
4525
4526 // Type of event.
4527 EventType type;
4528 // Start of the instructions.
4529 void* code_start;
4530 // Size of the instructions.
4531 size_t code_len;
4532 // Script info for CODE_ADDED event.
4533 Handle<Script> script;
4534 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
4535 // code line information which is returned from the
4536 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
4537 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
4538 void* user_data;
4539
4540 struct name_t {
4541 // Name of the object associated with the code, note that the string is not
4542 // zero-terminated.
4543 const char* str;
4544 // Number of chars in str.
4545 size_t len;
4546 };
4547
4548 struct line_info_t {
4549 // PC offset
4550 size_t offset;
4551 // Code postion
4552 size_t pos;
4553 // The position type.
4554 PositionType position_type;
4555 };
4556
4557 union {
4558 // Only valid for CODE_ADDED.
4559 struct name_t name;
4560
4561 // Only valid for CODE_ADD_LINE_POS_INFO
4562 struct line_info_t line_info;
4563
4564 // New location of instructions. Only valid for CODE_MOVED.
4565 void* new_code_start;
4566 };
4567 };
4568
4569 /**
4570 * Option flags passed to the SetJitCodeEventHandler function.
4571 */
4572 enum JitCodeEventOptions {
4573 kJitCodeEventDefault = 0,
4574 // Generate callbacks for already existent code.
4575 kJitCodeEventEnumExisting = 1
4576 };
4577
4578
4579 /**
4580 * Callback function passed to SetJitCodeEventHandler.
4581 *
4582 * \param event code add, move or removal event.
4583 */
4584 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
4585
4586
4587 /**
4588 * Interface for iterating through all external resources in the heap.
4589 */
4590 class V8_EXPORT ExternalResourceVisitor { // NOLINT
4591 public:
~ExternalResourceVisitor()4592 virtual ~ExternalResourceVisitor() {}
VisitExternalString(Handle<String> string)4593 virtual void VisitExternalString(Handle<String> string) {}
4594 };
4595
4596
4597 /**
4598 * Interface for iterating through all the persistent handles in the heap.
4599 */
4600 class V8_EXPORT PersistentHandleVisitor { // NOLINT
4601 public:
~PersistentHandleVisitor()4602 virtual ~PersistentHandleVisitor() {}
VisitPersistentHandle(Persistent<Value> * value,uint16_t class_id)4603 virtual void VisitPersistentHandle(Persistent<Value>* value,
4604 uint16_t class_id) {}
4605 };
4606
4607
4608 /**
4609 * Container class for static utility functions.
4610 */
4611 class V8_EXPORT V8 {
4612 public:
4613 /** Set the callback to invoke in case of fatal errors. */
4614 static void SetFatalErrorHandler(FatalErrorCallback that);
4615
4616 /**
4617 * Set the callback to invoke to check if code generation from
4618 * strings should be allowed.
4619 */
4620 static void SetAllowCodeGenerationFromStringsCallback(
4621 AllowCodeGenerationFromStringsCallback that);
4622
4623 /**
4624 * Set allocator to use for ArrayBuffer memory.
4625 * The allocator should be set only once. The allocator should be set
4626 * before any code tha uses ArrayBuffers is executed.
4627 * This allocator is used in all isolates.
4628 */
4629 static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
4630
4631 /**
4632 * Check if V8 is dead and therefore unusable. This is the case after
4633 * fatal errors such as out-of-memory situations.
4634 */
4635 static bool IsDead();
4636
4637 /**
4638 * The following 4 functions are to be used when V8 is built with
4639 * the 'compress_startup_data' flag enabled. In this case, the
4640 * embedder must decompress startup data prior to initializing V8.
4641 *
4642 * This is how interaction with V8 should look like:
4643 * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
4644 * v8::StartupData* compressed_data =
4645 * new v8::StartupData[compressed_data_count];
4646 * v8::V8::GetCompressedStartupData(compressed_data);
4647 * ... decompress data (compressed_data can be updated in-place) ...
4648 * v8::V8::SetDecompressedStartupData(compressed_data);
4649 * ... now V8 can be initialized
4650 * ... make sure the decompressed data stays valid until V8 shutdown
4651 *
4652 * A helper class StartupDataDecompressor is provided. It implements
4653 * the protocol of the interaction described above, and can be used in
4654 * most cases instead of calling these API functions directly.
4655 */
4656 static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
4657 static int GetCompressedStartupDataCount();
4658 static void GetCompressedStartupData(StartupData* compressed_data);
4659 static void SetDecompressedStartupData(StartupData* decompressed_data);
4660
4661 /**
4662 * Adds a message listener.
4663 *
4664 * The same message listener can be added more than once and in that
4665 * case it will be called more than once for each message.
4666 *
4667 * If data is specified, it will be passed to the callback when it is called.
4668 * Otherwise, the exception object will be passed to the callback instead.
4669 */
4670 static bool AddMessageListener(MessageCallback that,
4671 Handle<Value> data = Handle<Value>());
4672
4673 /**
4674 * Remove all message listeners from the specified callback function.
4675 */
4676 static void RemoveMessageListeners(MessageCallback that);
4677
4678 /**
4679 * Tells V8 to capture current stack trace when uncaught exception occurs
4680 * and report it to the message listeners. The option is off by default.
4681 */
4682 static void SetCaptureStackTraceForUncaughtExceptions(
4683 bool capture,
4684 int frame_limit = 10,
4685 StackTrace::StackTraceOptions options = StackTrace::kOverview);
4686
4687 /**
4688 * Sets V8 flags from a string.
4689 */
4690 static void SetFlagsFromString(const char* str, int length);
4691
4692 /**
4693 * Sets V8 flags from the command line.
4694 */
4695 static void SetFlagsFromCommandLine(int* argc,
4696 char** argv,
4697 bool remove_flags);
4698
4699 /** Get the version string. */
4700 static const char* GetVersion();
4701
4702 /**
4703 * Enables the host application to provide a mechanism for recording
4704 * statistics counters.
4705 *
4706 * Deprecated, use Isolate::SetCounterFunction instead.
4707 */
4708 static void SetCounterFunction(CounterLookupCallback);
4709
4710 /**
4711 * Enables the host application to provide a mechanism for recording
4712 * histograms. The CreateHistogram function returns a
4713 * histogram which will later be passed to the AddHistogramSample
4714 * function.
4715 *
4716 * Deprecated, use Isolate::SetCreateHistogramFunction instead.
4717 * Isolate::SetAddHistogramSampleFunction instead.
4718 */
4719 static void SetCreateHistogramFunction(CreateHistogramCallback);
4720
4721 /** Deprecated, use Isolate::SetAddHistogramSampleFunction instead. */
4722 static void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
4723
4724 /** Callback function for reporting failed access checks.*/
4725 static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
4726
4727 /**
4728 * Enables the host application to receive a notification before a
4729 * garbage collection. Allocations are not allowed in the
4730 * callback function, you therefore cannot manipulate objects (set
4731 * or delete properties for example) since it is possible such
4732 * operations will result in the allocation of objects. It is possible
4733 * to specify the GCType filter for your callback. But it is not possible to
4734 * register the same callback function two times with different
4735 * GCType filters.
4736 */
4737 static void AddGCPrologueCallback(
4738 GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
4739
4740 /**
4741 * This function removes callback which was installed by
4742 * AddGCPrologueCallback function.
4743 */
4744 static void RemoveGCPrologueCallback(GCPrologueCallback callback);
4745
4746 /**
4747 * Enables the host application to receive a notification after a
4748 * garbage collection. Allocations are not allowed in the
4749 * callback function, you therefore cannot manipulate objects (set
4750 * or delete properties for example) since it is possible such
4751 * operations will result in the allocation of objects. It is possible
4752 * to specify the GCType filter for your callback. But it is not possible to
4753 * register the same callback function two times with different
4754 * GCType filters.
4755 */
4756 static void AddGCEpilogueCallback(
4757 GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
4758
4759 /**
4760 * This function removes callback which was installed by
4761 * AddGCEpilogueCallback function.
4762 */
4763 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
4764
4765 /**
4766 * Enables the host application to provide a mechanism to be notified
4767 * and perform custom logging when V8 Allocates Executable Memory.
4768 */
4769 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
4770 ObjectSpace space,
4771 AllocationAction action);
4772
4773 /**
4774 * Removes callback that was installed by AddMemoryAllocationCallback.
4775 */
4776 static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
4777
4778 /**
4779 * Initializes from snapshot if possible. Otherwise, attempts to
4780 * initialize from scratch. This function is called implicitly if
4781 * you use the API without calling it first.
4782 */
4783 static bool Initialize();
4784
4785 /**
4786 * Allows the host application to provide a callback which can be used
4787 * as a source of entropy for random number generators.
4788 */
4789 static void SetEntropySource(EntropySource source);
4790
4791 /**
4792 * Allows the host application to provide a callback that allows v8 to
4793 * cooperate with a profiler that rewrites return addresses on stack.
4794 */
4795 static void SetReturnAddressLocationResolver(
4796 ReturnAddressLocationResolver return_address_resolver);
4797
4798 /**
4799 * Allows the host application to provide the address of a function that's
4800 * invoked on entry to every V8-generated function.
4801 * Note that \p entry_hook is invoked at the very start of each
4802 * generated function.
4803 *
4804 * \param isolate the isolate to operate on.
4805 * \param entry_hook a function that will be invoked on entry to every
4806 * V8-generated function.
4807 * \returns true on success on supported platforms, false on failure.
4808 * \note Setting an entry hook can only be done very early in an isolates
4809 * lifetime, and once set, the entry hook cannot be revoked.
4810 */
4811 static bool SetFunctionEntryHook(Isolate* isolate,
4812 FunctionEntryHook entry_hook);
4813
4814 /**
4815 * Allows the host application to provide the address of a function that is
4816 * notified each time code is added, moved or removed.
4817 *
4818 * \param options options for the JIT code event handler.
4819 * \param event_handler the JIT code event handler, which will be invoked
4820 * each time code is added, moved or removed.
4821 * \note \p event_handler won't get notified of existent code.
4822 * \note since code removal notifications are not currently issued, the
4823 * \p event_handler may get notifications of code that overlaps earlier
4824 * code notifications. This happens when code areas are reused, and the
4825 * earlier overlapping code areas should therefore be discarded.
4826 * \note the events passed to \p event_handler and the strings they point to
4827 * are not guaranteed to live past each call. The \p event_handler must
4828 * copy strings and other parameters it needs to keep around.
4829 * \note the set of events declared in JitCodeEvent::EventType is expected to
4830 * grow over time, and the JitCodeEvent structure is expected to accrue
4831 * new members. The \p event_handler function must ignore event codes
4832 * it does not recognize to maintain future compatibility.
4833 */
4834 static void SetJitCodeEventHandler(JitCodeEventOptions options,
4835 JitCodeEventHandler event_handler);
4836
4837 /**
4838 * Forcefully terminate the current thread of JavaScript execution
4839 * in the given isolate.
4840 *
4841 * This method can be used by any thread even if that thread has not
4842 * acquired the V8 lock with a Locker object.
4843 *
4844 * \param isolate The isolate in which to terminate the current JS execution.
4845 */
4846 static void TerminateExecution(Isolate* isolate);
4847
4848 /**
4849 * Is V8 terminating JavaScript execution.
4850 *
4851 * Returns true if JavaScript execution is currently terminating
4852 * because of a call to TerminateExecution. In that case there are
4853 * still JavaScript frames on the stack and the termination
4854 * exception is still active.
4855 *
4856 * \param isolate The isolate in which to check.
4857 */
4858 static bool IsExecutionTerminating(Isolate* isolate = NULL);
4859
4860 /**
4861 * Resume execution capability in the given isolate, whose execution
4862 * was previously forcefully terminated using TerminateExecution().
4863 *
4864 * When execution is forcefully terminated using TerminateExecution(),
4865 * the isolate can not resume execution until all JavaScript frames
4866 * have propagated the uncatchable exception which is generated. This
4867 * method allows the program embedding the engine to handle the
4868 * termination event and resume execution capability, even if
4869 * JavaScript frames remain on the stack.
4870 *
4871 * This method can be used by any thread even if that thread has not
4872 * acquired the V8 lock with a Locker object.
4873 *
4874 * \param isolate The isolate in which to resume execution capability.
4875 */
4876 static void CancelTerminateExecution(Isolate* isolate);
4877
4878 /**
4879 * Releases any resources used by v8 and stops any utility threads
4880 * that may be running. Note that disposing v8 is permanent, it
4881 * cannot be reinitialized.
4882 *
4883 * It should generally not be necessary to dispose v8 before exiting
4884 * a process, this should happen automatically. It is only necessary
4885 * to use if the process needs the resources taken up by v8.
4886 */
4887 static bool Dispose();
4888
4889 /**
4890 * Iterates through all external resources referenced from current isolate
4891 * heap. GC is not invoked prior to iterating, therefore there is no
4892 * guarantee that visited objects are still alive.
4893 */
4894 static void VisitExternalResources(ExternalResourceVisitor* visitor);
4895
4896 /**
4897 * Iterates through all the persistent handles in the current isolate's heap
4898 * that have class_ids.
4899 */
4900 static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
4901
4902 /**
4903 * Iterates through all the persistent handles in the current isolate's heap
4904 * that have class_ids and are candidates to be marked as partially dependent
4905 * handles. This will visit handles to young objects created since the last
4906 * garbage collection but is free to visit an arbitrary superset of these
4907 * objects.
4908 */
4909 static void VisitHandlesForPartialDependence(
4910 Isolate* isolate, PersistentHandleVisitor* visitor);
4911
4912 /**
4913 * Optional notification that the embedder is idle.
4914 * V8 uses the notification to reduce memory footprint.
4915 * This call can be used repeatedly if the embedder remains idle.
4916 * Returns true if the embedder should stop calling IdleNotification
4917 * until real work has been done. This indicates that V8 has done
4918 * as much cleanup as it will be able to do.
4919 *
4920 * The hint argument specifies the amount of work to be done in the function
4921 * on scale from 1 to 1000. There is no guarantee that the actual work will
4922 * match the hint.
4923 */
4924 static bool IdleNotification(int hint = 1000);
4925
4926 /**
4927 * Optional notification that the system is running low on memory.
4928 * V8 uses these notifications to attempt to free memory.
4929 */
4930 static void LowMemoryNotification();
4931
4932 /**
4933 * Optional notification that a context has been disposed. V8 uses
4934 * these notifications to guide the GC heuristic. Returns the number
4935 * of context disposals - including this one - since the last time
4936 * V8 had a chance to clean up.
4937 */
4938 static int ContextDisposedNotification();
4939
4940 /**
4941 * Initialize the ICU library bundled with V8. The embedder should only
4942 * invoke this method when using the bundled ICU. Returns true on success.
4943 *
4944 * If V8 was compiled with the ICU data in an external file, the location
4945 * of the data file has to be provided.
4946 */
4947 static bool InitializeICU(const char* icu_data_file = NULL);
4948
4949 /**
4950 * Sets the v8::Platform to use. This should be invoked before V8 is
4951 * initialized.
4952 */
4953 static void InitializePlatform(Platform* platform);
4954
4955 /**
4956 * Clears all references to the v8::Platform. This should be invoked after
4957 * V8 was disposed.
4958 */
4959 static void ShutdownPlatform();
4960
4961 private:
4962 V8();
4963
4964 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
4965 internal::Object** handle);
4966 static internal::Object** CopyPersistent(internal::Object** handle);
4967 static void DisposeGlobal(internal::Object** global_handle);
4968 typedef WeakCallbackData<Value, void>::Callback WeakCallback;
4969 static void MakeWeak(internal::Object** global_handle,
4970 void* data,
4971 WeakCallback weak_callback);
4972 static void* ClearWeak(internal::Object** global_handle);
4973 static void Eternalize(Isolate* isolate,
4974 Value* handle,
4975 int* index);
4976 static Local<Value> GetEternal(Isolate* isolate, int index);
4977
4978 template <class T> friend class Handle;
4979 template <class T> friend class Local;
4980 template <class T> friend class Eternal;
4981 template <class T> friend class PersistentBase;
4982 template <class T, class M> friend class Persistent;
4983 friend class Context;
4984 };
4985
4986
4987 /**
4988 * An external exception handler.
4989 */
4990 class V8_EXPORT TryCatch {
4991 public:
4992 /**
4993 * Creates a new try/catch block and registers it with v8. Note that
4994 * all TryCatch blocks should be stack allocated because the memory
4995 * location itself is compared against JavaScript try/catch blocks.
4996 */
4997 TryCatch();
4998
4999 /**
5000 * Unregisters and deletes this try/catch block.
5001 */
5002 ~TryCatch();
5003
5004 /**
5005 * Returns true if an exception has been caught by this try/catch block.
5006 */
5007 bool HasCaught() const;
5008
5009 /**
5010 * For certain types of exceptions, it makes no sense to continue execution.
5011 *
5012 * If CanContinue returns false, the correct action is to perform any C++
5013 * cleanup needed and then return. If CanContinue returns false and
5014 * HasTerminated returns true, it is possible to call
5015 * CancelTerminateExecution in order to continue calling into the engine.
5016 */
5017 bool CanContinue() const;
5018
5019 /**
5020 * Returns true if an exception has been caught due to script execution
5021 * being terminated.
5022 *
5023 * There is no JavaScript representation of an execution termination
5024 * exception. Such exceptions are thrown when the TerminateExecution
5025 * methods are called to terminate a long-running script.
5026 *
5027 * If such an exception has been thrown, HasTerminated will return true,
5028 * indicating that it is possible to call CancelTerminateExecution in order
5029 * to continue calling into the engine.
5030 */
5031 bool HasTerminated() const;
5032
5033 /**
5034 * Throws the exception caught by this TryCatch in a way that avoids
5035 * it being caught again by this same TryCatch. As with ThrowException
5036 * it is illegal to execute any JavaScript operations after calling
5037 * ReThrow; the caller must return immediately to where the exception
5038 * is caught.
5039 */
5040 Handle<Value> ReThrow();
5041
5042 /**
5043 * Returns the exception caught by this try/catch block. If no exception has
5044 * been caught an empty handle is returned.
5045 *
5046 * The returned handle is valid until this TryCatch block has been destroyed.
5047 */
5048 Local<Value> Exception() const;
5049
5050 /**
5051 * Returns the .stack property of the thrown object. If no .stack
5052 * property is present an empty handle is returned.
5053 */
5054 Local<Value> StackTrace() const;
5055
5056 /**
5057 * Returns the message associated with this exception. If there is
5058 * no message associated an empty handle is returned.
5059 *
5060 * The returned handle is valid until this TryCatch block has been
5061 * destroyed.
5062 */
5063 Local<v8::Message> Message() const;
5064
5065 /**
5066 * Clears any exceptions that may have been caught by this try/catch block.
5067 * After this method has been called, HasCaught() will return false.
5068 *
5069 * It is not necessary to clear a try/catch block before using it again; if
5070 * another exception is thrown the previously caught exception will just be
5071 * overwritten. However, it is often a good idea since it makes it easier
5072 * to determine which operation threw a given exception.
5073 */
5074 void Reset();
5075
5076 /**
5077 * Set verbosity of the external exception handler.
5078 *
5079 * By default, exceptions that are caught by an external exception
5080 * handler are not reported. Call SetVerbose with true on an
5081 * external exception handler to have exceptions caught by the
5082 * handler reported as if they were not caught.
5083 */
5084 void SetVerbose(bool value);
5085
5086 /**
5087 * Set whether or not this TryCatch should capture a Message object
5088 * which holds source information about where the exception
5089 * occurred. True by default.
5090 */
5091 void SetCaptureMessage(bool value);
5092
5093 /**
5094 * There are cases when the raw address of C++ TryCatch object cannot be
5095 * used for comparisons with addresses into the JS stack. The cases are:
5096 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
5097 * 2) Address sanitizer allocates local C++ object in the heap when
5098 * UseAfterReturn mode is enabled.
5099 * This method returns address that can be used for comparisons with
5100 * addresses into the JS stack. When neither simulator nor ASAN's
5101 * UseAfterReturn is enabled, then the address returned will be the address
5102 * of the C++ try catch handler itself.
5103 */
JSStackComparableAddress(v8::TryCatch * handler)5104 static void* JSStackComparableAddress(v8::TryCatch* handler) {
5105 if (handler == NULL) return NULL;
5106 return handler->js_stack_comparable_address_;
5107 }
5108
5109 private:
5110 // Make it hard to create heap-allocated TryCatch blocks.
5111 TryCatch(const TryCatch&);
5112 void operator=(const TryCatch&);
5113 void* operator new(size_t size);
5114 void operator delete(void*, size_t);
5115
5116 v8::internal::Isolate* isolate_;
5117 v8::TryCatch* next_;
5118 void* exception_;
5119 void* message_obj_;
5120 void* message_script_;
5121 void* js_stack_comparable_address_;
5122 int message_start_pos_;
5123 int message_end_pos_;
5124 bool is_verbose_ : 1;
5125 bool can_continue_ : 1;
5126 bool capture_message_ : 1;
5127 bool rethrow_ : 1;
5128 bool has_terminated_ : 1;
5129
5130 friend class v8::internal::Isolate;
5131 };
5132
5133
5134 // --- Context ---
5135
5136
5137 /**
5138 * A container for extension names.
5139 */
5140 class V8_EXPORT ExtensionConfiguration {
5141 public:
ExtensionConfiguration()5142 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
ExtensionConfiguration(int name_count,const char * names[])5143 ExtensionConfiguration(int name_count, const char* names[])
5144 : name_count_(name_count), names_(names) { }
5145
begin()5146 const char** begin() const { return &names_[0]; }
end()5147 const char** end() const { return &names_[name_count_]; }
5148
5149 private:
5150 const int name_count_;
5151 const char** names_;
5152 };
5153
5154
5155 /**
5156 * A sandboxed execution context with its own set of built-in objects
5157 * and functions.
5158 */
5159 class V8_EXPORT Context {
5160 public:
5161 /**
5162 * Returns the global proxy object.
5163 *
5164 * Global proxy object is a thin wrapper whose prototype points to actual
5165 * context's global object with the properties like Object, etc. This is done
5166 * that way for security reasons (for more details see
5167 * https://wiki.mozilla.org/Gecko:SplitWindow).
5168 *
5169 * Please note that changes to global proxy object prototype most probably
5170 * would break VM---v8 expects only global object as a prototype of global
5171 * proxy object.
5172 */
5173 Local<Object> Global();
5174
5175 /**
5176 * Detaches the global object from its context before
5177 * the global object can be reused to create a new context.
5178 */
5179 void DetachGlobal();
5180
5181 /**
5182 * Creates a new context and returns a handle to the newly allocated
5183 * context.
5184 *
5185 * \param isolate The isolate in which to create the context.
5186 *
5187 * \param extensions An optional extension configuration containing
5188 * the extensions to be installed in the newly created context.
5189 *
5190 * \param global_template An optional object template from which the
5191 * global object for the newly created context will be created.
5192 *
5193 * \param global_object An optional global object to be reused for
5194 * the newly created context. This global object must have been
5195 * created by a previous call to Context::New with the same global
5196 * template. The state of the global object will be completely reset
5197 * and only object identify will remain.
5198 */
5199 static Local<Context> New(
5200 Isolate* isolate,
5201 ExtensionConfiguration* extensions = NULL,
5202 Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
5203 Handle<Value> global_object = Handle<Value>());
5204
5205 /**
5206 * Sets the security token for the context. To access an object in
5207 * another context, the security tokens must match.
5208 */
5209 void SetSecurityToken(Handle<Value> token);
5210
5211 /** Restores the security token to the default value. */
5212 void UseDefaultSecurityToken();
5213
5214 /** Returns the security token of this context.*/
5215 Handle<Value> GetSecurityToken();
5216
5217 /**
5218 * Enter this context. After entering a context, all code compiled
5219 * and run is compiled and run in this context. If another context
5220 * is already entered, this old context is saved so it can be
5221 * restored when the new context is exited.
5222 */
5223 void Enter();
5224
5225 /**
5226 * Exit this context. Exiting the current context restores the
5227 * context that was in place when entering the current context.
5228 */
5229 void Exit();
5230
5231 /**
5232 * Returns true if the context has experienced an out of memory situation.
5233 * Since V8 always treats OOM as fatal error, this can no longer return true.
5234 * Therefore this is now deprecated.
5235 * */
5236 V8_DEPRECATED("This can no longer happen. OOM is a fatal error.",
HasOutOfMemoryException()5237 bool HasOutOfMemoryException()) { return false; }
5238
5239 /** Returns an isolate associated with a current context. */
5240 v8::Isolate* GetIsolate();
5241
5242 /**
5243 * Gets the embedder data with the given index, which must have been set by a
5244 * previous call to SetEmbedderData with the same index. Note that index 0
5245 * currently has a special meaning for Chrome's debugger.
5246 */
5247 V8_INLINE Local<Value> GetEmbedderData(int index);
5248
5249 /**
5250 * Sets the embedder data with the given index, growing the data as
5251 * needed. Note that index 0 currently has a special meaning for Chrome's
5252 * debugger.
5253 */
5254 void SetEmbedderData(int index, Handle<Value> value);
5255
5256 /**
5257 * Gets a 2-byte-aligned native pointer from the embedder data with the given
5258 * index, which must have bees set by a previous call to
5259 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
5260 * currently has a special meaning for Chrome's debugger.
5261 */
5262 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
5263
5264 /**
5265 * Sets a 2-byte-aligned native pointer in the embedder data with the given
5266 * index, growing the data as needed. Note that index 0 currently has a
5267 * special meaning for Chrome's debugger.
5268 */
5269 void SetAlignedPointerInEmbedderData(int index, void* value);
5270
5271 /**
5272 * Control whether code generation from strings is allowed. Calling
5273 * this method with false will disable 'eval' and the 'Function'
5274 * constructor for code running in this context. If 'eval' or the
5275 * 'Function' constructor are used an exception will be thrown.
5276 *
5277 * If code generation from strings is not allowed the
5278 * V8::AllowCodeGenerationFromStrings callback will be invoked if
5279 * set before blocking the call to 'eval' or the 'Function'
5280 * constructor. If that callback returns true, the call will be
5281 * allowed, otherwise an exception will be thrown. If no callback is
5282 * set an exception will be thrown.
5283 */
5284 void AllowCodeGenerationFromStrings(bool allow);
5285
5286 /**
5287 * Returns true if code generation from strings is allowed for the context.
5288 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
5289 */
5290 bool IsCodeGenerationFromStringsAllowed();
5291
5292 /**
5293 * Sets the error description for the exception that is thrown when
5294 * code generation from strings is not allowed and 'eval' or the 'Function'
5295 * constructor are called.
5296 */
5297 void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
5298
5299 /**
5300 * Stack-allocated class which sets the execution context for all
5301 * operations executed within a local scope.
5302 */
5303 class Scope {
5304 public:
Scope(Handle<Context> context)5305 explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
5306 context_->Enter();
5307 }
~Scope()5308 V8_INLINE ~Scope() { context_->Exit(); }
5309
5310 private:
5311 Handle<Context> context_;
5312 };
5313
5314 private:
5315 friend class Value;
5316 friend class Script;
5317 friend class Object;
5318 friend class Function;
5319
5320 Local<Value> SlowGetEmbedderData(int index);
5321 void* SlowGetAlignedPointerFromEmbedderData(int index);
5322 };
5323
5324
5325 /**
5326 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
5327 * to use any given V8 isolate, see the comments in the Isolate class. The
5328 * definition of 'using a V8 isolate' includes accessing handles or holding onto
5329 * object pointers obtained from V8 handles while in the particular V8 isolate.
5330 * It is up to the user of V8 to ensure, perhaps with locking, that this
5331 * constraint is not violated. In addition to any other synchronization
5332 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
5333 * used to signal thead switches to V8.
5334 *
5335 * v8::Locker is a scoped lock object. While it's active, i.e. between its
5336 * construction and destruction, the current thread is allowed to use the locked
5337 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
5338 * any time. In other words, the scope of a v8::Locker is a critical section.
5339 *
5340 * Sample usage:
5341 * \code
5342 * ...
5343 * {
5344 * v8::Locker locker(isolate);
5345 * v8::Isolate::Scope isolate_scope(isolate);
5346 * ...
5347 * // Code using V8 and isolate goes here.
5348 * ...
5349 * } // Destructor called here
5350 * \endcode
5351 *
5352 * If you wish to stop using V8 in a thread A you can do this either by
5353 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
5354 * object:
5355 *
5356 * \code
5357 * {
5358 * isolate->Exit();
5359 * v8::Unlocker unlocker(isolate);
5360 * ...
5361 * // Code not using V8 goes here while V8 can run in another thread.
5362 * ...
5363 * } // Destructor called here.
5364 * isolate->Enter();
5365 * \endcode
5366 *
5367 * The Unlocker object is intended for use in a long-running callback from V8,
5368 * where you want to release the V8 lock for other threads to use.
5369 *
5370 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
5371 * given thread. This can be useful if you have code that can be called either
5372 * from code that holds the lock or from code that does not. The Unlocker is
5373 * not recursive so you can not have several Unlockers on the stack at once, and
5374 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
5375 *
5376 * An unlocker will unlock several lockers if it has to and reinstate the
5377 * correct depth of locking on its destruction, e.g.:
5378 *
5379 * \code
5380 * // V8 not locked.
5381 * {
5382 * v8::Locker locker(isolate);
5383 * Isolate::Scope isolate_scope(isolate);
5384 * // V8 locked.
5385 * {
5386 * v8::Locker another_locker(isolate);
5387 * // V8 still locked (2 levels).
5388 * {
5389 * isolate->Exit();
5390 * v8::Unlocker unlocker(isolate);
5391 * // V8 not locked.
5392 * }
5393 * isolate->Enter();
5394 * // V8 locked again (2 levels).
5395 * }
5396 * // V8 still locked (1 level).
5397 * }
5398 * // V8 Now no longer locked.
5399 * \endcode
5400 */
5401 class V8_EXPORT Unlocker {
5402 public:
5403 /**
5404 * Initialize Unlocker for a given Isolate.
5405 */
Unlocker(Isolate * isolate)5406 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
5407
5408 ~Unlocker();
5409 private:
5410 void Initialize(Isolate* isolate);
5411
5412 internal::Isolate* isolate_;
5413 };
5414
5415
5416 class V8_EXPORT Locker {
5417 public:
5418 /**
5419 * Initialize Locker for a given Isolate.
5420 */
Locker(Isolate * isolate)5421 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
5422
5423 ~Locker();
5424
5425 /**
5426 * Returns whether or not the locker for a given isolate, is locked by the
5427 * current thread.
5428 */
5429 static bool IsLocked(Isolate* isolate);
5430
5431 /**
5432 * Returns whether v8::Locker is being used by this V8 instance.
5433 */
5434 static bool IsActive();
5435
5436 private:
5437 void Initialize(Isolate* isolate);
5438
5439 bool has_lock_;
5440 bool top_level_;
5441 internal::Isolate* isolate_;
5442
5443 static bool active_;
5444
5445 // Disallow copying and assigning.
5446 Locker(const Locker&);
5447 void operator=(const Locker&);
5448 };
5449
5450
5451 // --- Implementation ---
5452
5453
5454 namespace internal {
5455
5456 const int kApiPointerSize = sizeof(void*); // NOLINT
5457 const int kApiIntSize = sizeof(int); // NOLINT
5458 const int kApiInt64Size = sizeof(int64_t); // NOLINT
5459
5460 // Tag information for HeapObject.
5461 const int kHeapObjectTag = 1;
5462 const int kHeapObjectTagSize = 2;
5463 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
5464
5465 // Tag information for Smi.
5466 const int kSmiTag = 0;
5467 const int kSmiTagSize = 1;
5468 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
5469
5470 template <size_t ptr_size> struct SmiTagging;
5471
5472 template<int kSmiShiftSize>
IntToSmi(int value)5473 V8_INLINE internal::Object* IntToSmi(int value) {
5474 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
5475 intptr_t tagged_value =
5476 (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
5477 return reinterpret_cast<internal::Object*>(tagged_value);
5478 }
5479
5480 // Smi constants for 32-bit systems.
5481 template <> struct SmiTagging<4> {
5482 static const int kSmiShiftSize = 0;
5483 static const int kSmiValueSize = 31;
5484 V8_INLINE static int SmiToInt(internal::Object* value) {
5485 int shift_bits = kSmiTagSize + kSmiShiftSize;
5486 // Throw away top 32 bits and shift down (requires >> to be sign extending).
5487 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
5488 }
5489 V8_INLINE static internal::Object* IntToSmi(int value) {
5490 return internal::IntToSmi<kSmiShiftSize>(value);
5491 }
5492 V8_INLINE static bool IsValidSmi(intptr_t value) {
5493 // To be representable as an tagged small integer, the two
5494 // most-significant bits of 'value' must be either 00 or 11 due to
5495 // sign-extension. To check this we add 01 to the two
5496 // most-significant bits, and check if the most-significant bit is 0
5497 //
5498 // CAUTION: The original code below:
5499 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
5500 // may lead to incorrect results according to the C language spec, and
5501 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
5502 // compiler may produce undefined results in case of signed integer
5503 // overflow. The computation must be done w/ unsigned ints.
5504 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
5505 }
5506 };
5507
5508 // Smi constants for 64-bit systems.
5509 template <> struct SmiTagging<8> {
5510 static const int kSmiShiftSize = 31;
5511 static const int kSmiValueSize = 32;
5512 V8_INLINE static int SmiToInt(internal::Object* value) {
5513 int shift_bits = kSmiTagSize + kSmiShiftSize;
5514 // Shift down and throw away top 32 bits.
5515 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
5516 }
5517 V8_INLINE static internal::Object* IntToSmi(int value) {
5518 return internal::IntToSmi<kSmiShiftSize>(value);
5519 }
5520 V8_INLINE static bool IsValidSmi(intptr_t value) {
5521 // To be representable as a long smi, the value must be a 32-bit integer.
5522 return (value == static_cast<int32_t>(value));
5523 }
5524 };
5525
5526 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
5527 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
5528 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
5529 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
5530 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
5531
5532 /**
5533 * This class exports constants and functionality from within v8 that
5534 * is necessary to implement inline functions in the v8 api. Don't
5535 * depend on functions and constants defined here.
5536 */
5537 class Internals {
5538 public:
5539 // These values match non-compiler-dependent values defined within
5540 // the implementation of v8.
5541 static const int kHeapObjectMapOffset = 0;
5542 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
5543 static const int kStringResourceOffset = 3 * kApiPointerSize;
5544
5545 static const int kOddballKindOffset = 3 * kApiPointerSize;
5546 static const int kForeignAddressOffset = kApiPointerSize;
5547 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
5548 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
5549 static const int kContextHeaderSize = 2 * kApiPointerSize;
5550 static const int kContextEmbedderDataIndex = 76;
5551 static const int kFullStringRepresentationMask = 0x07;
5552 static const int kStringEncodingMask = 0x4;
5553 static const int kExternalTwoByteRepresentationTag = 0x02;
5554 static const int kExternalAsciiRepresentationTag = 0x06;
5555
5556 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
5557 static const int kAmountOfExternalAllocatedMemoryOffset =
5558 4 * kApiPointerSize;
5559 static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
5560 kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
5561 static const int kIsolateRootsOffset =
5562 kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
5563 kApiPointerSize;
5564 static const int kUndefinedValueRootIndex = 5;
5565 static const int kNullValueRootIndex = 7;
5566 static const int kTrueValueRootIndex = 8;
5567 static const int kFalseValueRootIndex = 9;
5568 static const int kEmptyStringRootIndex = 163;
5569
5570 // The external allocation limit should be below 256 MB on all architectures
5571 // to avoid that resource-constrained embedders run low on memory.
5572 static const int kExternalAllocationLimit = 192 * 1024 * 1024;
5573
5574 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
5575 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
5576 static const int kNodeStateMask = 0xf;
5577 static const int kNodeStateIsWeakValue = 2;
5578 static const int kNodeStateIsPendingValue = 3;
5579 static const int kNodeStateIsNearDeathValue = 4;
5580 static const int kNodeIsIndependentShift = 4;
5581 static const int kNodeIsPartiallyDependentShift = 5;
5582
5583 static const int kJSObjectType = 0xbb;
5584 static const int kFirstNonstringType = 0x80;
5585 static const int kOddballType = 0x83;
5586 static const int kForeignType = 0x87;
5587
5588 static const int kUndefinedOddballKind = 5;
5589 static const int kNullOddballKind = 3;
5590
5591 static const uint32_t kNumIsolateDataSlots = 4;
5592
5593 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
5594 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
5595 #ifdef V8_ENABLE_CHECKS
5596 CheckInitializedImpl(isolate);
5597 #endif
5598 }
5599
5600 V8_INLINE static bool HasHeapObjectTag(internal::Object* value) {
5601 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
5602 kHeapObjectTag);
5603 }
5604
5605 V8_INLINE static int SmiValue(internal::Object* value) {
5606 return PlatformSmiTagging::SmiToInt(value);
5607 }
5608
5609 V8_INLINE static internal::Object* IntToSmi(int value) {
5610 return PlatformSmiTagging::IntToSmi(value);
5611 }
5612
5613 V8_INLINE static bool IsValidSmi(intptr_t value) {
5614 return PlatformSmiTagging::IsValidSmi(value);
5615 }
5616
5617 V8_INLINE static int GetInstanceType(internal::Object* obj) {
5618 typedef internal::Object O;
5619 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
5620 return ReadField<uint8_t>(map, kMapInstanceTypeOffset);
5621 }
5622
5623 V8_INLINE static int GetOddballKind(internal::Object* obj) {
5624 typedef internal::Object O;
5625 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
5626 }
5627
5628 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
5629 int representation = (instance_type & kFullStringRepresentationMask);
5630 return representation == kExternalTwoByteRepresentationTag;
5631 }
5632
5633 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
5634 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5635 return *addr & static_cast<uint8_t>(1U << shift);
5636 }
5637
5638 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
5639 bool value, int shift) {
5640 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5641 uint8_t mask = static_cast<uint8_t>(1 << shift);
5642 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
5643 }
5644
5645 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
5646 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5647 return *addr & kNodeStateMask;
5648 }
5649
5650 V8_INLINE static void UpdateNodeState(internal::Object** obj,
5651 uint8_t value) {
5652 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
5653 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
5654 }
5655
5656 V8_INLINE static void SetEmbedderData(v8::Isolate *isolate,
5657 uint32_t slot,
5658 void *data) {
5659 uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
5660 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5661 *reinterpret_cast<void**>(addr) = data;
5662 }
5663
5664 V8_INLINE static void* GetEmbedderData(v8::Isolate* isolate, uint32_t slot) {
5665 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
5666 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
5667 return *reinterpret_cast<void**>(addr);
5668 }
5669
5670 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
5671 int index) {
5672 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
5673 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
5674 }
5675
5676 template <typename T>
5677 V8_INLINE static T ReadField(internal::Object* ptr, int offset) {
5678 uint8_t* addr = reinterpret_cast<uint8_t*>(ptr) + offset - kHeapObjectTag;
5679 return *reinterpret_cast<T*>(addr);
5680 }
5681
5682 template <typename T>
5683 V8_INLINE static T ReadEmbedderData(v8::Context* context, int index) {
5684 typedef internal::Object O;
5685 typedef internal::Internals I;
5686 O* ctx = *reinterpret_cast<O**>(context);
5687 int embedder_data_offset = I::kContextHeaderSize +
5688 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
5689 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
5690 int value_offset =
5691 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
5692 return I::ReadField<T>(embedder_data, value_offset);
5693 }
5694 };
5695
5696 } // namespace internal
5697
5698
5699 template <class T>
5700 Local<T>::Local() : Handle<T>() { }
5701
5702
5703 template <class T>
5704 Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
5705 return New(isolate, that.val_);
5706 }
5707
5708 template <class T>
5709 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
5710 return New(isolate, that.val_);
5711 }
5712
5713 template <class T>
5714 Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
5715 if (that == NULL) return Handle<T>();
5716 T* that_ptr = that;
5717 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5718 return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5719 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5720 }
5721
5722
5723 template <class T>
5724 Local<T> Local<T>::New(Isolate* isolate, T* that) {
5725 if (that == NULL) return Local<T>();
5726 T* that_ptr = that;
5727 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
5728 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
5729 reinterpret_cast<internal::Isolate*>(isolate), *p)));
5730 }
5731
5732
5733 template<class T>
5734 template<class S>
5735 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
5736 TYPE_CHECK(T, S);
5737 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
5738 }
5739
5740
5741 template<class T>
5742 Local<T> Eternal<T>::Get(Isolate* isolate) {
5743 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
5744 }
5745
5746
5747 template <class T>
5748 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
5749 if (that == NULL) return NULL;
5750 internal::Object** p = reinterpret_cast<internal::Object**>(that);
5751 return reinterpret_cast<T*>(
5752 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
5753 p));
5754 }
5755
5756
5757 template <class T, class M>
5758 template <class S, class M2>
5759 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
5760 TYPE_CHECK(T, S);
5761 this->Reset();
5762 if (that.IsEmpty()) return;
5763 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
5764 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
5765 M::Copy(that, this);
5766 }
5767
5768
5769 template <class T>
5770 bool PersistentBase<T>::IsIndependent() const {
5771 typedef internal::Internals I;
5772 if (this->IsEmpty()) return false;
5773 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5774 I::kNodeIsIndependentShift);
5775 }
5776
5777
5778 template <class T>
5779 bool PersistentBase<T>::IsNearDeath() const {
5780 typedef internal::Internals I;
5781 if (this->IsEmpty()) return false;
5782 uint8_t node_state =
5783 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
5784 return node_state == I::kNodeStateIsNearDeathValue ||
5785 node_state == I::kNodeStateIsPendingValue;
5786 }
5787
5788
5789 template <class T>
5790 bool PersistentBase<T>::IsWeak() const {
5791 typedef internal::Internals I;
5792 if (this->IsEmpty()) return false;
5793 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
5794 I::kNodeStateIsWeakValue;
5795 }
5796
5797
5798 template <class T>
5799 void PersistentBase<T>::Reset() {
5800 if (this->IsEmpty()) return;
5801 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
5802 val_ = 0;
5803 }
5804
5805
5806 template <class T>
5807 template <class S>
5808 void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
5809 TYPE_CHECK(T, S);
5810 Reset();
5811 if (other.IsEmpty()) return;
5812 this->val_ = New(isolate, other.val_);
5813 }
5814
5815
5816 template <class T>
5817 template <class S>
5818 void PersistentBase<T>::Reset(Isolate* isolate,
5819 const PersistentBase<S>& other) {
5820 TYPE_CHECK(T, S);
5821 Reset();
5822 if (other.IsEmpty()) return;
5823 this->val_ = New(isolate, other.val_);
5824 }
5825
5826
5827 template <class T>
5828 template <typename S, typename P>
5829 void PersistentBase<T>::SetWeak(
5830 P* parameter,
5831 typename WeakCallbackData<S, P>::Callback callback) {
5832 TYPE_CHECK(S, T);
5833 typedef typename WeakCallbackData<Value, void>::Callback Callback;
5834 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
5835 parameter,
5836 reinterpret_cast<Callback>(callback));
5837 }
5838
5839
5840 template <class T>
5841 template <typename P>
5842 void PersistentBase<T>::SetWeak(
5843 P* parameter,
5844 typename WeakCallbackData<T, P>::Callback callback) {
5845 SetWeak<T, P>(parameter, callback);
5846 }
5847
5848
5849 template <class T>
5850 template<typename P>
5851 P* PersistentBase<T>::ClearWeak() {
5852 return reinterpret_cast<P*>(
5853 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
5854 }
5855
5856
5857 template <class T>
5858 void PersistentBase<T>::MarkIndependent() {
5859 typedef internal::Internals I;
5860 if (this->IsEmpty()) return;
5861 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5862 true,
5863 I::kNodeIsIndependentShift);
5864 }
5865
5866
5867 template <class T>
5868 void PersistentBase<T>::MarkPartiallyDependent() {
5869 typedef internal::Internals I;
5870 if (this->IsEmpty()) return;
5871 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
5872 true,
5873 I::kNodeIsPartiallyDependentShift);
5874 }
5875
5876
5877 template <class T, class M>
5878 T* Persistent<T, M>::ClearAndLeak() {
5879 T* old;
5880 old = this->val_;
5881 this->val_ = NULL;
5882 return old;
5883 }
5884
5885
5886 template <class T>
5887 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
5888 typedef internal::Internals I;
5889 if (this->IsEmpty()) return;
5890 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5891 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5892 *reinterpret_cast<uint16_t*>(addr) = class_id;
5893 }
5894
5895
5896 template <class T>
5897 uint16_t PersistentBase<T>::WrapperClassId() const {
5898 typedef internal::Internals I;
5899 if (this->IsEmpty()) return 0;
5900 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
5901 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
5902 return *reinterpret_cast<uint16_t*>(addr);
5903 }
5904
5905
5906 template<typename T>
5907 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
5908
5909 template<typename T>
5910 template<typename S>
5911 void ReturnValue<T>::Set(const Persistent<S>& handle) {
5912 TYPE_CHECK(T, S);
5913 if (V8_UNLIKELY(handle.IsEmpty())) {
5914 *value_ = GetDefaultValue();
5915 } else {
5916 *value_ = *reinterpret_cast<internal::Object**>(*handle);
5917 }
5918 }
5919
5920 template<typename T>
5921 template<typename S>
5922 void ReturnValue<T>::Set(const Handle<S> handle) {
5923 TYPE_CHECK(T, S);
5924 if (V8_UNLIKELY(handle.IsEmpty())) {
5925 *value_ = GetDefaultValue();
5926 } else {
5927 *value_ = *reinterpret_cast<internal::Object**>(*handle);
5928 }
5929 }
5930
5931 template<typename T>
5932 void ReturnValue<T>::Set(double i) {
5933 TYPE_CHECK(T, Number);
5934 Set(Number::New(GetIsolate(), i));
5935 }
5936
5937 template<typename T>
5938 void ReturnValue<T>::Set(int32_t i) {
5939 TYPE_CHECK(T, Integer);
5940 typedef internal::Internals I;
5941 if (V8_LIKELY(I::IsValidSmi(i))) {
5942 *value_ = I::IntToSmi(i);
5943 return;
5944 }
5945 Set(Integer::New(GetIsolate(), i));
5946 }
5947
5948 template<typename T>
5949 void ReturnValue<T>::Set(uint32_t i) {
5950 TYPE_CHECK(T, Integer);
5951 // Can't simply use INT32_MAX here for whatever reason.
5952 bool fits_into_int32_t = (i & (1U << 31)) == 0;
5953 if (V8_LIKELY(fits_into_int32_t)) {
5954 Set(static_cast<int32_t>(i));
5955 return;
5956 }
5957 Set(Integer::NewFromUnsigned(GetIsolate(), i));
5958 }
5959
5960 template<typename T>
5961 void ReturnValue<T>::Set(bool value) {
5962 TYPE_CHECK(T, Boolean);
5963 typedef internal::Internals I;
5964 int root_index;
5965 if (value) {
5966 root_index = I::kTrueValueRootIndex;
5967 } else {
5968 root_index = I::kFalseValueRootIndex;
5969 }
5970 *value_ = *I::GetRoot(GetIsolate(), root_index);
5971 }
5972
5973 template<typename T>
5974 void ReturnValue<T>::SetNull() {
5975 TYPE_CHECK(T, Primitive);
5976 typedef internal::Internals I;
5977 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
5978 }
5979
5980 template<typename T>
5981 void ReturnValue<T>::SetUndefined() {
5982 TYPE_CHECK(T, Primitive);
5983 typedef internal::Internals I;
5984 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
5985 }
5986
5987 template<typename T>
5988 void ReturnValue<T>::SetEmptyString() {
5989 TYPE_CHECK(T, String);
5990 typedef internal::Internals I;
5991 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
5992 }
5993
5994 template<typename T>
5995 Isolate* ReturnValue<T>::GetIsolate() {
5996 // Isolate is always the pointer below the default value on the stack.
5997 return *reinterpret_cast<Isolate**>(&value_[-2]);
5998 }
5999
6000 template<typename T>
6001 template<typename S>
6002 void ReturnValue<T>::Set(S* whatever) {
6003 // Uncompilable to prevent inadvertent misuse.
6004 TYPE_CHECK(S*, Primitive);
6005 }
6006
6007 template<typename T>
6008 internal::Object* ReturnValue<T>::GetDefaultValue() {
6009 // Default value is always the pointer below value_ on the stack.
6010 return value_[-1];
6011 }
6012
6013
6014 template<typename T>
6015 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
6016 internal::Object** values,
6017 int length,
6018 bool is_construct_call)
6019 : implicit_args_(implicit_args),
6020 values_(values),
6021 length_(length),
6022 is_construct_call_(is_construct_call) { }
6023
6024
6025 template<typename T>
6026 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
6027 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
6028 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
6029 }
6030
6031
6032 template<typename T>
6033 Local<Function> FunctionCallbackInfo<T>::Callee() const {
6034 return Local<Function>(reinterpret_cast<Function*>(
6035 &implicit_args_[kCalleeIndex]));
6036 }
6037
6038
6039 template<typename T>
6040 Local<Object> FunctionCallbackInfo<T>::This() const {
6041 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
6042 }
6043
6044
6045 template<typename T>
6046 Local<Object> FunctionCallbackInfo<T>::Holder() const {
6047 return Local<Object>(reinterpret_cast<Object*>(
6048 &implicit_args_[kHolderIndex]));
6049 }
6050
6051
6052 template<typename T>
6053 Local<Value> FunctionCallbackInfo<T>::Data() const {
6054 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
6055 }
6056
6057
6058 template<typename T>
6059 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
6060 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
6061 }
6062
6063
6064 template<typename T>
6065 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
6066 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
6067 }
6068
6069
6070 template<typename T>
6071 bool FunctionCallbackInfo<T>::IsConstructCall() const {
6072 return is_construct_call_;
6073 }
6074
6075
6076 template<typename T>
6077 int FunctionCallbackInfo<T>::Length() const {
6078 return length_;
6079 }
6080
6081
6082 Handle<Value> ScriptOrigin::ResourceName() const {
6083 return resource_name_;
6084 }
6085
6086
6087 Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
6088 return resource_line_offset_;
6089 }
6090
6091
6092 Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
6093 return resource_column_offset_;
6094 }
6095
6096 Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
6097 return resource_is_shared_cross_origin_;
6098 }
6099
6100
6101 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
6102 CachedData* data)
6103 : source_string(string),
6104 resource_name(origin.ResourceName()),
6105 resource_line_offset(origin.ResourceLineOffset()),
6106 resource_column_offset(origin.ResourceColumnOffset()),
6107 resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
6108 cached_data(data) {}
6109
6110
6111 ScriptCompiler::Source::Source(Local<String> string,
6112 CachedData* data)
6113 : source_string(string), cached_data(data) {}
6114
6115
6116 ScriptCompiler::Source::~Source() {
6117 delete cached_data;
6118 }
6119
6120
6121 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
6122 const {
6123 return cached_data;
6124 }
6125
6126
6127 Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
6128 return value ? True(isolate) : False(isolate);
6129 }
6130
6131
6132 void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
6133 Set(v8::String::NewFromUtf8(isolate, name), value);
6134 }
6135
6136
6137 Local<Value> Object::GetInternalField(int index) {
6138 #ifndef V8_ENABLE_CHECKS
6139 typedef internal::Object O;
6140 typedef internal::HeapObject HO;
6141 typedef internal::Internals I;
6142 O* obj = *reinterpret_cast<O**>(this);
6143 // Fast path: If the object is a plain JSObject, which is the common case, we
6144 // know where to find the internal fields and can return the value directly.
6145 if (I::GetInstanceType(obj) == I::kJSObjectType) {
6146 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6147 O* value = I::ReadField<O*>(obj, offset);
6148 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
6149 return Local<Value>(reinterpret_cast<Value*>(result));
6150 }
6151 #endif
6152 return SlowGetInternalField(index);
6153 }
6154
6155
6156 void* Object::GetAlignedPointerFromInternalField(int index) {
6157 #ifndef V8_ENABLE_CHECKS
6158 typedef internal::Object O;
6159 typedef internal::Internals I;
6160 O* obj = *reinterpret_cast<O**>(this);
6161 // Fast path: If the object is a plain JSObject, which is the common case, we
6162 // know where to find the internal fields and can return the value directly.
6163 if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
6164 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
6165 return I::ReadField<void*>(obj, offset);
6166 }
6167 #endif
6168 return SlowGetAlignedPointerFromInternalField(index);
6169 }
6170
6171
6172 String* String::Cast(v8::Value* value) {
6173 #ifdef V8_ENABLE_CHECKS
6174 CheckCast(value);
6175 #endif
6176 return static_cast<String*>(value);
6177 }
6178
6179
6180 Local<String> String::Empty(Isolate* isolate) {
6181 typedef internal::Object* S;
6182 typedef internal::Internals I;
6183 I::CheckInitialized(isolate);
6184 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
6185 return Local<String>(reinterpret_cast<String*>(slot));
6186 }
6187
6188
6189 String::ExternalStringResource* String::GetExternalStringResource() const {
6190 typedef internal::Object O;
6191 typedef internal::Internals I;
6192 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6193 String::ExternalStringResource* result;
6194 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
6195 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6196 result = reinterpret_cast<String::ExternalStringResource*>(value);
6197 } else {
6198 result = NULL;
6199 }
6200 #ifdef V8_ENABLE_CHECKS
6201 VerifyExternalStringResource(result);
6202 #endif
6203 return result;
6204 }
6205
6206
6207 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
6208 String::Encoding* encoding_out) const {
6209 typedef internal::Object O;
6210 typedef internal::Internals I;
6211 O* obj = *reinterpret_cast<O**>(const_cast<String*>(this));
6212 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
6213 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
6214 ExternalStringResourceBase* resource = NULL;
6215 if (type == I::kExternalAsciiRepresentationTag ||
6216 type == I::kExternalTwoByteRepresentationTag) {
6217 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
6218 resource = static_cast<ExternalStringResourceBase*>(value);
6219 }
6220 #ifdef V8_ENABLE_CHECKS
6221 VerifyExternalStringResourceBase(resource, *encoding_out);
6222 #endif
6223 return resource;
6224 }
6225
6226
6227 bool Value::IsUndefined() const {
6228 #ifdef V8_ENABLE_CHECKS
6229 return FullIsUndefined();
6230 #else
6231 return QuickIsUndefined();
6232 #endif
6233 }
6234
6235 bool Value::QuickIsUndefined() const {
6236 typedef internal::Object O;
6237 typedef internal::Internals I;
6238 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6239 if (!I::HasHeapObjectTag(obj)) return false;
6240 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6241 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
6242 }
6243
6244
6245 bool Value::IsNull() const {
6246 #ifdef V8_ENABLE_CHECKS
6247 return FullIsNull();
6248 #else
6249 return QuickIsNull();
6250 #endif
6251 }
6252
6253 bool Value::QuickIsNull() const {
6254 typedef internal::Object O;
6255 typedef internal::Internals I;
6256 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6257 if (!I::HasHeapObjectTag(obj)) return false;
6258 if (I::GetInstanceType(obj) != I::kOddballType) return false;
6259 return (I::GetOddballKind(obj) == I::kNullOddballKind);
6260 }
6261
6262
6263 bool Value::IsString() const {
6264 #ifdef V8_ENABLE_CHECKS
6265 return FullIsString();
6266 #else
6267 return QuickIsString();
6268 #endif
6269 }
6270
6271 bool Value::QuickIsString() const {
6272 typedef internal::Object O;
6273 typedef internal::Internals I;
6274 O* obj = *reinterpret_cast<O**>(const_cast<Value*>(this));
6275 if (!I::HasHeapObjectTag(obj)) return false;
6276 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
6277 }
6278
6279
6280 template <class T> Value* Value::Cast(T* value) {
6281 return static_cast<Value*>(value);
6282 }
6283
6284
6285 Symbol* Symbol::Cast(v8::Value* value) {
6286 #ifdef V8_ENABLE_CHECKS
6287 CheckCast(value);
6288 #endif
6289 return static_cast<Symbol*>(value);
6290 }
6291
6292
6293 Number* Number::Cast(v8::Value* value) {
6294 #ifdef V8_ENABLE_CHECKS
6295 CheckCast(value);
6296 #endif
6297 return static_cast<Number*>(value);
6298 }
6299
6300
6301 Integer* Integer::Cast(v8::Value* value) {
6302 #ifdef V8_ENABLE_CHECKS
6303 CheckCast(value);
6304 #endif
6305 return static_cast<Integer*>(value);
6306 }
6307
6308
6309 Date* Date::Cast(v8::Value* value) {
6310 #ifdef V8_ENABLE_CHECKS
6311 CheckCast(value);
6312 #endif
6313 return static_cast<Date*>(value);
6314 }
6315
6316
6317 StringObject* StringObject::Cast(v8::Value* value) {
6318 #ifdef V8_ENABLE_CHECKS
6319 CheckCast(value);
6320 #endif
6321 return static_cast<StringObject*>(value);
6322 }
6323
6324
6325 SymbolObject* SymbolObject::Cast(v8::Value* value) {
6326 #ifdef V8_ENABLE_CHECKS
6327 CheckCast(value);
6328 #endif
6329 return static_cast<SymbolObject*>(value);
6330 }
6331
6332
6333 NumberObject* NumberObject::Cast(v8::Value* value) {
6334 #ifdef V8_ENABLE_CHECKS
6335 CheckCast(value);
6336 #endif
6337 return static_cast<NumberObject*>(value);
6338 }
6339
6340
6341 BooleanObject* BooleanObject::Cast(v8::Value* value) {
6342 #ifdef V8_ENABLE_CHECKS
6343 CheckCast(value);
6344 #endif
6345 return static_cast<BooleanObject*>(value);
6346 }
6347
6348
6349 RegExp* RegExp::Cast(v8::Value* value) {
6350 #ifdef V8_ENABLE_CHECKS
6351 CheckCast(value);
6352 #endif
6353 return static_cast<RegExp*>(value);
6354 }
6355
6356
6357 Object* Object::Cast(v8::Value* value) {
6358 #ifdef V8_ENABLE_CHECKS
6359 CheckCast(value);
6360 #endif
6361 return static_cast<Object*>(value);
6362 }
6363
6364
6365 Array* Array::Cast(v8::Value* value) {
6366 #ifdef V8_ENABLE_CHECKS
6367 CheckCast(value);
6368 #endif
6369 return static_cast<Array*>(value);
6370 }
6371
6372
6373 Promise* Promise::Cast(v8::Value* value) {
6374 #ifdef V8_ENABLE_CHECKS
6375 CheckCast(value);
6376 #endif
6377 return static_cast<Promise*>(value);
6378 }
6379
6380
6381 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
6382 #ifdef V8_ENABLE_CHECKS
6383 CheckCast(value);
6384 #endif
6385 return static_cast<Promise::Resolver*>(value);
6386 }
6387
6388
6389 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
6390 #ifdef V8_ENABLE_CHECKS
6391 CheckCast(value);
6392 #endif
6393 return static_cast<ArrayBuffer*>(value);
6394 }
6395
6396
6397 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
6398 #ifdef V8_ENABLE_CHECKS
6399 CheckCast(value);
6400 #endif
6401 return static_cast<ArrayBufferView*>(value);
6402 }
6403
6404
6405 TypedArray* TypedArray::Cast(v8::Value* value) {
6406 #ifdef V8_ENABLE_CHECKS
6407 CheckCast(value);
6408 #endif
6409 return static_cast<TypedArray*>(value);
6410 }
6411
6412
6413 Uint8Array* Uint8Array::Cast(v8::Value* value) {
6414 #ifdef V8_ENABLE_CHECKS
6415 CheckCast(value);
6416 #endif
6417 return static_cast<Uint8Array*>(value);
6418 }
6419
6420
6421 Int8Array* Int8Array::Cast(v8::Value* value) {
6422 #ifdef V8_ENABLE_CHECKS
6423 CheckCast(value);
6424 #endif
6425 return static_cast<Int8Array*>(value);
6426 }
6427
6428
6429 Uint16Array* Uint16Array::Cast(v8::Value* value) {
6430 #ifdef V8_ENABLE_CHECKS
6431 CheckCast(value);
6432 #endif
6433 return static_cast<Uint16Array*>(value);
6434 }
6435
6436
6437 Int16Array* Int16Array::Cast(v8::Value* value) {
6438 #ifdef V8_ENABLE_CHECKS
6439 CheckCast(value);
6440 #endif
6441 return static_cast<Int16Array*>(value);
6442 }
6443
6444
6445 Uint32Array* Uint32Array::Cast(v8::Value* value) {
6446 #ifdef V8_ENABLE_CHECKS
6447 CheckCast(value);
6448 #endif
6449 return static_cast<Uint32Array*>(value);
6450 }
6451
6452
6453 Int32Array* Int32Array::Cast(v8::Value* value) {
6454 #ifdef V8_ENABLE_CHECKS
6455 CheckCast(value);
6456 #endif
6457 return static_cast<Int32Array*>(value);
6458 }
6459
6460
6461 Float32Array* Float32Array::Cast(v8::Value* value) {
6462 #ifdef V8_ENABLE_CHECKS
6463 CheckCast(value);
6464 #endif
6465 return static_cast<Float32Array*>(value);
6466 }
6467
6468
6469 Float64Array* Float64Array::Cast(v8::Value* value) {
6470 #ifdef V8_ENABLE_CHECKS
6471 CheckCast(value);
6472 #endif
6473 return static_cast<Float64Array*>(value);
6474 }
6475
6476
6477 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
6478 #ifdef V8_ENABLE_CHECKS
6479 CheckCast(value);
6480 #endif
6481 return static_cast<Uint8ClampedArray*>(value);
6482 }
6483
6484
6485 DataView* DataView::Cast(v8::Value* value) {
6486 #ifdef V8_ENABLE_CHECKS
6487 CheckCast(value);
6488 #endif
6489 return static_cast<DataView*>(value);
6490 }
6491
6492
6493 Function* Function::Cast(v8::Value* value) {
6494 #ifdef V8_ENABLE_CHECKS
6495 CheckCast(value);
6496 #endif
6497 return static_cast<Function*>(value);
6498 }
6499
6500
6501 External* External::Cast(v8::Value* value) {
6502 #ifdef V8_ENABLE_CHECKS
6503 CheckCast(value);
6504 #endif
6505 return static_cast<External*>(value);
6506 }
6507
6508
6509 template<typename T>
6510 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
6511 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
6512 }
6513
6514
6515 template<typename T>
6516 Local<Value> PropertyCallbackInfo<T>::Data() const {
6517 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
6518 }
6519
6520
6521 template<typename T>
6522 Local<Object> PropertyCallbackInfo<T>::This() const {
6523 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
6524 }
6525
6526
6527 template<typename T>
6528 Local<Object> PropertyCallbackInfo<T>::Holder() const {
6529 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
6530 }
6531
6532
6533 template<typename T>
6534 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
6535 return ReturnValue<T>(&args_[kReturnValueIndex]);
6536 }
6537
6538
6539 Handle<Primitive> Undefined(Isolate* isolate) {
6540 typedef internal::Object* S;
6541 typedef internal::Internals I;
6542 I::CheckInitialized(isolate);
6543 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
6544 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6545 }
6546
6547
6548 Handle<Primitive> Null(Isolate* isolate) {
6549 typedef internal::Object* S;
6550 typedef internal::Internals I;
6551 I::CheckInitialized(isolate);
6552 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
6553 return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
6554 }
6555
6556
6557 Handle<Boolean> True(Isolate* isolate) {
6558 typedef internal::Object* S;
6559 typedef internal::Internals I;
6560 I::CheckInitialized(isolate);
6561 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
6562 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6563 }
6564
6565
6566 Handle<Boolean> False(Isolate* isolate) {
6567 typedef internal::Object* S;
6568 typedef internal::Internals I;
6569 I::CheckInitialized(isolate);
6570 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
6571 return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
6572 }
6573
6574
6575 void Isolate::SetData(uint32_t slot, void* data) {
6576 typedef internal::Internals I;
6577 I::SetEmbedderData(this, slot, data);
6578 }
6579
6580
6581 void* Isolate::GetData(uint32_t slot) {
6582 typedef internal::Internals I;
6583 return I::GetEmbedderData(this, slot);
6584 }
6585
6586
6587 uint32_t Isolate::GetNumberOfDataSlots() {
6588 typedef internal::Internals I;
6589 return I::kNumIsolateDataSlots;
6590 }
6591
6592
6593 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
6594 int64_t change_in_bytes) {
6595 typedef internal::Internals I;
6596 int64_t* amount_of_external_allocated_memory =
6597 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
6598 I::kAmountOfExternalAllocatedMemoryOffset);
6599 int64_t* amount_of_external_allocated_memory_at_last_global_gc =
6600 reinterpret_cast<int64_t*>(
6601 reinterpret_cast<uint8_t*>(this) +
6602 I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
6603 int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
6604 if (change_in_bytes > 0 &&
6605 amount - *amount_of_external_allocated_memory_at_last_global_gc >
6606 I::kExternalAllocationLimit) {
6607 CollectAllGarbage("external memory allocation limit reached.");
6608 } else {
6609 *amount_of_external_allocated_memory = amount;
6610 }
6611 return *amount_of_external_allocated_memory;
6612 }
6613
6614
6615 template<typename T>
6616 void Isolate::SetObjectGroupId(const Persistent<T>& object,
6617 UniqueId id) {
6618 TYPE_CHECK(Value, T);
6619 SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
6620 }
6621
6622
6623 template<typename T>
6624 void Isolate::SetReferenceFromGroup(UniqueId id,
6625 const Persistent<T>& object) {
6626 TYPE_CHECK(Value, T);
6627 SetReferenceFromGroup(id,
6628 reinterpret_cast<v8::internal::Object**>(object.val_));
6629 }
6630
6631
6632 template<typename T, typename S>
6633 void Isolate::SetReference(const Persistent<T>& parent,
6634 const Persistent<S>& child) {
6635 TYPE_CHECK(Object, T);
6636 TYPE_CHECK(Value, S);
6637 SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
6638 reinterpret_cast<v8::internal::Object**>(child.val_));
6639 }
6640
6641
6642 Local<Value> Context::GetEmbedderData(int index) {
6643 #ifndef V8_ENABLE_CHECKS
6644 typedef internal::Object O;
6645 typedef internal::HeapObject HO;
6646 typedef internal::Internals I;
6647 HO* context = *reinterpret_cast<HO**>(this);
6648 O** result =
6649 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
6650 return Local<Value>(reinterpret_cast<Value*>(result));
6651 #else
6652 return SlowGetEmbedderData(index);
6653 #endif
6654 }
6655
6656
6657 void* Context::GetAlignedPointerFromEmbedderData(int index) {
6658 #ifndef V8_ENABLE_CHECKS
6659 typedef internal::Internals I;
6660 return I::ReadEmbedderData<void*>(this, index);
6661 #else
6662 return SlowGetAlignedPointerFromEmbedderData(index);
6663 #endif
6664 }
6665
6666
6667 /**
6668 * \example shell.cc
6669 * A simple shell that takes a list of expressions on the
6670 * command-line and executes them.
6671 */
6672
6673
6674 /**
6675 * \example process.cc
6676 */
6677
6678
6679 } // namespace v8
6680
6681
6682 #undef TYPE_CHECK
6683
6684
6685 #endif // V8_H_
6686