1 // Copyright 2012 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 /** \mainpage V8 API Reference Guide 6 * 7 * V8 is Google's open source JavaScript engine. 8 * 9 * This set of documents provides reference material generated from the 10 * V8 header file, include/v8.h. 11 * 12 * For other documentation see http://code.google.com/apis/v8/ 13 */ 14 15 #ifndef INCLUDE_V8_H_ 16 #define INCLUDE_V8_H_ 17 18 #include <stddef.h> 19 #include <stdint.h> 20 #include <stdio.h> 21 #include <memory> 22 #include <utility> 23 #include <vector> 24 25 #include "v8-version.h" // NOLINT(build/include) 26 #include "v8config.h" // NOLINT(build/include) 27 28 // We reserve the V8_* prefix for macros defined in V8 public API and 29 // assume there are no name conflicts with the embedder's code. 30 31 #ifdef V8_OS_WIN 32 33 // Setup for Windows DLL export/import. When building the V8 DLL the 34 // BUILDING_V8_SHARED needs to be defined. When building a program which uses 35 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 36 // static library or building a program which uses the V8 static library neither 37 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. 38 #ifdef BUILDING_V8_SHARED 39 # define V8_EXPORT __declspec(dllexport) 40 #elif USING_V8_SHARED 41 # define V8_EXPORT __declspec(dllimport) 42 #else 43 # define V8_EXPORT 44 #endif // BUILDING_V8_SHARED 45 46 #else // V8_OS_WIN 47 48 // Setup for Linux shared library export. 49 #if V8_HAS_ATTRIBUTE_VISIBILITY 50 # ifdef BUILDING_V8_SHARED 51 # define V8_EXPORT __attribute__ ((visibility("default"))) 52 # else 53 # define V8_EXPORT 54 # endif 55 #else 56 # define V8_EXPORT 57 #endif 58 59 #endif // V8_OS_WIN 60 61 /** 62 * The v8 JavaScript engine. 63 */ 64 namespace v8 { 65 66 class AccessorSignature; 67 class Array; 68 class ArrayBuffer; 69 class Boolean; 70 class BooleanObject; 71 class Context; 72 class CpuProfiler; 73 class Data; 74 class Date; 75 class External; 76 class Function; 77 class FunctionTemplate; 78 class HeapProfiler; 79 class ImplementationUtilities; 80 class Int32; 81 class Integer; 82 class Isolate; 83 template <class T> 84 class Maybe; 85 class Name; 86 class Number; 87 class NumberObject; 88 class Object; 89 class ObjectOperationDescriptor; 90 class ObjectTemplate; 91 class Platform; 92 class Primitive; 93 class Promise; 94 class PropertyDescriptor; 95 class Proxy; 96 class RawOperationDescriptor; 97 class Script; 98 class SharedArrayBuffer; 99 class Signature; 100 class StartupData; 101 class StackFrame; 102 class StackTrace; 103 class String; 104 class StringObject; 105 class Symbol; 106 class SymbolObject; 107 class Private; 108 class Uint32; 109 class Utils; 110 class Value; 111 template <class T> class Local; 112 template <class T> 113 class MaybeLocal; 114 template <class T> class Eternal; 115 template<class T> class NonCopyablePersistentTraits; 116 template<class T> class PersistentBase; 117 template <class T, class M = NonCopyablePersistentTraits<T> > 118 class Persistent; 119 template <class T> 120 class Global; 121 template<class K, class V, class T> class PersistentValueMap; 122 template <class K, class V, class T> 123 class PersistentValueMapBase; 124 template <class K, class V, class T> 125 class GlobalValueMap; 126 template<class V, class T> class PersistentValueVector; 127 template<class T, class P> class WeakCallbackObject; 128 class FunctionTemplate; 129 class ObjectTemplate; 130 class Data; 131 template<typename T> class FunctionCallbackInfo; 132 template<typename T> class PropertyCallbackInfo; 133 class StackTrace; 134 class StackFrame; 135 class Isolate; 136 class CallHandlerHelper; 137 class EscapableHandleScope; 138 template<typename T> class ReturnValue; 139 140 namespace experimental { 141 class FastAccessorBuilder; 142 } // namespace experimental 143 144 namespace internal { 145 class Arguments; 146 class Heap; 147 class HeapObject; 148 class Isolate; 149 class Object; 150 struct StreamedSource; 151 template<typename T> class CustomArguments; 152 class PropertyCallbackArguments; 153 class FunctionCallbackArguments; 154 class GlobalHandles; 155 } // namespace internal 156 157 158 /** 159 * General purpose unique identifier. 160 */ 161 class UniqueId { 162 public: 163 explicit UniqueId(intptr_t data) 164 : data_(data) {} 165 166 bool operator==(const UniqueId& other) const { 167 return data_ == other.data_; 168 } 169 170 bool operator!=(const UniqueId& other) const { 171 return data_ != other.data_; 172 } 173 174 bool operator<(const UniqueId& other) const { 175 return data_ < other.data_; 176 } 177 178 private: 179 intptr_t data_; 180 }; 181 182 // --- Handles --- 183 184 #define TYPE_CHECK(T, S) \ 185 while (false) { \ 186 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \ 187 } 188 189 190 /** 191 * An object reference managed by the v8 garbage collector. 192 * 193 * All objects returned from v8 have to be tracked by the garbage 194 * collector so that it knows that the objects are still alive. Also, 195 * because the garbage collector may move objects, it is unsafe to 196 * point directly to an object. Instead, all objects are stored in 197 * handles which are known by the garbage collector and updated 198 * whenever an object moves. Handles should always be passed by value 199 * (except in cases like out-parameters) and they should never be 200 * allocated on the heap. 201 * 202 * There are two types of handles: local and persistent handles. 203 * Local handles are light-weight and transient and typically used in 204 * local operations. They are managed by HandleScopes. Persistent 205 * handles can be used when storing objects across several independent 206 * operations and have to be explicitly deallocated when they're no 207 * longer used. 208 * 209 * It is safe to extract the object stored in the handle by 210 * dereferencing the handle (for instance, to extract the Object* from 211 * a Local<Object>); the value will still be governed by a handle 212 * behind the scenes and the same rules apply to these values as to 213 * their handles. 214 */ 215 template <class T> 216 class Local { 217 public: 218 V8_INLINE Local() : val_(0) {} 219 template <class S> 220 V8_INLINE Local(Local<S> that) 221 : val_(reinterpret_cast<T*>(*that)) { 222 /** 223 * This check fails when trying to convert between incompatible 224 * handles. For example, converting from a Local<String> to a 225 * Local<Number>. 226 */ 227 TYPE_CHECK(T, S); 228 } 229 230 /** 231 * Returns true if the handle is empty. 232 */ 233 V8_INLINE bool IsEmpty() const { return val_ == 0; } 234 235 /** 236 * Sets the handle to be empty. IsEmpty() will then return true. 237 */ 238 V8_INLINE void Clear() { val_ = 0; } 239 240 V8_INLINE T* operator->() const { return val_; } 241 242 V8_INLINE T* operator*() const { return val_; } 243 244 /** 245 * Checks whether two handles are the same. 246 * Returns true if both are empty, or if the objects 247 * to which they refer are identical. 248 * The handles' references are not checked. 249 */ 250 template <class S> 251 V8_INLINE bool operator==(const Local<S>& that) const { 252 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_); 253 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_); 254 if (a == 0) return b == 0; 255 if (b == 0) return false; 256 return *a == *b; 257 } 258 259 template <class S> V8_INLINE bool operator==( 260 const PersistentBase<S>& that) const { 261 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_); 262 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_); 263 if (a == 0) return b == 0; 264 if (b == 0) return false; 265 return *a == *b; 266 } 267 268 /** 269 * Checks whether two handles are different. 270 * Returns true if only one of the handles is empty, or if 271 * the objects to which they refer are different. 272 * The handles' references are not checked. 273 */ 274 template <class S> 275 V8_INLINE bool operator!=(const Local<S>& that) const { 276 return !operator==(that); 277 } 278 279 template <class S> V8_INLINE bool operator!=( 280 const Persistent<S>& that) const { 281 return !operator==(that); 282 } 283 284 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) { 285 #ifdef V8_ENABLE_CHECKS 286 // If we're going to perform the type check then we have to check 287 // that the handle isn't empty before doing the checked cast. 288 if (that.IsEmpty()) return Local<T>(); 289 #endif 290 return Local<T>(T::Cast(*that)); 291 } 292 293 template <class S> 294 V8_INLINE Local<S> As() const { 295 return Local<S>::Cast(*this); 296 } 297 298 /** 299 * Create a local handle for the content of another handle. 300 * The referee is kept alive by the local handle even when 301 * the original handle is destroyed/disposed. 302 */ 303 V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that); 304 V8_INLINE static Local<T> New(Isolate* isolate, 305 const PersistentBase<T>& that); 306 307 private: 308 friend class Utils; 309 template<class F> friend class Eternal; 310 template<class F> friend class PersistentBase; 311 template<class F, class M> friend class Persistent; 312 template<class F> friend class Local; 313 template <class F> 314 friend class MaybeLocal; 315 template<class F> friend class FunctionCallbackInfo; 316 template<class F> friend class PropertyCallbackInfo; 317 friend class String; 318 friend class Object; 319 friend class Context; 320 friend class Private; 321 template<class F> friend class internal::CustomArguments; 322 friend Local<Primitive> Undefined(Isolate* isolate); 323 friend Local<Primitive> Null(Isolate* isolate); 324 friend Local<Boolean> True(Isolate* isolate); 325 friend Local<Boolean> False(Isolate* isolate); 326 friend class HandleScope; 327 friend class EscapableHandleScope; 328 template <class F1, class F2, class F3> 329 friend class PersistentValueMapBase; 330 template<class F1, class F2> friend class PersistentValueVector; 331 template <class F> 332 friend class ReturnValue; 333 334 explicit V8_INLINE Local(T* that) : val_(that) {} 335 V8_INLINE static Local<T> New(Isolate* isolate, T* that); 336 T* val_; 337 }; 338 339 340 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS) 341 // Handle is an alias for Local for historical reasons. 342 template <class T> 343 using Handle = Local<T>; 344 #endif 345 346 347 /** 348 * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether 349 * the Local<> is empty before it can be used. 350 * 351 * If an API method returns a MaybeLocal<>, the API method can potentially fail 352 * either because an exception is thrown, or because an exception is pending, 353 * e.g. because a previous API call threw an exception that hasn't been caught 354 * yet, or because a TerminateExecution exception was thrown. In that case, an 355 * empty MaybeLocal is returned. 356 */ 357 template <class T> 358 class MaybeLocal { 359 public: 360 V8_INLINE MaybeLocal() : val_(nullptr) {} 361 template <class S> 362 V8_INLINE MaybeLocal(Local<S> that) 363 : val_(reinterpret_cast<T*>(*that)) { 364 TYPE_CHECK(T, S); 365 } 366 367 V8_INLINE bool IsEmpty() const { return val_ == nullptr; } 368 369 template <class S> 370 V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const { 371 out->val_ = IsEmpty() ? nullptr : this->val_; 372 return !IsEmpty(); 373 } 374 375 // Will crash if the MaybeLocal<> is empty. 376 V8_INLINE Local<T> ToLocalChecked(); 377 378 template <class S> 379 V8_INLINE Local<S> FromMaybe(Local<S> default_value) const { 380 return IsEmpty() ? default_value : Local<S>(val_); 381 } 382 383 private: 384 T* val_; 385 }; 386 387 388 // Eternal handles are set-once handles that live for the life of the isolate. 389 template <class T> class Eternal { 390 public: 391 V8_INLINE Eternal() : index_(kInitialValue) { } 392 template<class S> 393 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) { 394 Set(isolate, handle); 395 } 396 // Can only be safely called if already set. 397 V8_INLINE Local<T> Get(Isolate* isolate); 398 V8_INLINE bool IsEmpty() { return index_ == kInitialValue; } 399 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle); 400 401 private: 402 static const int kInitialValue = -1; 403 int index_; 404 }; 405 406 407 static const int kInternalFieldsInWeakCallback = 2; 408 409 410 template <typename T> 411 class WeakCallbackInfo { 412 public: 413 typedef void (*Callback)(const WeakCallbackInfo<T>& data); 414 415 WeakCallbackInfo(Isolate* isolate, T* parameter, 416 void* internal_fields[kInternalFieldsInWeakCallback], 417 Callback* callback) 418 : isolate_(isolate), parameter_(parameter), callback_(callback) { 419 for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) { 420 internal_fields_[i] = internal_fields[i]; 421 } 422 } 423 424 V8_INLINE Isolate* GetIsolate() const { return isolate_; } 425 V8_INLINE T* GetParameter() const { return parameter_; } 426 V8_INLINE void* GetInternalField(int index) const; 427 428 V8_INLINE V8_DEPRECATED("use indexed version", 429 void* GetInternalField1() const) { 430 return internal_fields_[0]; 431 } 432 V8_INLINE V8_DEPRECATED("use indexed version", 433 void* GetInternalField2() const) { 434 return internal_fields_[1]; 435 } 436 437 V8_DEPRECATED("Not realiable once SetSecondPassCallback() was used.", 438 bool IsFirstPass() const) { 439 return callback_ != nullptr; 440 } 441 442 // When first called, the embedder MUST Reset() the Global which triggered the 443 // callback. The Global itself is unusable for anything else. No v8 other api 444 // calls may be called in the first callback. Should additional work be 445 // required, the embedder must set a second pass callback, which will be 446 // called after all the initial callbacks are processed. 447 // Calling SetSecondPassCallback on the second pass will immediately crash. 448 void SetSecondPassCallback(Callback callback) const { *callback_ = callback; } 449 450 private: 451 Isolate* isolate_; 452 T* parameter_; 453 Callback* callback_; 454 void* internal_fields_[kInternalFieldsInWeakCallback]; 455 }; 456 457 458 // kParameter will pass a void* parameter back to the callback, kInternalFields 459 // will pass the first two internal fields back to the callback, kFinalizer 460 // will pass a void* parameter back, but is invoked before the object is 461 // actually collected, so it can be resurrected. In the last case, it is not 462 // possible to request a second pass callback. 463 enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer }; 464 465 /** 466 * An object reference that is independent of any handle scope. Where 467 * a Local handle only lives as long as the HandleScope in which it was 468 * allocated, a PersistentBase handle remains valid until it is explicitly 469 * disposed. 470 * 471 * A persistent handle contains a reference to a storage cell within 472 * the v8 engine which holds an object value and which is updated by 473 * the garbage collector whenever the object is moved. A new storage 474 * cell can be created using the constructor or PersistentBase::Reset and 475 * existing handles can be disposed using PersistentBase::Reset. 476 * 477 */ 478 template <class T> class PersistentBase { 479 public: 480 /** 481 * If non-empty, destroy the underlying storage cell 482 * IsEmpty() will return true after this call. 483 */ 484 V8_INLINE void Reset(); 485 /** 486 * If non-empty, destroy the underlying storage cell 487 * and create a new one with the contents of other if other is non empty 488 */ 489 template <class S> 490 V8_INLINE void Reset(Isolate* isolate, const Local<S>& other); 491 492 /** 493 * If non-empty, destroy the underlying storage cell 494 * and create a new one with the contents of other if other is non empty 495 */ 496 template <class S> 497 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other); 498 499 V8_INLINE bool IsEmpty() const { return val_ == NULL; } 500 V8_INLINE void Empty() { val_ = 0; } 501 502 V8_INLINE Local<T> Get(Isolate* isolate) const { 503 return Local<T>::New(isolate, *this); 504 } 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 == NULL) return b == NULL; 511 if (b == NULL) return false; 512 return *a == *b; 513 } 514 515 template <class S> 516 V8_INLINE bool operator==(const Local<S>& that) const { 517 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_); 518 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_); 519 if (a == NULL) return b == NULL; 520 if (b == NULL) return false; 521 return *a == *b; 522 } 523 524 template <class S> 525 V8_INLINE bool operator!=(const PersistentBase<S>& that) const { 526 return !operator==(that); 527 } 528 529 template <class S> 530 V8_INLINE bool operator!=(const Local<S>& that) const { 531 return !operator==(that); 532 } 533 534 /** 535 * Install a finalization callback on this object. 536 * NOTE: There is no guarantee as to *when* or even *if* the callback is 537 * invoked. The invocation is performed solely on a best effort basis. 538 * As always, GC-based finalization should *not* be relied upon for any 539 * critical form of resource management! 540 */ 541 template <typename P> 542 V8_INLINE void SetWeak(P* parameter, 543 typename WeakCallbackInfo<P>::Callback callback, 544 WeakCallbackType type); 545 546 /** 547 * Turns this handle into a weak phantom handle without finalization callback. 548 * The handle will be reset automatically when the garbage collector detects 549 * that the object is no longer reachable. 550 * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall 551 * returns how many phantom handles were reset by the garbage collector. 552 */ 553 V8_INLINE void SetWeak(); 554 555 template<typename P> 556 V8_INLINE P* ClearWeak(); 557 558 // TODO(dcarney): remove this. 559 V8_INLINE void ClearWeak() { ClearWeak<void>(); } 560 561 /** 562 * Allows the embedder to tell the v8 garbage collector that a certain object 563 * is alive. Only allowed when the embedder is asked to trace its heap by 564 * EmbedderHeapTracer. 565 */ 566 V8_INLINE void RegisterExternalReference(Isolate* isolate) const; 567 568 /** 569 * Marks the reference to this object independent. Garbage collector is free 570 * to ignore any object groups containing this object. Weak callback for an 571 * independent handle should not assume that it will be preceded by a global 572 * GC prologue callback or followed by a global GC epilogue callback. 573 */ 574 V8_INLINE void MarkIndependent(); 575 576 /** 577 * Marks the reference to this object as active. The scavenge garbage 578 * collection should not reclaim the objects marked as active. 579 * This bit is cleared after the each garbage collection pass. 580 */ 581 V8_INLINE void MarkActive(); 582 583 V8_INLINE bool IsIndependent() const; 584 585 /** Checks if the handle holds the only reference to an object. */ 586 V8_INLINE bool IsNearDeath() const; 587 588 /** Returns true if the handle's reference is weak. */ 589 V8_INLINE bool IsWeak() const; 590 591 /** 592 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface 593 * description in v8-profiler.h for details. 594 */ 595 V8_INLINE void SetWrapperClassId(uint16_t class_id); 596 597 /** 598 * Returns the class ID previously assigned to this handle or 0 if no class ID 599 * was previously assigned. 600 */ 601 V8_INLINE uint16_t WrapperClassId() const; 602 603 PersistentBase(const PersistentBase& other) = delete; // NOLINT 604 void operator=(const PersistentBase&) = delete; 605 606 private: 607 friend class Isolate; 608 friend class Utils; 609 template<class F> friend class Local; 610 template<class F1, class F2> friend class Persistent; 611 template <class F> 612 friend class Global; 613 template<class F> friend class PersistentBase; 614 template<class F> friend class ReturnValue; 615 template <class F1, class F2, class F3> 616 friend class PersistentValueMapBase; 617 template<class F1, class F2> friend class PersistentValueVector; 618 friend class Object; 619 620 explicit V8_INLINE PersistentBase(T* val) : val_(val) {} 621 V8_INLINE static T* New(Isolate* isolate, T* that); 622 623 T* val_; 624 }; 625 626 627 /** 628 * Default traits for Persistent. This class does not allow 629 * use of the copy constructor or assignment operator. 630 * At present kResetInDestructor is not set, but that will change in a future 631 * version. 632 */ 633 template<class T> 634 class NonCopyablePersistentTraits { 635 public: 636 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent; 637 static const bool kResetInDestructor = false; 638 template<class S, class M> 639 V8_INLINE static void Copy(const Persistent<S, M>& source, 640 NonCopyablePersistent* dest) { 641 Uncompilable<Object>(); 642 } 643 // TODO(dcarney): come up with a good compile error here. 644 template<class O> V8_INLINE static void Uncompilable() { 645 TYPE_CHECK(O, Primitive); 646 } 647 }; 648 649 650 /** 651 * Helper class traits to allow copying and assignment of Persistent. 652 * This will clone the contents of storage cell, but not any of the flags, etc. 653 */ 654 template<class T> 655 struct CopyablePersistentTraits { 656 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent; 657 static const bool kResetInDestructor = true; 658 template<class S, class M> 659 static V8_INLINE void Copy(const Persistent<S, M>& source, 660 CopyablePersistent* dest) { 661 // do nothing, just allow copy 662 } 663 }; 664 665 666 /** 667 * A PersistentBase which allows copy and assignment. 668 * 669 * Copy, assignment and destructor behavior is controlled by the traits 670 * class M. 671 * 672 * Note: Persistent class hierarchy is subject to future changes. 673 */ 674 template <class T, class M> class Persistent : public PersistentBase<T> { 675 public: 676 /** 677 * A Persistent with no storage cell. 678 */ 679 V8_INLINE Persistent() : PersistentBase<T>(0) { } 680 /** 681 * Construct a Persistent from a Local. 682 * When the Local is non-empty, a new storage cell is created 683 * pointing to the same object, and no flags are set. 684 */ 685 template <class S> 686 V8_INLINE Persistent(Isolate* isolate, Local<S> that) 687 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) { 688 TYPE_CHECK(T, S); 689 } 690 /** 691 * Construct a Persistent from a Persistent. 692 * When the Persistent is non-empty, a new storage cell is created 693 * pointing to the same object, and no flags are set. 694 */ 695 template <class S, class M2> 696 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that) 697 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) { 698 TYPE_CHECK(T, S); 699 } 700 /** 701 * The copy constructors and assignment operator create a Persistent 702 * exactly as the Persistent constructor, but the Copy function from the 703 * traits class is called, allowing the setting of flags based on the 704 * copied Persistent. 705 */ 706 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) { 707 Copy(that); 708 } 709 template <class S, class M2> 710 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) { 711 Copy(that); 712 } 713 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT 714 Copy(that); 715 return *this; 716 } 717 template <class S, class M2> 718 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT 719 Copy(that); 720 return *this; 721 } 722 /** 723 * The destructor will dispose the Persistent based on the 724 * kResetInDestructor flags in the traits class. Since not calling dispose 725 * can result in a memory leak, it is recommended to always set this flag. 726 */ 727 V8_INLINE ~Persistent() { 728 if (M::kResetInDestructor) this->Reset(); 729 } 730 731 // TODO(dcarney): this is pretty useless, fix or remove 732 template <class S> 733 V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT 734 #ifdef V8_ENABLE_CHECKS 735 // If we're going to perform the type check then we have to check 736 // that the handle isn't empty before doing the checked cast. 737 if (!that.IsEmpty()) T::Cast(*that); 738 #endif 739 return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that)); 740 } 741 742 // TODO(dcarney): this is pretty useless, fix or remove 743 template <class S> 744 V8_INLINE Persistent<S>& As() const { // NOLINT 745 return Persistent<S>::Cast(*this); 746 } 747 748 private: 749 friend class Isolate; 750 friend class Utils; 751 template<class F> friend class Local; 752 template<class F1, class F2> friend class Persistent; 753 template<class F> friend class ReturnValue; 754 755 explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {} 756 V8_INLINE T* operator*() const { return this->val_; } 757 template<class S, class M2> 758 V8_INLINE void Copy(const Persistent<S, M2>& that); 759 }; 760 761 762 /** 763 * A PersistentBase which has move semantics. 764 * 765 * Note: Persistent class hierarchy is subject to future changes. 766 */ 767 template <class T> 768 class Global : public PersistentBase<T> { 769 public: 770 /** 771 * A Global with no storage cell. 772 */ 773 V8_INLINE Global() : PersistentBase<T>(nullptr) {} 774 /** 775 * Construct a Global from a Local. 776 * When the Local is non-empty, a new storage cell is created 777 * pointing to the same object, and no flags are set. 778 */ 779 template <class S> 780 V8_INLINE Global(Isolate* isolate, Local<S> that) 781 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) { 782 TYPE_CHECK(T, S); 783 } 784 /** 785 * Construct a Global from a PersistentBase. 786 * When the Persistent is non-empty, a new storage cell is created 787 * pointing to the same object, and no flags are set. 788 */ 789 template <class S> 790 V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that) 791 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) { 792 TYPE_CHECK(T, S); 793 } 794 /** 795 * Move constructor. 796 */ 797 V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) { // NOLINT 798 other.val_ = nullptr; 799 } 800 V8_INLINE ~Global() { this->Reset(); } 801 /** 802 * Move via assignment. 803 */ 804 template <class S> 805 V8_INLINE Global& operator=(Global<S>&& rhs) { // NOLINT 806 TYPE_CHECK(T, S); 807 if (this != &rhs) { 808 this->Reset(); 809 this->val_ = rhs.val_; 810 rhs.val_ = nullptr; 811 } 812 return *this; 813 } 814 /** 815 * Pass allows returning uniques from functions, etc. 816 */ 817 Global Pass() { return static_cast<Global&&>(*this); } // NOLINT 818 819 /* 820 * For compatibility with Chromium's base::Bind (base::Passed). 821 */ 822 typedef void MoveOnlyTypeForCPP03; 823 824 Global(const Global&) = delete; 825 void operator=(const Global&) = delete; 826 827 private: 828 template <class F> 829 friend class ReturnValue; 830 V8_INLINE T* operator*() const { return this->val_; } 831 }; 832 833 834 // UniquePersistent is an alias for Global for historical reason. 835 template <class T> 836 using UniquePersistent = Global<T>; 837 838 839 /** 840 * A stack-allocated class that governs a number of local handles. 841 * After a handle scope has been created, all local handles will be 842 * allocated within that handle scope until either the handle scope is 843 * deleted or another handle scope is created. If there is already a 844 * handle scope and a new one is created, all allocations will take 845 * place in the new handle scope until it is deleted. After that, 846 * new handles will again be allocated in the original handle scope. 847 * 848 * After the handle scope of a local handle has been deleted the 849 * garbage collector will no longer track the object stored in the 850 * handle and may deallocate it. The behavior of accessing a handle 851 * for which the handle scope has been deleted is undefined. 852 */ 853 class V8_EXPORT HandleScope { 854 public: 855 explicit HandleScope(Isolate* isolate); 856 857 ~HandleScope(); 858 859 /** 860 * Counts the number of allocated handles. 861 */ 862 static int NumberOfHandles(Isolate* isolate); 863 864 V8_INLINE Isolate* GetIsolate() const { 865 return reinterpret_cast<Isolate*>(isolate_); 866 } 867 868 HandleScope(const HandleScope&) = delete; 869 void operator=(const HandleScope&) = delete; 870 void* operator new(size_t size); 871 void operator delete(void*, size_t); 872 873 protected: 874 V8_INLINE HandleScope() {} 875 876 void Initialize(Isolate* isolate); 877 878 static internal::Object** CreateHandle(internal::Isolate* isolate, 879 internal::Object* value); 880 881 private: 882 // Uses heap_object to obtain the current Isolate. 883 static internal::Object** CreateHandle(internal::HeapObject* heap_object, 884 internal::Object* value); 885 886 internal::Isolate* isolate_; 887 internal::Object** prev_next_; 888 internal::Object** prev_limit_; 889 890 // Local::New uses CreateHandle with an Isolate* parameter. 891 template<class F> friend class Local; 892 893 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with 894 // a HeapObject* in their shortcuts. 895 friend class Object; 896 friend class Context; 897 }; 898 899 900 /** 901 * A HandleScope which first allocates a handle in the current scope 902 * which will be later filled with the escape value. 903 */ 904 class V8_EXPORT EscapableHandleScope : public HandleScope { 905 public: 906 explicit EscapableHandleScope(Isolate* isolate); 907 V8_INLINE ~EscapableHandleScope() {} 908 909 /** 910 * Pushes the value into the previous scope and returns a handle to it. 911 * Cannot be called twice. 912 */ 913 template <class T> 914 V8_INLINE Local<T> Escape(Local<T> value) { 915 internal::Object** slot = 916 Escape(reinterpret_cast<internal::Object**>(*value)); 917 return Local<T>(reinterpret_cast<T*>(slot)); 918 } 919 920 EscapableHandleScope(const EscapableHandleScope&) = delete; 921 void operator=(const EscapableHandleScope&) = delete; 922 void* operator new(size_t size); 923 void operator delete(void*, size_t); 924 925 private: 926 internal::Object** Escape(internal::Object** escape_value); 927 internal::Object** escape_slot_; 928 }; 929 930 class V8_EXPORT SealHandleScope { 931 public: 932 SealHandleScope(Isolate* isolate); 933 ~SealHandleScope(); 934 935 SealHandleScope(const SealHandleScope&) = delete; 936 void operator=(const SealHandleScope&) = delete; 937 void* operator new(size_t size); 938 void operator delete(void*, size_t); 939 940 private: 941 internal::Isolate* const isolate_; 942 internal::Object** prev_limit_; 943 int prev_sealed_level_; 944 }; 945 946 947 // --- Special objects --- 948 949 950 /** 951 * The superclass of values and API object templates. 952 */ 953 class V8_EXPORT Data { 954 private: 955 Data(); 956 }; 957 958 959 /** 960 * The optional attributes of ScriptOrigin. 961 */ 962 class ScriptOriginOptions { 963 public: 964 V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false, 965 bool is_opaque = false, bool is_wasm = false, 966 bool is_module = false) 967 : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) | 968 (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) | 969 (is_module ? kIsModule : 0)) {} 970 V8_INLINE ScriptOriginOptions(int flags) 971 : flags_(flags & 972 (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {} 973 974 bool IsSharedCrossOrigin() const { 975 return (flags_ & kIsSharedCrossOrigin) != 0; 976 } 977 bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; } 978 bool IsWasm() const { return (flags_ & kIsWasm) != 0; } 979 bool IsModule() const { return (flags_ & kIsModule) != 0; } 980 981 int Flags() const { return flags_; } 982 983 private: 984 enum { 985 kIsSharedCrossOrigin = 1, 986 kIsOpaque = 1 << 1, 987 kIsWasm = 1 << 2, 988 kIsModule = 1 << 3 989 }; 990 const int flags_; 991 }; 992 993 /** 994 * The origin, within a file, of a script. 995 */ 996 class ScriptOrigin { 997 public: 998 V8_INLINE ScriptOrigin( 999 Local<Value> resource_name, 1000 Local<Integer> resource_line_offset = Local<Integer>(), 1001 Local<Integer> resource_column_offset = Local<Integer>(), 1002 Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(), 1003 Local<Integer> script_id = Local<Integer>(), 1004 Local<Value> source_map_url = Local<Value>(), 1005 Local<Boolean> resource_is_opaque = Local<Boolean>(), 1006 Local<Boolean> is_wasm = Local<Boolean>(), 1007 Local<Boolean> is_module = Local<Boolean>()); 1008 1009 V8_INLINE Local<Value> ResourceName() const; 1010 V8_INLINE Local<Integer> ResourceLineOffset() const; 1011 V8_INLINE Local<Integer> ResourceColumnOffset() const; 1012 /** 1013 * Returns true for embedder's debugger scripts 1014 */ 1015 V8_INLINE Local<Integer> ScriptID() const; 1016 V8_INLINE Local<Value> SourceMapUrl() const; 1017 V8_INLINE ScriptOriginOptions Options() const { return options_; } 1018 1019 private: 1020 Local<Value> resource_name_; 1021 Local<Integer> resource_line_offset_; 1022 Local<Integer> resource_column_offset_; 1023 ScriptOriginOptions options_; 1024 Local<Integer> script_id_; 1025 Local<Value> source_map_url_; 1026 }; 1027 1028 1029 /** 1030 * A compiled JavaScript script, not yet tied to a Context. 1031 */ 1032 class V8_EXPORT UnboundScript { 1033 public: 1034 /** 1035 * Binds the script to the currently entered context. 1036 */ 1037 Local<Script> BindToCurrentContext(); 1038 1039 int GetId(); 1040 Local<Value> GetScriptName(); 1041 1042 /** 1043 * Data read from magic sourceURL comments. 1044 */ 1045 Local<Value> GetSourceURL(); 1046 /** 1047 * Data read from magic sourceMappingURL comments. 1048 */ 1049 Local<Value> GetSourceMappingURL(); 1050 1051 /** 1052 * Returns zero based line number of the code_pos location in the script. 1053 * -1 will be returned if no information available. 1054 */ 1055 int GetLineNumber(int code_pos); 1056 1057 static const int kNoScriptId = 0; 1058 }; 1059 1060 /** 1061 * This is an unfinished experimental feature, and is only exposed 1062 * here for internal testing purposes. DO NOT USE. 1063 * 1064 * A compiled JavaScript module. 1065 */ 1066 class V8_EXPORT Module { 1067 public: 1068 /** 1069 * Returns the number of modules requested by this module. 1070 */ 1071 int GetModuleRequestsLength() const; 1072 1073 /** 1074 * Returns the ith module specifier in this module. 1075 * i must be < GetModuleRequestsLength() and >= 0. 1076 */ 1077 Local<String> GetModuleRequest(int i) const; 1078 1079 /** 1080 * Returns the identity hash for this object. 1081 */ 1082 int GetIdentityHash() const; 1083 1084 typedef MaybeLocal<Module> (*ResolveCallback)(Local<Context> context, 1085 Local<String> specifier, 1086 Local<Module> referrer); 1087 1088 /** 1089 * ModuleDeclarationInstantiation 1090 * 1091 * Returns false if an exception occurred during instantiation. 1092 */ 1093 V8_WARN_UNUSED_RESULT bool Instantiate(Local<Context> context, 1094 ResolveCallback callback); 1095 1096 /** 1097 * ModuleEvaluation 1098 */ 1099 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Evaluate(Local<Context> context); 1100 }; 1101 1102 /** 1103 * A compiled JavaScript script, tied to a Context which was active when the 1104 * script was compiled. 1105 */ 1106 class V8_EXPORT Script { 1107 public: 1108 /** 1109 * A shorthand for ScriptCompiler::Compile(). 1110 */ 1111 static V8_DEPRECATE_SOON( 1112 "Use maybe version", 1113 Local<Script> Compile(Local<String> source, 1114 ScriptOrigin* origin = nullptr)); 1115 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile( 1116 Local<Context> context, Local<String> source, 1117 ScriptOrigin* origin = nullptr); 1118 1119 static Local<Script> V8_DEPRECATE_SOON("Use maybe version", 1120 Compile(Local<String> source, 1121 Local<String> file_name)); 1122 1123 /** 1124 * Runs the script returning the resulting value. It will be run in the 1125 * context in which it was created (ScriptCompiler::CompileBound or 1126 * UnboundScript::BindToCurrentContext()). 1127 */ 1128 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run()); 1129 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context); 1130 1131 /** 1132 * Returns the corresponding context-unbound script. 1133 */ 1134 Local<UnboundScript> GetUnboundScript(); 1135 }; 1136 1137 1138 /** 1139 * For compiling scripts. 1140 */ 1141 class V8_EXPORT ScriptCompiler { 1142 public: 1143 /** 1144 * Compilation data that the embedder can cache and pass back to speed up 1145 * future compilations. The data is produced if the CompilerOptions passed to 1146 * the compilation functions in ScriptCompiler contains produce_data_to_cache 1147 * = true. The data to cache can then can be retrieved from 1148 * UnboundScript. 1149 */ 1150 struct V8_EXPORT CachedData { 1151 enum BufferPolicy { 1152 BufferNotOwned, 1153 BufferOwned 1154 }; 1155 1156 CachedData() 1157 : data(NULL), 1158 length(0), 1159 rejected(false), 1160 buffer_policy(BufferNotOwned) {} 1161 1162 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of 1163 // data and guarantees that it stays alive until the CachedData object is 1164 // destroyed. If the policy is BufferOwned, the given data will be deleted 1165 // (with delete[]) when the CachedData object is destroyed. 1166 CachedData(const uint8_t* data, int length, 1167 BufferPolicy buffer_policy = BufferNotOwned); 1168 ~CachedData(); 1169 // TODO(marja): Async compilation; add constructors which take a callback 1170 // which will be called when V8 no longer needs the data. 1171 const uint8_t* data; 1172 int length; 1173 bool rejected; 1174 BufferPolicy buffer_policy; 1175 1176 // Prevent copying. 1177 CachedData(const CachedData&) = delete; 1178 CachedData& operator=(const CachedData&) = delete; 1179 }; 1180 1181 /** 1182 * Source code which can be then compiled to a UnboundScript or Script. 1183 */ 1184 class Source { 1185 public: 1186 // Source takes ownership of CachedData. 1187 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin, 1188 CachedData* cached_data = NULL); 1189 V8_INLINE Source(Local<String> source_string, 1190 CachedData* cached_data = NULL); 1191 V8_INLINE ~Source(); 1192 1193 // Ownership of the CachedData or its buffers is *not* transferred to the 1194 // caller. The CachedData object is alive as long as the Source object is 1195 // alive. 1196 V8_INLINE const CachedData* GetCachedData() const; 1197 1198 V8_INLINE const ScriptOriginOptions& GetResourceOptions() const; 1199 1200 // Prevent copying. 1201 Source(const Source&) = delete; 1202 Source& operator=(const Source&) = delete; 1203 1204 private: 1205 friend class ScriptCompiler; 1206 1207 Local<String> source_string; 1208 1209 // Origin information 1210 Local<Value> resource_name; 1211 Local<Integer> resource_line_offset; 1212 Local<Integer> resource_column_offset; 1213 ScriptOriginOptions resource_options; 1214 Local<Value> source_map_url; 1215 1216 // Cached data from previous compilation (if a kConsume*Cache flag is 1217 // set), or hold newly generated cache data (kProduce*Cache flags) are 1218 // set when calling a compile method. 1219 CachedData* cached_data; 1220 }; 1221 1222 /** 1223 * For streaming incomplete script data to V8. The embedder should implement a 1224 * subclass of this class. 1225 */ 1226 class V8_EXPORT ExternalSourceStream { 1227 public: 1228 virtual ~ExternalSourceStream() {} 1229 1230 /** 1231 * V8 calls this to request the next chunk of data from the embedder. This 1232 * function will be called on a background thread, so it's OK to block and 1233 * wait for the data, if the embedder doesn't have data yet. Returns the 1234 * length of the data returned. When the data ends, GetMoreData should 1235 * return 0. Caller takes ownership of the data. 1236 * 1237 * When streaming UTF-8 data, V8 handles multi-byte characters split between 1238 * two data chunks, but doesn't handle multi-byte characters split between 1239 * more than two data chunks. The embedder can avoid this problem by always 1240 * returning at least 2 bytes of data. 1241 * 1242 * If the embedder wants to cancel the streaming, they should make the next 1243 * GetMoreData call return 0. V8 will interpret it as end of data (and most 1244 * probably, parsing will fail). The streaming task will return as soon as 1245 * V8 has parsed the data it received so far. 1246 */ 1247 virtual size_t GetMoreData(const uint8_t** src) = 0; 1248 1249 /** 1250 * V8 calls this method to set a 'bookmark' at the current position in 1251 * the source stream, for the purpose of (maybe) later calling 1252 * ResetToBookmark. If ResetToBookmark is called later, then subsequent 1253 * calls to GetMoreData should return the same data as they did when 1254 * SetBookmark was called earlier. 1255 * 1256 * The embedder may return 'false' to indicate it cannot provide this 1257 * functionality. 1258 */ 1259 virtual bool SetBookmark(); 1260 1261 /** 1262 * V8 calls this to return to a previously set bookmark. 1263 */ 1264 virtual void ResetToBookmark(); 1265 }; 1266 1267 1268 /** 1269 * Source code which can be streamed into V8 in pieces. It will be parsed 1270 * while streaming. It can be compiled after the streaming is complete. 1271 * StreamedSource must be kept alive while the streaming task is ran (see 1272 * ScriptStreamingTask below). 1273 */ 1274 class V8_EXPORT StreamedSource { 1275 public: 1276 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 }; 1277 1278 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding); 1279 ~StreamedSource(); 1280 1281 // Ownership of the CachedData or its buffers is *not* transferred to the 1282 // caller. The CachedData object is alive as long as the StreamedSource 1283 // object is alive. 1284 const CachedData* GetCachedData() const; 1285 1286 internal::StreamedSource* impl() const { return impl_; } 1287 1288 // Prevent copying. 1289 StreamedSource(const StreamedSource&) = delete; 1290 StreamedSource& operator=(const StreamedSource&) = delete; 1291 1292 private: 1293 internal::StreamedSource* impl_; 1294 }; 1295 1296 /** 1297 * A streaming task which the embedder must run on a background thread to 1298 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript. 1299 */ 1300 class ScriptStreamingTask { 1301 public: 1302 virtual ~ScriptStreamingTask() {} 1303 virtual void Run() = 0; 1304 }; 1305 1306 enum CompileOptions { 1307 kNoCompileOptions = 0, 1308 kProduceParserCache, 1309 kConsumeParserCache, 1310 kProduceCodeCache, 1311 kConsumeCodeCache 1312 }; 1313 1314 /** 1315 * Compiles the specified script (context-independent). 1316 * Cached data as part of the source object can be optionally produced to be 1317 * consumed later to speed up compilation of identical source scripts. 1318 * 1319 * Note that when producing cached data, the source must point to NULL for 1320 * cached data. When consuming cached data, the cached data must have been 1321 * produced by the same version of V8. 1322 * 1323 * \param source Script source code. 1324 * \return Compiled script object (context independent; for running it must be 1325 * bound to a context). 1326 */ 1327 static V8_DEPRECATED("Use maybe version", 1328 Local<UnboundScript> CompileUnbound( 1329 Isolate* isolate, Source* source, 1330 CompileOptions options = kNoCompileOptions)); 1331 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript( 1332 Isolate* isolate, Source* source, 1333 CompileOptions options = kNoCompileOptions); 1334 1335 /** 1336 * Compiles the specified script (bound to current context). 1337 * 1338 * \param source Script source code. 1339 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile() 1340 * using pre_data speeds compilation if it's done multiple times. 1341 * Owned by caller, no references are kept when this function returns. 1342 * \return Compiled script object, bound to the context that was active 1343 * when this function was called. When run it will always use this 1344 * context. 1345 */ 1346 static V8_DEPRECATED( 1347 "Use maybe version", 1348 Local<Script> Compile(Isolate* isolate, Source* source, 1349 CompileOptions options = kNoCompileOptions)); 1350 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile( 1351 Local<Context> context, Source* source, 1352 CompileOptions options = kNoCompileOptions); 1353 1354 /** 1355 * Returns a task which streams script data into V8, or NULL if the script 1356 * cannot be streamed. The user is responsible for running the task on a 1357 * background thread and deleting it. When ran, the task starts parsing the 1358 * script, and it will request data from the StreamedSource as needed. When 1359 * ScriptStreamingTask::Run exits, all data has been streamed and the script 1360 * can be compiled (see Compile below). 1361 * 1362 * This API allows to start the streaming with as little data as possible, and 1363 * the remaining data (for example, the ScriptOrigin) is passed to Compile. 1364 */ 1365 static ScriptStreamingTask* StartStreamingScript( 1366 Isolate* isolate, StreamedSource* source, 1367 CompileOptions options = kNoCompileOptions); 1368 1369 /** 1370 * Compiles a streamed script (bound to current context). 1371 * 1372 * This can only be called after the streaming has finished 1373 * (ScriptStreamingTask has been run). V8 doesn't construct the source string 1374 * during streaming, so the embedder needs to pass the full source here. 1375 */ 1376 static V8_DEPRECATED("Use maybe version", 1377 Local<Script> Compile(Isolate* isolate, 1378 StreamedSource* source, 1379 Local<String> full_source_string, 1380 const ScriptOrigin& origin)); 1381 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile( 1382 Local<Context> context, StreamedSource* source, 1383 Local<String> full_source_string, const ScriptOrigin& origin); 1384 1385 /** 1386 * Return a version tag for CachedData for the current V8 version & flags. 1387 * 1388 * This value is meant only for determining whether a previously generated 1389 * CachedData instance is still valid; the tag has no other meaing. 1390 * 1391 * Background: The data carried by CachedData may depend on the exact 1392 * V8 version number or currently compiler flags. This means when 1393 * persisting CachedData, the embedder must take care to not pass in 1394 * data from another V8 version, or the same version with different 1395 * features enabled. 1396 * 1397 * The easiest way to do so is to clear the embedder's cache on any 1398 * such change. 1399 * 1400 * Alternatively, this tag can be stored alongside the cached data and 1401 * compared when it is being used. 1402 */ 1403 static uint32_t CachedDataVersionTag(); 1404 1405 /** 1406 * This is an unfinished experimental feature, and is only exposed 1407 * here for internal testing purposes. DO NOT USE. 1408 * 1409 * Compile an ES module, returning a Module that encapsulates 1410 * the compiled code. 1411 * 1412 * Corresponds to the ParseModule abstract operation in the 1413 * ECMAScript specification. 1414 */ 1415 static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule( 1416 Isolate* isolate, Source* source); 1417 1418 /** 1419 * Compile a function for a given context. This is equivalent to running 1420 * 1421 * with (obj) { 1422 * return function(args) { ... } 1423 * } 1424 * 1425 * It is possible to specify multiple context extensions (obj in the above 1426 * example). 1427 */ 1428 static V8_DEPRECATE_SOON("Use maybe version", 1429 Local<Function> CompileFunctionInContext( 1430 Isolate* isolate, Source* source, 1431 Local<Context> context, size_t arguments_count, 1432 Local<String> arguments[], 1433 size_t context_extension_count, 1434 Local<Object> context_extensions[])); 1435 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext( 1436 Local<Context> context, Source* source, size_t arguments_count, 1437 Local<String> arguments[], size_t context_extension_count, 1438 Local<Object> context_extensions[]); 1439 1440 private: 1441 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal( 1442 Isolate* isolate, Source* source, CompileOptions options); 1443 }; 1444 1445 1446 /** 1447 * An error message. 1448 */ 1449 class V8_EXPORT Message { 1450 public: 1451 Local<String> Get() const; 1452 1453 V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const); 1454 V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine( 1455 Local<Context> context) const; 1456 1457 /** 1458 * Returns the origin for the script from where the function causing the 1459 * error originates. 1460 */ 1461 ScriptOrigin GetScriptOrigin() const; 1462 1463 /** 1464 * Returns the resource name for the script from where the function causing 1465 * the error originates. 1466 */ 1467 Local<Value> GetScriptResourceName() const; 1468 1469 /** 1470 * Exception stack trace. By default stack traces are not captured for 1471 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows 1472 * to change this option. 1473 */ 1474 Local<StackTrace> GetStackTrace() const; 1475 1476 /** 1477 * Returns the number, 1-based, of the line where the error occurred. 1478 */ 1479 V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const); 1480 V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const; 1481 1482 /** 1483 * Returns the index within the script of the first character where 1484 * the error occurred. 1485 */ 1486 int GetStartPosition() const; 1487 1488 /** 1489 * Returns the index within the script of the last character where 1490 * the error occurred. 1491 */ 1492 int GetEndPosition() const; 1493 1494 /** 1495 * Returns the error level of the message. 1496 */ 1497 int ErrorLevel() const; 1498 1499 /** 1500 * Returns the index within the line of the first character where 1501 * the error occurred. 1502 */ 1503 V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const); 1504 V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const; 1505 1506 /** 1507 * Returns the index within the line of the last character where 1508 * the error occurred. 1509 */ 1510 V8_DEPRECATED("Use maybe version", int GetEndColumn() const); 1511 V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const; 1512 1513 /** 1514 * Passes on the value set by the embedder when it fed the script from which 1515 * this Message was generated to V8. 1516 */ 1517 bool IsSharedCrossOrigin() const; 1518 bool IsOpaque() const; 1519 1520 // TODO(1245381): Print to a string instead of on a FILE. 1521 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out); 1522 1523 static const int kNoLineNumberInfo = 0; 1524 static const int kNoColumnInfo = 0; 1525 static const int kNoScriptIdInfo = 0; 1526 }; 1527 1528 1529 /** 1530 * Representation of a JavaScript stack trace. The information collected is a 1531 * snapshot of the execution stack and the information remains valid after 1532 * execution continues. 1533 */ 1534 class V8_EXPORT StackTrace { 1535 public: 1536 /** 1537 * Flags that determine what information is placed captured for each 1538 * StackFrame when grabbing the current stack trace. 1539 */ 1540 enum StackTraceOptions { 1541 kLineNumber = 1, 1542 kColumnOffset = 1 << 1 | kLineNumber, 1543 kScriptName = 1 << 2, 1544 kFunctionName = 1 << 3, 1545 kIsEval = 1 << 4, 1546 kIsConstructor = 1 << 5, 1547 kScriptNameOrSourceURL = 1 << 6, 1548 kScriptId = 1 << 7, 1549 kExposeFramesAcrossSecurityOrigins = 1 << 8, 1550 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName, 1551 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL 1552 }; 1553 1554 /** 1555 * Returns a StackFrame at a particular index. 1556 */ 1557 Local<StackFrame> GetFrame(uint32_t index) const; 1558 1559 /** 1560 * Returns the number of StackFrames. 1561 */ 1562 int GetFrameCount() const; 1563 1564 /** 1565 * Returns StackTrace as a v8::Array that contains StackFrame objects. 1566 */ 1567 Local<Array> AsArray(); 1568 1569 /** 1570 * Grab a snapshot of the current JavaScript execution stack. 1571 * 1572 * \param frame_limit The maximum number of stack frames we want to capture. 1573 * \param options Enumerates the set of things we will capture for each 1574 * StackFrame. 1575 */ 1576 static Local<StackTrace> CurrentStackTrace( 1577 Isolate* isolate, 1578 int frame_limit, 1579 StackTraceOptions options = kOverview); 1580 }; 1581 1582 1583 /** 1584 * A single JavaScript stack frame. 1585 */ 1586 class V8_EXPORT StackFrame { 1587 public: 1588 /** 1589 * Returns the number, 1-based, of the line for the associate function call. 1590 * This method will return Message::kNoLineNumberInfo if it is unable to 1591 * retrieve the line number, or if kLineNumber was not passed as an option 1592 * when capturing the StackTrace. 1593 */ 1594 int GetLineNumber() const; 1595 1596 /** 1597 * Returns the 1-based column offset on the line for the associated function 1598 * call. 1599 * This method will return Message::kNoColumnInfo if it is unable to retrieve 1600 * the column number, or if kColumnOffset was not passed as an option when 1601 * capturing the StackTrace. 1602 */ 1603 int GetColumn() const; 1604 1605 /** 1606 * Returns the id of the script for the function for this StackFrame. 1607 * This method will return Message::kNoScriptIdInfo if it is unable to 1608 * retrieve the script id, or if kScriptId was not passed as an option when 1609 * capturing the StackTrace. 1610 */ 1611 int GetScriptId() const; 1612 1613 /** 1614 * Returns the name of the resource that contains the script for the 1615 * function for this StackFrame. 1616 */ 1617 Local<String> GetScriptName() const; 1618 1619 /** 1620 * Returns the name of the resource that contains the script for the 1621 * function for this StackFrame or sourceURL value if the script name 1622 * is undefined and its source ends with //# sourceURL=... string or 1623 * deprecated //@ sourceURL=... string. 1624 */ 1625 Local<String> GetScriptNameOrSourceURL() const; 1626 1627 /** 1628 * Returns the name of the function associated with this stack frame. 1629 */ 1630 Local<String> GetFunctionName() const; 1631 1632 /** 1633 * Returns whether or not the associated function is compiled via a call to 1634 * eval(). 1635 */ 1636 bool IsEval() const; 1637 1638 /** 1639 * Returns whether or not the associated function is called as a 1640 * constructor via "new". 1641 */ 1642 bool IsConstructor() const; 1643 }; 1644 1645 1646 // A StateTag represents a possible state of the VM. 1647 enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE }; 1648 1649 // A RegisterState represents the current state of registers used 1650 // by the sampling profiler API. 1651 struct RegisterState { 1652 RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr) {} 1653 void* pc; // Instruction pointer. 1654 void* sp; // Stack pointer. 1655 void* fp; // Frame pointer. 1656 }; 1657 1658 // The output structure filled up by GetStackSample API function. 1659 struct SampleInfo { 1660 size_t frames_count; // Number of frames collected. 1661 StateTag vm_state; // Current VM state. 1662 void* external_callback_entry; // External callback address if VM is 1663 // executing an external callback. 1664 }; 1665 1666 /** 1667 * A JSON Parser and Stringifier. 1668 */ 1669 class V8_EXPORT JSON { 1670 public: 1671 /** 1672 * Tries to parse the string |json_string| and returns it as value if 1673 * successful. 1674 * 1675 * \param json_string The string to parse. 1676 * \return The corresponding value if successfully parsed. 1677 */ 1678 static V8_DEPRECATED("Use the maybe version taking context", 1679 Local<Value> Parse(Local<String> json_string)); 1680 static V8_DEPRECATE_SOON("Use the maybe version taking context", 1681 MaybeLocal<Value> Parse(Isolate* isolate, 1682 Local<String> json_string)); 1683 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse( 1684 Local<Context> context, Local<String> json_string); 1685 1686 /** 1687 * Tries to stringify the JSON-serializable object |json_object| and returns 1688 * it as string if successful. 1689 * 1690 * \param json_object The JSON-serializable object to stringify. 1691 * \return The corresponding string if successfully stringified. 1692 */ 1693 static V8_WARN_UNUSED_RESULT MaybeLocal<String> Stringify( 1694 Local<Context> context, Local<Object> json_object, 1695 Local<String> gap = Local<String>()); 1696 }; 1697 1698 /** 1699 * Value serialization compatible with the HTML structured clone algorithm. 1700 * The format is backward-compatible (i.e. safe to store to disk). 1701 * 1702 * WARNING: This API is under development, and changes (including incompatible 1703 * changes to the API or wire format) may occur without notice until this 1704 * warning is removed. 1705 */ 1706 class V8_EXPORT ValueSerializer { 1707 public: 1708 class V8_EXPORT Delegate { 1709 public: 1710 virtual ~Delegate() {} 1711 1712 /* 1713 * Handles the case where a DataCloneError would be thrown in the structured 1714 * clone spec. Other V8 embedders may throw some other appropriate exception 1715 * type. 1716 */ 1717 virtual void ThrowDataCloneError(Local<String> message) = 0; 1718 1719 /* 1720 * The embedder overrides this method to write some kind of host object, if 1721 * possible. If not, a suitable exception should be thrown and 1722 * Nothing<bool>() returned. 1723 */ 1724 virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object); 1725 1726 /* 1727 * Called when the ValueSerializer is going to serialize a 1728 * SharedArrayBuffer object. The embedder must return an ID for the 1729 * object, using the same ID if this SharedArrayBuffer has already been 1730 * serialized in this buffer. When deserializing, this ID will be passed to 1731 * ValueDeserializer::TransferSharedArrayBuffer as |transfer_id|. 1732 * 1733 * If the object cannot be serialized, an 1734 * exception should be thrown and Nothing<uint32_t>() returned. 1735 */ 1736 virtual Maybe<uint32_t> GetSharedArrayBufferId( 1737 Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer); 1738 1739 /* 1740 * Allocates memory for the buffer of at least the size provided. The actual 1741 * size (which may be greater or equal) is written to |actual_size|. If no 1742 * buffer has been allocated yet, nullptr will be provided. 1743 * 1744 * If the memory cannot be allocated, nullptr should be returned. 1745 * |actual_size| will be ignored. It is assumed that |old_buffer| is still 1746 * valid in this case and has not been modified. 1747 */ 1748 virtual void* ReallocateBufferMemory(void* old_buffer, size_t size, 1749 size_t* actual_size); 1750 1751 /* 1752 * Frees a buffer allocated with |ReallocateBufferMemory|. 1753 */ 1754 virtual void FreeBufferMemory(void* buffer); 1755 }; 1756 1757 explicit ValueSerializer(Isolate* isolate); 1758 ValueSerializer(Isolate* isolate, Delegate* delegate); 1759 ~ValueSerializer(); 1760 1761 /* 1762 * Writes out a header, which includes the format version. 1763 */ 1764 void WriteHeader(); 1765 1766 /* 1767 * Serializes a JavaScript value into the buffer. 1768 */ 1769 V8_WARN_UNUSED_RESULT Maybe<bool> WriteValue(Local<Context> context, 1770 Local<Value> value); 1771 1772 /* 1773 * Returns the stored data. This serializer should not be used once the buffer 1774 * is released. The contents are undefined if a previous write has failed. 1775 */ 1776 V8_DEPRECATE_SOON("Use Release()", std::vector<uint8_t> ReleaseBuffer()); 1777 1778 /* 1779 * Returns the stored data (allocated using the delegate's 1780 * AllocateBufferMemory) and its size. This serializer should not be used once 1781 * the buffer is released. The contents are undefined if a previous write has 1782 * failed. 1783 */ 1784 V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release(); 1785 1786 /* 1787 * Marks an ArrayBuffer as havings its contents transferred out of band. 1788 * Pass the corresponding ArrayBuffer in the deserializing context to 1789 * ValueDeserializer::TransferArrayBuffer. 1790 */ 1791 void TransferArrayBuffer(uint32_t transfer_id, 1792 Local<ArrayBuffer> array_buffer); 1793 1794 /* 1795 * Similar to TransferArrayBuffer, but for SharedArrayBuffer. 1796 */ 1797 V8_DEPRECATE_SOON("Use Delegate::GetSharedArrayBufferId", 1798 void TransferSharedArrayBuffer( 1799 uint32_t transfer_id, 1800 Local<SharedArrayBuffer> shared_array_buffer)); 1801 1802 /* 1803 * Indicate whether to treat ArrayBufferView objects as host objects, 1804 * i.e. pass them to Delegate::WriteHostObject. This should not be 1805 * called when no Delegate was passed. 1806 * 1807 * The default is not to treat ArrayBufferViews as host objects. 1808 */ 1809 void SetTreatArrayBufferViewsAsHostObjects(bool mode); 1810 1811 /* 1812 * Write raw data in various common formats to the buffer. 1813 * Note that integer types are written in base-128 varint format, not with a 1814 * binary copy. For use during an override of Delegate::WriteHostObject. 1815 */ 1816 void WriteUint32(uint32_t value); 1817 void WriteUint64(uint64_t value); 1818 void WriteDouble(double value); 1819 void WriteRawBytes(const void* source, size_t length); 1820 1821 private: 1822 ValueSerializer(const ValueSerializer&) = delete; 1823 void operator=(const ValueSerializer&) = delete; 1824 1825 struct PrivateData; 1826 PrivateData* private_; 1827 }; 1828 1829 /** 1830 * Deserializes values from data written with ValueSerializer, or a compatible 1831 * implementation. 1832 * 1833 * WARNING: This API is under development, and changes (including incompatible 1834 * changes to the API or wire format) may occur without notice until this 1835 * warning is removed. 1836 */ 1837 class V8_EXPORT ValueDeserializer { 1838 public: 1839 class V8_EXPORT Delegate { 1840 public: 1841 virtual ~Delegate() {} 1842 1843 /* 1844 * The embedder overrides this method to read some kind of host object, if 1845 * possible. If not, a suitable exception should be thrown and 1846 * MaybeLocal<Object>() returned. 1847 */ 1848 virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate); 1849 }; 1850 1851 ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size); 1852 ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size, 1853 Delegate* delegate); 1854 ~ValueDeserializer(); 1855 1856 /* 1857 * Reads and validates a header (including the format version). 1858 * May, for example, reject an invalid or unsupported wire format. 1859 */ 1860 V8_WARN_UNUSED_RESULT Maybe<bool> ReadHeader(Local<Context> context); 1861 1862 /* 1863 * Deserializes a JavaScript value from the buffer. 1864 */ 1865 V8_WARN_UNUSED_RESULT MaybeLocal<Value> ReadValue(Local<Context> context); 1866 1867 /* 1868 * Accepts the array buffer corresponding to the one passed previously to 1869 * ValueSerializer::TransferArrayBuffer. 1870 */ 1871 void TransferArrayBuffer(uint32_t transfer_id, 1872 Local<ArrayBuffer> array_buffer); 1873 1874 /* 1875 * Similar to TransferArrayBuffer, but for SharedArrayBuffer. 1876 * The id is not necessarily in the same namespace as unshared ArrayBuffer 1877 * objects. 1878 */ 1879 void TransferSharedArrayBuffer(uint32_t id, 1880 Local<SharedArrayBuffer> shared_array_buffer); 1881 1882 /* 1883 * Must be called before ReadHeader to enable support for reading the legacy 1884 * wire format (i.e., which predates this being shipped). 1885 * 1886 * Don't use this unless you need to read data written by previous versions of 1887 * blink::ScriptValueSerializer. 1888 */ 1889 void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format); 1890 1891 /* 1892 * Reads the underlying wire format version. Likely mostly to be useful to 1893 * legacy code reading old wire format versions. Must be called after 1894 * ReadHeader. 1895 */ 1896 uint32_t GetWireFormatVersion() const; 1897 1898 /* 1899 * Reads raw data in various common formats to the buffer. 1900 * Note that integer types are read in base-128 varint format, not with a 1901 * binary copy. For use during an override of Delegate::ReadHostObject. 1902 */ 1903 V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value); 1904 V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value); 1905 V8_WARN_UNUSED_RESULT bool ReadDouble(double* value); 1906 V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data); 1907 1908 private: 1909 ValueDeserializer(const ValueDeserializer&) = delete; 1910 void operator=(const ValueDeserializer&) = delete; 1911 1912 struct PrivateData; 1913 PrivateData* private_; 1914 }; 1915 1916 /** 1917 * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap 1918 * but can be created without entering a v8::Context and hence shouldn't 1919 * escape to JavaScript. 1920 */ 1921 class V8_EXPORT NativeWeakMap : public Data { 1922 public: 1923 static Local<NativeWeakMap> New(Isolate* isolate); 1924 void Set(Local<Value> key, Local<Value> value); 1925 Local<Value> Get(Local<Value> key); 1926 bool Has(Local<Value> key); 1927 bool Delete(Local<Value> key); 1928 }; 1929 1930 1931 // --- Value --- 1932 1933 1934 /** 1935 * The superclass of all JavaScript values and objects. 1936 */ 1937 class V8_EXPORT Value : public Data { 1938 public: 1939 /** 1940 * Returns true if this value is the undefined value. See ECMA-262 1941 * 4.3.10. 1942 */ 1943 V8_INLINE bool IsUndefined() const; 1944 1945 /** 1946 * Returns true if this value is the null value. See ECMA-262 1947 * 4.3.11. 1948 */ 1949 V8_INLINE bool IsNull() const; 1950 1951 /** 1952 * Returns true if this value is either the null or the undefined value. 1953 * See ECMA-262 1954 * 4.3.11. and 4.3.12 1955 */ 1956 V8_INLINE bool IsNullOrUndefined() const; 1957 1958 /** 1959 * Returns true if this value is true. 1960 */ 1961 bool IsTrue() const; 1962 1963 /** 1964 * Returns true if this value is false. 1965 */ 1966 bool IsFalse() const; 1967 1968 /** 1969 * Returns true if this value is a symbol or a string. 1970 */ 1971 bool IsName() const; 1972 1973 /** 1974 * Returns true if this value is an instance of the String type. 1975 * See ECMA-262 8.4. 1976 */ 1977 V8_INLINE bool IsString() const; 1978 1979 /** 1980 * Returns true if this value is a symbol. 1981 */ 1982 bool IsSymbol() const; 1983 1984 /** 1985 * Returns true if this value is a function. 1986 */ 1987 bool IsFunction() const; 1988 1989 /** 1990 * Returns true if this value is an array. Note that it will return false for 1991 * an Proxy for an array. 1992 */ 1993 bool IsArray() const; 1994 1995 /** 1996 * Returns true if this value is an object. 1997 */ 1998 bool IsObject() const; 1999 2000 /** 2001 * Returns true if this value is boolean. 2002 */ 2003 bool IsBoolean() const; 2004 2005 /** 2006 * Returns true if this value is a number. 2007 */ 2008 bool IsNumber() const; 2009 2010 /** 2011 * Returns true if this value is external. 2012 */ 2013 bool IsExternal() const; 2014 2015 /** 2016 * Returns true if this value is a 32-bit signed integer. 2017 */ 2018 bool IsInt32() const; 2019 2020 /** 2021 * Returns true if this value is a 32-bit unsigned integer. 2022 */ 2023 bool IsUint32() const; 2024 2025 /** 2026 * Returns true if this value is a Date. 2027 */ 2028 bool IsDate() const; 2029 2030 /** 2031 * Returns true if this value is an Arguments object. 2032 */ 2033 bool IsArgumentsObject() const; 2034 2035 /** 2036 * Returns true if this value is a Boolean object. 2037 */ 2038 bool IsBooleanObject() const; 2039 2040 /** 2041 * Returns true if this value is a Number object. 2042 */ 2043 bool IsNumberObject() const; 2044 2045 /** 2046 * Returns true if this value is a String object. 2047 */ 2048 bool IsStringObject() const; 2049 2050 /** 2051 * Returns true if this value is a Symbol object. 2052 */ 2053 bool IsSymbolObject() const; 2054 2055 /** 2056 * Returns true if this value is a NativeError. 2057 */ 2058 bool IsNativeError() const; 2059 2060 /** 2061 * Returns true if this value is a RegExp. 2062 */ 2063 bool IsRegExp() const; 2064 2065 /** 2066 * Returns true if this value is an async function. 2067 */ 2068 bool IsAsyncFunction() const; 2069 2070 /** 2071 * Returns true if this value is a Generator function. 2072 */ 2073 bool IsGeneratorFunction() const; 2074 2075 /** 2076 * Returns true if this value is a Generator object (iterator). 2077 */ 2078 bool IsGeneratorObject() const; 2079 2080 /** 2081 * Returns true if this value is a Promise. 2082 */ 2083 bool IsPromise() const; 2084 2085 /** 2086 * Returns true if this value is a Map. 2087 */ 2088 bool IsMap() const; 2089 2090 /** 2091 * Returns true if this value is a Set. 2092 */ 2093 bool IsSet() const; 2094 2095 /** 2096 * Returns true if this value is a Map Iterator. 2097 */ 2098 bool IsMapIterator() const; 2099 2100 /** 2101 * Returns true if this value is a Set Iterator. 2102 */ 2103 bool IsSetIterator() const; 2104 2105 /** 2106 * Returns true if this value is a WeakMap. 2107 */ 2108 bool IsWeakMap() const; 2109 2110 /** 2111 * Returns true if this value is a WeakSet. 2112 */ 2113 bool IsWeakSet() const; 2114 2115 /** 2116 * Returns true if this value is an ArrayBuffer. 2117 */ 2118 bool IsArrayBuffer() const; 2119 2120 /** 2121 * Returns true if this value is an ArrayBufferView. 2122 */ 2123 bool IsArrayBufferView() const; 2124 2125 /** 2126 * Returns true if this value is one of TypedArrays. 2127 */ 2128 bool IsTypedArray() const; 2129 2130 /** 2131 * Returns true if this value is an Uint8Array. 2132 */ 2133 bool IsUint8Array() const; 2134 2135 /** 2136 * Returns true if this value is an Uint8ClampedArray. 2137 */ 2138 bool IsUint8ClampedArray() const; 2139 2140 /** 2141 * Returns true if this value is an Int8Array. 2142 */ 2143 bool IsInt8Array() const; 2144 2145 /** 2146 * Returns true if this value is an Uint16Array. 2147 */ 2148 bool IsUint16Array() const; 2149 2150 /** 2151 * Returns true if this value is an Int16Array. 2152 */ 2153 bool IsInt16Array() const; 2154 2155 /** 2156 * Returns true if this value is an Uint32Array. 2157 */ 2158 bool IsUint32Array() const; 2159 2160 /** 2161 * Returns true if this value is an Int32Array. 2162 */ 2163 bool IsInt32Array() const; 2164 2165 /** 2166 * Returns true if this value is a Float32Array. 2167 */ 2168 bool IsFloat32Array() const; 2169 2170 /** 2171 * Returns true if this value is a Float64Array. 2172 */ 2173 bool IsFloat64Array() const; 2174 2175 /** 2176 * Returns true if this value is a DataView. 2177 */ 2178 bool IsDataView() const; 2179 2180 /** 2181 * Returns true if this value is a SharedArrayBuffer. 2182 * This is an experimental feature. 2183 */ 2184 bool IsSharedArrayBuffer() const; 2185 2186 /** 2187 * Returns true if this value is a JavaScript Proxy. 2188 */ 2189 bool IsProxy() const; 2190 2191 bool IsWebAssemblyCompiledModule() const; 2192 2193 V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean( 2194 Local<Context> context) const; 2195 V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber( 2196 Local<Context> context) const; 2197 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString( 2198 Local<Context> context) const; 2199 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString( 2200 Local<Context> context) const; 2201 V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject( 2202 Local<Context> context) const; 2203 V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger( 2204 Local<Context> context) const; 2205 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32( 2206 Local<Context> context) const; 2207 V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const; 2208 2209 V8_DEPRECATE_SOON("Use maybe version", 2210 Local<Boolean> ToBoolean(Isolate* isolate) const); 2211 V8_DEPRECATE_SOON("Use maybe version", 2212 Local<Number> ToNumber(Isolate* isolate) const); 2213 V8_DEPRECATE_SOON("Use maybe version", 2214 Local<String> ToString(Isolate* isolate) const); 2215 V8_DEPRECATED("Use maybe version", 2216 Local<String> ToDetailString(Isolate* isolate) const); 2217 V8_DEPRECATE_SOON("Use maybe version", 2218 Local<Object> ToObject(Isolate* isolate) const); 2219 V8_DEPRECATE_SOON("Use maybe version", 2220 Local<Integer> ToInteger(Isolate* isolate) const); 2221 V8_DEPRECATED("Use maybe version", 2222 Local<Uint32> ToUint32(Isolate* isolate) const); 2223 V8_DEPRECATE_SOON("Use maybe version", 2224 Local<Int32> ToInt32(Isolate* isolate) const); 2225 2226 inline V8_DEPRECATE_SOON("Use maybe version", 2227 Local<Boolean> ToBoolean() const); 2228 inline V8_DEPRECATED("Use maybe version", Local<Number> ToNumber() const); 2229 inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const); 2230 inline V8_DEPRECATED("Use maybe version", 2231 Local<String> ToDetailString() const); 2232 inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const); 2233 inline V8_DEPRECATE_SOON("Use maybe version", 2234 Local<Integer> ToInteger() const); 2235 inline V8_DEPRECATED("Use maybe version", Local<Uint32> ToUint32() const); 2236 inline V8_DEPRECATED("Use maybe version", Local<Int32> ToInt32() const); 2237 2238 /** 2239 * Attempts to convert a string to an array index. 2240 * Returns an empty handle if the conversion fails. 2241 */ 2242 V8_DEPRECATED("Use maybe version", Local<Uint32> ToArrayIndex() const); 2243 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex( 2244 Local<Context> context) const; 2245 2246 V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const; 2247 V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const; 2248 V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue( 2249 Local<Context> context) const; 2250 V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value( 2251 Local<Context> context) const; 2252 V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const; 2253 2254 V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const); 2255 V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const); 2256 V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const); 2257 V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const); 2258 V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const); 2259 2260 /** JS == */ 2261 V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const); 2262 V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context, 2263 Local<Value> that) const; 2264 bool StrictEquals(Local<Value> that) const; 2265 bool SameValue(Local<Value> that) const; 2266 2267 template <class T> V8_INLINE static Value* Cast(T* value); 2268 2269 Local<String> TypeOf(Isolate*); 2270 2271 private: 2272 V8_INLINE bool QuickIsUndefined() const; 2273 V8_INLINE bool QuickIsNull() const; 2274 V8_INLINE bool QuickIsNullOrUndefined() const; 2275 V8_INLINE bool QuickIsString() const; 2276 bool FullIsUndefined() const; 2277 bool FullIsNull() const; 2278 bool FullIsString() const; 2279 }; 2280 2281 2282 /** 2283 * The superclass of primitive values. See ECMA-262 4.3.2. 2284 */ 2285 class V8_EXPORT Primitive : public Value { }; 2286 2287 2288 /** 2289 * A primitive boolean value (ECMA-262, 4.3.14). Either the true 2290 * or false value. 2291 */ 2292 class V8_EXPORT Boolean : public Primitive { 2293 public: 2294 bool Value() const; 2295 V8_INLINE static Boolean* Cast(v8::Value* obj); 2296 V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value); 2297 2298 private: 2299 static void CheckCast(v8::Value* obj); 2300 }; 2301 2302 2303 /** 2304 * A superclass for symbols and strings. 2305 */ 2306 class V8_EXPORT Name : public Primitive { 2307 public: 2308 /** 2309 * Returns the identity hash for this object. The current implementation 2310 * uses an inline property on the object to store the identity hash. 2311 * 2312 * The return value will never be 0. Also, it is not guaranteed to be 2313 * unique. 2314 */ 2315 int GetIdentityHash(); 2316 2317 V8_INLINE static Name* Cast(Value* obj); 2318 2319 private: 2320 static void CheckCast(Value* obj); 2321 }; 2322 2323 2324 enum class NewStringType { kNormal, kInternalized }; 2325 2326 2327 /** 2328 * A JavaScript string value (ECMA-262, 4.3.17). 2329 */ 2330 class V8_EXPORT String : public Name { 2331 public: 2332 static const int kMaxLength = (1 << 28) - 16; 2333 2334 enum Encoding { 2335 UNKNOWN_ENCODING = 0x1, 2336 TWO_BYTE_ENCODING = 0x0, 2337 ONE_BYTE_ENCODING = 0x8 2338 }; 2339 /** 2340 * Returns the number of characters in this string. 2341 */ 2342 int Length() const; 2343 2344 /** 2345 * Returns the number of bytes in the UTF-8 encoded 2346 * representation of this string. 2347 */ 2348 int Utf8Length() const; 2349 2350 /** 2351 * Returns whether this string is known to contain only one byte data. 2352 * Does not read the string. 2353 * False negatives are possible. 2354 */ 2355 bool IsOneByte() const; 2356 2357 /** 2358 * Returns whether this string contain only one byte data. 2359 * Will read the entire string in some cases. 2360 */ 2361 bool ContainsOnlyOneByte() const; 2362 2363 /** 2364 * Write the contents of the string to an external buffer. 2365 * If no arguments are given, expects the buffer to be large 2366 * enough to hold the entire string and NULL terminator. Copies 2367 * the contents of the string and the NULL terminator into the 2368 * buffer. 2369 * 2370 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop 2371 * before the end of the buffer. 2372 * 2373 * Copies up to length characters into the output buffer. 2374 * Only null-terminates if there is enough space in the buffer. 2375 * 2376 * \param buffer The buffer into which the string will be copied. 2377 * \param start The starting position within the string at which 2378 * copying begins. 2379 * \param length The number of characters to copy from the string. For 2380 * WriteUtf8 the number of bytes in the buffer. 2381 * \param nchars_ref The number of characters written, can be NULL. 2382 * \param options Various options that might affect performance of this or 2383 * subsequent operations. 2384 * \return The number of characters copied to the buffer excluding the null 2385 * terminator. For WriteUtf8: The number of bytes copied to the buffer 2386 * including the null terminator (if written). 2387 */ 2388 enum WriteOptions { 2389 NO_OPTIONS = 0, 2390 HINT_MANY_WRITES_EXPECTED = 1, 2391 NO_NULL_TERMINATION = 2, 2392 PRESERVE_ONE_BYTE_NULL = 4, 2393 // Used by WriteUtf8 to replace orphan surrogate code units with the 2394 // unicode replacement character. Needs to be set to guarantee valid UTF-8 2395 // output. 2396 REPLACE_INVALID_UTF8 = 8 2397 }; 2398 2399 // 16-bit character codes. 2400 int Write(uint16_t* buffer, 2401 int start = 0, 2402 int length = -1, 2403 int options = NO_OPTIONS) const; 2404 // One byte characters. 2405 int WriteOneByte(uint8_t* buffer, 2406 int start = 0, 2407 int length = -1, 2408 int options = NO_OPTIONS) const; 2409 // UTF-8 encoded characters. 2410 int WriteUtf8(char* buffer, 2411 int length = -1, 2412 int* nchars_ref = NULL, 2413 int options = NO_OPTIONS) const; 2414 2415 /** 2416 * A zero length string. 2417 */ 2418 V8_INLINE static Local<String> Empty(Isolate* isolate); 2419 2420 /** 2421 * Returns true if the string is external 2422 */ 2423 bool IsExternal() const; 2424 2425 /** 2426 * Returns true if the string is both external and one-byte. 2427 */ 2428 bool IsExternalOneByte() const; 2429 2430 class V8_EXPORT ExternalStringResourceBase { // NOLINT 2431 public: 2432 virtual ~ExternalStringResourceBase() {} 2433 2434 virtual bool IsCompressible() const { return false; } 2435 2436 protected: 2437 ExternalStringResourceBase() {} 2438 2439 /** 2440 * Internally V8 will call this Dispose method when the external string 2441 * resource is no longer needed. The default implementation will use the 2442 * delete operator. This method can be overridden in subclasses to 2443 * control how allocated external string resources are disposed. 2444 */ 2445 virtual void Dispose() { delete this; } 2446 2447 // Disallow copying and assigning. 2448 ExternalStringResourceBase(const ExternalStringResourceBase&) = delete; 2449 void operator=(const ExternalStringResourceBase&) = delete; 2450 2451 private: 2452 friend class internal::Heap; 2453 friend class v8::String; 2454 }; 2455 2456 /** 2457 * An ExternalStringResource is a wrapper around a two-byte string 2458 * buffer that resides outside V8's heap. Implement an 2459 * ExternalStringResource to manage the life cycle of the underlying 2460 * buffer. Note that the string data must be immutable. 2461 */ 2462 class V8_EXPORT ExternalStringResource 2463 : public ExternalStringResourceBase { 2464 public: 2465 /** 2466 * Override the destructor to manage the life cycle of the underlying 2467 * buffer. 2468 */ 2469 virtual ~ExternalStringResource() {} 2470 2471 /** 2472 * The string data from the underlying buffer. 2473 */ 2474 virtual const uint16_t* data() const = 0; 2475 2476 /** 2477 * The length of the string. That is, the number of two-byte characters. 2478 */ 2479 virtual size_t length() const = 0; 2480 2481 protected: 2482 ExternalStringResource() {} 2483 }; 2484 2485 /** 2486 * An ExternalOneByteStringResource is a wrapper around an one-byte 2487 * string buffer that resides outside V8's heap. Implement an 2488 * ExternalOneByteStringResource to manage the life cycle of the 2489 * underlying buffer. Note that the string data must be immutable 2490 * and that the data must be Latin-1 and not UTF-8, which would require 2491 * special treatment internally in the engine and do not allow efficient 2492 * indexing. Use String::New or convert to 16 bit data for non-Latin1. 2493 */ 2494 2495 class V8_EXPORT ExternalOneByteStringResource 2496 : public ExternalStringResourceBase { 2497 public: 2498 /** 2499 * Override the destructor to manage the life cycle of the underlying 2500 * buffer. 2501 */ 2502 virtual ~ExternalOneByteStringResource() {} 2503 /** The string data from the underlying buffer.*/ 2504 virtual const char* data() const = 0; 2505 /** The number of Latin-1 characters in the string.*/ 2506 virtual size_t length() const = 0; 2507 protected: 2508 ExternalOneByteStringResource() {} 2509 }; 2510 2511 /** 2512 * If the string is an external string, return the ExternalStringResourceBase 2513 * regardless of the encoding, otherwise return NULL. The encoding of the 2514 * string is returned in encoding_out. 2515 */ 2516 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase( 2517 Encoding* encoding_out) const; 2518 2519 /** 2520 * Get the ExternalStringResource for an external string. Returns 2521 * NULL if IsExternal() doesn't return true. 2522 */ 2523 V8_INLINE ExternalStringResource* GetExternalStringResource() const; 2524 2525 /** 2526 * Get the ExternalOneByteStringResource for an external one-byte string. 2527 * Returns NULL if IsExternalOneByte() doesn't return true. 2528 */ 2529 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const; 2530 2531 V8_INLINE static String* Cast(v8::Value* obj); 2532 2533 // TODO(dcarney): remove with deprecation of New functions. 2534 enum NewStringType { 2535 kNormalString = static_cast<int>(v8::NewStringType::kNormal), 2536 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized) 2537 }; 2538 2539 /** Allocates a new string from UTF-8 data.*/ 2540 static V8_DEPRECATE_SOON( 2541 "Use maybe version", 2542 Local<String> NewFromUtf8(Isolate* isolate, const char* data, 2543 NewStringType type = kNormalString, 2544 int length = -1)); 2545 2546 /** Allocates a new string from UTF-8 data. Only returns an empty value when 2547 * length > kMaxLength. **/ 2548 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8( 2549 Isolate* isolate, const char* data, v8::NewStringType type, 2550 int length = -1); 2551 2552 /** Allocates a new string from Latin-1 data.*/ 2553 static V8_DEPRECATED( 2554 "Use maybe version", 2555 Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data, 2556 NewStringType type = kNormalString, 2557 int length = -1)); 2558 2559 /** Allocates a new string from Latin-1 data. Only returns an empty value 2560 * when length > kMaxLength. **/ 2561 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte( 2562 Isolate* isolate, const uint8_t* data, v8::NewStringType type, 2563 int length = -1); 2564 2565 /** Allocates a new string from UTF-16 data.*/ 2566 static V8_DEPRECATE_SOON( 2567 "Use maybe version", 2568 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data, 2569 NewStringType type = kNormalString, 2570 int length = -1)); 2571 2572 /** Allocates a new string from UTF-16 data. Only returns an empty value when 2573 * length > kMaxLength. **/ 2574 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte( 2575 Isolate* isolate, const uint16_t* data, v8::NewStringType type, 2576 int length = -1); 2577 2578 /** 2579 * Creates a new string by concatenating the left and the right strings 2580 * passed in as parameters. 2581 */ 2582 static Local<String> Concat(Local<String> left, Local<String> right); 2583 2584 /** 2585 * Creates a new external string using the data defined in the given 2586 * resource. When the external string is no longer live on V8's heap the 2587 * resource will be disposed by calling its Dispose method. The caller of 2588 * this function should not otherwise delete or modify the resource. Neither 2589 * should the underlying buffer be deallocated or modified except through the 2590 * destructor of the external string resource. 2591 */ 2592 static V8_DEPRECATED("Use maybe version", 2593 Local<String> NewExternal( 2594 Isolate* isolate, ExternalStringResource* resource)); 2595 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte( 2596 Isolate* isolate, ExternalStringResource* resource); 2597 2598 /** 2599 * Associate an external string resource with this string by transforming it 2600 * in place so that existing references to this string in the JavaScript heap 2601 * will use the external string resource. The external string resource's 2602 * character contents need to be equivalent to this string. 2603 * Returns true if the string has been changed to be an external string. 2604 * The string is not modified if the operation fails. See NewExternal for 2605 * information on the lifetime of the resource. 2606 */ 2607 bool MakeExternal(ExternalStringResource* resource); 2608 2609 /** 2610 * Creates a new external string using the one-byte data defined in the given 2611 * resource. When the external string is no longer live on V8's heap the 2612 * resource will be disposed by calling its Dispose method. The caller of 2613 * this function should not otherwise delete or modify the resource. Neither 2614 * should the underlying buffer be deallocated or modified except through the 2615 * destructor of the external string resource. 2616 */ 2617 static V8_DEPRECATE_SOON( 2618 "Use maybe version", 2619 Local<String> NewExternal(Isolate* isolate, 2620 ExternalOneByteStringResource* resource)); 2621 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte( 2622 Isolate* isolate, ExternalOneByteStringResource* resource); 2623 2624 /** 2625 * Associate an external string resource with this string by transforming it 2626 * in place so that existing references to this string in the JavaScript heap 2627 * will use the external string resource. The external string resource's 2628 * character contents need to be equivalent to this string. 2629 * Returns true if the string has been changed to be an external string. 2630 * The string is not modified if the operation fails. See NewExternal for 2631 * information on the lifetime of the resource. 2632 */ 2633 bool MakeExternal(ExternalOneByteStringResource* resource); 2634 2635 /** 2636 * Returns true if this string can be made external. 2637 */ 2638 bool CanMakeExternal(); 2639 2640 /** 2641 * Converts an object to a UTF-8-encoded character array. Useful if 2642 * you want to print the object. If conversion to a string fails 2643 * (e.g. due to an exception in the toString() method of the object) 2644 * then the length() method returns 0 and the * operator returns 2645 * NULL. 2646 */ 2647 class V8_EXPORT Utf8Value { 2648 public: 2649 explicit Utf8Value(Local<v8::Value> obj); 2650 ~Utf8Value(); 2651 char* operator*() { return str_; } 2652 const char* operator*() const { return str_; } 2653 int length() const { return length_; } 2654 2655 // Disallow copying and assigning. 2656 Utf8Value(const Utf8Value&) = delete; 2657 void operator=(const Utf8Value&) = delete; 2658 2659 private: 2660 char* str_; 2661 int length_; 2662 }; 2663 2664 /** 2665 * Converts an object to a two-byte string. 2666 * If conversion to a string fails (eg. due to an exception in the toString() 2667 * method of the object) then the length() method returns 0 and the * operator 2668 * returns NULL. 2669 */ 2670 class V8_EXPORT Value { 2671 public: 2672 explicit Value(Local<v8::Value> obj); 2673 ~Value(); 2674 uint16_t* operator*() { return str_; } 2675 const uint16_t* operator*() const { return str_; } 2676 int length() const { return length_; } 2677 2678 // Disallow copying and assigning. 2679 Value(const Value&) = delete; 2680 void operator=(const Value&) = delete; 2681 2682 private: 2683 uint16_t* str_; 2684 int length_; 2685 }; 2686 2687 private: 2688 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v, 2689 Encoding encoding) const; 2690 void VerifyExternalStringResource(ExternalStringResource* val) const; 2691 static void CheckCast(v8::Value* obj); 2692 }; 2693 2694 2695 /** 2696 * A JavaScript symbol (ECMA-262 edition 6) 2697 */ 2698 class V8_EXPORT Symbol : public Name { 2699 public: 2700 // Returns the print name string of the symbol, or undefined if none. 2701 Local<Value> Name() const; 2702 2703 // Create a symbol. If name is not empty, it will be used as the description. 2704 static Local<Symbol> New(Isolate* isolate, 2705 Local<String> name = Local<String>()); 2706 2707 // Access global symbol registry. 2708 // Note that symbols created this way are never collected, so 2709 // they should only be used for statically fixed properties. 2710 // Also, there is only one global name space for the names used as keys. 2711 // To minimize the potential for clashes, use qualified names as keys. 2712 static Local<Symbol> For(Isolate *isolate, Local<String> name); 2713 2714 // Retrieve a global symbol. Similar to |For|, but using a separate 2715 // registry that is not accessible by (and cannot clash with) JavaScript code. 2716 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name); 2717 2718 // Well-known symbols 2719 static Local<Symbol> GetIterator(Isolate* isolate); 2720 static Local<Symbol> GetUnscopables(Isolate* isolate); 2721 static Local<Symbol> GetToPrimitive(Isolate* isolate); 2722 static Local<Symbol> GetToStringTag(Isolate* isolate); 2723 static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate); 2724 2725 V8_INLINE static Symbol* Cast(Value* obj); 2726 2727 private: 2728 Symbol(); 2729 static void CheckCast(Value* obj); 2730 }; 2731 2732 2733 /** 2734 * A private symbol 2735 * 2736 * This is an experimental feature. Use at your own risk. 2737 */ 2738 class V8_EXPORT Private : public Data { 2739 public: 2740 // Returns the print name string of the private symbol, or undefined if none. 2741 Local<Value> Name() const; 2742 2743 // Create a private symbol. If name is not empty, it will be the description. 2744 static Local<Private> New(Isolate* isolate, 2745 Local<String> name = Local<String>()); 2746 2747 // Retrieve a global private symbol. If a symbol with this name has not 2748 // been retrieved in the same isolate before, it is created. 2749 // Note that private symbols created this way are never collected, so 2750 // they should only be used for statically fixed properties. 2751 // Also, there is only one global name space for the names used as keys. 2752 // To minimize the potential for clashes, use qualified names as keys, 2753 // e.g., "Class#property". 2754 static Local<Private> ForApi(Isolate* isolate, Local<String> name); 2755 2756 private: 2757 Private(); 2758 }; 2759 2760 2761 /** 2762 * A JavaScript number value (ECMA-262, 4.3.20) 2763 */ 2764 class V8_EXPORT Number : public Primitive { 2765 public: 2766 double Value() const; 2767 static Local<Number> New(Isolate* isolate, double value); 2768 V8_INLINE static Number* Cast(v8::Value* obj); 2769 private: 2770 Number(); 2771 static void CheckCast(v8::Value* obj); 2772 }; 2773 2774 2775 /** 2776 * A JavaScript value representing a signed integer. 2777 */ 2778 class V8_EXPORT Integer : public Number { 2779 public: 2780 static Local<Integer> New(Isolate* isolate, int32_t value); 2781 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value); 2782 int64_t Value() const; 2783 V8_INLINE static Integer* Cast(v8::Value* obj); 2784 private: 2785 Integer(); 2786 static void CheckCast(v8::Value* obj); 2787 }; 2788 2789 2790 /** 2791 * A JavaScript value representing a 32-bit signed integer. 2792 */ 2793 class V8_EXPORT Int32 : public Integer { 2794 public: 2795 int32_t Value() const; 2796 V8_INLINE static Int32* Cast(v8::Value* obj); 2797 2798 private: 2799 Int32(); 2800 static void CheckCast(v8::Value* obj); 2801 }; 2802 2803 2804 /** 2805 * A JavaScript value representing a 32-bit unsigned integer. 2806 */ 2807 class V8_EXPORT Uint32 : public Integer { 2808 public: 2809 uint32_t Value() const; 2810 V8_INLINE static Uint32* Cast(v8::Value* obj); 2811 2812 private: 2813 Uint32(); 2814 static void CheckCast(v8::Value* obj); 2815 }; 2816 2817 /** 2818 * PropertyAttribute. 2819 */ 2820 enum PropertyAttribute { 2821 /** None. **/ 2822 None = 0, 2823 /** ReadOnly, i.e., not writable. **/ 2824 ReadOnly = 1 << 0, 2825 /** DontEnum, i.e., not enumerable. **/ 2826 DontEnum = 1 << 1, 2827 /** DontDelete, i.e., not configurable. **/ 2828 DontDelete = 1 << 2 2829 }; 2830 2831 /** 2832 * Accessor[Getter|Setter] are used as callback functions when 2833 * setting|getting a particular property. See Object and ObjectTemplate's 2834 * method SetAccessor. 2835 */ 2836 typedef void (*AccessorGetterCallback)( 2837 Local<String> property, 2838 const PropertyCallbackInfo<Value>& info); 2839 typedef void (*AccessorNameGetterCallback)( 2840 Local<Name> property, 2841 const PropertyCallbackInfo<Value>& info); 2842 2843 2844 typedef void (*AccessorSetterCallback)( 2845 Local<String> property, 2846 Local<Value> value, 2847 const PropertyCallbackInfo<void>& info); 2848 typedef void (*AccessorNameSetterCallback)( 2849 Local<Name> property, 2850 Local<Value> value, 2851 const PropertyCallbackInfo<void>& info); 2852 2853 2854 /** 2855 * Access control specifications. 2856 * 2857 * Some accessors should be accessible across contexts. These 2858 * accessors have an explicit access control parameter which specifies 2859 * the kind of cross-context access that should be allowed. 2860 * 2861 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused. 2862 */ 2863 enum AccessControl { 2864 DEFAULT = 0, 2865 ALL_CAN_READ = 1, 2866 ALL_CAN_WRITE = 1 << 1, 2867 PROHIBITS_OVERWRITING = 1 << 2 2868 }; 2869 2870 /** 2871 * Property filter bits. They can be or'ed to build a composite filter. 2872 */ 2873 enum PropertyFilter { 2874 ALL_PROPERTIES = 0, 2875 ONLY_WRITABLE = 1, 2876 ONLY_ENUMERABLE = 2, 2877 ONLY_CONFIGURABLE = 4, 2878 SKIP_STRINGS = 8, 2879 SKIP_SYMBOLS = 16 2880 }; 2881 2882 /** 2883 * Keys/Properties filter enums: 2884 * 2885 * KeyCollectionMode limits the range of collected properties. kOwnOnly limits 2886 * the collected properties to the given Object only. kIncludesPrototypes will 2887 * include all keys of the objects's prototype chain as well. 2888 */ 2889 enum class KeyCollectionMode { kOwnOnly, kIncludePrototypes }; 2890 2891 /** 2892 * kIncludesIndices allows for integer indices to be collected, while 2893 * kSkipIndices will exclude integer indicies from being collected. 2894 */ 2895 enum class IndexFilter { kIncludeIndices, kSkipIndices }; 2896 2897 /** 2898 * Integrity level for objects. 2899 */ 2900 enum class IntegrityLevel { kFrozen, kSealed }; 2901 2902 /** 2903 * A JavaScript object (ECMA-262, 4.3.3) 2904 */ 2905 class V8_EXPORT Object : public Value { 2906 public: 2907 V8_DEPRECATE_SOON("Use maybe version", 2908 bool Set(Local<Value> key, Local<Value> value)); 2909 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, 2910 Local<Value> key, Local<Value> value); 2911 2912 V8_DEPRECATE_SOON("Use maybe version", 2913 bool Set(uint32_t index, Local<Value> value)); 2914 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index, 2915 Local<Value> value); 2916 2917 // Implements CreateDataProperty (ECMA-262, 7.3.4). 2918 // 2919 // Defines a configurable, writable, enumerable property with the given value 2920 // on the object unless the property already exists and is not configurable 2921 // or the object is not extensible. 2922 // 2923 // Returns true on success. 2924 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context, 2925 Local<Name> key, 2926 Local<Value> value); 2927 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context, 2928 uint32_t index, 2929 Local<Value> value); 2930 2931 // Implements DefineOwnProperty. 2932 // 2933 // In general, CreateDataProperty will be faster, however, does not allow 2934 // for specifying attributes. 2935 // 2936 // Returns true on success. 2937 V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty( 2938 Local<Context> context, Local<Name> key, Local<Value> value, 2939 PropertyAttribute attributes = None); 2940 2941 // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4. 2942 // 2943 // The defineProperty function is used to add an own property or 2944 // update the attributes of an existing own property of an object. 2945 // 2946 // Both data and accessor descriptors can be used. 2947 // 2948 // In general, CreateDataProperty is faster, however, does not allow 2949 // for specifying attributes or an accessor descriptor. 2950 // 2951 // The PropertyDescriptor can change when redefining a property. 2952 // 2953 // Returns true on success. 2954 V8_WARN_UNUSED_RESULT Maybe<bool> DefineProperty( 2955 Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor); 2956 2957 // Sets an own property on this object bypassing interceptors and 2958 // overriding accessors or read-only properties. 2959 // 2960 // Note that if the object has an interceptor the property will be set 2961 // locally, but since the interceptor takes precedence the local property 2962 // will only be returned if the interceptor doesn't return a value. 2963 // 2964 // Note also that this only works for named properties. 2965 V8_DEPRECATED("Use CreateDataProperty / DefineOwnProperty", 2966 bool ForceSet(Local<Value> key, Local<Value> value, 2967 PropertyAttribute attribs = None)); 2968 V8_DEPRECATE_SOON("Use CreateDataProperty / DefineOwnProperty", 2969 Maybe<bool> ForceSet(Local<Context> context, 2970 Local<Value> key, Local<Value> value, 2971 PropertyAttribute attribs = None)); 2972 2973 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key)); 2974 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context, 2975 Local<Value> key); 2976 2977 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index)); 2978 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context, 2979 uint32_t index); 2980 2981 /** 2982 * Gets the property attributes of a property which can be None or 2983 * any combination of ReadOnly, DontEnum and DontDelete. Returns 2984 * None when the property doesn't exist. 2985 */ 2986 V8_DEPRECATED("Use maybe version", 2987 PropertyAttribute GetPropertyAttributes(Local<Value> key)); 2988 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes( 2989 Local<Context> context, Local<Value> key); 2990 2991 /** 2992 * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3. 2993 */ 2994 V8_DEPRECATED("Use maybe version", 2995 Local<Value> GetOwnPropertyDescriptor(Local<String> key)); 2996 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor( 2997 Local<Context> context, Local<String> key); 2998 2999 V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key)); 3000 /** 3001 * Object::Has() calls the abstract operation HasProperty(O, P) described 3002 * in ECMA-262, 7.3.10. Has() returns 3003 * true, if the object has the property, either own or on the prototype chain. 3004 * Interceptors, i.e., PropertyQueryCallbacks, are called if present. 3005 * 3006 * Has() has the same side effects as JavaScript's `variable in object`. 3007 * For example, calling Has() on a revoked proxy will throw an exception. 3008 * 3009 * \note Has() converts the key to a name, which possibly calls back into 3010 * JavaScript. 3011 * 3012 * See also v8::Object::HasOwnProperty() and 3013 * v8::Object::HasRealNamedProperty(). 3014 */ 3015 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, 3016 Local<Value> key); 3017 3018 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key)); 3019 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT 3020 Maybe<bool> Delete(Local<Context> context, Local<Value> key); 3021 3022 V8_DEPRECATED("Use maybe version", bool Has(uint32_t index)); 3023 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index); 3024 3025 V8_DEPRECATED("Use maybe version", bool Delete(uint32_t index)); 3026 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT 3027 Maybe<bool> Delete(Local<Context> context, uint32_t index); 3028 3029 V8_DEPRECATED("Use maybe version", 3030 bool SetAccessor(Local<String> name, 3031 AccessorGetterCallback getter, 3032 AccessorSetterCallback setter = 0, 3033 Local<Value> data = Local<Value>(), 3034 AccessControl settings = DEFAULT, 3035 PropertyAttribute attribute = None)); 3036 V8_DEPRECATED("Use maybe version", 3037 bool SetAccessor(Local<Name> name, 3038 AccessorNameGetterCallback getter, 3039 AccessorNameSetterCallback setter = 0, 3040 Local<Value> data = Local<Value>(), 3041 AccessControl settings = DEFAULT, 3042 PropertyAttribute attribute = None)); 3043 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT 3044 Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name, 3045 AccessorNameGetterCallback getter, 3046 AccessorNameSetterCallback setter = 0, 3047 MaybeLocal<Value> data = MaybeLocal<Value>(), 3048 AccessControl settings = DEFAULT, 3049 PropertyAttribute attribute = None); 3050 3051 void SetAccessorProperty(Local<Name> name, Local<Function> getter, 3052 Local<Function> setter = Local<Function>(), 3053 PropertyAttribute attribute = None, 3054 AccessControl settings = DEFAULT); 3055 3056 /** 3057 * Functionality for private properties. 3058 * This is an experimental feature, use at your own risk. 3059 * Note: Private properties are not inherited. Do not rely on this, since it 3060 * may change. 3061 */ 3062 Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key); 3063 Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key, 3064 Local<Value> value); 3065 Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key); 3066 MaybeLocal<Value> GetPrivate(Local<Context> context, Local<Private> key); 3067 3068 /** 3069 * Returns an array containing the names of the enumerable properties 3070 * of this object, including properties from prototype objects. The 3071 * array returned by this method contains the same values as would 3072 * be enumerated by a for-in statement over this object. 3073 */ 3074 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames()); 3075 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames( 3076 Local<Context> context); 3077 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames( 3078 Local<Context> context, KeyCollectionMode mode, 3079 PropertyFilter property_filter, IndexFilter index_filter); 3080 3081 /** 3082 * This function has the same functionality as GetPropertyNames but 3083 * the returned array doesn't contain the names of properties from 3084 * prototype objects. 3085 */ 3086 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames()); 3087 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames( 3088 Local<Context> context); 3089 3090 /** 3091 * Returns an array containing the names of the filtered properties 3092 * of this object, including properties from prototype objects. The 3093 * array returned by this method contains the same values as would 3094 * be enumerated by a for-in statement over this object. 3095 */ 3096 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames( 3097 Local<Context> context, PropertyFilter filter); 3098 3099 /** 3100 * Get the prototype object. This does not skip objects marked to 3101 * be skipped by __proto__ and it does not consult the security 3102 * handler. 3103 */ 3104 Local<Value> GetPrototype(); 3105 3106 /** 3107 * Set the prototype object. This does not skip objects marked to 3108 * be skipped by __proto__ and it does not consult the security 3109 * handler. 3110 */ 3111 V8_DEPRECATED("Use maybe version", bool SetPrototype(Local<Value> prototype)); 3112 V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context, 3113 Local<Value> prototype); 3114 3115 /** 3116 * Finds an instance of the given function template in the prototype 3117 * chain. 3118 */ 3119 Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl); 3120 3121 /** 3122 * Call builtin Object.prototype.toString on this object. 3123 * This is different from Value::ToString() that may call 3124 * user-defined toString function. This one does not. 3125 */ 3126 V8_DEPRECATED("Use maybe version", Local<String> ObjectProtoToString()); 3127 V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString( 3128 Local<Context> context); 3129 3130 /** 3131 * Returns the name of the function invoked as a constructor for this object. 3132 */ 3133 Local<String> GetConstructorName(); 3134 3135 /** 3136 * Sets the integrity level of the object. 3137 */ 3138 Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level); 3139 3140 /** Gets the number of internal fields for this Object. */ 3141 int InternalFieldCount(); 3142 3143 /** Same as above, but works for Persistents */ 3144 V8_INLINE static int InternalFieldCount( 3145 const PersistentBase<Object>& object) { 3146 return object.val_->InternalFieldCount(); 3147 } 3148 3149 /** Gets the value from an internal field. */ 3150 V8_INLINE Local<Value> GetInternalField(int index); 3151 3152 /** Sets the value in an internal field. */ 3153 void SetInternalField(int index, Local<Value> value); 3154 3155 /** 3156 * Gets a 2-byte-aligned native pointer from an internal field. This field 3157 * must have been set by SetAlignedPointerInInternalField, everything else 3158 * leads to undefined behavior. 3159 */ 3160 V8_INLINE void* GetAlignedPointerFromInternalField(int index); 3161 3162 /** Same as above, but works for Persistents */ 3163 V8_INLINE static void* GetAlignedPointerFromInternalField( 3164 const PersistentBase<Object>& object, int index) { 3165 return object.val_->GetAlignedPointerFromInternalField(index); 3166 } 3167 3168 /** 3169 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such 3170 * a field, GetAlignedPointerFromInternalField must be used, everything else 3171 * leads to undefined behavior. 3172 */ 3173 void SetAlignedPointerInInternalField(int index, void* value); 3174 void SetAlignedPointerInInternalFields(int argc, int indices[], 3175 void* values[]); 3176 3177 // Testers for local properties. 3178 V8_DEPRECATED("Use maybe version", bool HasOwnProperty(Local<String> key)); 3179 3180 /** 3181 * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty(). 3182 * 3183 * See also v8::Object::Has() and v8::Object::HasRealNamedProperty(). 3184 */ 3185 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context, 3186 Local<Name> key); 3187 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context, 3188 uint32_t index); 3189 V8_DEPRECATE_SOON("Use maybe version", 3190 bool HasRealNamedProperty(Local<String> key)); 3191 /** 3192 * Use HasRealNamedProperty() if you want to check if an object has an own 3193 * property without causing side effects, i.e., without calling interceptors. 3194 * 3195 * This function is similar to v8::Object::HasOwnProperty(), but it does not 3196 * call interceptors. 3197 * 3198 * \note Consider using non-masking interceptors, i.e., the interceptors are 3199 * not called if the receiver has the real named property. See 3200 * `v8::PropertyHandlerFlags::kNonMasking`. 3201 * 3202 * See also v8::Object::Has(). 3203 */ 3204 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context, 3205 Local<Name> key); 3206 V8_DEPRECATE_SOON("Use maybe version", 3207 bool HasRealIndexedProperty(uint32_t index)); 3208 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty( 3209 Local<Context> context, uint32_t index); 3210 V8_DEPRECATE_SOON("Use maybe version", 3211 bool HasRealNamedCallbackProperty(Local<String> key)); 3212 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty( 3213 Local<Context> context, Local<Name> key); 3214 3215 /** 3216 * If result.IsEmpty() no real property was located in the prototype chain. 3217 * This means interceptors in the prototype chain are not called. 3218 */ 3219 V8_DEPRECATED( 3220 "Use maybe version", 3221 Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key)); 3222 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain( 3223 Local<Context> context, Local<Name> key); 3224 3225 /** 3226 * Gets the property attributes of a real property in the prototype chain, 3227 * which can be None or any combination of ReadOnly, DontEnum and DontDelete. 3228 * Interceptors in the prototype chain are not called. 3229 */ 3230 V8_DEPRECATED( 3231 "Use maybe version", 3232 Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain( 3233 Local<String> key)); 3234 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> 3235 GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context, 3236 Local<Name> key); 3237 3238 /** 3239 * If result.IsEmpty() no real property was located on the object or 3240 * in the prototype chain. 3241 * This means interceptors in the prototype chain are not called. 3242 */ 3243 V8_DEPRECATED("Use maybe version", 3244 Local<Value> GetRealNamedProperty(Local<String> key)); 3245 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty( 3246 Local<Context> context, Local<Name> key); 3247 3248 /** 3249 * Gets the property attributes of a real property which can be 3250 * None or any combination of ReadOnly, DontEnum and DontDelete. 3251 * Interceptors in the prototype chain are not called. 3252 */ 3253 V8_DEPRECATED("Use maybe version", 3254 Maybe<PropertyAttribute> GetRealNamedPropertyAttributes( 3255 Local<String> key)); 3256 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes( 3257 Local<Context> context, Local<Name> key); 3258 3259 /** Tests for a named lookup interceptor.*/ 3260 bool HasNamedLookupInterceptor(); 3261 3262 /** Tests for an index lookup interceptor.*/ 3263 bool HasIndexedLookupInterceptor(); 3264 3265 /** 3266 * Returns the identity hash for this object. The current implementation 3267 * uses a hidden property on the object to store the identity hash. 3268 * 3269 * The return value will never be 0. Also, it is not guaranteed to be 3270 * unique. 3271 */ 3272 int GetIdentityHash(); 3273 3274 /** 3275 * Clone this object with a fast but shallow copy. Values will point 3276 * to the same values as the original object. 3277 */ 3278 // TODO(dcarney): take an isolate and optionally bail out? 3279 Local<Object> Clone(); 3280 3281 /** 3282 * Returns the context in which the object was created. 3283 */ 3284 Local<Context> CreationContext(); 3285 3286 /** Same as above, but works for Persistents */ 3287 V8_INLINE static Local<Context> CreationContext( 3288 const PersistentBase<Object>& object) { 3289 return object.val_->CreationContext(); 3290 } 3291 3292 /** 3293 * Checks whether a callback is set by the 3294 * ObjectTemplate::SetCallAsFunctionHandler method. 3295 * When an Object is callable this method returns true. 3296 */ 3297 bool IsCallable(); 3298 3299 /** 3300 * True if this object is a constructor. 3301 */ 3302 bool IsConstructor(); 3303 3304 /** 3305 * Call an Object as a function if a callback is set by the 3306 * ObjectTemplate::SetCallAsFunctionHandler method. 3307 */ 3308 V8_DEPRECATED("Use maybe version", 3309 Local<Value> CallAsFunction(Local<Value> recv, int argc, 3310 Local<Value> argv[])); 3311 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context, 3312 Local<Value> recv, 3313 int argc, 3314 Local<Value> argv[]); 3315 3316 /** 3317 * Call an Object as a constructor if a callback is set by the 3318 * ObjectTemplate::SetCallAsFunctionHandler method. 3319 * Note: This method behaves like the Function::NewInstance method. 3320 */ 3321 V8_DEPRECATED("Use maybe version", 3322 Local<Value> CallAsConstructor(int argc, Local<Value> argv[])); 3323 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor( 3324 Local<Context> context, int argc, Local<Value> argv[]); 3325 3326 /** 3327 * Return the isolate to which the Object belongs to. 3328 */ 3329 V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate()); 3330 3331 static Local<Object> New(Isolate* isolate); 3332 3333 V8_INLINE static Object* Cast(Value* obj); 3334 3335 private: 3336 Object(); 3337 static void CheckCast(Value* obj); 3338 Local<Value> SlowGetInternalField(int index); 3339 void* SlowGetAlignedPointerFromInternalField(int index); 3340 }; 3341 3342 3343 /** 3344 * An instance of the built-in array constructor (ECMA-262, 15.4.2). 3345 */ 3346 class V8_EXPORT Array : public Object { 3347 public: 3348 uint32_t Length() const; 3349 3350 /** 3351 * Clones an element at index |index|. Returns an empty 3352 * handle if cloning fails (for any reason). 3353 */ 3354 V8_DEPRECATED("Cloning is not supported.", 3355 Local<Object> CloneElementAt(uint32_t index)); 3356 V8_DEPRECATED("Cloning is not supported.", 3357 MaybeLocal<Object> CloneElementAt(Local<Context> context, 3358 uint32_t index)); 3359 3360 /** 3361 * Creates a JavaScript array with the given length. If the length 3362 * is negative the returned array will have length 0. 3363 */ 3364 static Local<Array> New(Isolate* isolate, int length = 0); 3365 3366 V8_INLINE static Array* Cast(Value* obj); 3367 private: 3368 Array(); 3369 static void CheckCast(Value* obj); 3370 }; 3371 3372 3373 /** 3374 * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1). 3375 */ 3376 class V8_EXPORT Map : public Object { 3377 public: 3378 size_t Size() const; 3379 void Clear(); 3380 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context, 3381 Local<Value> key); 3382 V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context, 3383 Local<Value> key, 3384 Local<Value> value); 3385 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, 3386 Local<Value> key); 3387 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context, 3388 Local<Value> key); 3389 3390 /** 3391 * Returns an array of length Size() * 2, where index N is the Nth key and 3392 * index N + 1 is the Nth value. 3393 */ 3394 Local<Array> AsArray() const; 3395 3396 /** 3397 * Creates a new empty Map. 3398 */ 3399 static Local<Map> New(Isolate* isolate); 3400 3401 V8_INLINE static Map* Cast(Value* obj); 3402 3403 private: 3404 Map(); 3405 static void CheckCast(Value* obj); 3406 }; 3407 3408 3409 /** 3410 * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1). 3411 */ 3412 class V8_EXPORT Set : public Object { 3413 public: 3414 size_t Size() const; 3415 void Clear(); 3416 V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context, 3417 Local<Value> key); 3418 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, 3419 Local<Value> key); 3420 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context, 3421 Local<Value> key); 3422 3423 /** 3424 * Returns an array of the keys in this Set. 3425 */ 3426 Local<Array> AsArray() const; 3427 3428 /** 3429 * Creates a new empty Set. 3430 */ 3431 static Local<Set> New(Isolate* isolate); 3432 3433 V8_INLINE static Set* Cast(Value* obj); 3434 3435 private: 3436 Set(); 3437 static void CheckCast(Value* obj); 3438 }; 3439 3440 3441 template<typename T> 3442 class ReturnValue { 3443 public: 3444 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that) 3445 : value_(that.value_) { 3446 TYPE_CHECK(T, S); 3447 } 3448 // Local setters 3449 template <typename S> 3450 V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead", 3451 void Set(const Persistent<S>& handle)); 3452 template <typename S> 3453 V8_INLINE void Set(const Global<S>& handle); 3454 template <typename S> 3455 V8_INLINE void Set(const Local<S> handle); 3456 // Fast primitive setters 3457 V8_INLINE void Set(bool value); 3458 V8_INLINE void Set(double i); 3459 V8_INLINE void Set(int32_t i); 3460 V8_INLINE void Set(uint32_t i); 3461 // Fast JS primitive setters 3462 V8_INLINE void SetNull(); 3463 V8_INLINE void SetUndefined(); 3464 V8_INLINE void SetEmptyString(); 3465 // Convenience getter for Isolate 3466 V8_INLINE Isolate* GetIsolate() const; 3467 3468 // Pointer setter: Uncompilable to prevent inadvertent misuse. 3469 template <typename S> 3470 V8_INLINE void Set(S* whatever); 3471 3472 // Getter. Creates a new Local<> so it comes with a certain performance 3473 // hit. If the ReturnValue was not yet set, this will return the undefined 3474 // value. 3475 V8_INLINE Local<Value> Get() const; 3476 3477 private: 3478 template<class F> friend class ReturnValue; 3479 template<class F> friend class FunctionCallbackInfo; 3480 template<class F> friend class PropertyCallbackInfo; 3481 template <class F, class G, class H> 3482 friend class PersistentValueMapBase; 3483 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; } 3484 V8_INLINE internal::Object* GetDefaultValue(); 3485 V8_INLINE explicit ReturnValue(internal::Object** slot); 3486 internal::Object** value_; 3487 }; 3488 3489 3490 /** 3491 * The argument information given to function call callbacks. This 3492 * class provides access to information about the context of the call, 3493 * including the receiver, the number and values of arguments, and 3494 * the holder of the function. 3495 */ 3496 template<typename T> 3497 class FunctionCallbackInfo { 3498 public: 3499 V8_INLINE int Length() const; 3500 V8_INLINE Local<Value> operator[](int i) const; 3501 V8_INLINE V8_DEPRECATED("Use Data() to explicitly pass Callee instead", 3502 Local<Function> Callee() const); 3503 V8_INLINE Local<Object> This() const; 3504 V8_INLINE Local<Object> Holder() const; 3505 V8_INLINE Local<Value> NewTarget() const; 3506 V8_INLINE bool IsConstructCall() const; 3507 V8_INLINE Local<Value> Data() const; 3508 V8_INLINE Isolate* GetIsolate() const; 3509 V8_INLINE ReturnValue<T> GetReturnValue() const; 3510 // This shouldn't be public, but the arm compiler needs it. 3511 static const int kArgsLength = 8; 3512 3513 protected: 3514 friend class internal::FunctionCallbackArguments; 3515 friend class internal::CustomArguments<FunctionCallbackInfo>; 3516 static const int kHolderIndex = 0; 3517 static const int kIsolateIndex = 1; 3518 static const int kReturnValueDefaultValueIndex = 2; 3519 static const int kReturnValueIndex = 3; 3520 static const int kDataIndex = 4; 3521 static const int kCalleeIndex = 5; 3522 static const int kContextSaveIndex = 6; 3523 static const int kNewTargetIndex = 7; 3524 3525 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args, 3526 internal::Object** values, int length); 3527 internal::Object** implicit_args_; 3528 internal::Object** values_; 3529 int length_; 3530 }; 3531 3532 3533 /** 3534 * The information passed to a property callback about the context 3535 * of the property access. 3536 */ 3537 template<typename T> 3538 class PropertyCallbackInfo { 3539 public: 3540 /** 3541 * \return The isolate of the property access. 3542 */ 3543 V8_INLINE Isolate* GetIsolate() const; 3544 3545 /** 3546 * \return The data set in the configuration, i.e., in 3547 * `NamedPropertyHandlerConfiguration` or 3548 * `IndexedPropertyHandlerConfiguration.` 3549 */ 3550 V8_INLINE Local<Value> Data() const; 3551 3552 /** 3553 * \return The receiver. In many cases, this is the object on which the 3554 * property access was intercepted. When using 3555 * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the 3556 * object passed in as receiver or thisArg. 3557 * 3558 * \code 3559 * void GetterCallback(Local<Name> name, 3560 * const v8::PropertyCallbackInfo<v8::Value>& info) { 3561 * auto context = info.GetIsolate()->GetCurrentContext(); 3562 * 3563 * v8::Local<v8::Value> a_this = 3564 * info.This() 3565 * ->GetRealNamedProperty(context, v8_str("a")) 3566 * .ToLocalChecked(); 3567 * v8::Local<v8::Value> a_holder = 3568 * info.Holder() 3569 * ->GetRealNamedProperty(context, v8_str("a")) 3570 * .ToLocalChecked(); 3571 * 3572 * CHECK(v8_str("r")->Equals(context, a_this).FromJust()); 3573 * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust()); 3574 * 3575 * info.GetReturnValue().Set(name); 3576 * } 3577 * 3578 * v8::Local<v8::FunctionTemplate> templ = 3579 * v8::FunctionTemplate::New(isolate); 3580 * templ->InstanceTemplate()->SetHandler( 3581 * v8::NamedPropertyHandlerConfiguration(GetterCallback)); 3582 * LocalContext env; 3583 * env->Global() 3584 * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local()) 3585 * .ToLocalChecked() 3586 * ->NewInstance(env.local()) 3587 * .ToLocalChecked()) 3588 * .FromJust(); 3589 * 3590 * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)"); 3591 * \endcode 3592 */ 3593 V8_INLINE Local<Object> This() const; 3594 3595 /** 3596 * \return The object in the prototype chain of the receiver that has the 3597 * interceptor. Suppose you have `x` and its prototype is `y`, and `y` 3598 * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`. 3599 * The Holder() could be a hidden object (the global object, rather 3600 * than the global proxy). 3601 * 3602 * \note For security reasons, do not pass the object back into the runtime. 3603 */ 3604 V8_INLINE Local<Object> Holder() const; 3605 3606 /** 3607 * \return The return value of the callback. 3608 * Can be changed by calling Set(). 3609 * \code 3610 * info.GetReturnValue().Set(...) 3611 * \endcode 3612 * 3613 */ 3614 V8_INLINE ReturnValue<T> GetReturnValue() const; 3615 3616 /** 3617 * \return True if the intercepted function should throw if an error occurs. 3618 * Usually, `true` corresponds to `'use strict'`. 3619 * 3620 * \note Always `false` when intercepting `Reflect.set()` 3621 * independent of the language mode. 3622 */ 3623 V8_INLINE bool ShouldThrowOnError() const; 3624 3625 // This shouldn't be public, but the arm compiler needs it. 3626 static const int kArgsLength = 7; 3627 3628 protected: 3629 friend class MacroAssembler; 3630 friend class internal::PropertyCallbackArguments; 3631 friend class internal::CustomArguments<PropertyCallbackInfo>; 3632 static const int kShouldThrowOnErrorIndex = 0; 3633 static const int kHolderIndex = 1; 3634 static const int kIsolateIndex = 2; 3635 static const int kReturnValueDefaultValueIndex = 3; 3636 static const int kReturnValueIndex = 4; 3637 static const int kDataIndex = 5; 3638 static const int kThisIndex = 6; 3639 3640 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {} 3641 internal::Object** args_; 3642 }; 3643 3644 3645 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info); 3646 3647 enum class ConstructorBehavior { kThrow, kAllow }; 3648 3649 /** 3650 * A JavaScript function object (ECMA-262, 15.3). 3651 */ 3652 class V8_EXPORT Function : public Object { 3653 public: 3654 /** 3655 * Create a function in the current execution context 3656 * for a given FunctionCallback. 3657 */ 3658 static MaybeLocal<Function> New( 3659 Local<Context> context, FunctionCallback callback, 3660 Local<Value> data = Local<Value>(), int length = 0, 3661 ConstructorBehavior behavior = ConstructorBehavior::kAllow); 3662 static V8_DEPRECATE_SOON( 3663 "Use maybe version", 3664 Local<Function> New(Isolate* isolate, FunctionCallback callback, 3665 Local<Value> data = Local<Value>(), int length = 0)); 3666 3667 V8_DEPRECATED("Use maybe version", 3668 Local<Object> NewInstance(int argc, Local<Value> argv[]) const); 3669 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance( 3670 Local<Context> context, int argc, Local<Value> argv[]) const; 3671 3672 V8_DEPRECATED("Use maybe version", Local<Object> NewInstance() const); 3673 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance( 3674 Local<Context> context) const { 3675 return NewInstance(context, 0, nullptr); 3676 } 3677 3678 V8_DEPRECATE_SOON("Use maybe version", 3679 Local<Value> Call(Local<Value> recv, int argc, 3680 Local<Value> argv[])); 3681 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context, 3682 Local<Value> recv, int argc, 3683 Local<Value> argv[]); 3684 3685 void SetName(Local<String> name); 3686 Local<Value> GetName() const; 3687 3688 /** 3689 * Name inferred from variable or property assignment of this function. 3690 * Used to facilitate debugging and profiling of JavaScript code written 3691 * in an OO style, where many functions are anonymous but are assigned 3692 * to object properties. 3693 */ 3694 Local<Value> GetInferredName() const; 3695 3696 /** 3697 * displayName if it is set, otherwise name if it is configured, otherwise 3698 * function name, otherwise inferred name. 3699 */ 3700 Local<Value> GetDebugName() const; 3701 3702 /** 3703 * User-defined name assigned to the "displayName" property of this function. 3704 * Used to facilitate debugging and profiling of JavaScript code. 3705 */ 3706 Local<Value> GetDisplayName() const; 3707 3708 /** 3709 * Returns zero based line number of function body and 3710 * kLineOffsetNotFound if no information available. 3711 */ 3712 int GetScriptLineNumber() const; 3713 /** 3714 * Returns zero based column number of function body and 3715 * kLineOffsetNotFound if no information available. 3716 */ 3717 int GetScriptColumnNumber() const; 3718 3719 /** 3720 * Tells whether this function is builtin. 3721 */ 3722 V8_DEPRECATED("this should no longer be used.", bool IsBuiltin() const); 3723 3724 /** 3725 * Returns scriptId. 3726 */ 3727 int ScriptId() const; 3728 3729 /** 3730 * Returns the original function if this function is bound, else returns 3731 * v8::Undefined. 3732 */ 3733 Local<Value> GetBoundFunction() const; 3734 3735 ScriptOrigin GetScriptOrigin() const; 3736 V8_INLINE static Function* Cast(Value* obj); 3737 static const int kLineOffsetNotFound; 3738 3739 private: 3740 Function(); 3741 static void CheckCast(Value* obj); 3742 }; 3743 3744 3745 /** 3746 * An instance of the built-in Promise constructor (ES6 draft). 3747 */ 3748 class V8_EXPORT Promise : public Object { 3749 public: 3750 /** 3751 * State of the promise. Each value corresponds to one of the possible values 3752 * of the [[PromiseState]] field. 3753 */ 3754 enum PromiseState { kPending, kFulfilled, kRejected }; 3755 3756 class V8_EXPORT Resolver : public Object { 3757 public: 3758 /** 3759 * Create a new resolver, along with an associated promise in pending state. 3760 */ 3761 static V8_DEPRECATE_SOON("Use maybe version", 3762 Local<Resolver> New(Isolate* isolate)); 3763 static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New( 3764 Local<Context> context); 3765 3766 /** 3767 * Extract the associated promise. 3768 */ 3769 Local<Promise> GetPromise(); 3770 3771 /** 3772 * Resolve/reject the associated promise with a given value. 3773 * Ignored if the promise is no longer pending. 3774 */ 3775 V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value)); 3776 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT 3777 Maybe<bool> Resolve(Local<Context> context, Local<Value> value); 3778 3779 V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value)); 3780 // TODO(dcarney): mark V8_WARN_UNUSED_RESULT 3781 Maybe<bool> Reject(Local<Context> context, Local<Value> value); 3782 3783 V8_INLINE static Resolver* Cast(Value* obj); 3784 3785 private: 3786 Resolver(); 3787 static void CheckCast(Value* obj); 3788 }; 3789 3790 /** 3791 * Register a resolution/rejection handler with a promise. 3792 * The handler is given the respective resolution/rejection value as 3793 * an argument. If the promise is already resolved/rejected, the handler is 3794 * invoked at the end of turn. 3795 */ 3796 V8_DEPRECATED("Use maybe version", 3797 Local<Promise> Catch(Local<Function> handler)); 3798 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context, 3799 Local<Function> handler); 3800 3801 V8_DEPRECATED("Use maybe version", 3802 Local<Promise> Then(Local<Function> handler)); 3803 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context, 3804 Local<Function> handler); 3805 3806 /** 3807 * Returns true if the promise has at least one derived promise, and 3808 * therefore resolve/reject handlers (including default handler). 3809 */ 3810 bool HasHandler(); 3811 3812 /** 3813 * Returns the content of the [[PromiseResult]] field. The Promise must not 3814 * be pending. 3815 */ 3816 Local<Value> Result(); 3817 3818 /** 3819 * Returns the value of the [[PromiseState]] field. 3820 */ 3821 PromiseState State(); 3822 3823 V8_INLINE static Promise* Cast(Value* obj); 3824 3825 private: 3826 Promise(); 3827 static void CheckCast(Value* obj); 3828 }; 3829 3830 /** 3831 * An instance of a Property Descriptor, see Ecma-262 6.2.4. 3832 * 3833 * Properties in a descriptor are present or absent. If you do not set 3834 * `enumerable`, `configurable`, and `writable`, they are absent. If `value`, 3835 * `get`, or `set` are absent, but you must specify them in the constructor, use 3836 * empty handles. 3837 * 3838 * Accessors `get` and `set` must be callable or undefined if they are present. 3839 * 3840 * \note Only query properties if they are present, i.e., call `x()` only if 3841 * `has_x()` returns true. 3842 * 3843 * \code 3844 * // var desc = {writable: false} 3845 * v8::PropertyDescriptor d(Local<Value>()), false); 3846 * d.value(); // error, value not set 3847 * if (d.has_writable()) { 3848 * d.writable(); // false 3849 * } 3850 * 3851 * // var desc = {value: undefined} 3852 * v8::PropertyDescriptor d(v8::Undefined(isolate)); 3853 * 3854 * // var desc = {get: undefined} 3855 * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>())); 3856 * \endcode 3857 */ 3858 class V8_EXPORT PropertyDescriptor { 3859 public: 3860 // GenericDescriptor 3861 PropertyDescriptor(); 3862 3863 // DataDescriptor 3864 PropertyDescriptor(Local<Value> value); 3865 3866 // DataDescriptor with writable property 3867 PropertyDescriptor(Local<Value> value, bool writable); 3868 3869 // AccessorDescriptor 3870 PropertyDescriptor(Local<Value> get, Local<Value> set); 3871 3872 ~PropertyDescriptor(); 3873 3874 Local<Value> value() const; 3875 bool has_value() const; 3876 3877 Local<Value> get() const; 3878 bool has_get() const; 3879 Local<Value> set() const; 3880 bool has_set() const; 3881 3882 void set_enumerable(bool enumerable); 3883 bool enumerable() const; 3884 bool has_enumerable() const; 3885 3886 void set_configurable(bool configurable); 3887 bool configurable() const; 3888 bool has_configurable() const; 3889 3890 bool writable() const; 3891 bool has_writable() const; 3892 3893 struct PrivateData; 3894 PrivateData* get_private() const { return private_; } 3895 3896 PropertyDescriptor(const PropertyDescriptor&) = delete; 3897 void operator=(const PropertyDescriptor&) = delete; 3898 3899 private: 3900 PrivateData* private_; 3901 }; 3902 3903 /** 3904 * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition, 3905 * 26.2.1). 3906 */ 3907 class V8_EXPORT Proxy : public Object { 3908 public: 3909 Local<Object> GetTarget(); 3910 Local<Value> GetHandler(); 3911 bool IsRevoked(); 3912 void Revoke(); 3913 3914 /** 3915 * Creates a new Proxy for the target object. 3916 */ 3917 static MaybeLocal<Proxy> New(Local<Context> context, 3918 Local<Object> local_target, 3919 Local<Object> local_handler); 3920 3921 V8_INLINE static Proxy* Cast(Value* obj); 3922 3923 private: 3924 Proxy(); 3925 static void CheckCast(Value* obj); 3926 }; 3927 3928 class V8_EXPORT WasmCompiledModule : public Object { 3929 public: 3930 typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> SerializedModule; 3931 // A buffer that is owned by the caller. 3932 typedef std::pair<const uint8_t*, size_t> CallerOwnedBuffer; 3933 // Get the wasm-encoded bytes that were used to compile this module. 3934 Local<String> GetWasmWireBytes(); 3935 3936 // Serialize the compiled module. The serialized data does not include the 3937 // uncompiled bytes. 3938 SerializedModule Serialize(); 3939 3940 // If possible, deserialize the module, otherwise compile it from the provided 3941 // uncompiled bytes. 3942 static MaybeLocal<WasmCompiledModule> DeserializeOrCompile( 3943 Isolate* isolate, const CallerOwnedBuffer& serialized_module, 3944 const CallerOwnedBuffer& wire_bytes); 3945 V8_INLINE static WasmCompiledModule* Cast(Value* obj); 3946 3947 private: 3948 static MaybeLocal<WasmCompiledModule> Deserialize( 3949 Isolate* isolate, const CallerOwnedBuffer& serialized_module, 3950 const CallerOwnedBuffer& wire_bytes); 3951 static MaybeLocal<WasmCompiledModule> Compile(Isolate* isolate, 3952 const uint8_t* start, 3953 size_t length); 3954 WasmCompiledModule(); 3955 static void CheckCast(Value* obj); 3956 }; 3957 3958 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 3959 // The number of required internal fields can be defined by embedder. 3960 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2 3961 #endif 3962 3963 3964 enum class ArrayBufferCreationMode { kInternalized, kExternalized }; 3965 3966 3967 /** 3968 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5). 3969 */ 3970 class V8_EXPORT ArrayBuffer : public Object { 3971 public: 3972 /** 3973 * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory. 3974 * The allocator is a global V8 setting. It has to be set via 3975 * Isolate::CreateParams. 3976 * 3977 * Memory allocated through this allocator by V8 is accounted for as external 3978 * memory by V8. Note that V8 keeps track of the memory for all internalized 3979 * |ArrayBuffer|s. Responsibility for tracking external memory (using 3980 * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the 3981 * embedder upon externalization and taken over upon internalization (creating 3982 * an internalized buffer from an existing buffer). 3983 * 3984 * Note that it is unsafe to call back into V8 from any of the allocator 3985 * functions. 3986 */ 3987 class V8_EXPORT Allocator { // NOLINT 3988 public: 3989 virtual ~Allocator() {} 3990 3991 /** 3992 * Allocate |length| bytes. Return NULL if allocation is not successful. 3993 * Memory should be initialized to zeroes. 3994 */ 3995 virtual void* Allocate(size_t length) = 0; 3996 3997 /** 3998 * Allocate |length| bytes. Return NULL if allocation is not successful. 3999 * Memory does not have to be initialized. 4000 */ 4001 virtual void* AllocateUninitialized(size_t length) = 0; 4002 4003 /** 4004 * Free the memory block of size |length|, pointed to by |data|. 4005 * That memory is guaranteed to be previously allocated by |Allocate|. 4006 */ 4007 virtual void Free(void* data, size_t length) = 0; 4008 4009 /** 4010 * malloc/free based convenience allocator. 4011 * 4012 * Caller takes ownership. 4013 */ 4014 static Allocator* NewDefaultAllocator(); 4015 }; 4016 4017 /** 4018 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer| 4019 * returns an instance of this class, populated, with a pointer to data 4020 * and byte length. 4021 * 4022 * The Data pointer of ArrayBuffer::Contents is always allocated with 4023 * Allocator::Allocate that is set via Isolate::CreateParams. 4024 */ 4025 class V8_EXPORT Contents { // NOLINT 4026 public: 4027 Contents() : data_(NULL), byte_length_(0) {} 4028 4029 void* Data() const { return data_; } 4030 size_t ByteLength() const { return byte_length_; } 4031 4032 private: 4033 void* data_; 4034 size_t byte_length_; 4035 4036 friend class ArrayBuffer; 4037 }; 4038 4039 4040 /** 4041 * Data length in bytes. 4042 */ 4043 size_t ByteLength() const; 4044 4045 /** 4046 * Create a new ArrayBuffer. Allocate |byte_length| bytes. 4047 * Allocated memory will be owned by a created ArrayBuffer and 4048 * will be deallocated when it is garbage-collected, 4049 * unless the object is externalized. 4050 */ 4051 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length); 4052 4053 /** 4054 * Create a new ArrayBuffer over an existing memory block. 4055 * The created array buffer is by default immediately in externalized state. 4056 * The memory block will not be reclaimed when a created ArrayBuffer 4057 * is garbage-collected. 4058 */ 4059 static Local<ArrayBuffer> New( 4060 Isolate* isolate, void* data, size_t byte_length, 4061 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized); 4062 4063 /** 4064 * Returns true if ArrayBuffer is externalized, that is, does not 4065 * own its memory block. 4066 */ 4067 bool IsExternal() const; 4068 4069 /** 4070 * Returns true if this ArrayBuffer may be neutered. 4071 */ 4072 bool IsNeuterable() const; 4073 4074 /** 4075 * Neuters this ArrayBuffer and all its views (typed arrays). 4076 * Neutering sets the byte length of the buffer and all typed arrays to zero, 4077 * preventing JavaScript from ever accessing underlying backing store. 4078 * ArrayBuffer should have been externalized and must be neuterable. 4079 */ 4080 void Neuter(); 4081 4082 /** 4083 * Make this ArrayBuffer external. The pointer to underlying memory block 4084 * and byte length are returned as |Contents| structure. After ArrayBuffer 4085 * had been externalized, it does no longer own the memory block. The caller 4086 * should take steps to free memory when it is no longer needed. 4087 * 4088 * The memory block is guaranteed to be allocated with |Allocator::Allocate| 4089 * that has been set via Isolate::CreateParams. 4090 */ 4091 Contents Externalize(); 4092 4093 /** 4094 * Get a pointer to the ArrayBuffer's underlying memory block without 4095 * externalizing it. If the ArrayBuffer is not externalized, this pointer 4096 * will become invalid as soon as the ArrayBuffer gets garbage collected. 4097 * 4098 * The embedder should make sure to hold a strong reference to the 4099 * ArrayBuffer while accessing this pointer. 4100 * 4101 * The memory block is guaranteed to be allocated with |Allocator::Allocate|. 4102 */ 4103 Contents GetContents(); 4104 4105 V8_INLINE static ArrayBuffer* Cast(Value* obj); 4106 4107 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT; 4108 4109 private: 4110 ArrayBuffer(); 4111 static void CheckCast(Value* obj); 4112 }; 4113 4114 4115 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 4116 // The number of required internal fields can be defined by embedder. 4117 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2 4118 #endif 4119 4120 4121 /** 4122 * A base class for an instance of one of "views" over ArrayBuffer, 4123 * including TypedArrays and DataView (ES6 draft 15.13). 4124 */ 4125 class V8_EXPORT ArrayBufferView : public Object { 4126 public: 4127 /** 4128 * Returns underlying ArrayBuffer. 4129 */ 4130 Local<ArrayBuffer> Buffer(); 4131 /** 4132 * Byte offset in |Buffer|. 4133 */ 4134 size_t ByteOffset(); 4135 /** 4136 * Size of a view in bytes. 4137 */ 4138 size_t ByteLength(); 4139 4140 /** 4141 * Copy the contents of the ArrayBufferView's buffer to an embedder defined 4142 * memory without additional overhead that calling ArrayBufferView::Buffer 4143 * might incur. 4144 * 4145 * Will write at most min(|byte_length|, ByteLength) bytes starting at 4146 * ByteOffset of the underlying buffer to the memory starting at |dest|. 4147 * Returns the number of bytes actually written. 4148 */ 4149 size_t CopyContents(void* dest, size_t byte_length); 4150 4151 /** 4152 * Returns true if ArrayBufferView's backing ArrayBuffer has already been 4153 * allocated. 4154 */ 4155 bool HasBuffer() const; 4156 4157 V8_INLINE static ArrayBufferView* Cast(Value* obj); 4158 4159 static const int kInternalFieldCount = 4160 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT; 4161 4162 private: 4163 ArrayBufferView(); 4164 static void CheckCast(Value* obj); 4165 }; 4166 4167 4168 /** 4169 * A base class for an instance of TypedArray series of constructors 4170 * (ES6 draft 15.13.6). 4171 */ 4172 class V8_EXPORT TypedArray : public ArrayBufferView { 4173 public: 4174 /** 4175 * Number of elements in this typed array 4176 * (e.g. for Int16Array, |ByteLength|/2). 4177 */ 4178 size_t Length(); 4179 4180 V8_INLINE static TypedArray* Cast(Value* obj); 4181 4182 private: 4183 TypedArray(); 4184 static void CheckCast(Value* obj); 4185 }; 4186 4187 4188 /** 4189 * An instance of Uint8Array constructor (ES6 draft 15.13.6). 4190 */ 4191 class V8_EXPORT Uint8Array : public TypedArray { 4192 public: 4193 static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer, 4194 size_t byte_offset, size_t length); 4195 static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4196 size_t byte_offset, size_t length); 4197 V8_INLINE static Uint8Array* Cast(Value* obj); 4198 4199 private: 4200 Uint8Array(); 4201 static void CheckCast(Value* obj); 4202 }; 4203 4204 4205 /** 4206 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6). 4207 */ 4208 class V8_EXPORT Uint8ClampedArray : public TypedArray { 4209 public: 4210 static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer, 4211 size_t byte_offset, size_t length); 4212 static Local<Uint8ClampedArray> New( 4213 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, 4214 size_t length); 4215 V8_INLINE static Uint8ClampedArray* Cast(Value* obj); 4216 4217 private: 4218 Uint8ClampedArray(); 4219 static void CheckCast(Value* obj); 4220 }; 4221 4222 /** 4223 * An instance of Int8Array constructor (ES6 draft 15.13.6). 4224 */ 4225 class V8_EXPORT Int8Array : public TypedArray { 4226 public: 4227 static Local<Int8Array> New(Local<ArrayBuffer> array_buffer, 4228 size_t byte_offset, size_t length); 4229 static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4230 size_t byte_offset, size_t length); 4231 V8_INLINE static Int8Array* Cast(Value* obj); 4232 4233 private: 4234 Int8Array(); 4235 static void CheckCast(Value* obj); 4236 }; 4237 4238 4239 /** 4240 * An instance of Uint16Array constructor (ES6 draft 15.13.6). 4241 */ 4242 class V8_EXPORT Uint16Array : public TypedArray { 4243 public: 4244 static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer, 4245 size_t byte_offset, size_t length); 4246 static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4247 size_t byte_offset, size_t length); 4248 V8_INLINE static Uint16Array* Cast(Value* obj); 4249 4250 private: 4251 Uint16Array(); 4252 static void CheckCast(Value* obj); 4253 }; 4254 4255 4256 /** 4257 * An instance of Int16Array constructor (ES6 draft 15.13.6). 4258 */ 4259 class V8_EXPORT Int16Array : public TypedArray { 4260 public: 4261 static Local<Int16Array> New(Local<ArrayBuffer> array_buffer, 4262 size_t byte_offset, size_t length); 4263 static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4264 size_t byte_offset, size_t length); 4265 V8_INLINE static Int16Array* Cast(Value* obj); 4266 4267 private: 4268 Int16Array(); 4269 static void CheckCast(Value* obj); 4270 }; 4271 4272 4273 /** 4274 * An instance of Uint32Array constructor (ES6 draft 15.13.6). 4275 */ 4276 class V8_EXPORT Uint32Array : public TypedArray { 4277 public: 4278 static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer, 4279 size_t byte_offset, size_t length); 4280 static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4281 size_t byte_offset, size_t length); 4282 V8_INLINE static Uint32Array* Cast(Value* obj); 4283 4284 private: 4285 Uint32Array(); 4286 static void CheckCast(Value* obj); 4287 }; 4288 4289 4290 /** 4291 * An instance of Int32Array constructor (ES6 draft 15.13.6). 4292 */ 4293 class V8_EXPORT Int32Array : public TypedArray { 4294 public: 4295 static Local<Int32Array> New(Local<ArrayBuffer> array_buffer, 4296 size_t byte_offset, size_t length); 4297 static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4298 size_t byte_offset, size_t length); 4299 V8_INLINE static Int32Array* Cast(Value* obj); 4300 4301 private: 4302 Int32Array(); 4303 static void CheckCast(Value* obj); 4304 }; 4305 4306 4307 /** 4308 * An instance of Float32Array constructor (ES6 draft 15.13.6). 4309 */ 4310 class V8_EXPORT Float32Array : public TypedArray { 4311 public: 4312 static Local<Float32Array> New(Local<ArrayBuffer> array_buffer, 4313 size_t byte_offset, size_t length); 4314 static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4315 size_t byte_offset, size_t length); 4316 V8_INLINE static Float32Array* Cast(Value* obj); 4317 4318 private: 4319 Float32Array(); 4320 static void CheckCast(Value* obj); 4321 }; 4322 4323 4324 /** 4325 * An instance of Float64Array constructor (ES6 draft 15.13.6). 4326 */ 4327 class V8_EXPORT Float64Array : public TypedArray { 4328 public: 4329 static Local<Float64Array> New(Local<ArrayBuffer> array_buffer, 4330 size_t byte_offset, size_t length); 4331 static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer, 4332 size_t byte_offset, size_t length); 4333 V8_INLINE static Float64Array* Cast(Value* obj); 4334 4335 private: 4336 Float64Array(); 4337 static void CheckCast(Value* obj); 4338 }; 4339 4340 4341 /** 4342 * An instance of DataView constructor (ES6 draft 15.13.7). 4343 */ 4344 class V8_EXPORT DataView : public ArrayBufferView { 4345 public: 4346 static Local<DataView> New(Local<ArrayBuffer> array_buffer, 4347 size_t byte_offset, size_t length); 4348 static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer, 4349 size_t byte_offset, size_t length); 4350 V8_INLINE static DataView* Cast(Value* obj); 4351 4352 private: 4353 DataView(); 4354 static void CheckCast(Value* obj); 4355 }; 4356 4357 4358 /** 4359 * An instance of the built-in SharedArrayBuffer constructor. 4360 * This API is experimental and may change significantly. 4361 */ 4362 class V8_EXPORT SharedArrayBuffer : public Object { 4363 public: 4364 /** 4365 * The contents of an |SharedArrayBuffer|. Externalization of 4366 * |SharedArrayBuffer| returns an instance of this class, populated, with a 4367 * pointer to data and byte length. 4368 * 4369 * The Data pointer of SharedArrayBuffer::Contents is always allocated with 4370 * |ArrayBuffer::Allocator::Allocate| by the allocator specified in 4371 * v8::Isolate::CreateParams::array_buffer_allocator. 4372 * 4373 * This API is experimental and may change significantly. 4374 */ 4375 class V8_EXPORT Contents { // NOLINT 4376 public: 4377 Contents() : data_(NULL), byte_length_(0) {} 4378 4379 void* Data() const { return data_; } 4380 size_t ByteLength() const { return byte_length_; } 4381 4382 private: 4383 void* data_; 4384 size_t byte_length_; 4385 4386 friend class SharedArrayBuffer; 4387 }; 4388 4389 4390 /** 4391 * Data length in bytes. 4392 */ 4393 size_t ByteLength() const; 4394 4395 /** 4396 * Create a new SharedArrayBuffer. Allocate |byte_length| bytes. 4397 * Allocated memory will be owned by a created SharedArrayBuffer and 4398 * will be deallocated when it is garbage-collected, 4399 * unless the object is externalized. 4400 */ 4401 static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length); 4402 4403 /** 4404 * Create a new SharedArrayBuffer over an existing memory block. The created 4405 * array buffer is immediately in externalized state unless otherwise 4406 * specified. The memory block will not be reclaimed when a created 4407 * SharedArrayBuffer is garbage-collected. 4408 */ 4409 static Local<SharedArrayBuffer> New( 4410 Isolate* isolate, void* data, size_t byte_length, 4411 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized); 4412 4413 /** 4414 * Returns true if SharedArrayBuffer is externalized, that is, does not 4415 * own its memory block. 4416 */ 4417 bool IsExternal() const; 4418 4419 /** 4420 * Make this SharedArrayBuffer external. The pointer to underlying memory 4421 * block and byte length are returned as |Contents| structure. After 4422 * SharedArrayBuffer had been externalized, it does no longer own the memory 4423 * block. The caller should take steps to free memory when it is no longer 4424 * needed. 4425 * 4426 * The memory block is guaranteed to be allocated with |Allocator::Allocate| 4427 * by the allocator specified in 4428 * v8::Isolate::CreateParams::array_buffer_allocator. 4429 * 4430 */ 4431 Contents Externalize(); 4432 4433 /** 4434 * Get a pointer to the ArrayBuffer's underlying memory block without 4435 * externalizing it. If the ArrayBuffer is not externalized, this pointer 4436 * will become invalid as soon as the ArrayBuffer became garbage collected. 4437 * 4438 * The embedder should make sure to hold a strong reference to the 4439 * ArrayBuffer while accessing this pointer. 4440 * 4441 * The memory block is guaranteed to be allocated with |Allocator::Allocate| 4442 * by the allocator specified in 4443 * v8::Isolate::CreateParams::array_buffer_allocator. 4444 */ 4445 Contents GetContents(); 4446 4447 V8_INLINE static SharedArrayBuffer* Cast(Value* obj); 4448 4449 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT; 4450 4451 private: 4452 SharedArrayBuffer(); 4453 static void CheckCast(Value* obj); 4454 }; 4455 4456 4457 /** 4458 * An instance of the built-in Date constructor (ECMA-262, 15.9). 4459 */ 4460 class V8_EXPORT Date : public Object { 4461 public: 4462 static V8_DEPRECATE_SOON("Use maybe version.", 4463 Local<Value> New(Isolate* isolate, double time)); 4464 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context, 4465 double time); 4466 4467 /** 4468 * A specialization of Value::NumberValue that is more efficient 4469 * because we know the structure of this object. 4470 */ 4471 double ValueOf() const; 4472 4473 V8_INLINE static Date* Cast(Value* obj); 4474 4475 /** 4476 * Notification that the embedder has changed the time zone, 4477 * daylight savings time, or other date / time configuration 4478 * parameters. V8 keeps a cache of various values used for 4479 * date / time computation. This notification will reset 4480 * those cached values for the current context so that date / 4481 * time configuration changes would be reflected in the Date 4482 * object. 4483 * 4484 * This API should not be called more than needed as it will 4485 * negatively impact the performance of date operations. 4486 */ 4487 static void DateTimeConfigurationChangeNotification(Isolate* isolate); 4488 4489 private: 4490 static void CheckCast(Value* obj); 4491 }; 4492 4493 4494 /** 4495 * A Number object (ECMA-262, 4.3.21). 4496 */ 4497 class V8_EXPORT NumberObject : public Object { 4498 public: 4499 static Local<Value> New(Isolate* isolate, double value); 4500 4501 double ValueOf() const; 4502 4503 V8_INLINE static NumberObject* Cast(Value* obj); 4504 4505 private: 4506 static void CheckCast(Value* obj); 4507 }; 4508 4509 4510 /** 4511 * A Boolean object (ECMA-262, 4.3.15). 4512 */ 4513 class V8_EXPORT BooleanObject : public Object { 4514 public: 4515 static Local<Value> New(Isolate* isolate, bool value); 4516 V8_DEPRECATED("Pass an isolate", static Local<Value> New(bool value)); 4517 4518 bool ValueOf() const; 4519 4520 V8_INLINE static BooleanObject* Cast(Value* obj); 4521 4522 private: 4523 static void CheckCast(Value* obj); 4524 }; 4525 4526 4527 /** 4528 * A String object (ECMA-262, 4.3.18). 4529 */ 4530 class V8_EXPORT StringObject : public Object { 4531 public: 4532 static Local<Value> New(Local<String> value); 4533 4534 Local<String> ValueOf() const; 4535 4536 V8_INLINE static StringObject* Cast(Value* obj); 4537 4538 private: 4539 static void CheckCast(Value* obj); 4540 }; 4541 4542 4543 /** 4544 * A Symbol object (ECMA-262 edition 6). 4545 */ 4546 class V8_EXPORT SymbolObject : public Object { 4547 public: 4548 static Local<Value> New(Isolate* isolate, Local<Symbol> value); 4549 4550 Local<Symbol> ValueOf() const; 4551 4552 V8_INLINE static SymbolObject* Cast(Value* obj); 4553 4554 private: 4555 static void CheckCast(Value* obj); 4556 }; 4557 4558 4559 /** 4560 * An instance of the built-in RegExp constructor (ECMA-262, 15.10). 4561 */ 4562 class V8_EXPORT RegExp : public Object { 4563 public: 4564 /** 4565 * Regular expression flag bits. They can be or'ed to enable a set 4566 * of flags. 4567 */ 4568 enum Flags { 4569 kNone = 0, 4570 kGlobal = 1, 4571 kIgnoreCase = 2, 4572 kMultiline = 4, 4573 kSticky = 8, 4574 kUnicode = 16 4575 }; 4576 4577 /** 4578 * Creates a regular expression from the given pattern string and 4579 * the flags bit field. May throw a JavaScript exception as 4580 * described in ECMA-262, 15.10.4.1. 4581 * 4582 * For example, 4583 * RegExp::New(v8::String::New("foo"), 4584 * static_cast<RegExp::Flags>(kGlobal | kMultiline)) 4585 * is equivalent to evaluating "/foo/gm". 4586 */ 4587 static V8_DEPRECATE_SOON("Use maybe version", 4588 Local<RegExp> New(Local<String> pattern, 4589 Flags flags)); 4590 static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context, 4591 Local<String> pattern, 4592 Flags flags); 4593 4594 /** 4595 * Returns the value of the source property: a string representing 4596 * the regular expression. 4597 */ 4598 Local<String> GetSource() const; 4599 4600 /** 4601 * Returns the flags bit field. 4602 */ 4603 Flags GetFlags() const; 4604 4605 V8_INLINE static RegExp* Cast(Value* obj); 4606 4607 private: 4608 static void CheckCast(Value* obj); 4609 }; 4610 4611 4612 /** 4613 * A JavaScript value that wraps a C++ void*. This type of value is mainly used 4614 * to associate C++ data structures with JavaScript objects. 4615 */ 4616 class V8_EXPORT External : public Value { 4617 public: 4618 static Local<External> New(Isolate* isolate, void* value); 4619 V8_INLINE static External* Cast(Value* obj); 4620 void* Value() const; 4621 private: 4622 static void CheckCast(v8::Value* obj); 4623 }; 4624 4625 #define V8_INTRINSICS_LIST(F) \ 4626 F(ArrayProto_entries, array_entries_iterator) \ 4627 F(ArrayProto_forEach, array_for_each_iterator) \ 4628 F(ArrayProto_keys, array_keys_iterator) \ 4629 F(ArrayProto_values, array_values_iterator) 4630 4631 enum Intrinsic { 4632 #define V8_DECL_INTRINSIC(name, iname) k##name, 4633 V8_INTRINSICS_LIST(V8_DECL_INTRINSIC) 4634 #undef V8_DECL_INTRINSIC 4635 }; 4636 4637 4638 // --- Templates --- 4639 4640 4641 /** 4642 * The superclass of object and function templates. 4643 */ 4644 class V8_EXPORT Template : public Data { 4645 public: 4646 /** 4647 * Adds a property to each instance created by this template. 4648 * 4649 * The property must be defined either as a primitive value, or a template. 4650 */ 4651 void Set(Local<Name> name, Local<Data> value, 4652 PropertyAttribute attributes = None); 4653 void SetPrivate(Local<Private> name, Local<Data> value, 4654 PropertyAttribute attributes = None); 4655 V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value); 4656 4657 void SetAccessorProperty( 4658 Local<Name> name, 4659 Local<FunctionTemplate> getter = Local<FunctionTemplate>(), 4660 Local<FunctionTemplate> setter = Local<FunctionTemplate>(), 4661 PropertyAttribute attribute = None, 4662 AccessControl settings = DEFAULT); 4663 4664 /** 4665 * Whenever the property with the given name is accessed on objects 4666 * created from this Template the getter and setter callbacks 4667 * are called instead of getting and setting the property directly 4668 * on the JavaScript object. 4669 * 4670 * \param name The name of the property for which an accessor is added. 4671 * \param getter The callback to invoke when getting the property. 4672 * \param setter The callback to invoke when setting the property. 4673 * \param data A piece of data that will be passed to the getter and setter 4674 * callbacks whenever they are invoked. 4675 * \param settings Access control settings for the accessor. This is a bit 4676 * field consisting of one of more of 4677 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2. 4678 * The default is to not allow cross-context access. 4679 * ALL_CAN_READ means that all cross-context reads are allowed. 4680 * ALL_CAN_WRITE means that all cross-context writes are allowed. 4681 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all 4682 * cross-context access. 4683 * \param attribute The attributes of the property for which an accessor 4684 * is added. 4685 * \param signature The signature describes valid receivers for the accessor 4686 * and is used to perform implicit instance checks against them. If the 4687 * receiver is incompatible (i.e. is not an instance of the constructor as 4688 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is 4689 * thrown and no callback is invoked. 4690 */ 4691 void SetNativeDataProperty( 4692 Local<String> name, AccessorGetterCallback getter, 4693 AccessorSetterCallback setter = 0, 4694 // TODO(dcarney): gcc can't handle Local below 4695 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None, 4696 Local<AccessorSignature> signature = Local<AccessorSignature>(), 4697 AccessControl settings = DEFAULT); 4698 void SetNativeDataProperty( 4699 Local<Name> name, AccessorNameGetterCallback getter, 4700 AccessorNameSetterCallback setter = 0, 4701 // TODO(dcarney): gcc can't handle Local below 4702 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None, 4703 Local<AccessorSignature> signature = Local<AccessorSignature>(), 4704 AccessControl settings = DEFAULT); 4705 4706 /** 4707 * Like SetNativeDataProperty, but V8 will replace the native data property 4708 * with a real data property on first access. 4709 */ 4710 void SetLazyDataProperty(Local<Name> name, AccessorNameGetterCallback getter, 4711 Local<Value> data = Local<Value>(), 4712 PropertyAttribute attribute = None); 4713 4714 /** 4715 * During template instantiation, sets the value with the intrinsic property 4716 * from the correct context. 4717 */ 4718 void SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic, 4719 PropertyAttribute attribute = None); 4720 4721 private: 4722 Template(); 4723 4724 friend class ObjectTemplate; 4725 friend class FunctionTemplate; 4726 }; 4727 4728 4729 /** 4730 * NamedProperty[Getter|Setter] are used as interceptors on object. 4731 * See ObjectTemplate::SetNamedPropertyHandler. 4732 */ 4733 typedef void (*NamedPropertyGetterCallback)( 4734 Local<String> property, 4735 const PropertyCallbackInfo<Value>& info); 4736 4737 4738 /** 4739 * Returns the value if the setter intercepts the request. 4740 * Otherwise, returns an empty handle. 4741 */ 4742 typedef void (*NamedPropertySetterCallback)( 4743 Local<String> property, 4744 Local<Value> value, 4745 const PropertyCallbackInfo<Value>& info); 4746 4747 4748 /** 4749 * Returns a non-empty handle if the interceptor intercepts the request. 4750 * The result is an integer encoding property attributes (like v8::None, 4751 * v8::DontEnum, etc.) 4752 */ 4753 typedef void (*NamedPropertyQueryCallback)( 4754 Local<String> property, 4755 const PropertyCallbackInfo<Integer>& info); 4756 4757 4758 /** 4759 * Returns a non-empty handle if the deleter intercepts the request. 4760 * The return value is true if the property could be deleted and false 4761 * otherwise. 4762 */ 4763 typedef void (*NamedPropertyDeleterCallback)( 4764 Local<String> property, 4765 const PropertyCallbackInfo<Boolean>& info); 4766 4767 4768 /** 4769 * Returns an array containing the names of the properties the named 4770 * property getter intercepts. 4771 */ 4772 typedef void (*NamedPropertyEnumeratorCallback)( 4773 const PropertyCallbackInfo<Array>& info); 4774 4775 4776 // TODO(dcarney): Deprecate and remove previous typedefs, and replace 4777 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback. 4778 4779 /** 4780 * Interceptor for get requests on an object. 4781 * 4782 * Use `info.GetReturnValue().Set()` to set the return value of the 4783 * intercepted get request. 4784 * 4785 * \param property The name of the property for which the request was 4786 * intercepted. 4787 * \param info Information about the intercepted request, such as 4788 * isolate, receiver, return value, or whether running in `'use strict`' mode. 4789 * See `PropertyCallbackInfo`. 4790 * 4791 * \code 4792 * void GetterCallback( 4793 * Local<Name> name, 4794 * const v8::PropertyCallbackInfo<v8::Value>& info) { 4795 * info.GetReturnValue().Set(v8_num(42)); 4796 * } 4797 * 4798 * v8::Local<v8::FunctionTemplate> templ = 4799 * v8::FunctionTemplate::New(isolate); 4800 * templ->InstanceTemplate()->SetHandler( 4801 * v8::NamedPropertyHandlerConfiguration(GetterCallback)); 4802 * LocalContext env; 4803 * env->Global() 4804 * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local()) 4805 * .ToLocalChecked() 4806 * ->NewInstance(env.local()) 4807 * .ToLocalChecked()) 4808 * .FromJust(); 4809 * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a"); 4810 * CHECK(v8_num(42)->Equals(env.local(), result).FromJust()); 4811 * \endcode 4812 * 4813 * See also `ObjectTemplate::SetHandler`. 4814 */ 4815 typedef void (*GenericNamedPropertyGetterCallback)( 4816 Local<Name> property, const PropertyCallbackInfo<Value>& info); 4817 4818 /** 4819 * Interceptor for set requests on an object. 4820 * 4821 * Use `info.GetReturnValue()` to indicate whether the request was intercepted 4822 * or not. If the setter successfully intercepts the request, i.e., if the 4823 * request should not be further executed, call 4824 * `info.GetReturnValue().Set(value)`. If the setter 4825 * did not intercept the request, i.e., if the request should be handled as 4826 * if no interceptor is present, do not not call `Set()`. 4827 * 4828 * \param property The name of the property for which the request was 4829 * intercepted. 4830 * \param value The value which the property will have if the request 4831 * is not intercepted. 4832 * \param info Information about the intercepted request, such as 4833 * isolate, receiver, return value, or whether running in `'use strict'` mode. 4834 * See `PropertyCallbackInfo`. 4835 * 4836 * See also 4837 * `ObjectTemplate::SetHandler.` 4838 */ 4839 typedef void (*GenericNamedPropertySetterCallback)( 4840 Local<Name> property, Local<Value> value, 4841 const PropertyCallbackInfo<Value>& info); 4842 4843 /** 4844 * Intercepts all requests that query the attributes of the 4845 * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and 4846 * defineProperty(). 4847 * 4848 * Use `info.GetReturnValue().Set(value)` to set the property attributes. The 4849 * value is an interger encoding a `v8::PropertyAttribute`. 4850 * 4851 * \param property The name of the property for which the request was 4852 * intercepted. 4853 * \param info Information about the intercepted request, such as 4854 * isolate, receiver, return value, or whether running in `'use strict'` mode. 4855 * See `PropertyCallbackInfo`. 4856 * 4857 * \note Some functions query the property attributes internally, even though 4858 * they do not return the attributes. For example, `hasOwnProperty()` can 4859 * trigger this interceptor depending on the state of the object. 4860 * 4861 * See also 4862 * `ObjectTemplate::SetHandler.` 4863 */ 4864 typedef void (*GenericNamedPropertyQueryCallback)( 4865 Local<Name> property, const PropertyCallbackInfo<Integer>& info); 4866 4867 /** 4868 * Interceptor for delete requests on an object. 4869 * 4870 * Use `info.GetReturnValue()` to indicate whether the request was intercepted 4871 * or not. If the deleter successfully intercepts the request, i.e., if the 4872 * request should not be further executed, call 4873 * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is 4874 * used as the return value of `delete`. 4875 * 4876 * \param property The name of the property for which the request was 4877 * intercepted. 4878 * \param info Information about the intercepted request, such as 4879 * isolate, receiver, return value, or whether running in `'use strict'` mode. 4880 * See `PropertyCallbackInfo`. 4881 * 4882 * \note If you need to mimic the behavior of `delete`, i.e., throw in strict 4883 * mode instead of returning false, use `info.ShouldThrowOnError()` to determine 4884 * if you are in strict mode. 4885 * 4886 * See also `ObjectTemplate::SetHandler.` 4887 */ 4888 typedef void (*GenericNamedPropertyDeleterCallback)( 4889 Local<Name> property, const PropertyCallbackInfo<Boolean>& info); 4890 4891 4892 /** 4893 * Returns an array containing the names of the properties the named 4894 * property getter intercepts. 4895 */ 4896 typedef void (*GenericNamedPropertyEnumeratorCallback)( 4897 const PropertyCallbackInfo<Array>& info); 4898 4899 /** 4900 * Interceptor for defineProperty requests on an object. 4901 * 4902 * Use `info.GetReturnValue()` to indicate whether the request was intercepted 4903 * or not. If the definer successfully intercepts the request, i.e., if the 4904 * request should not be further executed, call 4905 * `info.GetReturnValue().Set(value)`. If the definer 4906 * did not intercept the request, i.e., if the request should be handled as 4907 * if no interceptor is present, do not not call `Set()`. 4908 * 4909 * \param property The name of the property for which the request was 4910 * intercepted. 4911 * \param desc The property descriptor which is used to define the 4912 * property if the request is not intercepted. 4913 * \param info Information about the intercepted request, such as 4914 * isolate, receiver, return value, or whether running in `'use strict'` mode. 4915 * See `PropertyCallbackInfo`. 4916 * 4917 * See also `ObjectTemplate::SetHandler`. 4918 */ 4919 typedef void (*GenericNamedPropertyDefinerCallback)( 4920 Local<Name> property, const PropertyDescriptor& desc, 4921 const PropertyCallbackInfo<Value>& info); 4922 4923 /** 4924 * Interceptor for getOwnPropertyDescriptor requests on an object. 4925 * 4926 * Use `info.GetReturnValue().Set()` to set the return value of the 4927 * intercepted request. The return value must be an object that 4928 * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from 4929 * `v8::Object::getOwnPropertyDescriptor`. 4930 * 4931 * \param property The name of the property for which the request was 4932 * intercepted. 4933 * \info Information about the intercepted request, such as 4934 * isolate, receiver, return value, or whether running in `'use strict'` mode. 4935 * See `PropertyCallbackInfo`. 4936 * 4937 * \note If GetOwnPropertyDescriptor is intercepted, it will 4938 * always return true, i.e., indicate that the property was found. 4939 * 4940 * See also `ObjectTemplate::SetHandler`. 4941 */ 4942 typedef void (*GenericNamedPropertyDescriptorCallback)( 4943 Local<Name> property, const PropertyCallbackInfo<Value>& info); 4944 4945 /** 4946 * See `v8::GenericNamedPropertyGetterCallback`. 4947 */ 4948 typedef void (*IndexedPropertyGetterCallback)( 4949 uint32_t index, 4950 const PropertyCallbackInfo<Value>& info); 4951 4952 /** 4953 * See `v8::GenericNamedPropertySetterCallback`. 4954 */ 4955 typedef void (*IndexedPropertySetterCallback)( 4956 uint32_t index, 4957 Local<Value> value, 4958 const PropertyCallbackInfo<Value>& info); 4959 4960 /** 4961 * See `v8::GenericNamedPropertyQueryCallback`. 4962 */ 4963 typedef void (*IndexedPropertyQueryCallback)( 4964 uint32_t index, 4965 const PropertyCallbackInfo<Integer>& info); 4966 4967 /** 4968 * See `v8::GenericNamedPropertyDeleterCallback`. 4969 */ 4970 typedef void (*IndexedPropertyDeleterCallback)( 4971 uint32_t index, 4972 const PropertyCallbackInfo<Boolean>& info); 4973 4974 /** 4975 * See `v8::GenericNamedPropertyEnumeratorCallback`. 4976 */ 4977 typedef void (*IndexedPropertyEnumeratorCallback)( 4978 const PropertyCallbackInfo<Array>& info); 4979 4980 /** 4981 * See `v8::GenericNamedPropertyDefinerCallback`. 4982 */ 4983 typedef void (*IndexedPropertyDefinerCallback)( 4984 uint32_t index, const PropertyDescriptor& desc, 4985 const PropertyCallbackInfo<Value>& info); 4986 4987 /** 4988 * See `v8::GenericNamedPropertyDescriptorCallback`. 4989 */ 4990 typedef void (*IndexedPropertyDescriptorCallback)( 4991 uint32_t index, const PropertyCallbackInfo<Value>& info); 4992 4993 /** 4994 * Access type specification. 4995 */ 4996 enum AccessType { 4997 ACCESS_GET, 4998 ACCESS_SET, 4999 ACCESS_HAS, 5000 ACCESS_DELETE, 5001 ACCESS_KEYS 5002 }; 5003 5004 5005 /** 5006 * Returns true if the given context should be allowed to access the given 5007 * object. 5008 */ 5009 typedef bool (*AccessCheckCallback)(Local<Context> accessing_context, 5010 Local<Object> accessed_object, 5011 Local<Value> data); 5012 5013 /** 5014 * A FunctionTemplate is used to create functions at runtime. There 5015 * can only be one function created from a FunctionTemplate in a 5016 * context. The lifetime of the created function is equal to the 5017 * lifetime of the context. So in case the embedder needs to create 5018 * temporary functions that can be collected using Scripts is 5019 * preferred. 5020 * 5021 * Any modification of a FunctionTemplate after first instantiation will trigger 5022 * a crash. 5023 * 5024 * A FunctionTemplate can have properties, these properties are added to the 5025 * function object when it is created. 5026 * 5027 * A FunctionTemplate has a corresponding instance template which is 5028 * used to create object instances when the function is used as a 5029 * constructor. Properties added to the instance template are added to 5030 * each object instance. 5031 * 5032 * A FunctionTemplate can have a prototype template. The prototype template 5033 * is used to create the prototype object of the function. 5034 * 5035 * The following example shows how to use a FunctionTemplate: 5036 * 5037 * \code 5038 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate); 5039 * t->Set(isolate, "func_property", v8::Number::New(isolate, 1)); 5040 * 5041 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate(); 5042 * proto_t->Set(isolate, 5043 * "proto_method", 5044 * v8::FunctionTemplate::New(isolate, InvokeCallback)); 5045 * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2)); 5046 * 5047 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate(); 5048 * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"), 5049 * InstanceAccessorCallback); 5050 * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback); 5051 * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"), 5052 * Number::New(isolate, 3)); 5053 * 5054 * v8::Local<v8::Function> function = t->GetFunction(); 5055 * v8::Local<v8::Object> instance = function->NewInstance(); 5056 * \endcode 5057 * 5058 * Let's use "function" as the JS variable name of the function object 5059 * and "instance" for the instance object created above. The function 5060 * and the instance will have the following properties: 5061 * 5062 * \code 5063 * func_property in function == true; 5064 * function.func_property == 1; 5065 * 5066 * function.prototype.proto_method() invokes 'InvokeCallback' 5067 * function.prototype.proto_const == 2; 5068 * 5069 * instance instanceof function == true; 5070 * instance.instance_accessor calls 'InstanceAccessorCallback' 5071 * instance.instance_property == 3; 5072 * \endcode 5073 * 5074 * A FunctionTemplate can inherit from another one by calling the 5075 * FunctionTemplate::Inherit method. The following graph illustrates 5076 * the semantics of inheritance: 5077 * 5078 * \code 5079 * FunctionTemplate Parent -> Parent() . prototype -> { } 5080 * ^ ^ 5081 * | Inherit(Parent) | .__proto__ 5082 * | | 5083 * FunctionTemplate Child -> Child() . prototype -> { } 5084 * \endcode 5085 * 5086 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype 5087 * object of the Child() function has __proto__ pointing to the 5088 * Parent() function's prototype object. An instance of the Child 5089 * function has all properties on Parent's instance templates. 5090 * 5091 * Let Parent be the FunctionTemplate initialized in the previous 5092 * section and create a Child FunctionTemplate by: 5093 * 5094 * \code 5095 * Local<FunctionTemplate> parent = t; 5096 * Local<FunctionTemplate> child = FunctionTemplate::New(); 5097 * child->Inherit(parent); 5098 * 5099 * Local<Function> child_function = child->GetFunction(); 5100 * Local<Object> child_instance = child_function->NewInstance(); 5101 * \endcode 5102 * 5103 * The Child function and Child instance will have the following 5104 * properties: 5105 * 5106 * \code 5107 * child_func.prototype.__proto__ == function.prototype; 5108 * child_instance.instance_accessor calls 'InstanceAccessorCallback' 5109 * child_instance.instance_property == 3; 5110 * \endcode 5111 */ 5112 class V8_EXPORT FunctionTemplate : public Template { 5113 public: 5114 /** Creates a function template.*/ 5115 static Local<FunctionTemplate> New( 5116 Isolate* isolate, FunctionCallback callback = 0, 5117 Local<Value> data = Local<Value>(), 5118 Local<Signature> signature = Local<Signature>(), int length = 0, 5119 ConstructorBehavior behavior = ConstructorBehavior::kAllow); 5120 5121 /** Get a template included in the snapshot by index. */ 5122 static MaybeLocal<FunctionTemplate> FromSnapshot(Isolate* isolate, 5123 size_t index); 5124 5125 /** 5126 * Creates a function template with a fast handler. If a fast handler is set, 5127 * the callback cannot be null. 5128 */ 5129 static Local<FunctionTemplate> NewWithFastHandler( 5130 Isolate* isolate, FunctionCallback callback, 5131 experimental::FastAccessorBuilder* fast_handler = nullptr, 5132 Local<Value> data = Local<Value>(), 5133 Local<Signature> signature = Local<Signature>(), int length = 0); 5134 5135 /** 5136 * Creates a function template backed/cached by a private property. 5137 */ 5138 static Local<FunctionTemplate> NewWithCache( 5139 Isolate* isolate, FunctionCallback callback, 5140 Local<Private> cache_property, Local<Value> data = Local<Value>(), 5141 Local<Signature> signature = Local<Signature>(), int length = 0); 5142 5143 /** Returns the unique function instance in the current execution context.*/ 5144 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction()); 5145 V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction( 5146 Local<Context> context); 5147 5148 /** 5149 * Similar to Context::NewRemoteContext, this creates an instance that 5150 * isn't backed by an actual object. 5151 * 5152 * The InstanceTemplate of this FunctionTemplate must have access checks with 5153 * handlers installed. 5154 */ 5155 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewRemoteInstance(); 5156 5157 /** 5158 * Set the call-handler callback for a FunctionTemplate. This 5159 * callback is called whenever the function created from this 5160 * FunctionTemplate is called. 5161 */ 5162 void SetCallHandler( 5163 FunctionCallback callback, Local<Value> data = Local<Value>(), 5164 experimental::FastAccessorBuilder* fast_handler = nullptr); 5165 5166 /** Set the predefined length property for the FunctionTemplate. */ 5167 void SetLength(int length); 5168 5169 /** Get the InstanceTemplate. */ 5170 Local<ObjectTemplate> InstanceTemplate(); 5171 5172 /** 5173 * Causes the function template to inherit from a parent function template. 5174 * This means the the function's prototype.__proto__ is set to the parent 5175 * function's prototype. 5176 **/ 5177 void Inherit(Local<FunctionTemplate> parent); 5178 5179 /** 5180 * A PrototypeTemplate is the template used to create the prototype object 5181 * of the function created by this template. 5182 */ 5183 Local<ObjectTemplate> PrototypeTemplate(); 5184 5185 /** 5186 * A PrototypeProviderTemplate is another function template whose prototype 5187 * property is used for this template. This is mutually exclusive with setting 5188 * a prototype template indirectly by calling PrototypeTemplate() or using 5189 * Inherit(). 5190 **/ 5191 void SetPrototypeProviderTemplate(Local<FunctionTemplate> prototype_provider); 5192 5193 /** 5194 * Set the class name of the FunctionTemplate. This is used for 5195 * printing objects created with the function created from the 5196 * FunctionTemplate as its constructor. 5197 */ 5198 void SetClassName(Local<String> name); 5199 5200 5201 /** 5202 * When set to true, no access check will be performed on the receiver of a 5203 * function call. Currently defaults to true, but this is subject to change. 5204 */ 5205 void SetAcceptAnyReceiver(bool value); 5206 5207 /** 5208 * Determines whether the __proto__ accessor ignores instances of 5209 * the function template. If instances of the function template are 5210 * ignored, __proto__ skips all instances and instead returns the 5211 * next object in the prototype chain. 5212 * 5213 * Call with a value of true to make the __proto__ accessor ignore 5214 * instances of the function template. Call with a value of false 5215 * to make the __proto__ accessor not ignore instances of the 5216 * function template. By default, instances of a function template 5217 * are not ignored. 5218 */ 5219 void SetHiddenPrototype(bool value); 5220 5221 /** 5222 * Sets the ReadOnly flag in the attributes of the 'prototype' property 5223 * of functions created from this FunctionTemplate to true. 5224 */ 5225 void ReadOnlyPrototype(); 5226 5227 /** 5228 * Removes the prototype property from functions created from this 5229 * FunctionTemplate. 5230 */ 5231 void RemovePrototype(); 5232 5233 /** 5234 * Returns true if the given object is an instance of this function 5235 * template. 5236 */ 5237 bool HasInstance(Local<Value> object); 5238 5239 private: 5240 FunctionTemplate(); 5241 friend class Context; 5242 friend class ObjectTemplate; 5243 }; 5244 5245 /** 5246 * Configuration flags for v8::NamedPropertyHandlerConfiguration or 5247 * v8::IndexedPropertyHandlerConfiguration. 5248 */ 5249 enum class PropertyHandlerFlags { 5250 /** 5251 * None. 5252 */ 5253 kNone = 0, 5254 5255 /** 5256 * See ALL_CAN_READ above. 5257 */ 5258 kAllCanRead = 1, 5259 5260 /** Will not call into interceptor for properties on the receiver or prototype 5261 * chain, i.e., only call into interceptor for properties that do not exist. 5262 * Currently only valid for named interceptors. 5263 */ 5264 kNonMasking = 1 << 1, 5265 5266 /** 5267 * Will not call into interceptor for symbol lookup. Only meaningful for 5268 * named interceptors. 5269 */ 5270 kOnlyInterceptStrings = 1 << 2, 5271 }; 5272 5273 struct NamedPropertyHandlerConfiguration { 5274 NamedPropertyHandlerConfiguration( 5275 /** Note: getter is required */ 5276 GenericNamedPropertyGetterCallback getter = 0, 5277 GenericNamedPropertySetterCallback setter = 0, 5278 GenericNamedPropertyQueryCallback query = 0, 5279 GenericNamedPropertyDeleterCallback deleter = 0, 5280 GenericNamedPropertyEnumeratorCallback enumerator = 0, 5281 Local<Value> data = Local<Value>(), 5282 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone) 5283 : getter(getter), 5284 setter(setter), 5285 query(query), 5286 deleter(deleter), 5287 enumerator(enumerator), 5288 definer(0), 5289 descriptor(0), 5290 data(data), 5291 flags(flags) {} 5292 5293 NamedPropertyHandlerConfiguration( 5294 GenericNamedPropertyGetterCallback getter, 5295 GenericNamedPropertySetterCallback setter, 5296 GenericNamedPropertyDescriptorCallback descriptor, 5297 GenericNamedPropertyDeleterCallback deleter, 5298 GenericNamedPropertyEnumeratorCallback enumerator, 5299 GenericNamedPropertyDefinerCallback definer, 5300 Local<Value> data = Local<Value>(), 5301 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone) 5302 : getter(getter), 5303 setter(setter), 5304 query(0), 5305 deleter(deleter), 5306 enumerator(enumerator), 5307 definer(definer), 5308 descriptor(descriptor), 5309 data(data), 5310 flags(flags) {} 5311 5312 GenericNamedPropertyGetterCallback getter; 5313 GenericNamedPropertySetterCallback setter; 5314 GenericNamedPropertyQueryCallback query; 5315 GenericNamedPropertyDeleterCallback deleter; 5316 GenericNamedPropertyEnumeratorCallback enumerator; 5317 GenericNamedPropertyDefinerCallback definer; 5318 GenericNamedPropertyDescriptorCallback descriptor; 5319 Local<Value> data; 5320 PropertyHandlerFlags flags; 5321 }; 5322 5323 5324 struct IndexedPropertyHandlerConfiguration { 5325 IndexedPropertyHandlerConfiguration( 5326 /** Note: getter is required */ 5327 IndexedPropertyGetterCallback getter = 0, 5328 IndexedPropertySetterCallback setter = 0, 5329 IndexedPropertyQueryCallback query = 0, 5330 IndexedPropertyDeleterCallback deleter = 0, 5331 IndexedPropertyEnumeratorCallback enumerator = 0, 5332 Local<Value> data = Local<Value>(), 5333 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone) 5334 : getter(getter), 5335 setter(setter), 5336 query(query), 5337 deleter(deleter), 5338 enumerator(enumerator), 5339 definer(0), 5340 descriptor(0), 5341 data(data), 5342 flags(flags) {} 5343 5344 IndexedPropertyHandlerConfiguration( 5345 IndexedPropertyGetterCallback getter, 5346 IndexedPropertySetterCallback setter, 5347 IndexedPropertyDescriptorCallback descriptor, 5348 IndexedPropertyDeleterCallback deleter, 5349 IndexedPropertyEnumeratorCallback enumerator, 5350 IndexedPropertyDefinerCallback definer, 5351 Local<Value> data = Local<Value>(), 5352 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone) 5353 : getter(getter), 5354 setter(setter), 5355 query(0), 5356 deleter(deleter), 5357 enumerator(enumerator), 5358 definer(definer), 5359 descriptor(descriptor), 5360 data(data), 5361 flags(flags) {} 5362 5363 IndexedPropertyGetterCallback getter; 5364 IndexedPropertySetterCallback setter; 5365 IndexedPropertyQueryCallback query; 5366 IndexedPropertyDeleterCallback deleter; 5367 IndexedPropertyEnumeratorCallback enumerator; 5368 IndexedPropertyDefinerCallback definer; 5369 IndexedPropertyDescriptorCallback descriptor; 5370 Local<Value> data; 5371 PropertyHandlerFlags flags; 5372 }; 5373 5374 5375 /** 5376 * An ObjectTemplate is used to create objects at runtime. 5377 * 5378 * Properties added to an ObjectTemplate are added to each object 5379 * created from the ObjectTemplate. 5380 */ 5381 class V8_EXPORT ObjectTemplate : public Template { 5382 public: 5383 /** Creates an ObjectTemplate. */ 5384 static Local<ObjectTemplate> New( 5385 Isolate* isolate, 5386 Local<FunctionTemplate> constructor = Local<FunctionTemplate>()); 5387 static V8_DEPRECATED("Use isolate version", Local<ObjectTemplate> New()); 5388 5389 /** Get a template included in the snapshot by index. */ 5390 static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate, 5391 size_t index); 5392 5393 /** Creates a new instance of this template.*/ 5394 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance()); 5395 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context); 5396 5397 /** 5398 * Sets an accessor on the object template. 5399 * 5400 * Whenever the property with the given name is accessed on objects 5401 * created from this ObjectTemplate the getter and setter callbacks 5402 * are called instead of getting and setting the property directly 5403 * on the JavaScript object. 5404 * 5405 * \param name The name of the property for which an accessor is added. 5406 * \param getter The callback to invoke when getting the property. 5407 * \param setter The callback to invoke when setting the property. 5408 * \param data A piece of data that will be passed to the getter and setter 5409 * callbacks whenever they are invoked. 5410 * \param settings Access control settings for the accessor. This is a bit 5411 * field consisting of one of more of 5412 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2. 5413 * The default is to not allow cross-context access. 5414 * ALL_CAN_READ means that all cross-context reads are allowed. 5415 * ALL_CAN_WRITE means that all cross-context writes are allowed. 5416 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all 5417 * cross-context access. 5418 * \param attribute The attributes of the property for which an accessor 5419 * is added. 5420 * \param signature The signature describes valid receivers for the accessor 5421 * and is used to perform implicit instance checks against them. If the 5422 * receiver is incompatible (i.e. is not an instance of the constructor as 5423 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is 5424 * thrown and no callback is invoked. 5425 */ 5426 void SetAccessor( 5427 Local<String> name, AccessorGetterCallback getter, 5428 AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(), 5429 AccessControl settings = DEFAULT, PropertyAttribute attribute = None, 5430 Local<AccessorSignature> signature = Local<AccessorSignature>()); 5431 void SetAccessor( 5432 Local<Name> name, AccessorNameGetterCallback getter, 5433 AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(), 5434 AccessControl settings = DEFAULT, PropertyAttribute attribute = None, 5435 Local<AccessorSignature> signature = Local<AccessorSignature>()); 5436 5437 /** 5438 * Sets a named property handler on the object template. 5439 * 5440 * Whenever a property whose name is a string is accessed on objects created 5441 * from this object template, the provided callback is invoked instead of 5442 * accessing the property directly on the JavaScript object. 5443 * 5444 * SetNamedPropertyHandler() is different from SetHandler(), in 5445 * that the latter can intercept symbol-named properties as well as 5446 * string-named properties when called with a 5447 * NamedPropertyHandlerConfiguration. New code should use SetHandler(). 5448 * 5449 * \param getter The callback to invoke when getting a property. 5450 * \param setter The callback to invoke when setting a property. 5451 * \param query The callback to invoke to check if a property is present, 5452 * and if present, get its attributes. 5453 * \param deleter The callback to invoke when deleting a property. 5454 * \param enumerator The callback to invoke to enumerate all the named 5455 * properties of an object. 5456 * \param data A piece of data that will be passed to the callbacks 5457 * whenever they are invoked. 5458 */ 5459 // TODO(dcarney): deprecate 5460 void SetNamedPropertyHandler(NamedPropertyGetterCallback getter, 5461 NamedPropertySetterCallback setter = 0, 5462 NamedPropertyQueryCallback query = 0, 5463 NamedPropertyDeleterCallback deleter = 0, 5464 NamedPropertyEnumeratorCallback enumerator = 0, 5465 Local<Value> data = Local<Value>()); 5466 5467 /** 5468 * Sets a named property handler on the object template. 5469 * 5470 * Whenever a property whose name is a string or a symbol is accessed on 5471 * objects created from this object template, the provided callback is 5472 * invoked instead of accessing the property directly on the JavaScript 5473 * object. 5474 * 5475 * @param configuration The NamedPropertyHandlerConfiguration that defines the 5476 * callbacks to invoke when accessing a property. 5477 */ 5478 void SetHandler(const NamedPropertyHandlerConfiguration& configuration); 5479 5480 /** 5481 * Sets an indexed property handler on the object template. 5482 * 5483 * Whenever an indexed property is accessed on objects created from 5484 * this object template, the provided callback is invoked instead of 5485 * accessing the property directly on the JavaScript object. 5486 * 5487 * \param getter The callback to invoke when getting a property. 5488 * \param setter The callback to invoke when setting a property. 5489 * \param query The callback to invoke to check if an object has a property. 5490 * \param deleter The callback to invoke when deleting a property. 5491 * \param enumerator The callback to invoke to enumerate all the indexed 5492 * properties of an object. 5493 * \param data A piece of data that will be passed to the callbacks 5494 * whenever they are invoked. 5495 */ 5496 // TODO(dcarney): deprecate 5497 void SetIndexedPropertyHandler( 5498 IndexedPropertyGetterCallback getter, 5499 IndexedPropertySetterCallback setter = 0, 5500 IndexedPropertyQueryCallback query = 0, 5501 IndexedPropertyDeleterCallback deleter = 0, 5502 IndexedPropertyEnumeratorCallback enumerator = 0, 5503 Local<Value> data = Local<Value>()) { 5504 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query, 5505 deleter, enumerator, data)); 5506 } 5507 5508 /** 5509 * Sets an indexed property handler on the object template. 5510 * 5511 * Whenever an indexed property is accessed on objects created from 5512 * this object template, the provided callback is invoked instead of 5513 * accessing the property directly on the JavaScript object. 5514 * 5515 * @param configuration The IndexedPropertyHandlerConfiguration that defines 5516 * the callbacks to invoke when accessing a property. 5517 */ 5518 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration); 5519 5520 /** 5521 * Sets the callback to be used when calling instances created from 5522 * this template as a function. If no callback is set, instances 5523 * behave like normal JavaScript objects that cannot be called as a 5524 * function. 5525 */ 5526 void SetCallAsFunctionHandler(FunctionCallback callback, 5527 Local<Value> data = Local<Value>()); 5528 5529 /** 5530 * Mark object instances of the template as undetectable. 5531 * 5532 * In many ways, undetectable objects behave as though they are not 5533 * there. They behave like 'undefined' in conditionals and when 5534 * printed. However, properties can be accessed and called as on 5535 * normal objects. 5536 */ 5537 void MarkAsUndetectable(); 5538 5539 /** 5540 * Sets access check callback on the object template and enables access 5541 * checks. 5542 * 5543 * When accessing properties on instances of this object template, 5544 * the access check callback will be called to determine whether or 5545 * not to allow cross-context access to the properties. 5546 */ 5547 void SetAccessCheckCallback(AccessCheckCallback callback, 5548 Local<Value> data = Local<Value>()); 5549 5550 /** 5551 * Like SetAccessCheckCallback but invokes an interceptor on failed access 5552 * checks instead of looking up all-can-read properties. You can only use 5553 * either this method or SetAccessCheckCallback, but not both at the same 5554 * time. 5555 */ 5556 void SetAccessCheckCallbackAndHandler( 5557 AccessCheckCallback callback, 5558 const NamedPropertyHandlerConfiguration& named_handler, 5559 const IndexedPropertyHandlerConfiguration& indexed_handler, 5560 Local<Value> data = Local<Value>()); 5561 5562 /** 5563 * Gets the number of internal fields for objects generated from 5564 * this template. 5565 */ 5566 int InternalFieldCount(); 5567 5568 /** 5569 * Sets the number of internal fields for objects generated from 5570 * this template. 5571 */ 5572 void SetInternalFieldCount(int value); 5573 5574 /** 5575 * Returns true if the object will be an immutable prototype exotic object. 5576 */ 5577 bool IsImmutableProto(); 5578 5579 /** 5580 * Makes the ObjectTempate for an immutable prototype exotic object, with an 5581 * immutable __proto__. 5582 */ 5583 void SetImmutableProto(); 5584 5585 private: 5586 ObjectTemplate(); 5587 static Local<ObjectTemplate> New(internal::Isolate* isolate, 5588 Local<FunctionTemplate> constructor); 5589 friend class FunctionTemplate; 5590 }; 5591 5592 5593 /** 5594 * A Signature specifies which receiver is valid for a function. 5595 */ 5596 class V8_EXPORT Signature : public Data { 5597 public: 5598 static Local<Signature> New( 5599 Isolate* isolate, 5600 Local<FunctionTemplate> receiver = Local<FunctionTemplate>()); 5601 5602 private: 5603 Signature(); 5604 }; 5605 5606 5607 /** 5608 * An AccessorSignature specifies which receivers are valid parameters 5609 * to an accessor callback. 5610 */ 5611 class V8_EXPORT AccessorSignature : public Data { 5612 public: 5613 static Local<AccessorSignature> New( 5614 Isolate* isolate, 5615 Local<FunctionTemplate> receiver = Local<FunctionTemplate>()); 5616 5617 private: 5618 AccessorSignature(); 5619 }; 5620 5621 5622 // --- Extensions --- 5623 5624 class V8_EXPORT ExternalOneByteStringResourceImpl 5625 : public String::ExternalOneByteStringResource { 5626 public: 5627 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {} 5628 ExternalOneByteStringResourceImpl(const char* data, size_t length) 5629 : data_(data), length_(length) {} 5630 const char* data() const { return data_; } 5631 size_t length() const { return length_; } 5632 5633 private: 5634 const char* data_; 5635 size_t length_; 5636 }; 5637 5638 /** 5639 * Ignore 5640 */ 5641 class V8_EXPORT Extension { // NOLINT 5642 public: 5643 // Note that the strings passed into this constructor must live as long 5644 // as the Extension itself. 5645 Extension(const char* name, 5646 const char* source = 0, 5647 int dep_count = 0, 5648 const char** deps = 0, 5649 int source_length = -1); 5650 virtual ~Extension() { } 5651 virtual Local<FunctionTemplate> GetNativeFunctionTemplate( 5652 Isolate* isolate, Local<String> name) { 5653 return Local<FunctionTemplate>(); 5654 } 5655 5656 const char* name() const { return name_; } 5657 size_t source_length() const { return source_length_; } 5658 const String::ExternalOneByteStringResource* source() const { 5659 return &source_; } 5660 int dependency_count() { return dep_count_; } 5661 const char** dependencies() { return deps_; } 5662 void set_auto_enable(bool value) { auto_enable_ = value; } 5663 bool auto_enable() { return auto_enable_; } 5664 5665 // Disallow copying and assigning. 5666 Extension(const Extension&) = delete; 5667 void operator=(const Extension&) = delete; 5668 5669 private: 5670 const char* name_; 5671 size_t source_length_; // expected to initialize before source_ 5672 ExternalOneByteStringResourceImpl source_; 5673 int dep_count_; 5674 const char** deps_; 5675 bool auto_enable_; 5676 }; 5677 5678 5679 void V8_EXPORT RegisterExtension(Extension* extension); 5680 5681 5682 // --- Statics --- 5683 5684 V8_INLINE Local<Primitive> Undefined(Isolate* isolate); 5685 V8_INLINE Local<Primitive> Null(Isolate* isolate); 5686 V8_INLINE Local<Boolean> True(Isolate* isolate); 5687 V8_INLINE Local<Boolean> False(Isolate* isolate); 5688 5689 /** 5690 * A set of constraints that specifies the limits of the runtime's memory use. 5691 * You must set the heap size before initializing the VM - the size cannot be 5692 * adjusted after the VM is initialized. 5693 * 5694 * If you are using threads then you should hold the V8::Locker lock while 5695 * setting the stack limit and you must set a non-default stack limit separately 5696 * for each thread. 5697 * 5698 * The arguments for set_max_semi_space_size, set_max_old_space_size, 5699 * set_max_executable_size, set_code_range_size specify limits in MB. 5700 */ 5701 class V8_EXPORT ResourceConstraints { 5702 public: 5703 ResourceConstraints(); 5704 5705 /** 5706 * Configures the constraints with reasonable default values based on the 5707 * capabilities of the current device the VM is running on. 5708 * 5709 * \param physical_memory The total amount of physical memory on the current 5710 * device, in bytes. 5711 * \param virtual_memory_limit The amount of virtual memory on the current 5712 * device, in bytes, or zero, if there is no limit. 5713 */ 5714 void ConfigureDefaults(uint64_t physical_memory, 5715 uint64_t virtual_memory_limit); 5716 5717 int max_semi_space_size() const { return max_semi_space_size_; } 5718 void set_max_semi_space_size(int limit_in_mb) { 5719 max_semi_space_size_ = limit_in_mb; 5720 } 5721 int max_old_space_size() const { return max_old_space_size_; } 5722 void set_max_old_space_size(int limit_in_mb) { 5723 max_old_space_size_ = limit_in_mb; 5724 } 5725 int max_executable_size() const { return max_executable_size_; } 5726 void set_max_executable_size(int limit_in_mb) { 5727 max_executable_size_ = limit_in_mb; 5728 } 5729 uint32_t* stack_limit() const { return stack_limit_; } 5730 // Sets an address beyond which the VM's stack may not grow. 5731 void set_stack_limit(uint32_t* value) { stack_limit_ = value; } 5732 size_t code_range_size() const { return code_range_size_; } 5733 void set_code_range_size(size_t limit_in_mb) { 5734 code_range_size_ = limit_in_mb; 5735 } 5736 size_t max_zone_pool_size() const { return max_zone_pool_size_; } 5737 void set_max_zone_pool_size(const size_t bytes) { 5738 max_zone_pool_size_ = bytes; 5739 } 5740 5741 private: 5742 int max_semi_space_size_; 5743 int max_old_space_size_; 5744 int max_executable_size_; 5745 uint32_t* stack_limit_; 5746 size_t code_range_size_; 5747 size_t max_zone_pool_size_; 5748 }; 5749 5750 5751 // --- Exceptions --- 5752 5753 5754 typedef void (*FatalErrorCallback)(const char* location, const char* message); 5755 5756 typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom); 5757 5758 typedef void (*MessageCallback)(Local<Message> message, Local<Value> data); 5759 5760 // --- Tracing --- 5761 5762 typedef void (*LogEventCallback)(const char* name, int event); 5763 5764 /** 5765 * Create new error objects by calling the corresponding error object 5766 * constructor with the message. 5767 */ 5768 class V8_EXPORT Exception { 5769 public: 5770 static Local<Value> RangeError(Local<String> message); 5771 static Local<Value> ReferenceError(Local<String> message); 5772 static Local<Value> SyntaxError(Local<String> message); 5773 static Local<Value> TypeError(Local<String> message); 5774 static Local<Value> Error(Local<String> message); 5775 5776 /** 5777 * Creates an error message for the given exception. 5778 * Will try to reconstruct the original stack trace from the exception value, 5779 * or capture the current stack trace if not available. 5780 */ 5781 static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception); 5782 V8_DEPRECATED("Use version with an Isolate*", 5783 static Local<Message> CreateMessage(Local<Value> exception)); 5784 5785 /** 5786 * Returns the original stack trace that was captured at the creation time 5787 * of a given exception, or an empty handle if not available. 5788 */ 5789 static Local<StackTrace> GetStackTrace(Local<Value> exception); 5790 }; 5791 5792 5793 // --- Counters Callbacks --- 5794 5795 typedef int* (*CounterLookupCallback)(const char* name); 5796 5797 typedef void* (*CreateHistogramCallback)(const char* name, 5798 int min, 5799 int max, 5800 size_t buckets); 5801 5802 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample); 5803 5804 // --- Memory Allocation Callback --- 5805 enum ObjectSpace { 5806 kObjectSpaceNewSpace = 1 << 0, 5807 kObjectSpaceOldSpace = 1 << 1, 5808 kObjectSpaceCodeSpace = 1 << 2, 5809 kObjectSpaceMapSpace = 1 << 3, 5810 kObjectSpaceLoSpace = 1 << 4, 5811 kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldSpace | 5812 kObjectSpaceCodeSpace | kObjectSpaceMapSpace | 5813 kObjectSpaceLoSpace 5814 }; 5815 5816 enum AllocationAction { 5817 kAllocationActionAllocate = 1 << 0, 5818 kAllocationActionFree = 1 << 1, 5819 kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree 5820 }; 5821 5822 // --- Enter/Leave Script Callback --- 5823 typedef void (*BeforeCallEnteredCallback)(Isolate*); 5824 typedef void (*CallCompletedCallback)(Isolate*); 5825 typedef void (*DeprecatedCallCompletedCallback)(); 5826 5827 /** 5828 * PromiseHook with type kInit is called when a new promise is 5829 * created. When a new promise is created as part of the chain in the 5830 * case of Promise.then or in the intermediate promises created by 5831 * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise 5832 * otherwise we pass undefined. 5833 * 5834 * PromiseHook with type kResolve is called at the beginning of 5835 * resolve or reject function defined by CreateResolvingFunctions. 5836 * 5837 * PromiseHook with type kBefore is called at the beginning of the 5838 * PromiseReactionJob. 5839 * 5840 * PromiseHook with type kAfter is called right at the end of the 5841 * PromiseReactionJob. 5842 */ 5843 enum class PromiseHookType { kInit, kResolve, kBefore, kAfter }; 5844 5845 typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise, 5846 Local<Value> parent); 5847 5848 // --- Promise Reject Callback --- 5849 enum PromiseRejectEvent { 5850 kPromiseRejectWithNoHandler = 0, 5851 kPromiseHandlerAddedAfterReject = 1 5852 }; 5853 5854 class PromiseRejectMessage { 5855 public: 5856 PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event, 5857 Local<Value> value, Local<StackTrace> stack_trace) 5858 : promise_(promise), 5859 event_(event), 5860 value_(value), 5861 stack_trace_(stack_trace) {} 5862 5863 V8_INLINE Local<Promise> GetPromise() const { return promise_; } 5864 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; } 5865 V8_INLINE Local<Value> GetValue() const { return value_; } 5866 5867 V8_DEPRECATED("Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()", 5868 V8_INLINE Local<StackTrace> GetStackTrace() const) { 5869 return stack_trace_; 5870 } 5871 5872 private: 5873 Local<Promise> promise_; 5874 PromiseRejectEvent event_; 5875 Local<Value> value_; 5876 Local<StackTrace> stack_trace_; 5877 }; 5878 5879 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message); 5880 5881 // --- Microtasks Callbacks --- 5882 typedef void (*MicrotasksCompletedCallback)(Isolate*); 5883 typedef void (*MicrotaskCallback)(void* data); 5884 5885 5886 /** 5887 * Policy for running microtasks: 5888 * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method; 5889 * - scoped: microtasks invocation is controlled by MicrotasksScope objects; 5890 * - auto: microtasks are invoked when the script call depth decrements 5891 * to zero. 5892 */ 5893 enum class MicrotasksPolicy { kExplicit, kScoped, kAuto }; 5894 5895 5896 /** 5897 * This scope is used to control microtasks when kScopeMicrotasksInvocation 5898 * is used on Isolate. In this mode every non-primitive call to V8 should be 5899 * done inside some MicrotasksScope. 5900 * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks 5901 * exits. 5902 * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger 5903 * microtasks. 5904 */ 5905 class V8_EXPORT MicrotasksScope { 5906 public: 5907 enum Type { kRunMicrotasks, kDoNotRunMicrotasks }; 5908 5909 MicrotasksScope(Isolate* isolate, Type type); 5910 ~MicrotasksScope(); 5911 5912 /** 5913 * Runs microtasks if no kRunMicrotasks scope is currently active. 5914 */ 5915 static void PerformCheckpoint(Isolate* isolate); 5916 5917 /** 5918 * Returns current depth of nested kRunMicrotasks scopes. 5919 */ 5920 static int GetCurrentDepth(Isolate* isolate); 5921 5922 /** 5923 * Returns true while microtasks are being executed. 5924 */ 5925 static bool IsRunningMicrotasks(Isolate* isolate); 5926 5927 // Prevent copying. 5928 MicrotasksScope(const MicrotasksScope&) = delete; 5929 MicrotasksScope& operator=(const MicrotasksScope&) = delete; 5930 5931 private: 5932 internal::Isolate* const isolate_; 5933 bool run_; 5934 }; 5935 5936 5937 // --- Failed Access Check Callback --- 5938 typedef void (*FailedAccessCheckCallback)(Local<Object> target, 5939 AccessType type, 5940 Local<Value> data); 5941 5942 // --- AllowCodeGenerationFromStrings callbacks --- 5943 5944 /** 5945 * Callback to check if code generation from strings is allowed. See 5946 * Context::AllowCodeGenerationFromStrings. 5947 */ 5948 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context); 5949 5950 // --- WASM compilation callbacks --- 5951 5952 /** 5953 * Callback to check if a buffer source may be compiled to WASM, given 5954 * the compilation is attempted as a promise or not. 5955 */ 5956 5957 typedef bool (*AllowWasmCompileCallback)(Isolate* isolate, Local<Value> source, 5958 bool as_promise); 5959 5960 typedef bool (*AllowWasmInstantiateCallback)(Isolate* isolate, 5961 Local<Value> module_or_bytes, 5962 MaybeLocal<Value> ffi, 5963 bool as_promise); 5964 5965 // --- Garbage Collection Callbacks --- 5966 5967 /** 5968 * Applications can register callback functions which will be called before and 5969 * after certain garbage collection operations. Allocations are not allowed in 5970 * the callback functions, you therefore cannot manipulate objects (set or 5971 * delete properties for example) since it is possible such operations will 5972 * result in the allocation of objects. 5973 */ 5974 enum GCType { 5975 kGCTypeScavenge = 1 << 0, 5976 kGCTypeMarkSweepCompact = 1 << 1, 5977 kGCTypeIncrementalMarking = 1 << 2, 5978 kGCTypeProcessWeakCallbacks = 1 << 3, 5979 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact | 5980 kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks 5981 }; 5982 5983 /** 5984 * GCCallbackFlags is used to notify additional information about the GC 5985 * callback. 5986 * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for 5987 * constructing retained object infos. 5988 * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing. 5989 * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback 5990 * is called synchronously without getting posted to an idle task. 5991 * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called 5992 * in a phase where V8 is trying to collect all available garbage 5993 * (e.g., handling a low memory notification). 5994 */ 5995 enum GCCallbackFlags { 5996 kNoGCCallbackFlags = 0, 5997 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1, 5998 kGCCallbackFlagForced = 1 << 2, 5999 kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3, 6000 kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4, 6001 kGCCallbackFlagCollectAllExternalMemory = 1 << 5, 6002 }; 6003 6004 typedef void (*GCCallback)(GCType type, GCCallbackFlags flags); 6005 6006 typedef void (*InterruptCallback)(Isolate* isolate, void* data); 6007 6008 6009 /** 6010 * Collection of V8 heap information. 6011 * 6012 * Instances of this class can be passed to v8::V8::HeapStatistics to 6013 * get heap statistics from V8. 6014 */ 6015 class V8_EXPORT HeapStatistics { 6016 public: 6017 HeapStatistics(); 6018 size_t total_heap_size() { return total_heap_size_; } 6019 size_t total_heap_size_executable() { return total_heap_size_executable_; } 6020 size_t total_physical_size() { return total_physical_size_; } 6021 size_t total_available_size() { return total_available_size_; } 6022 size_t used_heap_size() { return used_heap_size_; } 6023 size_t heap_size_limit() { return heap_size_limit_; } 6024 size_t malloced_memory() { return malloced_memory_; } 6025 size_t peak_malloced_memory() { return peak_malloced_memory_; } 6026 size_t does_zap_garbage() { return does_zap_garbage_; } 6027 6028 private: 6029 size_t total_heap_size_; 6030 size_t total_heap_size_executable_; 6031 size_t total_physical_size_; 6032 size_t total_available_size_; 6033 size_t used_heap_size_; 6034 size_t heap_size_limit_; 6035 size_t malloced_memory_; 6036 size_t peak_malloced_memory_; 6037 bool does_zap_garbage_; 6038 6039 friend class V8; 6040 friend class Isolate; 6041 }; 6042 6043 6044 class V8_EXPORT HeapSpaceStatistics { 6045 public: 6046 HeapSpaceStatistics(); 6047 const char* space_name() { return space_name_; } 6048 size_t space_size() { return space_size_; } 6049 size_t space_used_size() { return space_used_size_; } 6050 size_t space_available_size() { return space_available_size_; } 6051 size_t physical_space_size() { return physical_space_size_; } 6052 6053 private: 6054 const char* space_name_; 6055 size_t space_size_; 6056 size_t space_used_size_; 6057 size_t space_available_size_; 6058 size_t physical_space_size_; 6059 6060 friend class Isolate; 6061 }; 6062 6063 6064 class V8_EXPORT HeapObjectStatistics { 6065 public: 6066 HeapObjectStatistics(); 6067 const char* object_type() { return object_type_; } 6068 const char* object_sub_type() { return object_sub_type_; } 6069 size_t object_count() { return object_count_; } 6070 size_t object_size() { return object_size_; } 6071 6072 private: 6073 const char* object_type_; 6074 const char* object_sub_type_; 6075 size_t object_count_; 6076 size_t object_size_; 6077 6078 friend class Isolate; 6079 }; 6080 6081 class V8_EXPORT HeapCodeStatistics { 6082 public: 6083 HeapCodeStatistics(); 6084 size_t code_and_metadata_size() { return code_and_metadata_size_; } 6085 size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; } 6086 6087 private: 6088 size_t code_and_metadata_size_; 6089 size_t bytecode_and_metadata_size_; 6090 6091 friend class Isolate; 6092 }; 6093 6094 class RetainedObjectInfo; 6095 6096 6097 /** 6098 * FunctionEntryHook is the type of the profile entry hook called at entry to 6099 * any generated function when function-level profiling is enabled. 6100 * 6101 * \param function the address of the function that's being entered. 6102 * \param return_addr_location points to a location on stack where the machine 6103 * return address resides. This can be used to identify the caller of 6104 * \p function, and/or modified to divert execution when \p function exits. 6105 * 6106 * \note the entry hook must not cause garbage collection. 6107 */ 6108 typedef void (*FunctionEntryHook)(uintptr_t function, 6109 uintptr_t return_addr_location); 6110 6111 /** 6112 * A JIT code event is issued each time code is added, moved or removed. 6113 * 6114 * \note removal events are not currently issued. 6115 */ 6116 struct JitCodeEvent { 6117 enum EventType { 6118 CODE_ADDED, 6119 CODE_MOVED, 6120 CODE_REMOVED, 6121 CODE_ADD_LINE_POS_INFO, 6122 CODE_START_LINE_INFO_RECORDING, 6123 CODE_END_LINE_INFO_RECORDING 6124 }; 6125 // Definition of the code position type. The "POSITION" type means the place 6126 // in the source code which are of interest when making stack traces to 6127 // pin-point the source location of a stack frame as close as possible. 6128 // The "STATEMENT_POSITION" means the place at the beginning of each 6129 // statement, and is used to indicate possible break locations. 6130 enum PositionType { POSITION, STATEMENT_POSITION }; 6131 6132 // Type of event. 6133 EventType type; 6134 // Start of the instructions. 6135 void* code_start; 6136 // Size of the instructions. 6137 size_t code_len; 6138 // Script info for CODE_ADDED event. 6139 Local<UnboundScript> script; 6140 // User-defined data for *_LINE_INFO_* event. It's used to hold the source 6141 // code line information which is returned from the 6142 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent 6143 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events. 6144 void* user_data; 6145 6146 struct name_t { 6147 // Name of the object associated with the code, note that the string is not 6148 // zero-terminated. 6149 const char* str; 6150 // Number of chars in str. 6151 size_t len; 6152 }; 6153 6154 struct line_info_t { 6155 // PC offset 6156 size_t offset; 6157 // Code postion 6158 size_t pos; 6159 // The position type. 6160 PositionType position_type; 6161 }; 6162 6163 union { 6164 // Only valid for CODE_ADDED. 6165 struct name_t name; 6166 6167 // Only valid for CODE_ADD_LINE_POS_INFO 6168 struct line_info_t line_info; 6169 6170 // New location of instructions. Only valid for CODE_MOVED. 6171 void* new_code_start; 6172 }; 6173 }; 6174 6175 /** 6176 * Option flags passed to the SetRAILMode function. 6177 * See documentation https://developers.google.com/web/tools/chrome-devtools/ 6178 * profile/evaluate-performance/rail 6179 */ 6180 enum RAILMode { 6181 // Response performance mode: In this mode very low virtual machine latency 6182 // is provided. V8 will try to avoid JavaScript execution interruptions. 6183 // Throughput may be throttled. 6184 PERFORMANCE_RESPONSE, 6185 // Animation performance mode: In this mode low virtual machine latency is 6186 // provided. V8 will try to avoid as many JavaScript execution interruptions 6187 // as possible. Throughput may be throttled. This is the default mode. 6188 PERFORMANCE_ANIMATION, 6189 // Idle performance mode: The embedder is idle. V8 can complete deferred work 6190 // in this mode. 6191 PERFORMANCE_IDLE, 6192 // Load performance mode: In this mode high throughput is provided. V8 may 6193 // turn off latency optimizations. 6194 PERFORMANCE_LOAD 6195 }; 6196 6197 /** 6198 * Option flags passed to the SetJitCodeEventHandler function. 6199 */ 6200 enum JitCodeEventOptions { 6201 kJitCodeEventDefault = 0, 6202 // Generate callbacks for already existent code. 6203 kJitCodeEventEnumExisting = 1 6204 }; 6205 6206 6207 /** 6208 * Callback function passed to SetJitCodeEventHandler. 6209 * 6210 * \param event code add, move or removal event. 6211 */ 6212 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event); 6213 6214 6215 /** 6216 * Interface for iterating through all external resources in the heap. 6217 */ 6218 class V8_EXPORT ExternalResourceVisitor { // NOLINT 6219 public: 6220 virtual ~ExternalResourceVisitor() {} 6221 virtual void VisitExternalString(Local<String> string) {} 6222 }; 6223 6224 6225 /** 6226 * Interface for iterating through all the persistent handles in the heap. 6227 */ 6228 class V8_EXPORT PersistentHandleVisitor { // NOLINT 6229 public: 6230 virtual ~PersistentHandleVisitor() {} 6231 virtual void VisitPersistentHandle(Persistent<Value>* value, 6232 uint16_t class_id) {} 6233 }; 6234 6235 /** 6236 * Memory pressure level for the MemoryPressureNotification. 6237 * kNone hints V8 that there is no memory pressure. 6238 * kModerate hints V8 to speed up incremental garbage collection at the cost of 6239 * of higher latency due to garbage collection pauses. 6240 * kCritical hints V8 to free memory as soon as possible. Garbage collection 6241 * pauses at this level will be large. 6242 */ 6243 enum class MemoryPressureLevel { kNone, kModerate, kCritical }; 6244 6245 /** 6246 * Interface for tracing through the embedder heap. During a v8 garbage 6247 * collection, v8 collects hidden fields of all potential wrappers, and at the 6248 * end of its marking phase iterates the collection and asks the embedder to 6249 * trace through its heap and use reporter to report each JavaScript object 6250 * reachable from any of the given wrappers. 6251 * 6252 * Before the first call to the TraceWrappersFrom function TracePrologue will be 6253 * called. When the garbage collection cycle is finished, TraceEpilogue will be 6254 * called. 6255 */ 6256 class V8_EXPORT EmbedderHeapTracer { 6257 public: 6258 enum ForceCompletionAction { FORCE_COMPLETION, DO_NOT_FORCE_COMPLETION }; 6259 6260 struct AdvanceTracingActions { 6261 explicit AdvanceTracingActions(ForceCompletionAction force_completion_) 6262 : force_completion(force_completion_) {} 6263 6264 ForceCompletionAction force_completion; 6265 }; 6266 6267 /** 6268 * Called by v8 to register internal fields of found wrappers. 6269 * 6270 * The embedder is expected to store them somewhere and trace reachable 6271 * wrappers from them when called through |AdvanceTracing|. 6272 */ 6273 virtual void RegisterV8References( 6274 const std::vector<std::pair<void*, void*> >& internal_fields) = 0; 6275 6276 /** 6277 * Called at the beginning of a GC cycle. 6278 */ 6279 virtual void TracePrologue() = 0; 6280 6281 /** 6282 * Called to to make a tracing step in the embedder. 6283 * 6284 * The embedder is expected to trace its heap starting from wrappers reported 6285 * by RegisterV8References method, and report back all reachable wrappers. 6286 * Furthermore, the embedder is expected to stop tracing by the given 6287 * deadline. 6288 * 6289 * Returns true if there is still work to do. 6290 */ 6291 virtual bool AdvanceTracing(double deadline_in_ms, 6292 AdvanceTracingActions actions) = 0; 6293 6294 /** 6295 * Called at the end of a GC cycle. 6296 * 6297 * Note that allocation is *not* allowed within |TraceEpilogue|. 6298 */ 6299 virtual void TraceEpilogue() = 0; 6300 6301 /** 6302 * Called upon entering the final marking pause. No more incremental marking 6303 * steps will follow this call. 6304 */ 6305 virtual void EnterFinalPause() = 0; 6306 6307 /** 6308 * Called when tracing is aborted. 6309 * 6310 * The embedder is expected to throw away all intermediate data and reset to 6311 * the initial state. 6312 */ 6313 virtual void AbortTracing() = 0; 6314 6315 /** 6316 * Returns the number of wrappers that are still to be traced by the embedder. 6317 */ 6318 virtual size_t NumberOfWrappersToTrace() { return 0; } 6319 6320 protected: 6321 virtual ~EmbedderHeapTracer() = default; 6322 }; 6323 6324 /** 6325 * Callback and supporting data used in SnapshotCreator to implement embedder 6326 * logic to serialize internal fields. 6327 */ 6328 struct SerializeInternalFieldsCallback { 6329 typedef StartupData (*CallbackFunction)(Local<Object> holder, int index, 6330 void* data); 6331 SerializeInternalFieldsCallback(CallbackFunction function = nullptr, 6332 void* data_arg = nullptr) 6333 : callback(function), data(data_arg) {} 6334 CallbackFunction callback; 6335 void* data; 6336 }; 6337 6338 /** 6339 * Callback and supporting data used to implement embedder logic to deserialize 6340 * internal fields. 6341 */ 6342 struct DeserializeInternalFieldsCallback { 6343 typedef void (*CallbackFunction)(Local<Object> holder, int index, 6344 StartupData payload, void* data); 6345 DeserializeInternalFieldsCallback(CallbackFunction function = nullptr, 6346 void* data_arg = nullptr) 6347 : callback(function), data(data_arg) {} 6348 void (*callback)(Local<Object> holder, int index, StartupData payload, 6349 void* data); 6350 void* data; 6351 }; 6352 6353 /** 6354 * Isolate represents an isolated instance of the V8 engine. V8 isolates have 6355 * completely separate states. Objects from one isolate must not be used in 6356 * other isolates. The embedder can create multiple isolates and use them in 6357 * parallel in multiple threads. An isolate can be entered by at most one 6358 * thread at any given time. The Locker/Unlocker API must be used to 6359 * synchronize. 6360 */ 6361 class V8_EXPORT Isolate { 6362 public: 6363 /** 6364 * Initial configuration parameters for a new Isolate. 6365 */ 6366 struct CreateParams { 6367 CreateParams() 6368 : entry_hook(nullptr), 6369 code_event_handler(nullptr), 6370 snapshot_blob(nullptr), 6371 counter_lookup_callback(nullptr), 6372 create_histogram_callback(nullptr), 6373 add_histogram_sample_callback(nullptr), 6374 array_buffer_allocator(nullptr), 6375 external_references(nullptr), 6376 allow_atomics_wait(true) {} 6377 6378 /** 6379 * The optional entry_hook allows the host application to provide the 6380 * address of a function that's invoked on entry to every V8-generated 6381 * function. Note that entry_hook is invoked at the very start of each 6382 * generated function. Furthermore, if an entry_hook is given, V8 will 6383 * not use a snapshot, including custom snapshots. 6384 */ 6385 FunctionEntryHook entry_hook; 6386 6387 /** 6388 * Allows the host application to provide the address of a function that is 6389 * notified each time code is added, moved or removed. 6390 */ 6391 JitCodeEventHandler code_event_handler; 6392 6393 /** 6394 * ResourceConstraints to use for the new Isolate. 6395 */ 6396 ResourceConstraints constraints; 6397 6398 /** 6399 * Explicitly specify a startup snapshot blob. The embedder owns the blob. 6400 */ 6401 StartupData* snapshot_blob; 6402 6403 6404 /** 6405 * Enables the host application to provide a mechanism for recording 6406 * statistics counters. 6407 */ 6408 CounterLookupCallback counter_lookup_callback; 6409 6410 /** 6411 * Enables the host application to provide a mechanism for recording 6412 * histograms. The CreateHistogram function returns a 6413 * histogram which will later be passed to the AddHistogramSample 6414 * function. 6415 */ 6416 CreateHistogramCallback create_histogram_callback; 6417 AddHistogramSampleCallback add_histogram_sample_callback; 6418 6419 /** 6420 * The ArrayBuffer::Allocator to use for allocating and freeing the backing 6421 * store of ArrayBuffers. 6422 */ 6423 ArrayBuffer::Allocator* array_buffer_allocator; 6424 6425 /** 6426 * Specifies an optional nullptr-terminated array of raw addresses in the 6427 * embedder that V8 can match against during serialization and use for 6428 * deserialization. This array and its content must stay valid for the 6429 * entire lifetime of the isolate. 6430 */ 6431 intptr_t* external_references; 6432 6433 /** 6434 * Whether calling Atomics.wait (a function that may block) is allowed in 6435 * this isolate. 6436 */ 6437 bool allow_atomics_wait; 6438 }; 6439 6440 6441 /** 6442 * Stack-allocated class which sets the isolate for all operations 6443 * executed within a local scope. 6444 */ 6445 class V8_EXPORT Scope { 6446 public: 6447 explicit Scope(Isolate* isolate) : isolate_(isolate) { 6448 isolate->Enter(); 6449 } 6450 6451 ~Scope() { isolate_->Exit(); } 6452 6453 // Prevent copying of Scope objects. 6454 Scope(const Scope&) = delete; 6455 Scope& operator=(const Scope&) = delete; 6456 6457 private: 6458 Isolate* const isolate_; 6459 }; 6460 6461 6462 /** 6463 * Assert that no Javascript code is invoked. 6464 */ 6465 class V8_EXPORT DisallowJavascriptExecutionScope { 6466 public: 6467 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE }; 6468 6469 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure); 6470 ~DisallowJavascriptExecutionScope(); 6471 6472 // Prevent copying of Scope objects. 6473 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) = 6474 delete; 6475 DisallowJavascriptExecutionScope& operator=( 6476 const DisallowJavascriptExecutionScope&) = delete; 6477 6478 private: 6479 bool on_failure_; 6480 void* internal_; 6481 }; 6482 6483 6484 /** 6485 * Introduce exception to DisallowJavascriptExecutionScope. 6486 */ 6487 class V8_EXPORT AllowJavascriptExecutionScope { 6488 public: 6489 explicit AllowJavascriptExecutionScope(Isolate* isolate); 6490 ~AllowJavascriptExecutionScope(); 6491 6492 // Prevent copying of Scope objects. 6493 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) = 6494 delete; 6495 AllowJavascriptExecutionScope& operator=( 6496 const AllowJavascriptExecutionScope&) = delete; 6497 6498 private: 6499 void* internal_throws_; 6500 void* internal_assert_; 6501 }; 6502 6503 /** 6504 * Do not run microtasks while this scope is active, even if microtasks are 6505 * automatically executed otherwise. 6506 */ 6507 class V8_EXPORT SuppressMicrotaskExecutionScope { 6508 public: 6509 explicit SuppressMicrotaskExecutionScope(Isolate* isolate); 6510 ~SuppressMicrotaskExecutionScope(); 6511 6512 // Prevent copying of Scope objects. 6513 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) = 6514 delete; 6515 SuppressMicrotaskExecutionScope& operator=( 6516 const SuppressMicrotaskExecutionScope&) = delete; 6517 6518 private: 6519 internal::Isolate* const isolate_; 6520 }; 6521 6522 /** 6523 * Types of garbage collections that can be requested via 6524 * RequestGarbageCollectionForTesting. 6525 */ 6526 enum GarbageCollectionType { 6527 kFullGarbageCollection, 6528 kMinorGarbageCollection 6529 }; 6530 6531 /** 6532 * Features reported via the SetUseCounterCallback callback. Do not change 6533 * assigned numbers of existing items; add new features to the end of this 6534 * list. 6535 */ 6536 enum UseCounterFeature { 6537 kUseAsm = 0, 6538 kBreakIterator = 1, 6539 kLegacyConst = 2, 6540 kMarkDequeOverflow = 3, 6541 kStoreBufferOverflow = 4, 6542 kSlotsBufferOverflow = 5, 6543 kObjectObserve = 6, 6544 kForcedGC = 7, 6545 kSloppyMode = 8, 6546 kStrictMode = 9, 6547 kStrongMode = 10, 6548 kRegExpPrototypeStickyGetter = 11, 6549 kRegExpPrototypeToString = 12, 6550 kRegExpPrototypeUnicodeGetter = 13, 6551 kIntlV8Parse = 14, 6552 kIntlPattern = 15, 6553 kIntlResolved = 16, 6554 kPromiseChain = 17, 6555 kPromiseAccept = 18, 6556 kPromiseDefer = 19, 6557 kHtmlCommentInExternalScript = 20, 6558 kHtmlComment = 21, 6559 kSloppyModeBlockScopedFunctionRedefinition = 22, 6560 kForInInitializer = 23, 6561 kArrayProtectorDirtied = 24, 6562 kArraySpeciesModified = 25, 6563 kArrayPrototypeConstructorModified = 26, 6564 kArrayInstanceProtoModified = 27, 6565 kArrayInstanceConstructorModified = 28, 6566 kLegacyFunctionDeclaration = 29, 6567 kRegExpPrototypeSourceGetter = 30, 6568 kRegExpPrototypeOldFlagGetter = 31, 6569 kDecimalWithLeadingZeroInStrictMode = 32, 6570 kLegacyDateParser = 33, 6571 kDefineGetterOrSetterWouldThrow = 34, 6572 kFunctionConstructorReturnedUndefined = 35, 6573 kAssigmentExpressionLHSIsCallInSloppy = 36, 6574 kAssigmentExpressionLHSIsCallInStrict = 37, 6575 kPromiseConstructorReturnedUndefined = 38, 6576 6577 // If you add new values here, you'll also need to update Chromium's: 6578 // UseCounter.h, V8PerIsolateData.cpp, histograms.xml 6579 kUseCounterFeatureCount // This enum value must be last. 6580 }; 6581 6582 enum MessageErrorLevel { 6583 kMessageLog = (1 << 0), 6584 kMessageDebug = (1 << 1), 6585 kMessageInfo = (1 << 2), 6586 kMessageError = (1 << 3), 6587 kMessageWarning = (1 << 4), 6588 kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError | 6589 kMessageWarning, 6590 }; 6591 6592 typedef void (*UseCounterCallback)(Isolate* isolate, 6593 UseCounterFeature feature); 6594 6595 6596 /** 6597 * Creates a new isolate. Does not change the currently entered 6598 * isolate. 6599 * 6600 * When an isolate is no longer used its resources should be freed 6601 * by calling Dispose(). Using the delete operator is not allowed. 6602 * 6603 * V8::Initialize() must have run prior to this. 6604 */ 6605 static Isolate* New(const CreateParams& params); 6606 6607 /** 6608 * Returns the entered isolate for the current thread or NULL in 6609 * case there is no current isolate. 6610 * 6611 * This method must not be invoked before V8::Initialize() was invoked. 6612 */ 6613 static Isolate* GetCurrent(); 6614 6615 /** 6616 * Custom callback used by embedders to help V8 determine if it should abort 6617 * when it throws and no internal handler is predicted to catch the 6618 * exception. If --abort-on-uncaught-exception is used on the command line, 6619 * then V8 will abort if either: 6620 * - no custom callback is set. 6621 * - the custom callback set returns true. 6622 * Otherwise, the custom callback will not be called and V8 will not abort. 6623 */ 6624 typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*); 6625 void SetAbortOnUncaughtExceptionCallback( 6626 AbortOnUncaughtExceptionCallback callback); 6627 6628 /** 6629 * Optional notification that the system is running low on memory. 6630 * V8 uses these notifications to guide heuristics. 6631 * It is allowed to call this function from another thread while 6632 * the isolate is executing long running JavaScript code. 6633 */ 6634 void MemoryPressureNotification(MemoryPressureLevel level); 6635 6636 /** 6637 * Methods below this point require holding a lock (using Locker) in 6638 * a multi-threaded environment. 6639 */ 6640 6641 /** 6642 * Sets this isolate as the entered one for the current thread. 6643 * Saves the previously entered one (if any), so that it can be 6644 * restored when exiting. Re-entering an isolate is allowed. 6645 */ 6646 void Enter(); 6647 6648 /** 6649 * Exits this isolate by restoring the previously entered one in the 6650 * current thread. The isolate may still stay the same, if it was 6651 * entered more than once. 6652 * 6653 * Requires: this == Isolate::GetCurrent(). 6654 */ 6655 void Exit(); 6656 6657 /** 6658 * Disposes the isolate. The isolate must not be entered by any 6659 * thread to be disposable. 6660 */ 6661 void Dispose(); 6662 6663 /** 6664 * Discards all V8 thread-specific data for the Isolate. Should be used 6665 * if a thread is terminating and it has used an Isolate that will outlive 6666 * the thread -- all thread-specific data for an Isolate is discarded when 6667 * an Isolate is disposed so this call is pointless if an Isolate is about 6668 * to be Disposed. 6669 */ 6670 void DiscardThreadSpecificMetadata(); 6671 6672 /** 6673 * Associate embedder-specific data with the isolate. |slot| has to be 6674 * between 0 and GetNumberOfDataSlots() - 1. 6675 */ 6676 V8_INLINE void SetData(uint32_t slot, void* data); 6677 6678 /** 6679 * Retrieve embedder-specific data from the isolate. 6680 * Returns NULL if SetData has never been called for the given |slot|. 6681 */ 6682 V8_INLINE void* GetData(uint32_t slot); 6683 6684 /** 6685 * Returns the maximum number of available embedder data slots. Valid slots 6686 * are in the range of 0 - GetNumberOfDataSlots() - 1. 6687 */ 6688 V8_INLINE static uint32_t GetNumberOfDataSlots(); 6689 6690 /** 6691 * Get statistics about the heap memory usage. 6692 */ 6693 void GetHeapStatistics(HeapStatistics* heap_statistics); 6694 6695 /** 6696 * Returns the number of spaces in the heap. 6697 */ 6698 size_t NumberOfHeapSpaces(); 6699 6700 /** 6701 * Get the memory usage of a space in the heap. 6702 * 6703 * \param space_statistics The HeapSpaceStatistics object to fill in 6704 * statistics. 6705 * \param index The index of the space to get statistics from, which ranges 6706 * from 0 to NumberOfHeapSpaces() - 1. 6707 * \returns true on success. 6708 */ 6709 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics, 6710 size_t index); 6711 6712 /** 6713 * Returns the number of types of objects tracked in the heap at GC. 6714 */ 6715 size_t NumberOfTrackedHeapObjectTypes(); 6716 6717 /** 6718 * Get statistics about objects in the heap. 6719 * 6720 * \param object_statistics The HeapObjectStatistics object to fill in 6721 * statistics of objects of given type, which were live in the previous GC. 6722 * \param type_index The index of the type of object to fill details about, 6723 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1. 6724 * \returns true on success. 6725 */ 6726 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics, 6727 size_t type_index); 6728 6729 /** 6730 * Get statistics about code and its metadata in the heap. 6731 * 6732 * \param object_statistics The HeapCodeStatistics object to fill in 6733 * statistics of code, bytecode and their metadata. 6734 * \returns true on success. 6735 */ 6736 bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics); 6737 6738 /** 6739 * Get a call stack sample from the isolate. 6740 * \param state Execution state. 6741 * \param frames Caller allocated buffer to store stack frames. 6742 * \param frames_limit Maximum number of frames to capture. The buffer must 6743 * be large enough to hold the number of frames. 6744 * \param sample_info The sample info is filled up by the function 6745 * provides number of actual captured stack frames and 6746 * the current VM state. 6747 * \note GetStackSample should only be called when the JS thread is paused or 6748 * interrupted. Otherwise the behavior is undefined. 6749 */ 6750 void GetStackSample(const RegisterState& state, void** frames, 6751 size_t frames_limit, SampleInfo* sample_info); 6752 6753 /** 6754 * Adjusts the amount of registered external memory. Used to give V8 an 6755 * indication of the amount of externally allocated memory that is kept alive 6756 * by JavaScript objects. V8 uses this to decide when to perform global 6757 * garbage collections. Registering externally allocated memory will trigger 6758 * global garbage collections more often than it would otherwise in an attempt 6759 * to garbage collect the JavaScript objects that keep the externally 6760 * allocated memory alive. 6761 * 6762 * \param change_in_bytes the change in externally allocated memory that is 6763 * kept alive by JavaScript objects. 6764 * \returns the adjusted value. 6765 */ 6766 V8_INLINE int64_t 6767 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes); 6768 6769 /** 6770 * Returns the number of phantom handles without callbacks that were reset 6771 * by the garbage collector since the last call to this function. 6772 */ 6773 size_t NumberOfPhantomHandleResetsSinceLastCall(); 6774 6775 /** 6776 * Returns heap profiler for this isolate. Will return NULL until the isolate 6777 * is initialized. 6778 */ 6779 HeapProfiler* GetHeapProfiler(); 6780 6781 /** 6782 * Returns CPU profiler for this isolate. Will return NULL unless the isolate 6783 * is initialized. It is the embedder's responsibility to stop all CPU 6784 * profiling activities if it has started any. 6785 */ 6786 V8_DEPRECATE_SOON("CpuProfiler should be created with CpuProfiler::New call.", 6787 CpuProfiler* GetCpuProfiler()); 6788 6789 /** Returns true if this isolate has a current context. */ 6790 bool InContext(); 6791 6792 /** 6793 * Returns the context of the currently running JavaScript, or the context 6794 * on the top of the stack if no JavaScript is running. 6795 */ 6796 Local<Context> GetCurrentContext(); 6797 6798 /** 6799 * Returns the context of the calling JavaScript code. That is the 6800 * context of the top-most JavaScript frame. If there are no 6801 * JavaScript frames an empty handle is returned. 6802 */ 6803 V8_DEPRECATE_SOON( 6804 "Calling context concept is not compatible with tail calls, and will be " 6805 "removed.", 6806 Local<Context> GetCallingContext()); 6807 6808 /** Returns the last context entered through V8's C++ API. */ 6809 Local<Context> GetEnteredContext(); 6810 6811 /** 6812 * Returns either the last context entered through V8's C++ API, or the 6813 * context of the currently running microtask while processing microtasks. 6814 * If a context is entered while executing a microtask, that context is 6815 * returned. 6816 */ 6817 Local<Context> GetEnteredOrMicrotaskContext(); 6818 6819 /** 6820 * Schedules an exception to be thrown when returning to JavaScript. When an 6821 * exception has been scheduled it is illegal to invoke any JavaScript 6822 * operation; the caller must return immediately and only after the exception 6823 * has been handled does it become legal to invoke JavaScript operations. 6824 */ 6825 Local<Value> ThrowException(Local<Value> exception); 6826 6827 /** 6828 * Allows the host application to group objects together. If one 6829 * object in the group is alive, all objects in the group are alive. 6830 * After each garbage collection, object groups are removed. It is 6831 * intended to be used in the before-garbage-collection callback 6832 * function, for instance to simulate DOM tree connections among JS 6833 * wrapper objects. Object groups for all dependent handles need to 6834 * be provided for kGCTypeMarkSweepCompact collections, for all other 6835 * garbage collection types it is sufficient to provide object groups 6836 * for partially dependent handles only. 6837 */ 6838 template <typename T> 6839 V8_DEPRECATED("Use EmbedderHeapTracer", 6840 void SetObjectGroupId(const Persistent<T>& object, 6841 UniqueId id)); 6842 6843 /** 6844 * Allows the host application to declare implicit references from an object 6845 * group to an object. If the objects of the object group are alive, the child 6846 * object is alive too. After each garbage collection, all implicit references 6847 * are removed. It is intended to be used in the before-garbage-collection 6848 * callback function. 6849 */ 6850 template <typename T> 6851 V8_DEPRECATED("Use EmbedderHeapTracer", 6852 void SetReferenceFromGroup(UniqueId id, 6853 const Persistent<T>& child)); 6854 6855 /** 6856 * Allows the host application to declare implicit references from an object 6857 * to another object. If the parent object is alive, the child object is alive 6858 * too. After each garbage collection, all implicit references are removed. It 6859 * is intended to be used in the before-garbage-collection callback function. 6860 */ 6861 template <typename T, typename S> 6862 V8_DEPRECATED("Use EmbedderHeapTracer", 6863 void SetReference(const Persistent<T>& parent, 6864 const Persistent<S>& child)); 6865 6866 typedef void (*GCCallback)(Isolate* isolate, GCType type, 6867 GCCallbackFlags flags); 6868 6869 /** 6870 * Enables the host application to receive a notification before a 6871 * garbage collection. Allocations are allowed in the callback function, 6872 * but the callback is not re-entrant: if the allocation inside it will 6873 * trigger the garbage collection, the callback won't be called again. 6874 * It is possible to specify the GCType filter for your callback. But it is 6875 * not possible to register the same callback function two times with 6876 * different GCType filters. 6877 */ 6878 void AddGCPrologueCallback(GCCallback callback, 6879 GCType gc_type_filter = kGCTypeAll); 6880 6881 /** 6882 * This function removes callback which was installed by 6883 * AddGCPrologueCallback function. 6884 */ 6885 void RemoveGCPrologueCallback(GCCallback callback); 6886 6887 /** 6888 * Sets the embedder heap tracer for the isolate. 6889 */ 6890 void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer); 6891 6892 /** 6893 * Enables the host application to receive a notification after a 6894 * garbage collection. Allocations are allowed in the callback function, 6895 * but the callback is not re-entrant: if the allocation inside it will 6896 * trigger the garbage collection, the callback won't be called again. 6897 * It is possible to specify the GCType filter for your callback. But it is 6898 * not possible to register the same callback function two times with 6899 * different GCType filters. 6900 */ 6901 void AddGCEpilogueCallback(GCCallback callback, 6902 GCType gc_type_filter = kGCTypeAll); 6903 6904 /** 6905 * This function removes callback which was installed by 6906 * AddGCEpilogueCallback function. 6907 */ 6908 void RemoveGCEpilogueCallback(GCCallback callback); 6909 6910 /** 6911 * Forcefully terminate the current thread of JavaScript execution 6912 * in the given isolate. 6913 * 6914 * This method can be used by any thread even if that thread has not 6915 * acquired the V8 lock with a Locker object. 6916 */ 6917 void TerminateExecution(); 6918 6919 /** 6920 * Is V8 terminating JavaScript execution. 6921 * 6922 * Returns true if JavaScript execution is currently terminating 6923 * because of a call to TerminateExecution. In that case there are 6924 * still JavaScript frames on the stack and the termination 6925 * exception is still active. 6926 */ 6927 bool IsExecutionTerminating(); 6928 6929 /** 6930 * Resume execution capability in the given isolate, whose execution 6931 * was previously forcefully terminated using TerminateExecution(). 6932 * 6933 * When execution is forcefully terminated using TerminateExecution(), 6934 * the isolate can not resume execution until all JavaScript frames 6935 * have propagated the uncatchable exception which is generated. This 6936 * method allows the program embedding the engine to handle the 6937 * termination event and resume execution capability, even if 6938 * JavaScript frames remain on the stack. 6939 * 6940 * This method can be used by any thread even if that thread has not 6941 * acquired the V8 lock with a Locker object. 6942 */ 6943 void CancelTerminateExecution(); 6944 6945 /** 6946 * Request V8 to interrupt long running JavaScript code and invoke 6947 * the given |callback| passing the given |data| to it. After |callback| 6948 * returns control will be returned to the JavaScript code. 6949 * There may be a number of interrupt requests in flight. 6950 * Can be called from another thread without acquiring a |Locker|. 6951 * Registered |callback| must not reenter interrupted Isolate. 6952 */ 6953 void RequestInterrupt(InterruptCallback callback, void* data); 6954 6955 /** 6956 * Request garbage collection in this Isolate. It is only valid to call this 6957 * function if --expose_gc was specified. 6958 * 6959 * This should only be used for testing purposes and not to enforce a garbage 6960 * collection schedule. It has strong negative impact on the garbage 6961 * collection performance. Use IdleNotificationDeadline() or 6962 * LowMemoryNotification() instead to influence the garbage collection 6963 * schedule. 6964 */ 6965 void RequestGarbageCollectionForTesting(GarbageCollectionType type); 6966 6967 /** 6968 * Set the callback to invoke for logging event. 6969 */ 6970 void SetEventLogger(LogEventCallback that); 6971 6972 /** 6973 * Adds a callback to notify the host application right before a script 6974 * is about to run. If a script re-enters the runtime during executing, the 6975 * BeforeCallEnteredCallback is invoked for each re-entrance. 6976 * Executing scripts inside the callback will re-trigger the callback. 6977 */ 6978 void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback); 6979 6980 /** 6981 * Removes callback that was installed by AddBeforeCallEnteredCallback. 6982 */ 6983 void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback); 6984 6985 /** 6986 * Adds a callback to notify the host application when a script finished 6987 * running. If a script re-enters the runtime during executing, the 6988 * CallCompletedCallback is only invoked when the outer-most script 6989 * execution ends. Executing scripts inside the callback do not trigger 6990 * further callbacks. 6991 */ 6992 void AddCallCompletedCallback(CallCompletedCallback callback); 6993 V8_DEPRECATE_SOON( 6994 "Use callback with parameter", 6995 void AddCallCompletedCallback(DeprecatedCallCompletedCallback callback)); 6996 6997 /** 6998 * Removes callback that was installed by AddCallCompletedCallback. 6999 */ 7000 void RemoveCallCompletedCallback(CallCompletedCallback callback); 7001 V8_DEPRECATE_SOON( 7002 "Use callback with parameter", 7003 void RemoveCallCompletedCallback( 7004 DeprecatedCallCompletedCallback callback)); 7005 7006 /** 7007 * Experimental: Set the PromiseHook callback for various promise 7008 * lifecycle events. 7009 */ 7010 void SetPromiseHook(PromiseHook hook); 7011 7012 /** 7013 * Set callback to notify about promise reject with no handler, or 7014 * revocation of such a previous notification once the handler is added. 7015 */ 7016 void SetPromiseRejectCallback(PromiseRejectCallback callback); 7017 7018 /** 7019 * Experimental: Runs the Microtask Work Queue until empty 7020 * Any exceptions thrown by microtask callbacks are swallowed. 7021 */ 7022 void RunMicrotasks(); 7023 7024 /** 7025 * Experimental: Enqueues the callback to the Microtask Work Queue 7026 */ 7027 void EnqueueMicrotask(Local<Function> microtask); 7028 7029 /** 7030 * Experimental: Enqueues the callback to the Microtask Work Queue 7031 */ 7032 void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL); 7033 7034 /** 7035 * Experimental: Controls how Microtasks are invoked. See MicrotasksPolicy 7036 * for details. 7037 */ 7038 void SetMicrotasksPolicy(MicrotasksPolicy policy); 7039 V8_DEPRECATE_SOON("Use SetMicrotasksPolicy", 7040 void SetAutorunMicrotasks(bool autorun)); 7041 7042 /** 7043 * Experimental: Returns the policy controlling how Microtasks are invoked. 7044 */ 7045 MicrotasksPolicy GetMicrotasksPolicy() const; 7046 V8_DEPRECATE_SOON("Use GetMicrotasksPolicy", 7047 bool WillAutorunMicrotasks() const); 7048 7049 /** 7050 * Experimental: adds a callback to notify the host application after 7051 * microtasks were run. The callback is triggered by explicit RunMicrotasks 7052 * call or automatic microtasks execution (see SetAutorunMicrotasks). 7053 * 7054 * Callback will trigger even if microtasks were attempted to run, 7055 * but the microtasks queue was empty and no single microtask was actually 7056 * executed. 7057 * 7058 * Executing scriptsinside the callback will not re-trigger microtasks and 7059 * the callback. 7060 */ 7061 void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback); 7062 7063 /** 7064 * Removes callback that was installed by AddMicrotasksCompletedCallback. 7065 */ 7066 void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback); 7067 7068 /** 7069 * Sets a callback for counting the number of times a feature of V8 is used. 7070 */ 7071 void SetUseCounterCallback(UseCounterCallback callback); 7072 7073 /** 7074 * Enables the host application to provide a mechanism for recording 7075 * statistics counters. 7076 */ 7077 void SetCounterFunction(CounterLookupCallback); 7078 7079 /** 7080 * Enables the host application to provide a mechanism for recording 7081 * histograms. The CreateHistogram function returns a 7082 * histogram which will later be passed to the AddHistogramSample 7083 * function. 7084 */ 7085 void SetCreateHistogramFunction(CreateHistogramCallback); 7086 void SetAddHistogramSampleFunction(AddHistogramSampleCallback); 7087 7088 /** 7089 * Optional notification that the embedder is idle. 7090 * V8 uses the notification to perform garbage collection. 7091 * This call can be used repeatedly if the embedder remains idle. 7092 * Returns true if the embedder should stop calling IdleNotificationDeadline 7093 * until real work has been done. This indicates that V8 has done 7094 * as much cleanup as it will be able to do. 7095 * 7096 * The deadline_in_seconds argument specifies the deadline V8 has to finish 7097 * garbage collection work. deadline_in_seconds is compared with 7098 * MonotonicallyIncreasingTime() and should be based on the same timebase as 7099 * that function. There is no guarantee that the actual work will be done 7100 * within the time limit. 7101 */ 7102 bool IdleNotificationDeadline(double deadline_in_seconds); 7103 7104 V8_DEPRECATED("use IdleNotificationDeadline()", 7105 bool IdleNotification(int idle_time_in_ms)); 7106 7107 /** 7108 * Optional notification that the system is running low on memory. 7109 * V8 uses these notifications to attempt to free memory. 7110 */ 7111 void LowMemoryNotification(); 7112 7113 /** 7114 * Optional notification that a context has been disposed. V8 uses 7115 * these notifications to guide the GC heuristic. Returns the number 7116 * of context disposals - including this one - since the last time 7117 * V8 had a chance to clean up. 7118 * 7119 * The optional parameter |dependant_context| specifies whether the disposed 7120 * context was depending on state from other contexts or not. 7121 */ 7122 int ContextDisposedNotification(bool dependant_context = true); 7123 7124 /** 7125 * Optional notification that the isolate switched to the foreground. 7126 * V8 uses these notifications to guide heuristics. 7127 */ 7128 void IsolateInForegroundNotification(); 7129 7130 /** 7131 * Optional notification that the isolate switched to the background. 7132 * V8 uses these notifications to guide heuristics. 7133 */ 7134 void IsolateInBackgroundNotification(); 7135 7136 /** 7137 * Optional notification to tell V8 the current performance requirements 7138 * of the embedder based on RAIL. 7139 * V8 uses these notifications to guide heuristics. 7140 * This is an unfinished experimental feature. Semantics and implementation 7141 * may change frequently. 7142 */ 7143 void SetRAILMode(RAILMode rail_mode); 7144 7145 /** 7146 * Optional notification to tell V8 the current isolate is used for debugging 7147 * and requires higher heap limit. 7148 */ 7149 void IncreaseHeapLimitForDebugging(); 7150 7151 /** 7152 * Restores the original heap limit after IncreaseHeapLimitForDebugging(). 7153 */ 7154 void RestoreOriginalHeapLimit(); 7155 7156 /** 7157 * Returns true if the heap limit was increased for debugging and the 7158 * original heap limit was not restored yet. 7159 */ 7160 bool IsHeapLimitIncreasedForDebugging(); 7161 7162 /** 7163 * Allows the host application to provide the address of a function that is 7164 * notified each time code is added, moved or removed. 7165 * 7166 * \param options options for the JIT code event handler. 7167 * \param event_handler the JIT code event handler, which will be invoked 7168 * each time code is added, moved or removed. 7169 * \note \p event_handler won't get notified of existent code. 7170 * \note since code removal notifications are not currently issued, the 7171 * \p event_handler may get notifications of code that overlaps earlier 7172 * code notifications. This happens when code areas are reused, and the 7173 * earlier overlapping code areas should therefore be discarded. 7174 * \note the events passed to \p event_handler and the strings they point to 7175 * are not guaranteed to live past each call. The \p event_handler must 7176 * copy strings and other parameters it needs to keep around. 7177 * \note the set of events declared in JitCodeEvent::EventType is expected to 7178 * grow over time, and the JitCodeEvent structure is expected to accrue 7179 * new members. The \p event_handler function must ignore event codes 7180 * it does not recognize to maintain future compatibility. 7181 * \note Use Isolate::CreateParams to get events for code executed during 7182 * Isolate setup. 7183 */ 7184 void SetJitCodeEventHandler(JitCodeEventOptions options, 7185 JitCodeEventHandler event_handler); 7186 7187 /** 7188 * Modifies the stack limit for this Isolate. 7189 * 7190 * \param stack_limit An address beyond which the Vm's stack may not grow. 7191 * 7192 * \note If you are using threads then you should hold the V8::Locker lock 7193 * while setting the stack limit and you must set a non-default stack 7194 * limit separately for each thread. 7195 */ 7196 void SetStackLimit(uintptr_t stack_limit); 7197 7198 /** 7199 * Returns a memory range that can potentially contain jitted code. 7200 * 7201 * On Win64, embedders are advised to install function table callbacks for 7202 * these ranges, as default SEH won't be able to unwind through jitted code. 7203 * 7204 * The first page of the code range is reserved for the embedder and is 7205 * committed, writable, and executable. 7206 * 7207 * Might be empty on other platforms. 7208 * 7209 * https://code.google.com/p/v8/issues/detail?id=3598 7210 */ 7211 void GetCodeRange(void** start, size_t* length_in_bytes); 7212 7213 /** Set the callback to invoke in case of fatal errors. */ 7214 void SetFatalErrorHandler(FatalErrorCallback that); 7215 7216 /** Set the callback to invoke in case of OOM errors. */ 7217 void SetOOMErrorHandler(OOMErrorCallback that); 7218 7219 /** 7220 * Set the callback to invoke to check if code generation from 7221 * strings should be allowed. 7222 */ 7223 void SetAllowCodeGenerationFromStringsCallback( 7224 AllowCodeGenerationFromStringsCallback callback); 7225 7226 /** 7227 * Set the callback to invoke to check if wasm compilation from 7228 * the specified object is allowed. By default, wasm compilation 7229 * is allowed. 7230 * 7231 * Similar for instantiate. 7232 */ 7233 void SetAllowWasmCompileCallback(AllowWasmCompileCallback callback); 7234 void SetAllowWasmInstantiateCallback(AllowWasmInstantiateCallback callback); 7235 7236 /** 7237 * Check if V8 is dead and therefore unusable. This is the case after 7238 * fatal errors such as out-of-memory situations. 7239 */ 7240 bool IsDead(); 7241 7242 /** 7243 * Adds a message listener (errors only). 7244 * 7245 * The same message listener can be added more than once and in that 7246 * case it will be called more than once for each message. 7247 * 7248 * If data is specified, it will be passed to the callback when it is called. 7249 * Otherwise, the exception object will be passed to the callback instead. 7250 */ 7251 bool AddMessageListener(MessageCallback that, 7252 Local<Value> data = Local<Value>()); 7253 7254 /** 7255 * Adds a message listener. 7256 * 7257 * The same message listener can be added more than once and in that 7258 * case it will be called more than once for each message. 7259 * 7260 * If data is specified, it will be passed to the callback when it is called. 7261 * Otherwise, the exception object will be passed to the callback instead. 7262 * 7263 * A listener can listen for particular error levels by providing a mask. 7264 */ 7265 bool AddMessageListenerWithErrorLevel(MessageCallback that, 7266 int message_levels, 7267 Local<Value> data = Local<Value>()); 7268 7269 /** 7270 * Remove all message listeners from the specified callback function. 7271 */ 7272 void RemoveMessageListeners(MessageCallback that); 7273 7274 /** Callback function for reporting failed access checks.*/ 7275 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback); 7276 7277 /** 7278 * Tells V8 to capture current stack trace when uncaught exception occurs 7279 * and report it to the message listeners. The option is off by default. 7280 */ 7281 void SetCaptureStackTraceForUncaughtExceptions( 7282 bool capture, int frame_limit = 10, 7283 StackTrace::StackTraceOptions options = StackTrace::kOverview); 7284 7285 /** 7286 * Iterates through all external resources referenced from current isolate 7287 * heap. GC is not invoked prior to iterating, therefore there is no 7288 * guarantee that visited objects are still alive. 7289 */ 7290 void VisitExternalResources(ExternalResourceVisitor* visitor); 7291 7292 /** 7293 * Iterates through all the persistent handles in the current isolate's heap 7294 * that have class_ids. 7295 */ 7296 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor); 7297 7298 /** 7299 * Iterates through all the persistent handles in the current isolate's heap 7300 * that have class_ids and are candidates to be marked as partially dependent 7301 * handles. This will visit handles to young objects created since the last 7302 * garbage collection but is free to visit an arbitrary superset of these 7303 * objects. 7304 */ 7305 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor); 7306 7307 /** 7308 * Iterates through all the persistent handles in the current isolate's heap 7309 * that have class_ids and are weak to be marked as inactive if there is no 7310 * pending activity for the handle. 7311 */ 7312 void VisitWeakHandles(PersistentHandleVisitor* visitor); 7313 7314 /** 7315 * Check if this isolate is in use. 7316 * True if at least one thread Enter'ed this isolate. 7317 */ 7318 bool IsInUse(); 7319 7320 Isolate() = delete; 7321 ~Isolate() = delete; 7322 Isolate(const Isolate&) = delete; 7323 Isolate& operator=(const Isolate&) = delete; 7324 void* operator new(size_t size) = delete; 7325 void operator delete(void*, size_t) = delete; 7326 7327 private: 7328 template <class K, class V, class Traits> 7329 friend class PersistentValueMapBase; 7330 7331 void SetObjectGroupId(internal::Object** object, UniqueId id); 7332 void SetReferenceFromGroup(UniqueId id, internal::Object** object); 7333 void SetReference(internal::Object** parent, internal::Object** child); 7334 void ReportExternalAllocationLimitReached(); 7335 }; 7336 7337 class V8_EXPORT StartupData { 7338 public: 7339 const char* data; 7340 int raw_size; 7341 }; 7342 7343 7344 /** 7345 * EntropySource is used as a callback function when v8 needs a source 7346 * of entropy. 7347 */ 7348 typedef bool (*EntropySource)(unsigned char* buffer, size_t length); 7349 7350 /** 7351 * ReturnAddressLocationResolver is used as a callback function when v8 is 7352 * resolving the location of a return address on the stack. Profilers that 7353 * change the return address on the stack can use this to resolve the stack 7354 * location to whereever the profiler stashed the original return address. 7355 * 7356 * \param return_addr_location A location on stack where a machine 7357 * return address resides. 7358 * \returns Either return_addr_location, or else a pointer to the profiler's 7359 * copy of the original return address. 7360 * 7361 * \note The resolver function must not cause garbage collection. 7362 */ 7363 typedef uintptr_t (*ReturnAddressLocationResolver)( 7364 uintptr_t return_addr_location); 7365 7366 7367 /** 7368 * Container class for static utility functions. 7369 */ 7370 class V8_EXPORT V8 { 7371 public: 7372 /** Set the callback to invoke in case of fatal errors. */ 7373 V8_INLINE static V8_DEPRECATED( 7374 "Use isolate version", 7375 void SetFatalErrorHandler(FatalErrorCallback that)); 7376 7377 /** 7378 * Set the callback to invoke to check if code generation from 7379 * strings should be allowed. 7380 */ 7381 V8_INLINE static V8_DEPRECATED( 7382 "Use isolate version", void SetAllowCodeGenerationFromStringsCallback( 7383 AllowCodeGenerationFromStringsCallback that)); 7384 7385 /** 7386 * Check if V8 is dead and therefore unusable. This is the case after 7387 * fatal errors such as out-of-memory situations. 7388 */ 7389 V8_INLINE static V8_DEPRECATED("Use isolate version", bool IsDead()); 7390 7391 /** 7392 * Hand startup data to V8, in case the embedder has chosen to build 7393 * V8 with external startup data. 7394 * 7395 * Note: 7396 * - By default the startup data is linked into the V8 library, in which 7397 * case this function is not meaningful. 7398 * - If this needs to be called, it needs to be called before V8 7399 * tries to make use of its built-ins. 7400 * - To avoid unnecessary copies of data, V8 will point directly into the 7401 * given data blob, so pretty please keep it around until V8 exit. 7402 * - Compression of the startup blob might be useful, but needs to 7403 * handled entirely on the embedders' side. 7404 * - The call will abort if the data is invalid. 7405 */ 7406 static void SetNativesDataBlob(StartupData* startup_blob); 7407 static void SetSnapshotDataBlob(StartupData* startup_blob); 7408 7409 /** 7410 * Bootstrap an isolate and a context from scratch to create a startup 7411 * snapshot. Include the side-effects of running the optional script. 7412 * Returns { NULL, 0 } on failure. 7413 * The caller acquires ownership of the data array in the return value. 7414 */ 7415 static StartupData CreateSnapshotDataBlob(const char* embedded_source = NULL); 7416 7417 /** 7418 * Bootstrap an isolate and a context from the cold startup blob, run the 7419 * warm-up script to trigger code compilation. The side effects are then 7420 * discarded. The resulting startup snapshot will include compiled code. 7421 * Returns { NULL, 0 } on failure. 7422 * The caller acquires ownership of the data array in the return value. 7423 * The argument startup blob is untouched. 7424 */ 7425 static StartupData WarmUpSnapshotDataBlob(StartupData cold_startup_blob, 7426 const char* warmup_source); 7427 7428 /** 7429 * Adds a message listener. 7430 * 7431 * The same message listener can be added more than once and in that 7432 * case it will be called more than once for each message. 7433 * 7434 * If data is specified, it will be passed to the callback when it is called. 7435 * Otherwise, the exception object will be passed to the callback instead. 7436 */ 7437 V8_INLINE static V8_DEPRECATED( 7438 "Use isolate version", 7439 bool AddMessageListener(MessageCallback that, 7440 Local<Value> data = Local<Value>())); 7441 7442 /** 7443 * Remove all message listeners from the specified callback function. 7444 */ 7445 V8_INLINE static V8_DEPRECATED( 7446 "Use isolate version", void RemoveMessageListeners(MessageCallback that)); 7447 7448 /** 7449 * Tells V8 to capture current stack trace when uncaught exception occurs 7450 * and report it to the message listeners. The option is off by default. 7451 */ 7452 V8_INLINE static V8_DEPRECATED( 7453 "Use isolate version", 7454 void SetCaptureStackTraceForUncaughtExceptions( 7455 bool capture, int frame_limit = 10, 7456 StackTrace::StackTraceOptions options = StackTrace::kOverview)); 7457 7458 /** 7459 * Sets V8 flags from a string. 7460 */ 7461 static void SetFlagsFromString(const char* str, int length); 7462 7463 /** 7464 * Sets V8 flags from the command line. 7465 */ 7466 static void SetFlagsFromCommandLine(int* argc, 7467 char** argv, 7468 bool remove_flags); 7469 7470 /** Get the version string. */ 7471 static const char* GetVersion(); 7472 7473 /** Callback function for reporting failed access checks.*/ 7474 V8_INLINE static V8_DEPRECATED( 7475 "Use isolate version", 7476 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback)); 7477 7478 /** 7479 * Enables the host application to receive a notification before a 7480 * garbage collection. Allocations are not allowed in the 7481 * callback function, you therefore cannot manipulate objects (set 7482 * or delete properties for example) since it is possible such 7483 * operations will result in the allocation of objects. It is possible 7484 * to specify the GCType filter for your callback. But it is not possible to 7485 * register the same callback function two times with different 7486 * GCType filters. 7487 */ 7488 static V8_DEPRECATED( 7489 "Use isolate version", 7490 void AddGCPrologueCallback(GCCallback callback, 7491 GCType gc_type_filter = kGCTypeAll)); 7492 7493 /** 7494 * This function removes callback which was installed by 7495 * AddGCPrologueCallback function. 7496 */ 7497 V8_INLINE static V8_DEPRECATED( 7498 "Use isolate version", 7499 void RemoveGCPrologueCallback(GCCallback callback)); 7500 7501 /** 7502 * Enables the host application to receive a notification after a 7503 * garbage collection. Allocations are not allowed in the 7504 * callback function, you therefore cannot manipulate objects (set 7505 * or delete properties for example) since it is possible such 7506 * operations will result in the allocation of objects. It is possible 7507 * to specify the GCType filter for your callback. But it is not possible to 7508 * register the same callback function two times with different 7509 * GCType filters. 7510 */ 7511 static V8_DEPRECATED( 7512 "Use isolate version", 7513 void AddGCEpilogueCallback(GCCallback callback, 7514 GCType gc_type_filter = kGCTypeAll)); 7515 7516 /** 7517 * This function removes callback which was installed by 7518 * AddGCEpilogueCallback function. 7519 */ 7520 V8_INLINE static V8_DEPRECATED( 7521 "Use isolate version", 7522 void RemoveGCEpilogueCallback(GCCallback callback)); 7523 7524 /** 7525 * Initializes V8. This function needs to be called before the first Isolate 7526 * is created. It always returns true. 7527 */ 7528 static bool Initialize(); 7529 7530 /** 7531 * Allows the host application to provide a callback which can be used 7532 * as a source of entropy for random number generators. 7533 */ 7534 static void SetEntropySource(EntropySource source); 7535 7536 /** 7537 * Allows the host application to provide a callback that allows v8 to 7538 * cooperate with a profiler that rewrites return addresses on stack. 7539 */ 7540 static void SetReturnAddressLocationResolver( 7541 ReturnAddressLocationResolver return_address_resolver); 7542 7543 /** 7544 * Forcefully terminate the current thread of JavaScript execution 7545 * in the given isolate. 7546 * 7547 * This method can be used by any thread even if that thread has not 7548 * acquired the V8 lock with a Locker object. 7549 * 7550 * \param isolate The isolate in which to terminate the current JS execution. 7551 */ 7552 V8_INLINE static V8_DEPRECATED("Use isolate version", 7553 void TerminateExecution(Isolate* isolate)); 7554 7555 /** 7556 * Is V8 terminating JavaScript execution. 7557 * 7558 * Returns true if JavaScript execution is currently terminating 7559 * because of a call to TerminateExecution. In that case there are 7560 * still JavaScript frames on the stack and the termination 7561 * exception is still active. 7562 * 7563 * \param isolate The isolate in which to check. 7564 */ 7565 V8_INLINE static V8_DEPRECATED( 7566 "Use isolate version", 7567 bool IsExecutionTerminating(Isolate* isolate = NULL)); 7568 7569 /** 7570 * Resume execution capability in the given isolate, whose execution 7571 * was previously forcefully terminated using TerminateExecution(). 7572 * 7573 * When execution is forcefully terminated using TerminateExecution(), 7574 * the isolate can not resume execution until all JavaScript frames 7575 * have propagated the uncatchable exception which is generated. This 7576 * method allows the program embedding the engine to handle the 7577 * termination event and resume execution capability, even if 7578 * JavaScript frames remain on the stack. 7579 * 7580 * This method can be used by any thread even if that thread has not 7581 * acquired the V8 lock with a Locker object. 7582 * 7583 * \param isolate The isolate in which to resume execution capability. 7584 */ 7585 V8_INLINE static V8_DEPRECATED( 7586 "Use isolate version", void CancelTerminateExecution(Isolate* isolate)); 7587 7588 /** 7589 * Releases any resources used by v8 and stops any utility threads 7590 * that may be running. Note that disposing v8 is permanent, it 7591 * cannot be reinitialized. 7592 * 7593 * It should generally not be necessary to dispose v8 before exiting 7594 * a process, this should happen automatically. It is only necessary 7595 * to use if the process needs the resources taken up by v8. 7596 */ 7597 static bool Dispose(); 7598 7599 /** 7600 * Iterates through all external resources referenced from current isolate 7601 * heap. GC is not invoked prior to iterating, therefore there is no 7602 * guarantee that visited objects are still alive. 7603 */ 7604 V8_INLINE static V8_DEPRECATED( 7605 "Use isolate version", 7606 void VisitExternalResources(ExternalResourceVisitor* visitor)); 7607 7608 /** 7609 * Iterates through all the persistent handles in the current isolate's heap 7610 * that have class_ids. 7611 */ 7612 V8_INLINE static V8_DEPRECATED( 7613 "Use isolate version", 7614 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor)); 7615 7616 /** 7617 * Iterates through all the persistent handles in isolate's heap that have 7618 * class_ids. 7619 */ 7620 V8_INLINE static V8_DEPRECATED( 7621 "Use isolate version", 7622 void VisitHandlesWithClassIds(Isolate* isolate, 7623 PersistentHandleVisitor* visitor)); 7624 7625 /** 7626 * Iterates through all the persistent handles in the current isolate's heap 7627 * that have class_ids and are candidates to be marked as partially dependent 7628 * handles. This will visit handles to young objects created since the last 7629 * garbage collection but is free to visit an arbitrary superset of these 7630 * objects. 7631 */ 7632 V8_INLINE static V8_DEPRECATED( 7633 "Use isolate version", 7634 void VisitHandlesForPartialDependence(Isolate* isolate, 7635 PersistentHandleVisitor* visitor)); 7636 7637 /** 7638 * Initialize the ICU library bundled with V8. The embedder should only 7639 * invoke this method when using the bundled ICU. Returns true on success. 7640 * 7641 * If V8 was compiled with the ICU data in an external file, the location 7642 * of the data file has to be provided. 7643 */ 7644 V8_DEPRECATE_SOON( 7645 "Use version with default location.", 7646 static bool InitializeICU(const char* icu_data_file = nullptr)); 7647 7648 /** 7649 * Initialize the ICU library bundled with V8. The embedder should only 7650 * invoke this method when using the bundled ICU. If V8 was compiled with 7651 * the ICU data in an external file and when the default location of that 7652 * file should be used, a path to the executable must be provided. 7653 * Returns true on success. 7654 * 7655 * The default is a file called icudtl.dat side-by-side with the executable. 7656 * 7657 * Optionally, the location of the data file can be provided to override the 7658 * default. 7659 */ 7660 static bool InitializeICUDefaultLocation(const char* exec_path, 7661 const char* icu_data_file = nullptr); 7662 7663 /** 7664 * Initialize the external startup data. The embedder only needs to 7665 * invoke this method when external startup data was enabled in a build. 7666 * 7667 * If V8 was compiled with the startup data in an external file, then 7668 * V8 needs to be given those external files during startup. There are 7669 * three ways to do this: 7670 * - InitializeExternalStartupData(const char*) 7671 * This will look in the given directory for files "natives_blob.bin" 7672 * and "snapshot_blob.bin" - which is what the default build calls them. 7673 * - InitializeExternalStartupData(const char*, const char*) 7674 * As above, but will directly use the two given file names. 7675 * - Call SetNativesDataBlob, SetNativesDataBlob. 7676 * This will read the blobs from the given data structures and will 7677 * not perform any file IO. 7678 */ 7679 static void InitializeExternalStartupData(const char* directory_path); 7680 static void InitializeExternalStartupData(const char* natives_blob, 7681 const char* snapshot_blob); 7682 /** 7683 * Sets the v8::Platform to use. This should be invoked before V8 is 7684 * initialized. 7685 */ 7686 static void InitializePlatform(Platform* platform); 7687 7688 /** 7689 * Clears all references to the v8::Platform. This should be invoked after 7690 * V8 was disposed. 7691 */ 7692 static void ShutdownPlatform(); 7693 7694 private: 7695 V8(); 7696 7697 static internal::Object** GlobalizeReference(internal::Isolate* isolate, 7698 internal::Object** handle); 7699 static internal::Object** CopyPersistent(internal::Object** handle); 7700 static void DisposeGlobal(internal::Object** global_handle); 7701 static void MakeWeak(internal::Object** location, void* data, 7702 WeakCallbackInfo<void>::Callback weak_callback, 7703 WeakCallbackType type); 7704 static void MakeWeak(internal::Object** location, void* data, 7705 // Must be 0 or -1. 7706 int internal_field_index1, 7707 // Must be 1 or -1. 7708 int internal_field_index2, 7709 WeakCallbackInfo<void>::Callback weak_callback); 7710 static void MakeWeak(internal::Object*** location_addr); 7711 static void* ClearWeak(internal::Object** location); 7712 static void Eternalize(Isolate* isolate, 7713 Value* handle, 7714 int* index); 7715 static Local<Value> GetEternal(Isolate* isolate, int index); 7716 7717 static void RegisterExternallyReferencedObject(internal::Object** object, 7718 internal::Isolate* isolate); 7719 7720 template <class K, class V, class T> 7721 friend class PersistentValueMapBase; 7722 7723 static void FromJustIsNothing(); 7724 static void ToLocalEmpty(); 7725 static void InternalFieldOutOfBounds(int index); 7726 template <class T> friend class Local; 7727 template <class T> 7728 friend class MaybeLocal; 7729 template <class T> 7730 friend class Maybe; 7731 template <class T> 7732 friend class WeakCallbackInfo; 7733 template <class T> friend class Eternal; 7734 template <class T> friend class PersistentBase; 7735 template <class T, class M> friend class Persistent; 7736 friend class Context; 7737 }; 7738 7739 /** 7740 * Helper class to create a snapshot data blob. 7741 */ 7742 class V8_EXPORT SnapshotCreator { 7743 public: 7744 enum class FunctionCodeHandling { kClear, kKeep }; 7745 7746 /** 7747 * Create and enter an isolate, and set it up for serialization. 7748 * The isolate is either created from scratch or from an existing snapshot. 7749 * The caller keeps ownership of the argument snapshot. 7750 * \param existing_blob existing snapshot from which to create this one. 7751 * \param external_references a null-terminated array of external references 7752 * that must be equivalent to CreateParams::external_references. 7753 */ 7754 SnapshotCreator(intptr_t* external_references = nullptr, 7755 StartupData* existing_blob = nullptr); 7756 7757 ~SnapshotCreator(); 7758 7759 /** 7760 * \returns the isolate prepared by the snapshot creator. 7761 */ 7762 Isolate* GetIsolate(); 7763 7764 /** 7765 * Set the default context to be included in the snapshot blob. 7766 * The snapshot will not contain the global proxy, and we expect one or a 7767 * global object template to create one, to be provided upon deserialization. 7768 */ 7769 void SetDefaultContext(Local<Context> context); 7770 7771 /** 7772 * Add additional context to be included in the snapshot blob. 7773 * The snapshot will include the global proxy. 7774 * 7775 * \param callback optional callback to serialize internal fields. 7776 * 7777 * \returns the index of the context in the snapshot blob. 7778 */ 7779 size_t AddContext(Local<Context> context, 7780 SerializeInternalFieldsCallback callback = 7781 SerializeInternalFieldsCallback()); 7782 7783 /** 7784 * Add a template to be included in the snapshot blob. 7785 * \returns the index of the template in the snapshot blob. 7786 */ 7787 size_t AddTemplate(Local<Template> template_obj); 7788 7789 /** 7790 * Created a snapshot data blob. 7791 * This must not be called from within a handle scope. 7792 * \param function_code_handling whether to include compiled function code 7793 * in the snapshot. 7794 * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The 7795 * caller acquires ownership of the data array in the return value. 7796 */ 7797 StartupData CreateBlob(FunctionCodeHandling function_code_handling); 7798 7799 // Disallow copying and assigning. 7800 SnapshotCreator(const SnapshotCreator&) = delete; 7801 void operator=(const SnapshotCreator&) = delete; 7802 7803 private: 7804 void* data_; 7805 }; 7806 7807 /** 7808 * A simple Maybe type, representing an object which may or may not have a 7809 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html. 7810 * 7811 * If an API method returns a Maybe<>, the API method can potentially fail 7812 * either because an exception is thrown, or because an exception is pending, 7813 * e.g. because a previous API call threw an exception that hasn't been caught 7814 * yet, or because a TerminateExecution exception was thrown. In that case, a 7815 * "Nothing" value is returned. 7816 */ 7817 template <class T> 7818 class Maybe { 7819 public: 7820 V8_INLINE bool IsNothing() const { return !has_value_; } 7821 V8_INLINE bool IsJust() const { return has_value_; } 7822 7823 // Will crash if the Maybe<> is nothing. 7824 V8_INLINE T ToChecked() const { return FromJust(); } 7825 7826 V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const { 7827 if (V8_LIKELY(IsJust())) *out = value_; 7828 return IsJust(); 7829 } 7830 7831 // Will crash if the Maybe<> is nothing. 7832 V8_INLINE T FromJust() const { 7833 if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing(); 7834 return value_; 7835 } 7836 7837 V8_INLINE T FromMaybe(const T& default_value) const { 7838 return has_value_ ? value_ : default_value; 7839 } 7840 7841 V8_INLINE bool operator==(const Maybe& other) const { 7842 return (IsJust() == other.IsJust()) && 7843 (!IsJust() || FromJust() == other.FromJust()); 7844 } 7845 7846 V8_INLINE bool operator!=(const Maybe& other) const { 7847 return !operator==(other); 7848 } 7849 7850 private: 7851 Maybe() : has_value_(false) {} 7852 explicit Maybe(const T& t) : has_value_(true), value_(t) {} 7853 7854 bool has_value_; 7855 T value_; 7856 7857 template <class U> 7858 friend Maybe<U> Nothing(); 7859 template <class U> 7860 friend Maybe<U> Just(const U& u); 7861 }; 7862 7863 7864 template <class T> 7865 inline Maybe<T> Nothing() { 7866 return Maybe<T>(); 7867 } 7868 7869 7870 template <class T> 7871 inline Maybe<T> Just(const T& t) { 7872 return Maybe<T>(t); 7873 } 7874 7875 7876 /** 7877 * An external exception handler. 7878 */ 7879 class V8_EXPORT TryCatch { 7880 public: 7881 /** 7882 * Creates a new try/catch block and registers it with v8. Note that 7883 * all TryCatch blocks should be stack allocated because the memory 7884 * location itself is compared against JavaScript try/catch blocks. 7885 */ 7886 V8_DEPRECATED("Use isolate version", TryCatch()); 7887 7888 /** 7889 * Creates a new try/catch block and registers it with v8. Note that 7890 * all TryCatch blocks should be stack allocated because the memory 7891 * location itself is compared against JavaScript try/catch blocks. 7892 */ 7893 TryCatch(Isolate* isolate); 7894 7895 /** 7896 * Unregisters and deletes this try/catch block. 7897 */ 7898 ~TryCatch(); 7899 7900 /** 7901 * Returns true if an exception has been caught by this try/catch block. 7902 */ 7903 bool HasCaught() const; 7904 7905 /** 7906 * For certain types of exceptions, it makes no sense to continue execution. 7907 * 7908 * If CanContinue returns false, the correct action is to perform any C++ 7909 * cleanup needed and then return. If CanContinue returns false and 7910 * HasTerminated returns true, it is possible to call 7911 * CancelTerminateExecution in order to continue calling into the engine. 7912 */ 7913 bool CanContinue() const; 7914 7915 /** 7916 * Returns true if an exception has been caught due to script execution 7917 * being terminated. 7918 * 7919 * There is no JavaScript representation of an execution termination 7920 * exception. Such exceptions are thrown when the TerminateExecution 7921 * methods are called to terminate a long-running script. 7922 * 7923 * If such an exception has been thrown, HasTerminated will return true, 7924 * indicating that it is possible to call CancelTerminateExecution in order 7925 * to continue calling into the engine. 7926 */ 7927 bool HasTerminated() const; 7928 7929 /** 7930 * Throws the exception caught by this TryCatch in a way that avoids 7931 * it being caught again by this same TryCatch. As with ThrowException 7932 * it is illegal to execute any JavaScript operations after calling 7933 * ReThrow; the caller must return immediately to where the exception 7934 * is caught. 7935 */ 7936 Local<Value> ReThrow(); 7937 7938 /** 7939 * Returns the exception caught by this try/catch block. If no exception has 7940 * been caught an empty handle is returned. 7941 * 7942 * The returned handle is valid until this TryCatch block has been destroyed. 7943 */ 7944 Local<Value> Exception() const; 7945 7946 /** 7947 * Returns the .stack property of the thrown object. If no .stack 7948 * property is present an empty handle is returned. 7949 */ 7950 V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const); 7951 V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace( 7952 Local<Context> context) const; 7953 7954 /** 7955 * Returns the message associated with this exception. If there is 7956 * no message associated an empty handle is returned. 7957 * 7958 * The returned handle is valid until this TryCatch block has been 7959 * destroyed. 7960 */ 7961 Local<v8::Message> Message() const; 7962 7963 /** 7964 * Clears any exceptions that may have been caught by this try/catch block. 7965 * After this method has been called, HasCaught() will return false. Cancels 7966 * the scheduled exception if it is caught and ReThrow() is not called before. 7967 * 7968 * It is not necessary to clear a try/catch block before using it again; if 7969 * another exception is thrown the previously caught exception will just be 7970 * overwritten. However, it is often a good idea since it makes it easier 7971 * to determine which operation threw a given exception. 7972 */ 7973 void Reset(); 7974 7975 /** 7976 * Set verbosity of the external exception handler. 7977 * 7978 * By default, exceptions that are caught by an external exception 7979 * handler are not reported. Call SetVerbose with true on an 7980 * external exception handler to have exceptions caught by the 7981 * handler reported as if they were not caught. 7982 */ 7983 void SetVerbose(bool value); 7984 7985 /** 7986 * Set whether or not this TryCatch should capture a Message object 7987 * which holds source information about where the exception 7988 * occurred. True by default. 7989 */ 7990 void SetCaptureMessage(bool value); 7991 7992 /** 7993 * There are cases when the raw address of C++ TryCatch object cannot be 7994 * used for comparisons with addresses into the JS stack. The cases are: 7995 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack. 7996 * 2) Address sanitizer allocates local C++ object in the heap when 7997 * UseAfterReturn mode is enabled. 7998 * This method returns address that can be used for comparisons with 7999 * addresses into the JS stack. When neither simulator nor ASAN's 8000 * UseAfterReturn is enabled, then the address returned will be the address 8001 * of the C++ try catch handler itself. 8002 */ 8003 static void* JSStackComparableAddress(TryCatch* handler) { 8004 if (handler == NULL) return NULL; 8005 return handler->js_stack_comparable_address_; 8006 } 8007 8008 TryCatch(const TryCatch&) = delete; 8009 void operator=(const TryCatch&) = delete; 8010 void* operator new(size_t size); 8011 void operator delete(void*, size_t); 8012 8013 private: 8014 void ResetInternal(); 8015 8016 internal::Isolate* isolate_; 8017 TryCatch* next_; 8018 void* exception_; 8019 void* message_obj_; 8020 void* js_stack_comparable_address_; 8021 bool is_verbose_ : 1; 8022 bool can_continue_ : 1; 8023 bool capture_message_ : 1; 8024 bool rethrow_ : 1; 8025 bool has_terminated_ : 1; 8026 8027 friend class internal::Isolate; 8028 }; 8029 8030 8031 // --- Context --- 8032 8033 8034 /** 8035 * A container for extension names. 8036 */ 8037 class V8_EXPORT ExtensionConfiguration { 8038 public: 8039 ExtensionConfiguration() : name_count_(0), names_(NULL) { } 8040 ExtensionConfiguration(int name_count, const char* names[]) 8041 : name_count_(name_count), names_(names) { } 8042 8043 const char** begin() const { return &names_[0]; } 8044 const char** end() const { return &names_[name_count_]; } 8045 8046 private: 8047 const int name_count_; 8048 const char** names_; 8049 }; 8050 8051 /** 8052 * A sandboxed execution context with its own set of built-in objects 8053 * and functions. 8054 */ 8055 class V8_EXPORT Context { 8056 public: 8057 /** 8058 * Returns the global proxy object. 8059 * 8060 * Global proxy object is a thin wrapper whose prototype points to actual 8061 * context's global object with the properties like Object, etc. This is done 8062 * that way for security reasons (for more details see 8063 * https://wiki.mozilla.org/Gecko:SplitWindow). 8064 * 8065 * Please note that changes to global proxy object prototype most probably 8066 * would break VM---v8 expects only global object as a prototype of global 8067 * proxy object. 8068 */ 8069 Local<Object> Global(); 8070 8071 /** 8072 * Detaches the global object from its context before 8073 * the global object can be reused to create a new context. 8074 */ 8075 void DetachGlobal(); 8076 8077 /** 8078 * Creates a new context and returns a handle to the newly allocated 8079 * context. 8080 * 8081 * \param isolate The isolate in which to create the context. 8082 * 8083 * \param extensions An optional extension configuration containing 8084 * the extensions to be installed in the newly created context. 8085 * 8086 * \param global_template An optional object template from which the 8087 * global object for the newly created context will be created. 8088 * 8089 * \param global_object An optional global object to be reused for 8090 * the newly created context. This global object must have been 8091 * created by a previous call to Context::New with the same global 8092 * template. The state of the global object will be completely reset 8093 * and only object identify will remain. 8094 */ 8095 static Local<Context> New( 8096 Isolate* isolate, ExtensionConfiguration* extensions = NULL, 8097 MaybeLocal<ObjectTemplate> global_template = MaybeLocal<ObjectTemplate>(), 8098 MaybeLocal<Value> global_object = MaybeLocal<Value>()); 8099 8100 /** 8101 * Create a new context from a (non-default) context snapshot. There 8102 * is no way to provide a global object template since we do not create 8103 * a new global object from template, but we can reuse a global object. 8104 * 8105 * \param isolate See v8::Context::New. 8106 * 8107 * \param context_snapshot_index The index of the context snapshot to 8108 * deserialize from. Use v8::Context::New for the default snapshot. 8109 * 8110 * \param internal_fields_deserializer Optional callback to deserialize 8111 * internal fields. It should match the SerializeInternalFieldCallback used 8112 * to serialize. 8113 * 8114 * \param extensions See v8::Context::New. 8115 * 8116 * \param global_object See v8::Context::New. 8117 */ 8118 8119 static MaybeLocal<Context> FromSnapshot( 8120 Isolate* isolate, size_t context_snapshot_index, 8121 DeserializeInternalFieldsCallback internal_fields_deserializer = 8122 DeserializeInternalFieldsCallback(), 8123 ExtensionConfiguration* extensions = nullptr, 8124 MaybeLocal<Value> global_object = MaybeLocal<Value>()); 8125 8126 /** 8127 * Returns an global object that isn't backed by an actual context. 8128 * 8129 * The global template needs to have access checks with handlers installed. 8130 * If an existing global object is passed in, the global object is detached 8131 * from its context. 8132 * 8133 * Note that this is different from a detached context where all accesses to 8134 * the global proxy will fail. Instead, the access check handlers are invoked. 8135 * 8136 * It is also not possible to detach an object returned by this method. 8137 * Instead, the access check handlers need to return nothing to achieve the 8138 * same effect. 8139 * 8140 * It is possible, however, to create a new context from the global object 8141 * returned by this method. 8142 */ 8143 static MaybeLocal<Object> NewRemoteContext( 8144 Isolate* isolate, Local<ObjectTemplate> global_template, 8145 MaybeLocal<Value> global_object = MaybeLocal<Value>()); 8146 8147 /** 8148 * Sets the security token for the context. To access an object in 8149 * another context, the security tokens must match. 8150 */ 8151 void SetSecurityToken(Local<Value> token); 8152 8153 /** Restores the security token to the default value. */ 8154 void UseDefaultSecurityToken(); 8155 8156 /** Returns the security token of this context.*/ 8157 Local<Value> GetSecurityToken(); 8158 8159 /** 8160 * Enter this context. After entering a context, all code compiled 8161 * and run is compiled and run in this context. If another context 8162 * is already entered, this old context is saved so it can be 8163 * restored when the new context is exited. 8164 */ 8165 void Enter(); 8166 8167 /** 8168 * Exit this context. Exiting the current context restores the 8169 * context that was in place when entering the current context. 8170 */ 8171 void Exit(); 8172 8173 /** Returns an isolate associated with a current context. */ 8174 Isolate* GetIsolate(); 8175 8176 /** 8177 * The field at kDebugIdIndex is reserved for V8 debugger implementation. 8178 * The value is propagated to the scripts compiled in given Context and 8179 * can be used for filtering scripts. 8180 */ 8181 enum EmbedderDataFields { kDebugIdIndex = 0 }; 8182 8183 /** 8184 * Gets the embedder data with the given index, which must have been set by a 8185 * previous call to SetEmbedderData with the same index. Note that index 0 8186 * currently has a special meaning for Chrome's debugger. 8187 */ 8188 V8_INLINE Local<Value> GetEmbedderData(int index); 8189 8190 /** 8191 * Gets the binding object used by V8 extras. Extra natives get a reference 8192 * to this object and can use it to "export" functionality by adding 8193 * properties. Extra natives can also "import" functionality by accessing 8194 * properties added by the embedder using the V8 API. 8195 */ 8196 Local<Object> GetExtrasBindingObject(); 8197 8198 /** 8199 * Sets the embedder data with the given index, growing the data as 8200 * needed. Note that index 0 currently has a special meaning for Chrome's 8201 * debugger. 8202 */ 8203 void SetEmbedderData(int index, Local<Value> value); 8204 8205 /** 8206 * Gets a 2-byte-aligned native pointer from the embedder data with the given 8207 * index, which must have been set by a previous call to 8208 * SetAlignedPointerInEmbedderData with the same index. Note that index 0 8209 * currently has a special meaning for Chrome's debugger. 8210 */ 8211 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index); 8212 8213 /** 8214 * Sets a 2-byte-aligned native pointer in the embedder data with the given 8215 * index, growing the data as needed. Note that index 0 currently has a 8216 * special meaning for Chrome's debugger. 8217 */ 8218 void SetAlignedPointerInEmbedderData(int index, void* value); 8219 8220 /** 8221 * Control whether code generation from strings is allowed. Calling 8222 * this method with false will disable 'eval' and the 'Function' 8223 * constructor for code running in this context. If 'eval' or the 8224 * 'Function' constructor are used an exception will be thrown. 8225 * 8226 * If code generation from strings is not allowed the 8227 * V8::AllowCodeGenerationFromStrings callback will be invoked if 8228 * set before blocking the call to 'eval' or the 'Function' 8229 * constructor. If that callback returns true, the call will be 8230 * allowed, otherwise an exception will be thrown. If no callback is 8231 * set an exception will be thrown. 8232 */ 8233 void AllowCodeGenerationFromStrings(bool allow); 8234 8235 /** 8236 * Returns true if code generation from strings is allowed for the context. 8237 * For more details see AllowCodeGenerationFromStrings(bool) documentation. 8238 */ 8239 bool IsCodeGenerationFromStringsAllowed(); 8240 8241 /** 8242 * Sets the error description for the exception that is thrown when 8243 * code generation from strings is not allowed and 'eval' or the 'Function' 8244 * constructor are called. 8245 */ 8246 void SetErrorMessageForCodeGenerationFromStrings(Local<String> message); 8247 8248 /** 8249 * Estimate the memory in bytes retained by this context. 8250 */ 8251 size_t EstimatedSize(); 8252 8253 /** 8254 * Stack-allocated class which sets the execution context for all 8255 * operations executed within a local scope. 8256 */ 8257 class Scope { 8258 public: 8259 explicit V8_INLINE Scope(Local<Context> context) : context_(context) { 8260 context_->Enter(); 8261 } 8262 V8_INLINE ~Scope() { context_->Exit(); } 8263 8264 private: 8265 Local<Context> context_; 8266 }; 8267 8268 private: 8269 friend class Value; 8270 friend class Script; 8271 friend class Object; 8272 friend class Function; 8273 8274 Local<Value> SlowGetEmbedderData(int index); 8275 void* SlowGetAlignedPointerFromEmbedderData(int index); 8276 }; 8277 8278 8279 /** 8280 * Multiple threads in V8 are allowed, but only one thread at a time is allowed 8281 * to use any given V8 isolate, see the comments in the Isolate class. The 8282 * definition of 'using a V8 isolate' includes accessing handles or holding onto 8283 * object pointers obtained from V8 handles while in the particular V8 isolate. 8284 * It is up to the user of V8 to ensure, perhaps with locking, that this 8285 * constraint is not violated. In addition to any other synchronization 8286 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be 8287 * used to signal thread switches to V8. 8288 * 8289 * v8::Locker is a scoped lock object. While it's active, i.e. between its 8290 * construction and destruction, the current thread is allowed to use the locked 8291 * isolate. V8 guarantees that an isolate can be locked by at most one thread at 8292 * any time. In other words, the scope of a v8::Locker is a critical section. 8293 * 8294 * Sample usage: 8295 * \code 8296 * ... 8297 * { 8298 * v8::Locker locker(isolate); 8299 * v8::Isolate::Scope isolate_scope(isolate); 8300 * ... 8301 * // Code using V8 and isolate goes here. 8302 * ... 8303 * } // Destructor called here 8304 * \endcode 8305 * 8306 * If you wish to stop using V8 in a thread A you can do this either by 8307 * destroying the v8::Locker object as above or by constructing a v8::Unlocker 8308 * object: 8309 * 8310 * \code 8311 * { 8312 * isolate->Exit(); 8313 * v8::Unlocker unlocker(isolate); 8314 * ... 8315 * // Code not using V8 goes here while V8 can run in another thread. 8316 * ... 8317 * } // Destructor called here. 8318 * isolate->Enter(); 8319 * \endcode 8320 * 8321 * The Unlocker object is intended for use in a long-running callback from V8, 8322 * where you want to release the V8 lock for other threads to use. 8323 * 8324 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a 8325 * given thread. This can be useful if you have code that can be called either 8326 * from code that holds the lock or from code that does not. The Unlocker is 8327 * not recursive so you can not have several Unlockers on the stack at once, and 8328 * you can not use an Unlocker in a thread that is not inside a Locker's scope. 8329 * 8330 * An unlocker will unlock several lockers if it has to and reinstate the 8331 * correct depth of locking on its destruction, e.g.: 8332 * 8333 * \code 8334 * // V8 not locked. 8335 * { 8336 * v8::Locker locker(isolate); 8337 * Isolate::Scope isolate_scope(isolate); 8338 * // V8 locked. 8339 * { 8340 * v8::Locker another_locker(isolate); 8341 * // V8 still locked (2 levels). 8342 * { 8343 * isolate->Exit(); 8344 * v8::Unlocker unlocker(isolate); 8345 * // V8 not locked. 8346 * } 8347 * isolate->Enter(); 8348 * // V8 locked again (2 levels). 8349 * } 8350 * // V8 still locked (1 level). 8351 * } 8352 * // V8 Now no longer locked. 8353 * \endcode 8354 */ 8355 class V8_EXPORT Unlocker { 8356 public: 8357 /** 8358 * Initialize Unlocker for a given Isolate. 8359 */ 8360 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); } 8361 8362 ~Unlocker(); 8363 private: 8364 void Initialize(Isolate* isolate); 8365 8366 internal::Isolate* isolate_; 8367 }; 8368 8369 8370 class V8_EXPORT Locker { 8371 public: 8372 /** 8373 * Initialize Locker for a given Isolate. 8374 */ 8375 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); } 8376 8377 ~Locker(); 8378 8379 /** 8380 * Returns whether or not the locker for a given isolate, is locked by the 8381 * current thread. 8382 */ 8383 static bool IsLocked(Isolate* isolate); 8384 8385 /** 8386 * Returns whether v8::Locker is being used by this V8 instance. 8387 */ 8388 static bool IsActive(); 8389 8390 // Disallow copying and assigning. 8391 Locker(const Locker&) = delete; 8392 void operator=(const Locker&) = delete; 8393 8394 private: 8395 void Initialize(Isolate* isolate); 8396 8397 bool has_lock_; 8398 bool top_level_; 8399 internal::Isolate* isolate_; 8400 }; 8401 8402 8403 // --- Implementation --- 8404 8405 8406 namespace internal { 8407 8408 const int kApiPointerSize = sizeof(void*); // NOLINT 8409 const int kApiIntSize = sizeof(int); // NOLINT 8410 const int kApiInt64Size = sizeof(int64_t); // NOLINT 8411 8412 // Tag information for HeapObject. 8413 const int kHeapObjectTag = 1; 8414 const int kHeapObjectTagSize = 2; 8415 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1; 8416 8417 // Tag information for Smi. 8418 const int kSmiTag = 0; 8419 const int kSmiTagSize = 1; 8420 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1; 8421 8422 template <size_t ptr_size> struct SmiTagging; 8423 8424 template<int kSmiShiftSize> 8425 V8_INLINE internal::Object* IntToSmi(int value) { 8426 int smi_shift_bits = kSmiTagSize + kSmiShiftSize; 8427 uintptr_t tagged_value = 8428 (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag; 8429 return reinterpret_cast<internal::Object*>(tagged_value); 8430 } 8431 8432 // Smi constants for 32-bit systems. 8433 template <> struct SmiTagging<4> { 8434 enum { kSmiShiftSize = 0, kSmiValueSize = 31 }; 8435 static int SmiShiftSize() { return kSmiShiftSize; } 8436 static int SmiValueSize() { return kSmiValueSize; } 8437 V8_INLINE static int SmiToInt(const internal::Object* value) { 8438 int shift_bits = kSmiTagSize + kSmiShiftSize; 8439 // Throw away top 32 bits and shift down (requires >> to be sign extending). 8440 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits; 8441 } 8442 V8_INLINE static internal::Object* IntToSmi(int value) { 8443 return internal::IntToSmi<kSmiShiftSize>(value); 8444 } 8445 V8_INLINE static bool IsValidSmi(intptr_t value) { 8446 // To be representable as an tagged small integer, the two 8447 // most-significant bits of 'value' must be either 00 or 11 due to 8448 // sign-extension. To check this we add 01 to the two 8449 // most-significant bits, and check if the most-significant bit is 0 8450 // 8451 // CAUTION: The original code below: 8452 // bool result = ((value + 0x40000000) & 0x80000000) == 0; 8453 // may lead to incorrect results according to the C language spec, and 8454 // in fact doesn't work correctly with gcc4.1.1 in some cases: The 8455 // compiler may produce undefined results in case of signed integer 8456 // overflow. The computation must be done w/ unsigned ints. 8457 return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U; 8458 } 8459 }; 8460 8461 // Smi constants for 64-bit systems. 8462 template <> struct SmiTagging<8> { 8463 enum { kSmiShiftSize = 31, kSmiValueSize = 32 }; 8464 static int SmiShiftSize() { return kSmiShiftSize; } 8465 static int SmiValueSize() { return kSmiValueSize; } 8466 V8_INLINE static int SmiToInt(const internal::Object* value) { 8467 int shift_bits = kSmiTagSize + kSmiShiftSize; 8468 // Shift down and throw away top 32 bits. 8469 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits); 8470 } 8471 V8_INLINE static internal::Object* IntToSmi(int value) { 8472 return internal::IntToSmi<kSmiShiftSize>(value); 8473 } 8474 V8_INLINE static bool IsValidSmi(intptr_t value) { 8475 // To be representable as a long smi, the value must be a 32-bit integer. 8476 return (value == static_cast<int32_t>(value)); 8477 } 8478 }; 8479 8480 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging; 8481 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize; 8482 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize; 8483 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; } 8484 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; } 8485 8486 /** 8487 * This class exports constants and functionality from within v8 that 8488 * is necessary to implement inline functions in the v8 api. Don't 8489 * depend on functions and constants defined here. 8490 */ 8491 class Internals { 8492 public: 8493 // These values match non-compiler-dependent values defined within 8494 // the implementation of v8. 8495 static const int kHeapObjectMapOffset = 0; 8496 static const int kMapInstanceTypeAndBitFieldOffset = 8497 1 * kApiPointerSize + kApiIntSize; 8498 static const int kStringResourceOffset = 3 * kApiPointerSize; 8499 8500 static const int kOddballKindOffset = 4 * kApiPointerSize + sizeof(double); 8501 static const int kForeignAddressOffset = kApiPointerSize; 8502 static const int kJSObjectHeaderSize = 3 * kApiPointerSize; 8503 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize; 8504 static const int kContextHeaderSize = 2 * kApiPointerSize; 8505 static const int kContextEmbedderDataIndex = 5; 8506 static const int kFullStringRepresentationMask = 0x0f; 8507 static const int kStringEncodingMask = 0x8; 8508 static const int kExternalTwoByteRepresentationTag = 0x02; 8509 static const int kExternalOneByteRepresentationTag = 0x0a; 8510 8511 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize; 8512 static const int kExternalMemoryOffset = 4 * kApiPointerSize; 8513 static const int kExternalMemoryLimitOffset = 8514 kExternalMemoryOffset + kApiInt64Size; 8515 static const int kIsolateRootsOffset = kExternalMemoryLimitOffset + 8516 kApiInt64Size + kApiInt64Size + 8517 kApiPointerSize + kApiPointerSize; 8518 static const int kUndefinedValueRootIndex = 4; 8519 static const int kTheHoleValueRootIndex = 5; 8520 static const int kNullValueRootIndex = 6; 8521 static const int kTrueValueRootIndex = 7; 8522 static const int kFalseValueRootIndex = 8; 8523 static const int kEmptyStringRootIndex = 9; 8524 8525 static const int kNodeClassIdOffset = 1 * kApiPointerSize; 8526 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3; 8527 static const int kNodeStateMask = 0x7; 8528 static const int kNodeStateIsWeakValue = 2; 8529 static const int kNodeStateIsPendingValue = 3; 8530 static const int kNodeStateIsNearDeathValue = 4; 8531 static const int kNodeIsIndependentShift = 3; 8532 static const int kNodeIsActiveShift = 4; 8533 8534 static const int kJSApiObjectType = 0xb9; 8535 static const int kJSObjectType = 0xba; 8536 static const int kFirstNonstringType = 0x80; 8537 static const int kOddballType = 0x82; 8538 static const int kForeignType = 0x86; 8539 8540 static const int kUndefinedOddballKind = 5; 8541 static const int kNullOddballKind = 3; 8542 8543 static const uint32_t kNumIsolateDataSlots = 4; 8544 8545 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate); 8546 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) { 8547 #ifdef V8_ENABLE_CHECKS 8548 CheckInitializedImpl(isolate); 8549 #endif 8550 } 8551 8552 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) { 8553 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) == 8554 kHeapObjectTag); 8555 } 8556 8557 V8_INLINE static int SmiValue(const internal::Object* value) { 8558 return PlatformSmiTagging::SmiToInt(value); 8559 } 8560 8561 V8_INLINE static internal::Object* IntToSmi(int value) { 8562 return PlatformSmiTagging::IntToSmi(value); 8563 } 8564 8565 V8_INLINE static bool IsValidSmi(intptr_t value) { 8566 return PlatformSmiTagging::IsValidSmi(value); 8567 } 8568 8569 V8_INLINE static int GetInstanceType(const internal::Object* obj) { 8570 typedef internal::Object O; 8571 O* map = ReadField<O*>(obj, kHeapObjectMapOffset); 8572 // Map::InstanceType is defined so that it will always be loaded into 8573 // the LS 8 bits of one 16-bit word, regardless of endianess. 8574 return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff; 8575 } 8576 8577 V8_INLINE static int GetOddballKind(const internal::Object* obj) { 8578 typedef internal::Object O; 8579 return SmiValue(ReadField<O*>(obj, kOddballKindOffset)); 8580 } 8581 8582 V8_INLINE static bool IsExternalTwoByteString(int instance_type) { 8583 int representation = (instance_type & kFullStringRepresentationMask); 8584 return representation == kExternalTwoByteRepresentationTag; 8585 } 8586 8587 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) { 8588 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset; 8589 return *addr & static_cast<uint8_t>(1U << shift); 8590 } 8591 8592 V8_INLINE static void UpdateNodeFlag(internal::Object** obj, 8593 bool value, int shift) { 8594 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset; 8595 uint8_t mask = static_cast<uint8_t>(1U << shift); 8596 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift)); 8597 } 8598 8599 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) { 8600 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset; 8601 return *addr & kNodeStateMask; 8602 } 8603 8604 V8_INLINE static void UpdateNodeState(internal::Object** obj, 8605 uint8_t value) { 8606 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset; 8607 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value); 8608 } 8609 8610 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate, 8611 uint32_t slot, 8612 void* data) { 8613 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + 8614 kIsolateEmbedderDataOffset + slot * kApiPointerSize; 8615 *reinterpret_cast<void**>(addr) = data; 8616 } 8617 8618 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate, 8619 uint32_t slot) { 8620 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) + 8621 kIsolateEmbedderDataOffset + slot * kApiPointerSize; 8622 return *reinterpret_cast<void* const*>(addr); 8623 } 8624 8625 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate, 8626 int index) { 8627 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset; 8628 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize); 8629 } 8630 8631 template <typename T> 8632 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) { 8633 const uint8_t* addr = 8634 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag; 8635 return *reinterpret_cast<const T*>(addr); 8636 } 8637 8638 template <typename T> 8639 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) { 8640 typedef internal::Object O; 8641 typedef internal::Internals I; 8642 O* ctx = *reinterpret_cast<O* const*>(context); 8643 int embedder_data_offset = I::kContextHeaderSize + 8644 (internal::kApiPointerSize * I::kContextEmbedderDataIndex); 8645 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset); 8646 int value_offset = 8647 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index); 8648 return I::ReadField<T>(embedder_data, value_offset); 8649 } 8650 }; 8651 8652 } // namespace internal 8653 8654 8655 template <class T> 8656 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) { 8657 return New(isolate, that.val_); 8658 } 8659 8660 template <class T> 8661 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) { 8662 return New(isolate, that.val_); 8663 } 8664 8665 8666 template <class T> 8667 Local<T> Local<T>::New(Isolate* isolate, T* that) { 8668 if (that == NULL) return Local<T>(); 8669 T* that_ptr = that; 8670 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr); 8671 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle( 8672 reinterpret_cast<internal::Isolate*>(isolate), *p))); 8673 } 8674 8675 8676 template<class T> 8677 template<class S> 8678 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) { 8679 TYPE_CHECK(T, S); 8680 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_); 8681 } 8682 8683 8684 template<class T> 8685 Local<T> Eternal<T>::Get(Isolate* isolate) { 8686 return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_))); 8687 } 8688 8689 8690 template <class T> 8691 Local<T> MaybeLocal<T>::ToLocalChecked() { 8692 if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty(); 8693 return Local<T>(val_); 8694 } 8695 8696 8697 template <class T> 8698 void* WeakCallbackInfo<T>::GetInternalField(int index) const { 8699 #ifdef V8_ENABLE_CHECKS 8700 if (index < 0 || index >= kInternalFieldsInWeakCallback) { 8701 V8::InternalFieldOutOfBounds(index); 8702 } 8703 #endif 8704 return internal_fields_[index]; 8705 } 8706 8707 8708 template <class T> 8709 T* PersistentBase<T>::New(Isolate* isolate, T* that) { 8710 if (that == NULL) return NULL; 8711 internal::Object** p = reinterpret_cast<internal::Object**>(that); 8712 return reinterpret_cast<T*>( 8713 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate), 8714 p)); 8715 } 8716 8717 8718 template <class T, class M> 8719 template <class S, class M2> 8720 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) { 8721 TYPE_CHECK(T, S); 8722 this->Reset(); 8723 if (that.IsEmpty()) return; 8724 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_); 8725 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p)); 8726 M::Copy(that, this); 8727 } 8728 8729 8730 template <class T> 8731 bool PersistentBase<T>::IsIndependent() const { 8732 typedef internal::Internals I; 8733 if (this->IsEmpty()) return false; 8734 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_), 8735 I::kNodeIsIndependentShift); 8736 } 8737 8738 8739 template <class T> 8740 bool PersistentBase<T>::IsNearDeath() const { 8741 typedef internal::Internals I; 8742 if (this->IsEmpty()) return false; 8743 uint8_t node_state = 8744 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)); 8745 return node_state == I::kNodeStateIsNearDeathValue || 8746 node_state == I::kNodeStateIsPendingValue; 8747 } 8748 8749 8750 template <class T> 8751 bool PersistentBase<T>::IsWeak() const { 8752 typedef internal::Internals I; 8753 if (this->IsEmpty()) return false; 8754 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) == 8755 I::kNodeStateIsWeakValue; 8756 } 8757 8758 8759 template <class T> 8760 void PersistentBase<T>::Reset() { 8761 if (this->IsEmpty()) return; 8762 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_)); 8763 val_ = 0; 8764 } 8765 8766 8767 template <class T> 8768 template <class S> 8769 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) { 8770 TYPE_CHECK(T, S); 8771 Reset(); 8772 if (other.IsEmpty()) return; 8773 this->val_ = New(isolate, other.val_); 8774 } 8775 8776 8777 template <class T> 8778 template <class S> 8779 void PersistentBase<T>::Reset(Isolate* isolate, 8780 const PersistentBase<S>& other) { 8781 TYPE_CHECK(T, S); 8782 Reset(); 8783 if (other.IsEmpty()) return; 8784 this->val_ = New(isolate, other.val_); 8785 } 8786 8787 8788 template <class T> 8789 template <typename P> 8790 V8_INLINE void PersistentBase<T>::SetWeak( 8791 P* parameter, typename WeakCallbackInfo<P>::Callback callback, 8792 WeakCallbackType type) { 8793 typedef typename WeakCallbackInfo<void>::Callback Callback; 8794 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter, 8795 reinterpret_cast<Callback>(callback), type); 8796 } 8797 8798 template <class T> 8799 void PersistentBase<T>::SetWeak() { 8800 V8::MakeWeak(reinterpret_cast<internal::Object***>(&this->val_)); 8801 } 8802 8803 template <class T> 8804 template <typename P> 8805 P* PersistentBase<T>::ClearWeak() { 8806 return reinterpret_cast<P*>( 8807 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_))); 8808 } 8809 8810 template <class T> 8811 void PersistentBase<T>::RegisterExternalReference(Isolate* isolate) const { 8812 if (IsEmpty()) return; 8813 V8::RegisterExternallyReferencedObject( 8814 reinterpret_cast<internal::Object**>(this->val_), 8815 reinterpret_cast<internal::Isolate*>(isolate)); 8816 } 8817 8818 template <class T> 8819 void PersistentBase<T>::MarkIndependent() { 8820 typedef internal::Internals I; 8821 if (this->IsEmpty()) return; 8822 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), 8823 true, 8824 I::kNodeIsIndependentShift); 8825 } 8826 8827 template <class T> 8828 void PersistentBase<T>::MarkActive() { 8829 typedef internal::Internals I; 8830 if (this->IsEmpty()) return; 8831 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true, 8832 I::kNodeIsActiveShift); 8833 } 8834 8835 8836 template <class T> 8837 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) { 8838 typedef internal::Internals I; 8839 if (this->IsEmpty()) return; 8840 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_); 8841 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset; 8842 *reinterpret_cast<uint16_t*>(addr) = class_id; 8843 } 8844 8845 8846 template <class T> 8847 uint16_t PersistentBase<T>::WrapperClassId() const { 8848 typedef internal::Internals I; 8849 if (this->IsEmpty()) return 0; 8850 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_); 8851 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset; 8852 return *reinterpret_cast<uint16_t*>(addr); 8853 } 8854 8855 8856 template<typename T> 8857 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {} 8858 8859 template<typename T> 8860 template<typename S> 8861 void ReturnValue<T>::Set(const Persistent<S>& handle) { 8862 TYPE_CHECK(T, S); 8863 if (V8_UNLIKELY(handle.IsEmpty())) { 8864 *value_ = GetDefaultValue(); 8865 } else { 8866 *value_ = *reinterpret_cast<internal::Object**>(*handle); 8867 } 8868 } 8869 8870 template <typename T> 8871 template <typename S> 8872 void ReturnValue<T>::Set(const Global<S>& handle) { 8873 TYPE_CHECK(T, S); 8874 if (V8_UNLIKELY(handle.IsEmpty())) { 8875 *value_ = GetDefaultValue(); 8876 } else { 8877 *value_ = *reinterpret_cast<internal::Object**>(*handle); 8878 } 8879 } 8880 8881 template <typename T> 8882 template <typename S> 8883 void ReturnValue<T>::Set(const Local<S> handle) { 8884 TYPE_CHECK(T, S); 8885 if (V8_UNLIKELY(handle.IsEmpty())) { 8886 *value_ = GetDefaultValue(); 8887 } else { 8888 *value_ = *reinterpret_cast<internal::Object**>(*handle); 8889 } 8890 } 8891 8892 template<typename T> 8893 void ReturnValue<T>::Set(double i) { 8894 TYPE_CHECK(T, Number); 8895 Set(Number::New(GetIsolate(), i)); 8896 } 8897 8898 template<typename T> 8899 void ReturnValue<T>::Set(int32_t i) { 8900 TYPE_CHECK(T, Integer); 8901 typedef internal::Internals I; 8902 if (V8_LIKELY(I::IsValidSmi(i))) { 8903 *value_ = I::IntToSmi(i); 8904 return; 8905 } 8906 Set(Integer::New(GetIsolate(), i)); 8907 } 8908 8909 template<typename T> 8910 void ReturnValue<T>::Set(uint32_t i) { 8911 TYPE_CHECK(T, Integer); 8912 // Can't simply use INT32_MAX here for whatever reason. 8913 bool fits_into_int32_t = (i & (1U << 31)) == 0; 8914 if (V8_LIKELY(fits_into_int32_t)) { 8915 Set(static_cast<int32_t>(i)); 8916 return; 8917 } 8918 Set(Integer::NewFromUnsigned(GetIsolate(), i)); 8919 } 8920 8921 template<typename T> 8922 void ReturnValue<T>::Set(bool value) { 8923 TYPE_CHECK(T, Boolean); 8924 typedef internal::Internals I; 8925 int root_index; 8926 if (value) { 8927 root_index = I::kTrueValueRootIndex; 8928 } else { 8929 root_index = I::kFalseValueRootIndex; 8930 } 8931 *value_ = *I::GetRoot(GetIsolate(), root_index); 8932 } 8933 8934 template<typename T> 8935 void ReturnValue<T>::SetNull() { 8936 TYPE_CHECK(T, Primitive); 8937 typedef internal::Internals I; 8938 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex); 8939 } 8940 8941 template<typename T> 8942 void ReturnValue<T>::SetUndefined() { 8943 TYPE_CHECK(T, Primitive); 8944 typedef internal::Internals I; 8945 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex); 8946 } 8947 8948 template<typename T> 8949 void ReturnValue<T>::SetEmptyString() { 8950 TYPE_CHECK(T, String); 8951 typedef internal::Internals I; 8952 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex); 8953 } 8954 8955 template <typename T> 8956 Isolate* ReturnValue<T>::GetIsolate() const { 8957 // Isolate is always the pointer below the default value on the stack. 8958 return *reinterpret_cast<Isolate**>(&value_[-2]); 8959 } 8960 8961 template <typename T> 8962 Local<Value> ReturnValue<T>::Get() const { 8963 typedef internal::Internals I; 8964 if (*value_ == *I::GetRoot(GetIsolate(), I::kTheHoleValueRootIndex)) 8965 return Local<Value>(*Undefined(GetIsolate())); 8966 return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_)); 8967 } 8968 8969 template <typename T> 8970 template <typename S> 8971 void ReturnValue<T>::Set(S* whatever) { 8972 // Uncompilable to prevent inadvertent misuse. 8973 TYPE_CHECK(S*, Primitive); 8974 } 8975 8976 template<typename T> 8977 internal::Object* ReturnValue<T>::GetDefaultValue() { 8978 // Default value is always the pointer below value_ on the stack. 8979 return value_[-1]; 8980 } 8981 8982 template <typename T> 8983 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args, 8984 internal::Object** values, 8985 int length) 8986 : implicit_args_(implicit_args), values_(values), length_(length) {} 8987 8988 template<typename T> 8989 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const { 8990 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate())); 8991 return Local<Value>(reinterpret_cast<Value*>(values_ - i)); 8992 } 8993 8994 8995 template<typename T> 8996 Local<Function> FunctionCallbackInfo<T>::Callee() const { 8997 return Local<Function>(reinterpret_cast<Function*>( 8998 &implicit_args_[kCalleeIndex])); 8999 } 9000 9001 9002 template<typename T> 9003 Local<Object> FunctionCallbackInfo<T>::This() const { 9004 return Local<Object>(reinterpret_cast<Object*>(values_ + 1)); 9005 } 9006 9007 9008 template<typename T> 9009 Local<Object> FunctionCallbackInfo<T>::Holder() const { 9010 return Local<Object>(reinterpret_cast<Object*>( 9011 &implicit_args_[kHolderIndex])); 9012 } 9013 9014 template <typename T> 9015 Local<Value> FunctionCallbackInfo<T>::NewTarget() const { 9016 return Local<Value>( 9017 reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex])); 9018 } 9019 9020 template <typename T> 9021 Local<Value> FunctionCallbackInfo<T>::Data() const { 9022 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex])); 9023 } 9024 9025 9026 template<typename T> 9027 Isolate* FunctionCallbackInfo<T>::GetIsolate() const { 9028 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]); 9029 } 9030 9031 9032 template<typename T> 9033 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const { 9034 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]); 9035 } 9036 9037 9038 template<typename T> 9039 bool FunctionCallbackInfo<T>::IsConstructCall() const { 9040 return !NewTarget()->IsUndefined(); 9041 } 9042 9043 9044 template<typename T> 9045 int FunctionCallbackInfo<T>::Length() const { 9046 return length_; 9047 } 9048 9049 ScriptOrigin::ScriptOrigin(Local<Value> resource_name, 9050 Local<Integer> resource_line_offset, 9051 Local<Integer> resource_column_offset, 9052 Local<Boolean> resource_is_shared_cross_origin, 9053 Local<Integer> script_id, 9054 Local<Value> source_map_url, 9055 Local<Boolean> resource_is_opaque, 9056 Local<Boolean> is_wasm, Local<Boolean> is_module) 9057 : resource_name_(resource_name), 9058 resource_line_offset_(resource_line_offset), 9059 resource_column_offset_(resource_column_offset), 9060 options_(!resource_is_shared_cross_origin.IsEmpty() && 9061 resource_is_shared_cross_origin->IsTrue(), 9062 !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(), 9063 !is_wasm.IsEmpty() && is_wasm->IsTrue(), 9064 !is_module.IsEmpty() && is_module->IsTrue()), 9065 script_id_(script_id), 9066 source_map_url_(source_map_url) {} 9067 9068 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; } 9069 9070 9071 Local<Integer> ScriptOrigin::ResourceLineOffset() const { 9072 return resource_line_offset_; 9073 } 9074 9075 9076 Local<Integer> ScriptOrigin::ResourceColumnOffset() const { 9077 return resource_column_offset_; 9078 } 9079 9080 9081 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; } 9082 9083 9084 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; } 9085 9086 9087 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin, 9088 CachedData* data) 9089 : source_string(string), 9090 resource_name(origin.ResourceName()), 9091 resource_line_offset(origin.ResourceLineOffset()), 9092 resource_column_offset(origin.ResourceColumnOffset()), 9093 resource_options(origin.Options()), 9094 source_map_url(origin.SourceMapUrl()), 9095 cached_data(data) {} 9096 9097 9098 ScriptCompiler::Source::Source(Local<String> string, 9099 CachedData* data) 9100 : source_string(string), cached_data(data) {} 9101 9102 9103 ScriptCompiler::Source::~Source() { 9104 delete cached_data; 9105 } 9106 9107 9108 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData() 9109 const { 9110 return cached_data; 9111 } 9112 9113 const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const { 9114 return resource_options; 9115 } 9116 9117 Local<Boolean> Boolean::New(Isolate* isolate, bool value) { 9118 return value ? True(isolate) : False(isolate); 9119 } 9120 9121 void Template::Set(Isolate* isolate, const char* name, Local<Data> value) { 9122 Set(String::NewFromUtf8(isolate, name, NewStringType::kInternalized) 9123 .ToLocalChecked(), 9124 value); 9125 } 9126 9127 9128 Local<Value> Object::GetInternalField(int index) { 9129 #ifndef V8_ENABLE_CHECKS 9130 typedef internal::Object O; 9131 typedef internal::HeapObject HO; 9132 typedef internal::Internals I; 9133 O* obj = *reinterpret_cast<O**>(this); 9134 // Fast path: If the object is a plain JSObject, which is the common case, we 9135 // know where to find the internal fields and can return the value directly. 9136 auto instance_type = I::GetInstanceType(obj); 9137 if (instance_type == I::kJSObjectType || 9138 instance_type == I::kJSApiObjectType) { 9139 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index); 9140 O* value = I::ReadField<O*>(obj, offset); 9141 O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value); 9142 return Local<Value>(reinterpret_cast<Value*>(result)); 9143 } 9144 #endif 9145 return SlowGetInternalField(index); 9146 } 9147 9148 9149 void* Object::GetAlignedPointerFromInternalField(int index) { 9150 #ifndef V8_ENABLE_CHECKS 9151 typedef internal::Object O; 9152 typedef internal::Internals I; 9153 O* obj = *reinterpret_cast<O**>(this); 9154 // Fast path: If the object is a plain JSObject, which is the common case, we 9155 // know where to find the internal fields and can return the value directly. 9156 auto instance_type = I::GetInstanceType(obj); 9157 if (V8_LIKELY(instance_type == I::kJSObjectType || 9158 instance_type == I::kJSApiObjectType)) { 9159 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index); 9160 return I::ReadField<void*>(obj, offset); 9161 } 9162 #endif 9163 return SlowGetAlignedPointerFromInternalField(index); 9164 } 9165 9166 String* String::Cast(v8::Value* value) { 9167 #ifdef V8_ENABLE_CHECKS 9168 CheckCast(value); 9169 #endif 9170 return static_cast<String*>(value); 9171 } 9172 9173 9174 Local<String> String::Empty(Isolate* isolate) { 9175 typedef internal::Object* S; 9176 typedef internal::Internals I; 9177 I::CheckInitialized(isolate); 9178 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex); 9179 return Local<String>(reinterpret_cast<String*>(slot)); 9180 } 9181 9182 9183 String::ExternalStringResource* String::GetExternalStringResource() const { 9184 typedef internal::Object O; 9185 typedef internal::Internals I; 9186 O* obj = *reinterpret_cast<O* const*>(this); 9187 String::ExternalStringResource* result; 9188 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) { 9189 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset); 9190 result = reinterpret_cast<String::ExternalStringResource*>(value); 9191 } else { 9192 result = NULL; 9193 } 9194 #ifdef V8_ENABLE_CHECKS 9195 VerifyExternalStringResource(result); 9196 #endif 9197 return result; 9198 } 9199 9200 9201 String::ExternalStringResourceBase* String::GetExternalStringResourceBase( 9202 String::Encoding* encoding_out) const { 9203 typedef internal::Object O; 9204 typedef internal::Internals I; 9205 O* obj = *reinterpret_cast<O* const*>(this); 9206 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask; 9207 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask); 9208 ExternalStringResourceBase* resource = NULL; 9209 if (type == I::kExternalOneByteRepresentationTag || 9210 type == I::kExternalTwoByteRepresentationTag) { 9211 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset); 9212 resource = static_cast<ExternalStringResourceBase*>(value); 9213 } 9214 #ifdef V8_ENABLE_CHECKS 9215 VerifyExternalStringResourceBase(resource, *encoding_out); 9216 #endif 9217 return resource; 9218 } 9219 9220 9221 bool Value::IsUndefined() const { 9222 #ifdef V8_ENABLE_CHECKS 9223 return FullIsUndefined(); 9224 #else 9225 return QuickIsUndefined(); 9226 #endif 9227 } 9228 9229 bool Value::QuickIsUndefined() const { 9230 typedef internal::Object O; 9231 typedef internal::Internals I; 9232 O* obj = *reinterpret_cast<O* const*>(this); 9233 if (!I::HasHeapObjectTag(obj)) return false; 9234 if (I::GetInstanceType(obj) != I::kOddballType) return false; 9235 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind); 9236 } 9237 9238 9239 bool Value::IsNull() const { 9240 #ifdef V8_ENABLE_CHECKS 9241 return FullIsNull(); 9242 #else 9243 return QuickIsNull(); 9244 #endif 9245 } 9246 9247 bool Value::QuickIsNull() const { 9248 typedef internal::Object O; 9249 typedef internal::Internals I; 9250 O* obj = *reinterpret_cast<O* const*>(this); 9251 if (!I::HasHeapObjectTag(obj)) return false; 9252 if (I::GetInstanceType(obj) != I::kOddballType) return false; 9253 return (I::GetOddballKind(obj) == I::kNullOddballKind); 9254 } 9255 9256 bool Value::IsNullOrUndefined() const { 9257 #ifdef V8_ENABLE_CHECKS 9258 return FullIsNull() || FullIsUndefined(); 9259 #else 9260 return QuickIsNullOrUndefined(); 9261 #endif 9262 } 9263 9264 bool Value::QuickIsNullOrUndefined() const { 9265 typedef internal::Object O; 9266 typedef internal::Internals I; 9267 O* obj = *reinterpret_cast<O* const*>(this); 9268 if (!I::HasHeapObjectTag(obj)) return false; 9269 if (I::GetInstanceType(obj) != I::kOddballType) return false; 9270 int kind = I::GetOddballKind(obj); 9271 return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind; 9272 } 9273 9274 bool Value::IsString() const { 9275 #ifdef V8_ENABLE_CHECKS 9276 return FullIsString(); 9277 #else 9278 return QuickIsString(); 9279 #endif 9280 } 9281 9282 bool Value::QuickIsString() const { 9283 typedef internal::Object O; 9284 typedef internal::Internals I; 9285 O* obj = *reinterpret_cast<O* const*>(this); 9286 if (!I::HasHeapObjectTag(obj)) return false; 9287 return (I::GetInstanceType(obj) < I::kFirstNonstringType); 9288 } 9289 9290 9291 template <class T> Value* Value::Cast(T* value) { 9292 return static_cast<Value*>(value); 9293 } 9294 9295 9296 Local<Boolean> Value::ToBoolean() const { 9297 return ToBoolean(Isolate::GetCurrent()->GetCurrentContext()) 9298 .FromMaybe(Local<Boolean>()); 9299 } 9300 9301 9302 Local<Number> Value::ToNumber() const { 9303 return ToNumber(Isolate::GetCurrent()->GetCurrentContext()) 9304 .FromMaybe(Local<Number>()); 9305 } 9306 9307 9308 Local<String> Value::ToString() const { 9309 return ToString(Isolate::GetCurrent()->GetCurrentContext()) 9310 .FromMaybe(Local<String>()); 9311 } 9312 9313 9314 Local<String> Value::ToDetailString() const { 9315 return ToDetailString(Isolate::GetCurrent()->GetCurrentContext()) 9316 .FromMaybe(Local<String>()); 9317 } 9318 9319 9320 Local<Object> Value::ToObject() const { 9321 return ToObject(Isolate::GetCurrent()->GetCurrentContext()) 9322 .FromMaybe(Local<Object>()); 9323 } 9324 9325 9326 Local<Integer> Value::ToInteger() const { 9327 return ToInteger(Isolate::GetCurrent()->GetCurrentContext()) 9328 .FromMaybe(Local<Integer>()); 9329 } 9330 9331 9332 Local<Uint32> Value::ToUint32() const { 9333 return ToUint32(Isolate::GetCurrent()->GetCurrentContext()) 9334 .FromMaybe(Local<Uint32>()); 9335 } 9336 9337 9338 Local<Int32> Value::ToInt32() const { 9339 return ToInt32(Isolate::GetCurrent()->GetCurrentContext()) 9340 .FromMaybe(Local<Int32>()); 9341 } 9342 9343 9344 Boolean* Boolean::Cast(v8::Value* value) { 9345 #ifdef V8_ENABLE_CHECKS 9346 CheckCast(value); 9347 #endif 9348 return static_cast<Boolean*>(value); 9349 } 9350 9351 9352 Name* Name::Cast(v8::Value* value) { 9353 #ifdef V8_ENABLE_CHECKS 9354 CheckCast(value); 9355 #endif 9356 return static_cast<Name*>(value); 9357 } 9358 9359 9360 Symbol* Symbol::Cast(v8::Value* value) { 9361 #ifdef V8_ENABLE_CHECKS 9362 CheckCast(value); 9363 #endif 9364 return static_cast<Symbol*>(value); 9365 } 9366 9367 9368 Number* Number::Cast(v8::Value* value) { 9369 #ifdef V8_ENABLE_CHECKS 9370 CheckCast(value); 9371 #endif 9372 return static_cast<Number*>(value); 9373 } 9374 9375 9376 Integer* Integer::Cast(v8::Value* value) { 9377 #ifdef V8_ENABLE_CHECKS 9378 CheckCast(value); 9379 #endif 9380 return static_cast<Integer*>(value); 9381 } 9382 9383 9384 Int32* Int32::Cast(v8::Value* value) { 9385 #ifdef V8_ENABLE_CHECKS 9386 CheckCast(value); 9387 #endif 9388 return static_cast<Int32*>(value); 9389 } 9390 9391 9392 Uint32* Uint32::Cast(v8::Value* value) { 9393 #ifdef V8_ENABLE_CHECKS 9394 CheckCast(value); 9395 #endif 9396 return static_cast<Uint32*>(value); 9397 } 9398 9399 9400 Date* Date::Cast(v8::Value* value) { 9401 #ifdef V8_ENABLE_CHECKS 9402 CheckCast(value); 9403 #endif 9404 return static_cast<Date*>(value); 9405 } 9406 9407 9408 StringObject* StringObject::Cast(v8::Value* value) { 9409 #ifdef V8_ENABLE_CHECKS 9410 CheckCast(value); 9411 #endif 9412 return static_cast<StringObject*>(value); 9413 } 9414 9415 9416 SymbolObject* SymbolObject::Cast(v8::Value* value) { 9417 #ifdef V8_ENABLE_CHECKS 9418 CheckCast(value); 9419 #endif 9420 return static_cast<SymbolObject*>(value); 9421 } 9422 9423 9424 NumberObject* NumberObject::Cast(v8::Value* value) { 9425 #ifdef V8_ENABLE_CHECKS 9426 CheckCast(value); 9427 #endif 9428 return static_cast<NumberObject*>(value); 9429 } 9430 9431 9432 BooleanObject* BooleanObject::Cast(v8::Value* value) { 9433 #ifdef V8_ENABLE_CHECKS 9434 CheckCast(value); 9435 #endif 9436 return static_cast<BooleanObject*>(value); 9437 } 9438 9439 9440 RegExp* RegExp::Cast(v8::Value* value) { 9441 #ifdef V8_ENABLE_CHECKS 9442 CheckCast(value); 9443 #endif 9444 return static_cast<RegExp*>(value); 9445 } 9446 9447 9448 Object* Object::Cast(v8::Value* value) { 9449 #ifdef V8_ENABLE_CHECKS 9450 CheckCast(value); 9451 #endif 9452 return static_cast<Object*>(value); 9453 } 9454 9455 9456 Array* Array::Cast(v8::Value* value) { 9457 #ifdef V8_ENABLE_CHECKS 9458 CheckCast(value); 9459 #endif 9460 return static_cast<Array*>(value); 9461 } 9462 9463 9464 Map* Map::Cast(v8::Value* value) { 9465 #ifdef V8_ENABLE_CHECKS 9466 CheckCast(value); 9467 #endif 9468 return static_cast<Map*>(value); 9469 } 9470 9471 9472 Set* Set::Cast(v8::Value* value) { 9473 #ifdef V8_ENABLE_CHECKS 9474 CheckCast(value); 9475 #endif 9476 return static_cast<Set*>(value); 9477 } 9478 9479 9480 Promise* Promise::Cast(v8::Value* value) { 9481 #ifdef V8_ENABLE_CHECKS 9482 CheckCast(value); 9483 #endif 9484 return static_cast<Promise*>(value); 9485 } 9486 9487 9488 Proxy* Proxy::Cast(v8::Value* value) { 9489 #ifdef V8_ENABLE_CHECKS 9490 CheckCast(value); 9491 #endif 9492 return static_cast<Proxy*>(value); 9493 } 9494 9495 WasmCompiledModule* WasmCompiledModule::Cast(v8::Value* value) { 9496 #ifdef V8_ENABLE_CHECKS 9497 CheckCast(value); 9498 #endif 9499 return static_cast<WasmCompiledModule*>(value); 9500 } 9501 9502 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) { 9503 #ifdef V8_ENABLE_CHECKS 9504 CheckCast(value); 9505 #endif 9506 return static_cast<Promise::Resolver*>(value); 9507 } 9508 9509 9510 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) { 9511 #ifdef V8_ENABLE_CHECKS 9512 CheckCast(value); 9513 #endif 9514 return static_cast<ArrayBuffer*>(value); 9515 } 9516 9517 9518 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) { 9519 #ifdef V8_ENABLE_CHECKS 9520 CheckCast(value); 9521 #endif 9522 return static_cast<ArrayBufferView*>(value); 9523 } 9524 9525 9526 TypedArray* TypedArray::Cast(v8::Value* value) { 9527 #ifdef V8_ENABLE_CHECKS 9528 CheckCast(value); 9529 #endif 9530 return static_cast<TypedArray*>(value); 9531 } 9532 9533 9534 Uint8Array* Uint8Array::Cast(v8::Value* value) { 9535 #ifdef V8_ENABLE_CHECKS 9536 CheckCast(value); 9537 #endif 9538 return static_cast<Uint8Array*>(value); 9539 } 9540 9541 9542 Int8Array* Int8Array::Cast(v8::Value* value) { 9543 #ifdef V8_ENABLE_CHECKS 9544 CheckCast(value); 9545 #endif 9546 return static_cast<Int8Array*>(value); 9547 } 9548 9549 9550 Uint16Array* Uint16Array::Cast(v8::Value* value) { 9551 #ifdef V8_ENABLE_CHECKS 9552 CheckCast(value); 9553 #endif 9554 return static_cast<Uint16Array*>(value); 9555 } 9556 9557 9558 Int16Array* Int16Array::Cast(v8::Value* value) { 9559 #ifdef V8_ENABLE_CHECKS 9560 CheckCast(value); 9561 #endif 9562 return static_cast<Int16Array*>(value); 9563 } 9564 9565 9566 Uint32Array* Uint32Array::Cast(v8::Value* value) { 9567 #ifdef V8_ENABLE_CHECKS 9568 CheckCast(value); 9569 #endif 9570 return static_cast<Uint32Array*>(value); 9571 } 9572 9573 9574 Int32Array* Int32Array::Cast(v8::Value* value) { 9575 #ifdef V8_ENABLE_CHECKS 9576 CheckCast(value); 9577 #endif 9578 return static_cast<Int32Array*>(value); 9579 } 9580 9581 9582 Float32Array* Float32Array::Cast(v8::Value* value) { 9583 #ifdef V8_ENABLE_CHECKS 9584 CheckCast(value); 9585 #endif 9586 return static_cast<Float32Array*>(value); 9587 } 9588 9589 9590 Float64Array* Float64Array::Cast(v8::Value* value) { 9591 #ifdef V8_ENABLE_CHECKS 9592 CheckCast(value); 9593 #endif 9594 return static_cast<Float64Array*>(value); 9595 } 9596 9597 9598 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) { 9599 #ifdef V8_ENABLE_CHECKS 9600 CheckCast(value); 9601 #endif 9602 return static_cast<Uint8ClampedArray*>(value); 9603 } 9604 9605 9606 DataView* DataView::Cast(v8::Value* value) { 9607 #ifdef V8_ENABLE_CHECKS 9608 CheckCast(value); 9609 #endif 9610 return static_cast<DataView*>(value); 9611 } 9612 9613 9614 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) { 9615 #ifdef V8_ENABLE_CHECKS 9616 CheckCast(value); 9617 #endif 9618 return static_cast<SharedArrayBuffer*>(value); 9619 } 9620 9621 9622 Function* Function::Cast(v8::Value* value) { 9623 #ifdef V8_ENABLE_CHECKS 9624 CheckCast(value); 9625 #endif 9626 return static_cast<Function*>(value); 9627 } 9628 9629 9630 External* External::Cast(v8::Value* value) { 9631 #ifdef V8_ENABLE_CHECKS 9632 CheckCast(value); 9633 #endif 9634 return static_cast<External*>(value); 9635 } 9636 9637 9638 template<typename T> 9639 Isolate* PropertyCallbackInfo<T>::GetIsolate() const { 9640 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]); 9641 } 9642 9643 9644 template<typename T> 9645 Local<Value> PropertyCallbackInfo<T>::Data() const { 9646 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex])); 9647 } 9648 9649 9650 template<typename T> 9651 Local<Object> PropertyCallbackInfo<T>::This() const { 9652 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex])); 9653 } 9654 9655 9656 template<typename T> 9657 Local<Object> PropertyCallbackInfo<T>::Holder() const { 9658 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex])); 9659 } 9660 9661 9662 template<typename T> 9663 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const { 9664 return ReturnValue<T>(&args_[kReturnValueIndex]); 9665 } 9666 9667 template <typename T> 9668 bool PropertyCallbackInfo<T>::ShouldThrowOnError() const { 9669 typedef internal::Internals I; 9670 return args_[kShouldThrowOnErrorIndex] != I::IntToSmi(0); 9671 } 9672 9673 9674 Local<Primitive> Undefined(Isolate* isolate) { 9675 typedef internal::Object* S; 9676 typedef internal::Internals I; 9677 I::CheckInitialized(isolate); 9678 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex); 9679 return Local<Primitive>(reinterpret_cast<Primitive*>(slot)); 9680 } 9681 9682 9683 Local<Primitive> Null(Isolate* isolate) { 9684 typedef internal::Object* S; 9685 typedef internal::Internals I; 9686 I::CheckInitialized(isolate); 9687 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex); 9688 return Local<Primitive>(reinterpret_cast<Primitive*>(slot)); 9689 } 9690 9691 9692 Local<Boolean> True(Isolate* isolate) { 9693 typedef internal::Object* S; 9694 typedef internal::Internals I; 9695 I::CheckInitialized(isolate); 9696 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex); 9697 return Local<Boolean>(reinterpret_cast<Boolean*>(slot)); 9698 } 9699 9700 9701 Local<Boolean> False(Isolate* isolate) { 9702 typedef internal::Object* S; 9703 typedef internal::Internals I; 9704 I::CheckInitialized(isolate); 9705 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex); 9706 return Local<Boolean>(reinterpret_cast<Boolean*>(slot)); 9707 } 9708 9709 9710 void Isolate::SetData(uint32_t slot, void* data) { 9711 typedef internal::Internals I; 9712 I::SetEmbedderData(this, slot, data); 9713 } 9714 9715 9716 void* Isolate::GetData(uint32_t slot) { 9717 typedef internal::Internals I; 9718 return I::GetEmbedderData(this, slot); 9719 } 9720 9721 9722 uint32_t Isolate::GetNumberOfDataSlots() { 9723 typedef internal::Internals I; 9724 return I::kNumIsolateDataSlots; 9725 } 9726 9727 9728 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory( 9729 int64_t change_in_bytes) { 9730 typedef internal::Internals I; 9731 int64_t* external_memory = reinterpret_cast<int64_t*>( 9732 reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset); 9733 const int64_t external_memory_limit = *reinterpret_cast<int64_t*>( 9734 reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset); 9735 const int64_t amount = *external_memory + change_in_bytes; 9736 *external_memory = amount; 9737 if (change_in_bytes > 0 && amount > external_memory_limit) { 9738 ReportExternalAllocationLimitReached(); 9739 } 9740 return *external_memory; 9741 } 9742 9743 9744 template<typename T> 9745 void Isolate::SetObjectGroupId(const Persistent<T>& object, 9746 UniqueId id) { 9747 TYPE_CHECK(Value, T); 9748 SetObjectGroupId(reinterpret_cast<internal::Object**>(object.val_), id); 9749 } 9750 9751 9752 template<typename T> 9753 void Isolate::SetReferenceFromGroup(UniqueId id, 9754 const Persistent<T>& object) { 9755 TYPE_CHECK(Value, T); 9756 SetReferenceFromGroup(id, reinterpret_cast<internal::Object**>(object.val_)); 9757 } 9758 9759 9760 template<typename T, typename S> 9761 void Isolate::SetReference(const Persistent<T>& parent, 9762 const Persistent<S>& child) { 9763 TYPE_CHECK(Object, T); 9764 TYPE_CHECK(Value, S); 9765 SetReference(reinterpret_cast<internal::Object**>(parent.val_), 9766 reinterpret_cast<internal::Object**>(child.val_)); 9767 } 9768 9769 9770 Local<Value> Context::GetEmbedderData(int index) { 9771 #ifndef V8_ENABLE_CHECKS 9772 typedef internal::Object O; 9773 typedef internal::HeapObject HO; 9774 typedef internal::Internals I; 9775 HO* context = *reinterpret_cast<HO**>(this); 9776 O** result = 9777 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index)); 9778 return Local<Value>(reinterpret_cast<Value*>(result)); 9779 #else 9780 return SlowGetEmbedderData(index); 9781 #endif 9782 } 9783 9784 9785 void* Context::GetAlignedPointerFromEmbedderData(int index) { 9786 #ifndef V8_ENABLE_CHECKS 9787 typedef internal::Internals I; 9788 return I::ReadEmbedderData<void*>(this, index); 9789 #else 9790 return SlowGetAlignedPointerFromEmbedderData(index); 9791 #endif 9792 } 9793 9794 9795 void V8::SetAllowCodeGenerationFromStringsCallback( 9796 AllowCodeGenerationFromStringsCallback callback) { 9797 Isolate* isolate = Isolate::GetCurrent(); 9798 isolate->SetAllowCodeGenerationFromStringsCallback(callback); 9799 } 9800 9801 9802 bool V8::IsDead() { 9803 Isolate* isolate = Isolate::GetCurrent(); 9804 return isolate->IsDead(); 9805 } 9806 9807 9808 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) { 9809 Isolate* isolate = Isolate::GetCurrent(); 9810 return isolate->AddMessageListener(that, data); 9811 } 9812 9813 9814 void V8::RemoveMessageListeners(MessageCallback that) { 9815 Isolate* isolate = Isolate::GetCurrent(); 9816 isolate->RemoveMessageListeners(that); 9817 } 9818 9819 9820 void V8::SetFailedAccessCheckCallbackFunction( 9821 FailedAccessCheckCallback callback) { 9822 Isolate* isolate = Isolate::GetCurrent(); 9823 isolate->SetFailedAccessCheckCallbackFunction(callback); 9824 } 9825 9826 9827 void V8::SetCaptureStackTraceForUncaughtExceptions( 9828 bool capture, int frame_limit, StackTrace::StackTraceOptions options) { 9829 Isolate* isolate = Isolate::GetCurrent(); 9830 isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit, 9831 options); 9832 } 9833 9834 9835 void V8::SetFatalErrorHandler(FatalErrorCallback callback) { 9836 Isolate* isolate = Isolate::GetCurrent(); 9837 isolate->SetFatalErrorHandler(callback); 9838 } 9839 9840 void V8::RemoveGCPrologueCallback(GCCallback callback) { 9841 Isolate* isolate = Isolate::GetCurrent(); 9842 isolate->RemoveGCPrologueCallback( 9843 reinterpret_cast<Isolate::GCCallback>(callback)); 9844 } 9845 9846 9847 void V8::RemoveGCEpilogueCallback(GCCallback callback) { 9848 Isolate* isolate = Isolate::GetCurrent(); 9849 isolate->RemoveGCEpilogueCallback( 9850 reinterpret_cast<Isolate::GCCallback>(callback)); 9851 } 9852 9853 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); } 9854 9855 9856 bool V8::IsExecutionTerminating(Isolate* isolate) { 9857 if (isolate == NULL) { 9858 isolate = Isolate::GetCurrent(); 9859 } 9860 return isolate->IsExecutionTerminating(); 9861 } 9862 9863 9864 void V8::CancelTerminateExecution(Isolate* isolate) { 9865 isolate->CancelTerminateExecution(); 9866 } 9867 9868 9869 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) { 9870 Isolate* isolate = Isolate::GetCurrent(); 9871 isolate->VisitExternalResources(visitor); 9872 } 9873 9874 9875 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) { 9876 Isolate* isolate = Isolate::GetCurrent(); 9877 isolate->VisitHandlesWithClassIds(visitor); 9878 } 9879 9880 9881 void V8::VisitHandlesWithClassIds(Isolate* isolate, 9882 PersistentHandleVisitor* visitor) { 9883 isolate->VisitHandlesWithClassIds(visitor); 9884 } 9885 9886 9887 void V8::VisitHandlesForPartialDependence(Isolate* isolate, 9888 PersistentHandleVisitor* visitor) { 9889 isolate->VisitHandlesForPartialDependence(visitor); 9890 } 9891 9892 /** 9893 * \example shell.cc 9894 * A simple shell that takes a list of expressions on the 9895 * command-line and executes them. 9896 */ 9897 9898 9899 /** 9900 * \example process.cc 9901 */ 9902 9903 9904 } // namespace v8 9905 9906 9907 #undef TYPE_CHECK 9908 9909 9910 #endif // INCLUDE_V8_H_ 9911