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