Where Online Learning is simpler!
The C and C++ Include Header Files
/usr/include/node/v8-isolate.h
$ cat -n /usr/include/node/v8-isolate.h 1 // Copyright 2021 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 #ifndef INCLUDE_V8_ISOLATE_H_ 6 #define INCLUDE_V8_ISOLATE_H_ 7 8 #include
9 #include
10 11 #include
12 #include
13 #include
14 15 #include "cppgc/common.h" 16 #include "v8-array-buffer.h" // NOLINT(build/include_directory) 17 #include "v8-callbacks.h" // NOLINT(build/include_directory) 18 #include "v8-data.h" // NOLINT(build/include_directory) 19 #include "v8-debug.h" // NOLINT(build/include_directory) 20 #include "v8-embedder-heap.h" // NOLINT(build/include_directory) 21 #include "v8-function-callback.h" // NOLINT(build/include_directory) 22 #include "v8-internal.h" // NOLINT(build/include_directory) 23 #include "v8-local-handle.h" // NOLINT(build/include_directory) 24 #include "v8-microtask.h" // NOLINT(build/include_directory) 25 #include "v8-persistent-handle.h" // NOLINT(build/include_directory) 26 #include "v8-primitive.h" // NOLINT(build/include_directory) 27 #include "v8-statistics.h" // NOLINT(build/include_directory) 28 #include "v8-unwinder.h" // NOLINT(build/include_directory) 29 #include "v8config.h" // NOLINT(build/include_directory) 30 31 namespace v8 { 32 33 class CppHeap; 34 class HeapProfiler; 35 class MicrotaskQueue; 36 class StartupData; 37 class ScriptOrModule; 38 class SharedArrayBuffer; 39 40 namespace internal { 41 class MicrotaskQueue; 42 class ThreadLocalTop; 43 } // namespace internal 44 45 namespace metrics { 46 class Recorder; 47 } // namespace metrics 48 49 /** 50 * A set of constraints that specifies the limits of the runtime's memory use. 51 * You must set the heap size before initializing the VM - the size cannot be 52 * adjusted after the VM is initialized. 53 * 54 * If you are using threads then you should hold the V8::Locker lock while 55 * setting the stack limit and you must set a non-default stack limit separately 56 * for each thread. 57 * 58 * The arguments for set_max_semi_space_size, set_max_old_space_size, 59 * set_max_executable_size, set_code_range_size specify limits in MB. 60 * 61 * The argument for set_max_semi_space_size_in_kb is in KB. 62 */ 63 class V8_EXPORT ResourceConstraints { 64 public: 65 /** 66 * Configures the constraints with reasonable default values based on the 67 * provided heap size limit. The heap size includes both the young and 68 * the old generation. 69 * 70 * \param initial_heap_size_in_bytes The initial heap size or zero. 71 * By default V8 starts with a small heap and dynamically grows it to 72 * match the set of live objects. This may lead to ineffective 73 * garbage collections at startup if the live set is large. 74 * Setting the initial heap size avoids such garbage collections. 75 * Note that this does not affect young generation garbage collections. 76 * 77 * \param maximum_heap_size_in_bytes The hard limit for the heap size. 78 * When the heap size approaches this limit, V8 will perform series of 79 * garbage collections and invoke the NearHeapLimitCallback. If the garbage 80 * collections do not help and the callback does not increase the limit, 81 * then V8 will crash with V8::FatalProcessOutOfMemory. 82 */ 83 void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes, 84 size_t maximum_heap_size_in_bytes); 85 86 /** 87 * Configures the constraints with reasonable default values based on the 88 * capabilities of the current device the VM is running on. 89 * 90 * \param physical_memory The total amount of physical memory on the current 91 * device, in bytes. 92 * \param virtual_memory_limit The amount of virtual memory on the current 93 * device, in bytes, or zero, if there is no limit. 94 */ 95 void ConfigureDefaults(uint64_t physical_memory, 96 uint64_t virtual_memory_limit); 97 98 /** 99 * The address beyond which the VM's stack may not grow. 100 */ 101 uint32_t* stack_limit() const { return stack_limit_; } 102 void set_stack_limit(uint32_t* value) { stack_limit_ = value; } 103 104 /** 105 * The amount of virtual memory reserved for generated code. This is relevant 106 * for 64-bit architectures that rely on code range for calls in code. 107 * 108 * When V8_COMPRESS_POINTERS_IN_SHARED_CAGE is defined, there is a shared 109 * process-wide code range that is lazily initialized. This value is used to 110 * configure that shared code range when the first Isolate is 111 * created. Subsequent Isolates ignore this value. 112 */ 113 size_t code_range_size_in_bytes() const { return code_range_size_; } 114 void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; } 115 116 /** 117 * The maximum size of the old generation. 118 * When the old generation approaches this limit, V8 will perform series of 119 * garbage collections and invoke the NearHeapLimitCallback. 120 * If the garbage collections do not help and the callback does not 121 * increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory. 122 */ 123 size_t max_old_generation_size_in_bytes() const { 124 return max_old_generation_size_; 125 } 126 void set_max_old_generation_size_in_bytes(size_t limit) { 127 max_old_generation_size_ = limit; 128 } 129 130 /** 131 * The maximum size of the young generation, which consists of two semi-spaces 132 * and a large object space. This affects frequency of Scavenge garbage 133 * collections and should be typically much smaller that the old generation. 134 */ 135 size_t max_young_generation_size_in_bytes() const { 136 return max_young_generation_size_; 137 } 138 void set_max_young_generation_size_in_bytes(size_t limit) { 139 max_young_generation_size_ = limit; 140 } 141 142 size_t initial_old_generation_size_in_bytes() const { 143 return initial_old_generation_size_; 144 } 145 void set_initial_old_generation_size_in_bytes(size_t initial_size) { 146 initial_old_generation_size_ = initial_size; 147 } 148 149 size_t initial_young_generation_size_in_bytes() const { 150 return initial_young_generation_size_; 151 } 152 void set_initial_young_generation_size_in_bytes(size_t initial_size) { 153 initial_young_generation_size_ = initial_size; 154 } 155 156 private: 157 static constexpr size_t kMB = 1048576u; 158 size_t code_range_size_ = 0; 159 size_t max_old_generation_size_ = 0; 160 size_t max_young_generation_size_ = 0; 161 size_t initial_old_generation_size_ = 0; 162 size_t initial_young_generation_size_ = 0; 163 uint32_t* stack_limit_ = nullptr; 164 }; 165 166 /** 167 * Option flags passed to the SetRAILMode function. 168 * See documentation https://developers.google.com/web/tools/chrome-devtools/ 169 * profile/evaluate-performance/rail 170 */ 171 enum RAILMode : unsigned { 172 // Response performance mode: In this mode very low virtual machine latency 173 // is provided. V8 will try to avoid JavaScript execution interruptions. 174 // Throughput may be throttled. 175 PERFORMANCE_RESPONSE, 176 // Animation performance mode: In this mode low virtual machine latency is 177 // provided. V8 will try to avoid as many JavaScript execution interruptions 178 // as possible. Throughput may be throttled. This is the default mode. 179 PERFORMANCE_ANIMATION, 180 // Idle performance mode: The embedder is idle. V8 can complete deferred work 181 // in this mode. 182 PERFORMANCE_IDLE, 183 // Load performance mode: In this mode high throughput is provided. V8 may 184 // turn off latency optimizations. 185 PERFORMANCE_LOAD 186 }; 187 188 /** 189 * Memory pressure level for the MemoryPressureNotification. 190 * kNone hints V8 that there is no memory pressure. 191 * kModerate hints V8 to speed up incremental garbage collection at the cost of 192 * of higher latency due to garbage collection pauses. 193 * kCritical hints V8 to free memory as soon as possible. Garbage collection 194 * pauses at this level will be large. 195 */ 196 enum class MemoryPressureLevel { kNone, kModerate, kCritical }; 197 198 /** 199 * Indicator for the stack state. 200 */ 201 using StackState = cppgc::EmbedderStackState; 202 203 /** 204 * Isolate represents an isolated instance of the V8 engine. V8 isolates have 205 * completely separate states. Objects from one isolate must not be used in 206 * other isolates. The embedder can create multiple isolates and use them in 207 * parallel in multiple threads. An isolate can be entered by at most one 208 * thread at any given time. The Locker/Unlocker API must be used to 209 * synchronize. 210 */ 211 class V8_EXPORT Isolate { 212 public: 213 /** 214 * Initial configuration parameters for a new Isolate. 215 */ 216 struct V8_EXPORT CreateParams { 217 CreateParams(); 218 ~CreateParams(); 219 220 ALLOW_COPY_AND_MOVE_WITH_DEPRECATED_FIELDS(CreateParams) 221 222 /** 223 * Allows the host application to provide the address of a function that is 224 * notified each time code is added, moved or removed. 225 */ 226 JitCodeEventHandler code_event_handler = nullptr; 227 228 /** 229 * ResourceConstraints to use for the new Isolate. 230 */ 231 ResourceConstraints constraints; 232 233 /** 234 * Explicitly specify a startup snapshot blob. The embedder owns the blob. 235 * The embedder *must* ensure that the snapshot is from a trusted source. 236 */ 237 const StartupData* snapshot_blob = nullptr; 238 239 /** 240 * Enables the host application to provide a mechanism for recording 241 * statistics counters. 242 */ 243 CounterLookupCallback counter_lookup_callback = nullptr; 244 245 /** 246 * Enables the host application to provide a mechanism for recording 247 * histograms. The CreateHistogram function returns a 248 * histogram which will later be passed to the AddHistogramSample 249 * function. 250 */ 251 CreateHistogramCallback create_histogram_callback = nullptr; 252 AddHistogramSampleCallback add_histogram_sample_callback = nullptr; 253 254 /** 255 * The ArrayBuffer::Allocator to use for allocating and freeing the backing 256 * store of ArrayBuffers. 257 * 258 * If the shared_ptr version is used, the Isolate instance and every 259 * |BackingStore| allocated using this allocator hold a std::shared_ptr 260 * to the allocator, in order to facilitate lifetime 261 * management for the allocator instance. 262 */ 263 ArrayBuffer::Allocator* array_buffer_allocator = nullptr; 264 std::shared_ptr
array_buffer_allocator_shared; 265 266 /** 267 * Specifies an optional nullptr-terminated array of raw addresses in the 268 * embedder that V8 can match against during serialization and use for 269 * deserialization. This array and its content must stay valid for the 270 * entire lifetime of the isolate. 271 */ 272 const intptr_t* external_references = nullptr; 273 274 /** 275 * Whether calling Atomics.wait (a function that may block) is allowed in 276 * this isolate. This can also be configured via SetAllowAtomicsWait. 277 */ 278 bool allow_atomics_wait = true; 279 280 /** 281 * Termination is postponed when there is no active SafeForTerminationScope. 282 */ 283 bool only_terminate_in_safe_scope = false; 284 285 /** 286 * The following parameters describe the offsets for addressing type info 287 * for wrapped API objects and are used by the fast C API 288 * (for details see v8-fast-api-calls.h). 289 */ 290 int embedder_wrapper_type_index = -1; 291 int embedder_wrapper_object_index = -1; 292 293 /** 294 * Callbacks to invoke in case of fatal or OOM errors. 295 */ 296 FatalErrorCallback fatal_error_callback = nullptr; 297 OOMErrorCallback oom_error_callback = nullptr; 298 299 /** 300 * A CppHeap used to construct the Isolate. V8 takes ownership of the 301 * CppHeap passed this way. 302 */ 303 CppHeap* cpp_heap = nullptr; 304 }; 305 306 /** 307 * Stack-allocated class which sets the isolate for all operations 308 * executed within a local scope. 309 */ 310 class V8_EXPORT V8_NODISCARD Scope { 311 public: 312 explicit Scope(Isolate* isolate) : v8_isolate_(isolate) { 313 v8_isolate_->Enter(); 314 } 315 316 ~Scope() { v8_isolate_->Exit(); } 317 318 // Prevent copying of Scope objects. 319 Scope(const Scope&) = delete; 320 Scope& operator=(const Scope&) = delete; 321 322 private: 323 Isolate* const v8_isolate_; 324 }; 325 326 /** 327 * Assert that no Javascript code is invoked. 328 */ 329 class V8_EXPORT V8_NODISCARD DisallowJavascriptExecutionScope { 330 public: 331 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE, DUMP_ON_FAILURE }; 332 333 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure); 334 ~DisallowJavascriptExecutionScope(); 335 336 // Prevent copying of Scope objects. 337 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) = 338 delete; 339 DisallowJavascriptExecutionScope& operator=( 340 const DisallowJavascriptExecutionScope&) = delete; 341 342 private: 343 v8::Isolate* const v8_isolate_; 344 const OnFailure on_failure_; 345 bool was_execution_allowed_; 346 }; 347 348 /** 349 * Introduce exception to DisallowJavascriptExecutionScope. 350 */ 351 class V8_EXPORT V8_NODISCARD AllowJavascriptExecutionScope { 352 public: 353 explicit AllowJavascriptExecutionScope(Isolate* isolate); 354 ~AllowJavascriptExecutionScope(); 355 356 // Prevent copying of Scope objects. 357 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) = 358 delete; 359 AllowJavascriptExecutionScope& operator=( 360 const AllowJavascriptExecutionScope&) = delete; 361 362 private: 363 Isolate* const v8_isolate_; 364 bool was_execution_allowed_assert_; 365 bool was_execution_allowed_throws_; 366 bool was_execution_allowed_dump_; 367 }; 368 369 /** 370 * Do not run microtasks while this scope is active, even if microtasks are 371 * automatically executed otherwise. 372 */ 373 class V8_EXPORT V8_NODISCARD SuppressMicrotaskExecutionScope { 374 public: 375 explicit SuppressMicrotaskExecutionScope( 376 Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr); 377 ~SuppressMicrotaskExecutionScope(); 378 379 // Prevent copying of Scope objects. 380 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) = 381 delete; 382 SuppressMicrotaskExecutionScope& operator=( 383 const SuppressMicrotaskExecutionScope&) = delete; 384 385 private: 386 internal::Isolate* const i_isolate_; 387 internal::MicrotaskQueue* const microtask_queue_; 388 internal::Address previous_stack_height_; 389 390 friend class internal::ThreadLocalTop; 391 }; 392 393 /** 394 * This scope allows terminations inside direct V8 API calls and forbid them 395 * inside any recursive API calls without explicit SafeForTerminationScope. 396 */ 397 class V8_EXPORT V8_NODISCARD SafeForTerminationScope { 398 public: 399 V8_DEPRECATE_SOON("All code should be safe for termination") 400 explicit SafeForTerminationScope(v8::Isolate* v8_isolate) {} 401 ~SafeForTerminationScope() {} 402 403 // Prevent copying of Scope objects. 404 SafeForTerminationScope(const SafeForTerminationScope&) = delete; 405 SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete; 406 }; 407 408 /** 409 * Types of garbage collections that can be requested via 410 * RequestGarbageCollectionForTesting. 411 */ 412 enum GarbageCollectionType { 413 kFullGarbageCollection, 414 kMinorGarbageCollection 415 }; 416 417 /** 418 * Features reported via the SetUseCounterCallback callback. Do not change 419 * assigned numbers of existing items; add new features to the end of this 420 * list. 421 * Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and 422 * then finally be renamed to `kOBSOLETE_...` to stop embedders from using 423 * them. 424 */ 425 enum UseCounterFeature { 426 kUseAsm = 0, 427 kBreakIterator = 1, 428 kOBSOLETE_LegacyConst = 2, 429 kOBSOLETE_MarkDequeOverflow = 3, 430 kOBSOLETE_StoreBufferOverflow = 4, 431 kOBSOLETE_SlotsBufferOverflow = 5, 432 kOBSOLETE_ObjectObserve = 6, 433 kForcedGC = 7, 434 kSloppyMode = 8, 435 kStrictMode = 9, 436 kOBSOLETE_StrongMode = 10, 437 kRegExpPrototypeStickyGetter = 11, 438 kRegExpPrototypeToString = 12, 439 kRegExpPrototypeUnicodeGetter = 13, 440 kOBSOLETE_IntlV8Parse = 14, 441 kOBSOLETE_IntlPattern = 15, 442 kOBSOLETE_IntlResolved = 16, 443 kOBSOLETE_PromiseChain = 17, 444 kOBSOLETE_PromiseAccept = 18, 445 kOBSOLETE_PromiseDefer = 19, 446 kHtmlCommentInExternalScript = 20, 447 kHtmlComment = 21, 448 kSloppyModeBlockScopedFunctionRedefinition = 22, 449 kForInInitializer = 23, 450 kOBSOLETE_ArrayProtectorDirtied = 24, 451 kArraySpeciesModified = 25, 452 kArrayPrototypeConstructorModified = 26, 453 kOBSOLETE_ArrayInstanceProtoModified = 27, 454 kArrayInstanceConstructorModified = 28, 455 kOBSOLETE_LegacyFunctionDeclaration = 29, 456 kOBSOLETE_RegExpPrototypeSourceGetter = 30, 457 kOBSOLETE_RegExpPrototypeOldFlagGetter = 31, 458 kDecimalWithLeadingZeroInStrictMode = 32, 459 kLegacyDateParser = 33, 460 kDefineGetterOrSetterWouldThrow = 34, 461 kFunctionConstructorReturnedUndefined = 35, 462 kAssigmentExpressionLHSIsCallInSloppy = 36, 463 kAssigmentExpressionLHSIsCallInStrict = 37, 464 kPromiseConstructorReturnedUndefined = 38, 465 kOBSOLETE_ConstructorNonUndefinedPrimitiveReturn = 39, 466 kOBSOLETE_LabeledExpressionStatement = 40, 467 kOBSOLETE_LineOrParagraphSeparatorAsLineTerminator = 41, 468 kIndexAccessor = 42, 469 kErrorCaptureStackTrace = 43, 470 kErrorPrepareStackTrace = 44, 471 kErrorStackTraceLimit = 45, 472 kWebAssemblyInstantiation = 46, 473 kDeoptimizerDisableSpeculation = 47, 474 kOBSOLETE_ArrayPrototypeSortJSArrayModifiedPrototype = 48, 475 kFunctionTokenOffsetTooLongForToString = 49, 476 kWasmSharedMemory = 50, 477 kWasmThreadOpcodes = 51, 478 kOBSOLETE_AtomicsNotify = 52, 479 kOBSOLETE_AtomicsWake = 53, 480 kCollator = 54, 481 kNumberFormat = 55, 482 kDateTimeFormat = 56, 483 kPluralRules = 57, 484 kRelativeTimeFormat = 58, 485 kLocale = 59, 486 kListFormat = 60, 487 kSegmenter = 61, 488 kStringLocaleCompare = 62, 489 kOBSOLETE_StringToLocaleUpperCase = 63, 490 kStringToLocaleLowerCase = 64, 491 kNumberToLocaleString = 65, 492 kDateToLocaleString = 66, 493 kDateToLocaleDateString = 67, 494 kDateToLocaleTimeString = 68, 495 kAttemptOverrideReadOnlyOnPrototypeSloppy = 69, 496 kAttemptOverrideReadOnlyOnPrototypeStrict = 70, 497 kOBSOLETE_OptimizedFunctionWithOneShotBytecode = 71, 498 kRegExpMatchIsTrueishOnNonJSRegExp = 72, 499 kRegExpMatchIsFalseishOnJSRegExp = 73, 500 kOBSOLETE_DateGetTimezoneOffset = 74, 501 kStringNormalize = 75, 502 kCallSiteAPIGetFunctionSloppyCall = 76, 503 kCallSiteAPIGetThisSloppyCall = 77, 504 kOBSOLETE_RegExpMatchAllWithNonGlobalRegExp = 78, 505 kRegExpExecCalledOnSlowRegExp = 79, 506 kRegExpReplaceCalledOnSlowRegExp = 80, 507 kDisplayNames = 81, 508 kSharedArrayBufferConstructed = 82, 509 kArrayPrototypeHasElements = 83, 510 kObjectPrototypeHasElements = 84, 511 kNumberFormatStyleUnit = 85, 512 kDateTimeFormatRange = 86, 513 kDateTimeFormatDateTimeStyle = 87, 514 kBreakIteratorTypeWord = 88, 515 kBreakIteratorTypeLine = 89, 516 kInvalidatedArrayBufferDetachingProtector = 90, 517 kInvalidatedArrayConstructorProtector = 91, 518 kInvalidatedArrayIteratorLookupChainProtector = 92, 519 kInvalidatedArraySpeciesLookupChainProtector = 93, 520 kInvalidatedIsConcatSpreadableLookupChainProtector = 94, 521 kInvalidatedMapIteratorLookupChainProtector = 95, 522 kInvalidatedNoElementsProtector = 96, 523 kInvalidatedPromiseHookProtector = 97, 524 kInvalidatedPromiseResolveLookupChainProtector = 98, 525 kInvalidatedPromiseSpeciesLookupChainProtector = 99, 526 kInvalidatedPromiseThenLookupChainProtector = 100, 527 kInvalidatedRegExpSpeciesLookupChainProtector = 101, 528 kInvalidatedSetIteratorLookupChainProtector = 102, 529 kInvalidatedStringIteratorLookupChainProtector = 103, 530 kInvalidatedStringLengthOverflowLookupChainProtector = 104, 531 kInvalidatedTypedArraySpeciesLookupChainProtector = 105, 532 kWasmSimdOpcodes = 106, 533 kVarRedeclaredCatchBinding = 107, 534 kWasmRefTypes = 108, 535 kOBSOLETE_WasmBulkMemory = 109, 536 kOBSOLETE_WasmMultiValue = 110, 537 kWasmExceptionHandling = 111, 538 kInvalidatedMegaDOMProtector = 112, 539 kFunctionPrototypeArguments = 113, 540 kFunctionPrototypeCaller = 114, 541 kTurboFanOsrCompileStarted = 115, 542 kAsyncStackTaggingCreateTaskCall = 116, 543 kDurationFormat = 117, 544 kInvalidatedNumberStringNotRegexpLikeProtector = 118, 545 kOBSOLETE_RegExpUnicodeSetIncompatibilitiesWithUnicodeMode = 119, 546 kImportAssertionDeprecatedSyntax = 120, 547 kLocaleInfoObsoletedGetters = 121, 548 kLocaleInfoFunctions = 122, 549 kCompileHintsMagicAll = 123, 550 kInvalidatedNoProfilingProtector = 124, 551 kWasmMemory64 = 125, 552 kWasmMultiMemory = 126, 553 kWasmGC = 127, 554 kWasmImportedStrings = 128, 555 kSourceMappingUrlMagicCommentAtSign = 129, 556 kTemporalObject = 130, 557 kWasmModuleCompilation = 131, 558 kInvalidatedNoUndetectableObjectsProtector = 132, 559 kWasmJavaScriptPromiseIntegration = 133, 560 kWasmReturnCall = 134, 561 kWasmExtendedConst = 135, 562 kWasmRelaxedSimd = 136, 563 kWasmTypeReflection = 137, 564 kWasmExnRef = 138, 565 kWasmTypedFuncRef = 139, 566 kInvalidatedStringWrapperToPrimitiveProtector = 140, 567 568 // If you add new values here, you'll also need to update Chromium's: 569 // web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to 570 // this list need to be landed first, then changes on the Chromium side. 571 kUseCounterFeatureCount // This enum value must be last. 572 }; 573 574 enum MessageErrorLevel { 575 kMessageLog = (1 << 0), 576 kMessageDebug = (1 << 1), 577 kMessageInfo = (1 << 2), 578 kMessageError = (1 << 3), 579 kMessageWarning = (1 << 4), 580 kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError | 581 kMessageWarning, 582 }; 583 584 using UseCounterCallback = void (*)(Isolate* isolate, 585 UseCounterFeature feature); 586 587 /** 588 * Allocates a new isolate but does not initialize it. Does not change the 589 * currently entered isolate. 590 * 591 * Only Isolate::GetData() and Isolate::SetData(), which access the 592 * embedder-controlled parts of the isolate, are allowed to be called on the 593 * uninitialized isolate. To initialize the isolate, call 594 * `Isolate::Initialize()` or initialize a `SnapshotCreator`. 595 * 596 * When an isolate is no longer used its resources should be freed 597 * by calling Dispose(). Using the delete operator is not allowed. 598 * 599 * V8::Initialize() must have run prior to this. 600 */ 601 static Isolate* Allocate(); 602 603 /** 604 * Initialize an Isolate previously allocated by Isolate::Allocate(). 605 */ 606 static void Initialize(Isolate* isolate, const CreateParams& params); 607 608 /** 609 * Creates a new isolate. Does not change the currently entered 610 * isolate. 611 * 612 * When an isolate is no longer used its resources should be freed 613 * by calling Dispose(). Using the delete operator is not allowed. 614 * 615 * V8::Initialize() must have run prior to this. 616 */ 617 static Isolate* New(const CreateParams& params); 618 619 /** 620 * Returns the entered isolate for the current thread or NULL in 621 * case there is no current isolate. 622 * 623 * This method must not be invoked before V8::Initialize() was invoked. 624 */ 625 static Isolate* GetCurrent(); 626 627 /** 628 * Returns the entered isolate for the current thread or NULL in 629 * case there is no current isolate. 630 * 631 * No checks are performed by this method. 632 */ 633 static Isolate* TryGetCurrent(); 634 635 /** 636 * Return true if this isolate is currently active. 637 **/ 638 bool IsCurrent() const; 639 640 /** 641 * Clears the set of objects held strongly by the heap. This set of 642 * objects are originally built when a WeakRef is created or 643 * successfully dereferenced. 644 * 645 * This is invoked automatically after microtasks are run. See 646 * MicrotasksPolicy for when microtasks are run. 647 * 648 * This needs to be manually invoked only if the embedder is manually running 649 * microtasks via a custom MicrotaskQueue class's PerformCheckpoint. In that 650 * case, it is the embedder's responsibility to make this call at a time which 651 * does not interrupt synchronous ECMAScript code execution. 652 */ 653 void ClearKeptObjects(); 654 655 /** 656 * Custom callback used by embedders to help V8 determine if it should abort 657 * when it throws and no internal handler is predicted to catch the 658 * exception. If --abort-on-uncaught-exception is used on the command line, 659 * then V8 will abort if either: 660 * - no custom callback is set. 661 * - the custom callback set returns true. 662 * Otherwise, the custom callback will not be called and V8 will not abort. 663 */ 664 using AbortOnUncaughtExceptionCallback = bool (*)(Isolate*); 665 void SetAbortOnUncaughtExceptionCallback( 666 AbortOnUncaughtExceptionCallback callback); 667 668 /** 669 * This specifies the callback called by the upcoming dynamic 670 * import() language feature to load modules. 671 */ 672 void SetHostImportModuleDynamicallyCallback( 673 HostImportModuleDynamicallyCallback callback); 674 675 /** 676 * This specifies the callback called by the upcoming import.meta 677 * language feature to retrieve host-defined meta data for a module. 678 */ 679 void SetHostInitializeImportMetaObjectCallback( 680 HostInitializeImportMetaObjectCallback callback); 681 682 /** 683 * This specifies the callback called by the upcoming ShadowRealm 684 * construction language feature to retrieve host created globals. 685 */ 686 void SetHostCreateShadowRealmContextCallback( 687 HostCreateShadowRealmContextCallback callback); 688 689 /** 690 * This specifies the callback called when the stack property of Error 691 * is accessed. 692 */ 693 void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback); 694 695 #if defined(V8_OS_WIN) 696 /** 697 * This specifies the callback called when an ETW tracing session starts. 698 */ 699 void SetFilterETWSessionByURLCallback(FilterETWSessionByURLCallback callback); 700 #endif // V8_OS_WIN 701 702 /** 703 * Optional notification that the system is running low on memory. 704 * V8 uses these notifications to guide heuristics. 705 * It is allowed to call this function from another thread while 706 * the isolate is executing long running JavaScript code. 707 */ 708 void MemoryPressureNotification(MemoryPressureLevel level); 709 710 /** 711 * Optional request from the embedder to tune v8 towards energy efficiency 712 * rather than speed if `battery_saver_mode_enabled` is true, because the 713 * embedder is in battery saver mode. If false, the correct tuning is left 714 * to v8 to decide. 715 */ 716 void SetBatterySaverMode(bool battery_saver_mode_enabled); 717 718 /** 719 * Drop non-essential caches. Should only be called from testing code. 720 * The method can potentially block for a long time and does not necessarily 721 * trigger GC. 722 */ 723 void ClearCachesForTesting(); 724 725 /** 726 * Methods below this point require holding a lock (using Locker) in 727 * a multi-threaded environment. 728 */ 729 730 /** 731 * Sets this isolate as the entered one for the current thread. 732 * Saves the previously entered one (if any), so that it can be 733 * restored when exiting. Re-entering an isolate is allowed. 734 */ 735 void Enter(); 736 737 /** 738 * Exits this isolate by restoring the previously entered one in the 739 * current thread. The isolate may still stay the same, if it was 740 * entered more than once. 741 * 742 * Requires: this == Isolate::GetCurrent(). 743 */ 744 void Exit(); 745 746 /** 747 * Disposes the isolate. The isolate must not be entered by any 748 * thread to be disposable. 749 */ 750 void Dispose(); 751 752 /** 753 * Dumps activated low-level V8 internal stats. This can be used instead 754 * of performing a full isolate disposal. 755 */ 756 void DumpAndResetStats(); 757 758 /** 759 * Discards all V8 thread-specific data for the Isolate. Should be used 760 * if a thread is terminating and it has used an Isolate that will outlive 761 * the thread -- all thread-specific data for an Isolate is discarded when 762 * an Isolate is disposed so this call is pointless if an Isolate is about 763 * to be Disposed. 764 */ 765 void DiscardThreadSpecificMetadata(); 766 767 /** 768 * Associate embedder-specific data with the isolate. |slot| has to be 769 * between 0 and GetNumberOfDataSlots() - 1. 770 */ 771 V8_INLINE void SetData(uint32_t slot, void* data); 772 773 /** 774 * Retrieve embedder-specific data from the isolate. 775 * Returns NULL if SetData has never been called for the given |slot|. 776 */ 777 V8_INLINE void* GetData(uint32_t slot); 778 779 /** 780 * Returns the maximum number of available embedder data slots. Valid slots 781 * are in the range of 0 - GetNumberOfDataSlots() - 1. 782 */ 783 V8_INLINE static uint32_t GetNumberOfDataSlots(); 784 785 /** 786 * Return data that was previously attached to the isolate snapshot via 787 * SnapshotCreator, and removes the reference to it. 788 * Repeated call with the same index returns an empty MaybeLocal. 789 */ 790 template
791 V8_INLINE MaybeLocal
GetDataFromSnapshotOnce(size_t index); 792 793 /** 794 * Returns the value that was set or restored by 795 * SetContinuationPreservedEmbedderData(), if any. 796 */ 797 Local
GetContinuationPreservedEmbedderData(); 798 799 /** 800 * Sets a value that will be stored on continuations and reset while the 801 * continuation runs. 802 */ 803 void SetContinuationPreservedEmbedderData(Local
data); 804 805 /** 806 * Get statistics about the heap memory usage. 807 */ 808 void GetHeapStatistics(HeapStatistics* heap_statistics); 809 810 /** 811 * Returns the number of spaces in the heap. 812 */ 813 size_t NumberOfHeapSpaces(); 814 815 /** 816 * Get the memory usage of a space in the heap. 817 * 818 * \param space_statistics The HeapSpaceStatistics object to fill in 819 * statistics. 820 * \param index The index of the space to get statistics from, which ranges 821 * from 0 to NumberOfHeapSpaces() - 1. 822 * \returns true on success. 823 */ 824 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics, 825 size_t index); 826 827 /** 828 * Returns the number of types of objects tracked in the heap at GC. 829 */ 830 size_t NumberOfTrackedHeapObjectTypes(); 831 832 /** 833 * Get statistics about objects in the heap. 834 * 835 * \param object_statistics The HeapObjectStatistics object to fill in 836 * statistics of objects of given type, which were live in the previous GC. 837 * \param type_index The index of the type of object to fill details about, 838 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1. 839 * \returns true on success. 840 */ 841 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics, 842 size_t type_index); 843 844 /** 845 * Get statistics about code and its metadata in the heap. 846 * 847 * \param object_statistics The HeapCodeStatistics object to fill in 848 * statistics of code, bytecode and their metadata. 849 * \returns true on success. 850 */ 851 bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics); 852 853 /** 854 * This API is experimental and may change significantly. 855 * 856 * Enqueues a memory measurement request and invokes the delegate with the 857 * results. 858 * 859 * \param delegate the delegate that defines which contexts to measure and 860 * reports the results. 861 * 862 * \param execution promptness executing the memory measurement. 863 * The kEager value is expected to be used only in tests. 864 */ 865 bool MeasureMemory( 866 std::unique_ptr
delegate, 867 MeasureMemoryExecution execution = MeasureMemoryExecution::kDefault); 868 869 /** 870 * Get a call stack sample from the isolate. 871 * \param state Execution state. 872 * \param frames Caller allocated buffer to store stack frames. 873 * \param frames_limit Maximum number of frames to capture. The buffer must 874 * be large enough to hold the number of frames. 875 * \param sample_info The sample info is filled up by the function 876 * provides number of actual captured stack frames and 877 * the current VM state. 878 * \note GetStackSample should only be called when the JS thread is paused or 879 * interrupted. Otherwise the behavior is undefined. 880 */ 881 void GetStackSample(const RegisterState& state, void** frames, 882 size_t frames_limit, SampleInfo* sample_info); 883 884 /** 885 * Adjusts the amount of registered external memory. Used to give V8 an 886 * indication of the amount of externally allocated memory that is kept alive 887 * by JavaScript objects. V8 uses this to decide when to perform global 888 * garbage collections. Registering externally allocated memory will trigger 889 * global garbage collections more often than it would otherwise in an attempt 890 * to garbage collect the JavaScript objects that keep the externally 891 * allocated memory alive. 892 * 893 * \param change_in_bytes the change in externally allocated memory that is 894 * kept alive by JavaScript objects. 895 * \returns the adjusted value. 896 */ 897 int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes); 898 899 /** 900 * Returns heap profiler for this isolate. Will return NULL until the isolate 901 * is initialized. 902 */ 903 HeapProfiler* GetHeapProfiler(); 904 905 /** 906 * Tells the VM whether the embedder is idle or not. 907 */ 908 void SetIdle(bool is_idle); 909 910 /** Returns the ArrayBuffer::Allocator used in this isolate. */ 911 ArrayBuffer::Allocator* GetArrayBufferAllocator(); 912 913 /** Returns true if this isolate has a current context. */ 914 bool InContext(); 915 916 /** 917 * Returns the context of the currently running JavaScript, or the context 918 * on the top of the stack if no JavaScript is running. 919 */ 920 Local
GetCurrentContext(); 921 922 /** 923 * Returns either the last context entered through V8's C++ API, or the 924 * context of the currently running microtask while processing microtasks. 925 * If a context is entered while executing a microtask, that context is 926 * returned. 927 */ 928 Local
GetEnteredOrMicrotaskContext(); 929 930 /** 931 * Returns the Context that corresponds to the Incumbent realm in HTML spec. 932 * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent 933 */ 934 Local
GetIncumbentContext(); 935 936 /** 937 * Schedules a v8::Exception::Error with the given message. 938 * See ThrowException for more details. Templatized to provide compile-time 939 * errors in case of too long strings (see v8::String::NewFromUtf8Literal). 940 */ 941 template
942 Local
ThrowError(const char (&message)[N]) { 943 return ThrowError(String::NewFromUtf8Literal(this, message)); 944 } 945 Local
ThrowError(Local
message); 946 947 /** 948 * Schedules an exception to be thrown when returning to JavaScript. When an 949 * exception has been scheduled it is illegal to invoke any JavaScript 950 * operation; the caller must return immediately and only after the exception 951 * has been handled does it become legal to invoke JavaScript operations. 952 */ 953 Local
ThrowException(Local
exception); 954 955 using GCCallback = void (*)(Isolate* isolate, GCType type, 956 GCCallbackFlags flags); 957 using GCCallbackWithData = void (*)(Isolate* isolate, GCType type, 958 GCCallbackFlags flags, void* data); 959 960 /** 961 * Enables the host application to receive a notification before a 962 * garbage collection. 963 * 964 * \param callback The callback to be invoked. The callback is allowed to 965 * allocate but invocation is not re-entrant: a callback triggering 966 * garbage collection will not be called again. JS execution is prohibited 967 * from these callbacks. A single callback may only be registered once. 968 * \param gc_type_filter A filter in case it should be applied. 969 */ 970 void AddGCPrologueCallback(GCCallback callback, 971 GCType gc_type_filter = kGCTypeAll); 972 973 /** 974 * \copydoc AddGCPrologueCallback(GCCallback, GCType) 975 * 976 * \param data Additional data that should be passed to the callback. 977 */ 978 void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr, 979 GCType gc_type_filter = kGCTypeAll); 980 981 /** 982 * This function removes a callback which was added by 983 * `AddGCPrologueCallback`. 984 * 985 * \param callback the callback to remove. 986 */ 987 void RemoveGCPrologueCallback(GCCallback callback); 988 989 /** 990 * \copydoc AddGCPrologueCallback(GCCallback) 991 * 992 * \param data Additional data that was used to install the callback. 993 */ 994 void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr); 995 996 /** 997 * Enables the host application to receive a notification after a 998 * garbage collection. 999 * 1000 * \copydetails AddGCPrologueCallback(GCCallback, GCType) 1001 */ 1002 void AddGCEpilogueCallback(GCCallback callback, 1003 GCType gc_type_filter = kGCTypeAll); 1004 1005 /** 1006 * \copydoc AddGCEpilogueCallback(GCCallback, GCType) 1007 * 1008 * \param data Additional data that should be passed to the callback. 1009 */ 1010 void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr, 1011 GCType gc_type_filter = kGCTypeAll); 1012 1013 /** 1014 * This function removes a callback which was added by 1015 * `AddGCEpilogueCallback`. 1016 * 1017 * \param callback the callback to remove. 1018 */ 1019 void RemoveGCEpilogueCallback(GCCallback callback); 1020 1021 /** 1022 * \copydoc RemoveGCEpilogueCallback(GCCallback) 1023 * 1024 * \param data Additional data that was used to install the callback. 1025 */ 1026 void RemoveGCEpilogueCallback(GCCallbackWithData callback, 1027 void* data = nullptr); 1028 1029 /** 1030 * Sets an embedder roots handle that V8 should consider when performing 1031 * non-unified heap garbage collections. The intended use case is for setting 1032 * a custom handler after invoking `AttachCppHeap()`. 1033 * 1034 * V8 does not take ownership of the handler. 1035 */ 1036 void SetEmbedderRootsHandler(EmbedderRootsHandler* handler); 1037 1038 /** 1039 * Attaches a managed C++ heap as an extension to the JavaScript heap. The 1040 * embedder maintains ownership of the CppHeap. At most one C++ heap can be 1041 * attached to V8. 1042 * 1043 * Multi-threaded use requires the use of v8::Locker/v8::Unlocker, see 1044 * CppHeap. 1045 * 1046 * If a CppHeap is set via CreateParams, then this call is a noop. 1047 */ 1048 V8_DEPRECATE_SOON( 1049 "Set the heap on Isolate creation using CreateParams instead.") 1050 void AttachCppHeap(CppHeap*); 1051 1052 /** 1053 * Detaches a managed C++ heap if one was attached using `AttachCppHeap()`. 1054 * 1055 * If a CppHeap is set via CreateParams, then this call is a noop. 1056 */ 1057 V8_DEPRECATE_SOON( 1058 "Set the heap on Isolate creation using CreateParams instead.") 1059 void DetachCppHeap(); 1060 1061 /** 1062 * \returns the C++ heap managed by V8. Only available if such a heap has been 1063 * attached using `AttachCppHeap()`. 1064 */ 1065 CppHeap* GetCppHeap() const; 1066 1067 /** 1068 * Use for |AtomicsWaitCallback| to indicate the type of event it receives. 1069 */ 1070 enum class AtomicsWaitEvent { 1071 /** Indicates that this call is happening before waiting. */ 1072 kStartWait, 1073 /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */ 1074 kWokenUp, 1075 /** `Atomics.wait()` finished because it timed out. */ 1076 kTimedOut, 1077 /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */ 1078 kTerminatedExecution, 1079 /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */ 1080 kAPIStopped, 1081 /** `Atomics.wait()` did not wait, as the initial condition was not met. */ 1082 kNotEqual 1083 }; 1084 1085 /** 1086 * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing 1087 * `Atomics.wait` call. 1088 */ 1089 class V8_EXPORT AtomicsWaitWakeHandle { 1090 public: 1091 /** 1092 * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback| 1093 * with |kAPIStopped|. 1094 * 1095 * This function may be called from another thread. The caller has to ensure 1096 * through proper synchronization that it is not called after 1097 * the finishing |AtomicsWaitCallback|. 1098 * 1099 * Note that the ECMAScript specification does not plan for the possibility 1100 * of wakeups that are neither coming from a timeout or an `Atomics.wake()` 1101 * call, so this may invalidate assumptions made by existing code. 1102 * The embedder may accordingly wish to schedule an exception in the 1103 * finishing |AtomicsWaitCallback|. 1104 */ 1105 void Wake(); 1106 }; 1107 1108 /** 1109 * Embedder callback for `Atomics.wait()` that can be added through 1110 * |SetAtomicsWaitCallback|. 1111 * 1112 * This will be called just before starting to wait with the |event| value 1113 * |kStartWait| and after finishing waiting with one of the other 1114 * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call. 1115 * 1116 * |array_buffer| will refer to the underlying SharedArrayBuffer, 1117 * |offset_in_bytes| to the location of the waited-on memory address inside 1118 * the SharedArrayBuffer. 1119 * 1120 * |value| and |timeout_in_ms| will be the values passed to 1121 * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms| 1122 * will be `INFINITY`. 1123 * 1124 * In the |kStartWait| callback, |stop_handle| will be an object that 1125 * is only valid until the corresponding finishing callback and that 1126 * can be used to stop the wait process while it is happening. 1127 * 1128 * This callback may schedule exceptions, *unless* |event| is equal to 1129 * |kTerminatedExecution|. 1130 */ 1131 using AtomicsWaitCallback = void (*)(AtomicsWaitEvent event, 1132 Local
array_buffer, 1133 size_t offset_in_bytes, int64_t value, 1134 double timeout_in_ms, 1135 AtomicsWaitWakeHandle* stop_handle, 1136 void* data); 1137 1138 /** 1139 * Set a new |AtomicsWaitCallback|. This overrides an earlier 1140 * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr, 1141 * this unsets the callback. |data| will be passed to the callback 1142 * as its last parameter. 1143 */ 1144 void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data); 1145 1146 using GetExternallyAllocatedMemoryInBytesCallback = size_t (*)(); 1147 1148 /** 1149 * Set the callback that tells V8 how much memory is currently allocated 1150 * externally of the V8 heap. Ideally this memory is somehow connected to V8 1151 * objects and may get freed-up when the corresponding V8 objects get 1152 * collected by a V8 garbage collection. 1153 */ 1154 void SetGetExternallyAllocatedMemoryInBytesCallback( 1155 GetExternallyAllocatedMemoryInBytesCallback callback); 1156 1157 /** 1158 * Forcefully terminate the current thread of JavaScript execution 1159 * in the given isolate. 1160 * 1161 * This method can be used by any thread even if that thread has not 1162 * acquired the V8 lock with a Locker object. 1163 */ 1164 void TerminateExecution(); 1165 1166 /** 1167 * Is V8 terminating JavaScript execution. 1168 * 1169 * Returns true if JavaScript execution is currently terminating 1170 * because of a call to TerminateExecution. In that case there are 1171 * still JavaScript frames on the stack and the termination 1172 * exception is still active. 1173 */ 1174 bool IsExecutionTerminating(); 1175 1176 /** 1177 * Resume execution capability in the given isolate, whose execution 1178 * was previously forcefully terminated using TerminateExecution(). 1179 * 1180 * When execution is forcefully terminated using TerminateExecution(), 1181 * the isolate can not resume execution until all JavaScript frames 1182 * have propagated the uncatchable exception which is generated. This 1183 * method allows the program embedding the engine to handle the 1184 * termination event and resume execution capability, even if 1185 * JavaScript frames remain on the stack. 1186 * 1187 * This method can be used by any thread even if that thread has not 1188 * acquired the V8 lock with a Locker object. 1189 */ 1190 void CancelTerminateExecution(); 1191 1192 /** 1193 * Request V8 to interrupt long running JavaScript code and invoke 1194 * the given |callback| passing the given |data| to it. After |callback| 1195 * returns control will be returned to the JavaScript code. 1196 * There may be a number of interrupt requests in flight. 1197 * Can be called from another thread without acquiring a |Locker|. 1198 * Registered |callback| must not reenter interrupted Isolate. 1199 */ 1200 void RequestInterrupt(InterruptCallback callback, void* data); 1201 1202 /** 1203 * Returns true if there is ongoing background work within V8 that will 1204 * eventually post a foreground task, like asynchronous WebAssembly 1205 * compilation. 1206 */ 1207 bool HasPendingBackgroundTasks(); 1208 1209 /** 1210 * Request garbage collection in this Isolate. It is only valid to call this 1211 * function if --expose_gc was specified. 1212 * 1213 * This should only be used for testing purposes and not to enforce a garbage 1214 * collection schedule. It has strong negative impact on the garbage 1215 * collection performance. Use MemoryPressureNotification() instead to 1216 * influence the garbage collection schedule. 1217 */ 1218 void RequestGarbageCollectionForTesting(GarbageCollectionType type); 1219 1220 /** 1221 * Request garbage collection with a specific embedderstack state in this 1222 * Isolate. It is only valid to call this function if --expose_gc was 1223 * specified. 1224 * 1225 * This should only be used for testing purposes and not to enforce a garbage 1226 * collection schedule. It has strong negative impact on the garbage 1227 * collection performance. Use MemoryPressureNotification() instead to 1228 * influence the garbage collection schedule. 1229 */ 1230 void RequestGarbageCollectionForTesting(GarbageCollectionType type, 1231 StackState stack_state); 1232 1233 /** 1234 * Set the callback to invoke for logging event. 1235 */ 1236 void SetEventLogger(LogEventCallback that); 1237 1238 /** 1239 * Adds a callback to notify the host application right before a script 1240 * is about to run. If a script re-enters the runtime during executing, the 1241 * BeforeCallEnteredCallback is invoked for each re-entrance. 1242 * Executing scripts inside the callback will re-trigger the callback. 1243 */ 1244 void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback); 1245 1246 /** 1247 * Removes callback that was installed by AddBeforeCallEnteredCallback. 1248 */ 1249 void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback); 1250 1251 /** 1252 * Adds a callback to notify the host application when a script finished 1253 * running. If a script re-enters the runtime during executing, the 1254 * CallCompletedCallback is only invoked when the outer-most script 1255 * execution ends. Executing scripts inside the callback do not trigger 1256 * further callbacks. 1257 */ 1258 void AddCallCompletedCallback(CallCompletedCallback callback); 1259 1260 /** 1261 * Removes callback that was installed by AddCallCompletedCallback. 1262 */ 1263 void RemoveCallCompletedCallback(CallCompletedCallback callback); 1264 1265 /** 1266 * Set the PromiseHook callback for various promise lifecycle 1267 * events. 1268 */ 1269 void SetPromiseHook(PromiseHook hook); 1270 1271 /** 1272 * Set callback to notify about promise reject with no handler, or 1273 * revocation of such a previous notification once the handler is added. 1274 */ 1275 void SetPromiseRejectCallback(PromiseRejectCallback callback); 1276 1277 /** 1278 * Runs the default MicrotaskQueue until it gets empty and perform other 1279 * microtask checkpoint steps, such as calling ClearKeptObjects. Asserts that 1280 * the MicrotasksPolicy is not kScoped. Any exceptions thrown by microtask 1281 * callbacks are swallowed. 1282 */ 1283 void PerformMicrotaskCheckpoint(); 1284 1285 /** 1286 * Enqueues the callback to the default MicrotaskQueue 1287 */ 1288 void EnqueueMicrotask(Local
microtask); 1289 1290 /** 1291 * Enqueues the callback to the default MicrotaskQueue 1292 */ 1293 void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr); 1294 1295 /** 1296 * Controls how Microtasks are invoked. See MicrotasksPolicy for details. 1297 */ 1298 void SetMicrotasksPolicy(MicrotasksPolicy policy); 1299 1300 /** 1301 * Returns the policy controlling how Microtasks are invoked. 1302 */ 1303 MicrotasksPolicy GetMicrotasksPolicy() const; 1304 1305 /** 1306 * Adds a callback to notify the host application after 1307 * microtasks were run on the default MicrotaskQueue. The callback is 1308 * triggered by explicit RunMicrotasks call or automatic microtasks execution 1309 * (see SetMicrotaskPolicy). 1310 * 1311 * Callback will trigger even if microtasks were attempted to run, 1312 * but the microtasks queue was empty and no single microtask was actually 1313 * executed. 1314 * 1315 * Executing scripts inside the callback will not re-trigger microtasks and 1316 * the callback. 1317 */ 1318 void AddMicrotasksCompletedCallback( 1319 MicrotasksCompletedCallbackWithData callback, void* data = nullptr); 1320 1321 /** 1322 * Removes callback that was installed by AddMicrotasksCompletedCallback. 1323 */ 1324 void RemoveMicrotasksCompletedCallback( 1325 MicrotasksCompletedCallbackWithData callback, void* data = nullptr); 1326 1327 /** 1328 * Sets a callback for counting the number of times a feature of V8 is used. 1329 */ 1330 void SetUseCounterCallback(UseCounterCallback callback); 1331 1332 /** 1333 * Enables the host application to provide a mechanism for recording 1334 * statistics counters. 1335 */ 1336 void SetCounterFunction(CounterLookupCallback); 1337 1338 /** 1339 * Enables the host application to provide a mechanism for recording 1340 * histograms. The CreateHistogram function returns a 1341 * histogram which will later be passed to the AddHistogramSample 1342 * function. 1343 */ 1344 void SetCreateHistogramFunction(CreateHistogramCallback); 1345 void SetAddHistogramSampleFunction(AddHistogramSampleCallback); 1346 1347 /** 1348 * Enables the host application to provide a mechanism for recording 1349 * event based metrics. In order to use this interface 1350 * include/v8-metrics.h 1351 * needs to be included and the recorder needs to be derived from the 1352 * Recorder base class defined there. 1353 * This method can only be called once per isolate and must happen during 1354 * isolate initialization before background threads are spawned. 1355 */ 1356 void SetMetricsRecorder( 1357 const std::shared_ptr
& metrics_recorder); 1358 1359 /** 1360 * Enables the host application to provide a mechanism for recording a 1361 * predefined set of data as crash keys to be used in postmortem debugging in 1362 * case of a crash. 1363 */ 1364 void SetAddCrashKeyCallback(AddCrashKeyCallback); 1365 1366 /** 1367 * Optional notification that the embedder is idle. 1368 * V8 uses the notification to perform garbage collection. 1369 * This call can be used repeatedly if the embedder remains idle. 1370 * Returns true if the embedder should stop calling IdleNotificationDeadline 1371 * until real work has been done. This indicates that V8 has done 1372 * as much cleanup as it will be able to do. 1373 * 1374 * The deadline_in_seconds argument specifies the deadline V8 has to finish 1375 * garbage collection work. deadline_in_seconds is compared with 1376 * MonotonicallyIncreasingTime() and should be based on the same timebase as 1377 * that function. There is no guarantee that the actual work will be done 1378 * within the time limit. 1379 */ 1380 V8_DEPRECATE_SOON( 1381 "Use MemoryPressureNotification() to influence the GC schedule.") 1382 bool IdleNotificationDeadline(double deadline_in_seconds); 1383 1384 /** 1385 * Optional notification that the system is running low on memory. 1386 * V8 uses these notifications to attempt to free memory. 1387 */ 1388 void LowMemoryNotification(); 1389 1390 /** 1391 * Optional notification that a context has been disposed. V8 uses these 1392 * notifications to guide the GC heuristic and cancel FinalizationRegistry 1393 * cleanup tasks. Returns the number of context disposals - including this one 1394 * - since the last time V8 had a chance to clean up. 1395 * 1396 * The optional parameter |dependant_context| specifies whether the disposed 1397 * context was depending on state from other contexts or not. 1398 */ 1399 int ContextDisposedNotification(bool dependant_context = true); 1400 1401 /** 1402 * Optional notification that the isolate switched to the foreground. 1403 * V8 uses these notifications to guide heuristics. 1404 */ 1405 void IsolateInForegroundNotification(); 1406 1407 /** 1408 * Optional notification that the isolate switched to the background. 1409 * V8 uses these notifications to guide heuristics. 1410 */ 1411 void IsolateInBackgroundNotification(); 1412 1413 /** 1414 * Optional notification to tell V8 the current performance requirements 1415 * of the embedder based on RAIL. 1416 * V8 uses these notifications to guide heuristics. 1417 * This is an unfinished experimental feature. Semantics and implementation 1418 * may change frequently. 1419 */ 1420 void SetRAILMode(RAILMode rail_mode); 1421 1422 /** 1423 * Update load start time of the RAIL mode 1424 */ 1425 void UpdateLoadStartTime(); 1426 1427 /** 1428 * Optional notification to tell V8 the current isolate is used for debugging 1429 * and requires higher heap limit. 1430 */ 1431 void IncreaseHeapLimitForDebugging(); 1432 1433 /** 1434 * Restores the original heap limit after IncreaseHeapLimitForDebugging(). 1435 */ 1436 void RestoreOriginalHeapLimit(); 1437 1438 /** 1439 * Returns true if the heap limit was increased for debugging and the 1440 * original heap limit was not restored yet. 1441 */ 1442 bool IsHeapLimitIncreasedForDebugging(); 1443 1444 /** 1445 * Allows the host application to provide the address of a function that is 1446 * notified each time code is added, moved or removed. 1447 * 1448 * \param options options for the JIT code event handler. 1449 * \param event_handler the JIT code event handler, which will be invoked 1450 * each time code is added, moved or removed. 1451 * \note \p event_handler won't get notified of existent code. 1452 * \note since code removal notifications are not currently issued, the 1453 * \p event_handler may get notifications of code that overlaps earlier 1454 * code notifications. This happens when code areas are reused, and the 1455 * earlier overlapping code areas should therefore be discarded. 1456 * \note the events passed to \p event_handler and the strings they point to 1457 * are not guaranteed to live past each call. The \p event_handler must 1458 * copy strings and other parameters it needs to keep around. 1459 * \note the set of events declared in JitCodeEvent::EventType is expected to 1460 * grow over time, and the JitCodeEvent structure is expected to accrue 1461 * new members. The \p event_handler function must ignore event codes 1462 * it does not recognize to maintain future compatibility. 1463 * \note Use Isolate::CreateParams to get events for code executed during 1464 * Isolate setup. 1465 */ 1466 void SetJitCodeEventHandler(JitCodeEventOptions options, 1467 JitCodeEventHandler event_handler); 1468 1469 /** 1470 * Modifies the stack limit for this Isolate. 1471 * 1472 * \param stack_limit An address beyond which the Vm's stack may not grow. 1473 * 1474 * \note If you are using threads then you should hold the V8::Locker lock 1475 * while setting the stack limit and you must set a non-default stack 1476 * limit separately for each thread. 1477 */ 1478 void SetStackLimit(uintptr_t stack_limit); 1479 1480 /** 1481 * Returns a memory range that can potentially contain jitted code. Code for 1482 * V8's 'builtins' will not be in this range if embedded builtins is enabled. 1483 * 1484 * On Win64, embedders are advised to install function table callbacks for 1485 * these ranges, as default SEH won't be able to unwind through jitted code. 1486 * The first page of the code range is reserved for the embedder and is 1487 * committed, writable, and executable, to be used to store unwind data, as 1488 * documented in 1489 * https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64. 1490 * 1491 * Might be empty on other platforms. 1492 * 1493 * https://code.google.com/p/v8/issues/detail?id=3598 1494 */ 1495 void GetCodeRange(void** start, size_t* length_in_bytes); 1496 1497 /** 1498 * As GetCodeRange, but for embedded builtins (these live in a distinct 1499 * memory region from other V8 Code objects). 1500 */ 1501 void GetEmbeddedCodeRange(const void** start, size_t* length_in_bytes); 1502 1503 /** 1504 * Returns the JSEntryStubs necessary for use with the Unwinder API. 1505 */ 1506 JSEntryStubs GetJSEntryStubs(); 1507 1508 static constexpr size_t kMinCodePagesBufferSize = 32; 1509 1510 /** 1511 * Copies the code heap pages currently in use by V8 into |code_pages_out|. 1512 * |code_pages_out| must have at least kMinCodePagesBufferSize capacity and 1513 * must be empty. 1514 * 1515 * Signal-safe, does not allocate, does not access the V8 heap. 1516 * No code on the stack can rely on pages that might be missing. 1517 * 1518 * Returns the number of pages available to be copied, which might be greater 1519 * than |capacity|. In this case, only |capacity| pages will be copied into 1520 * |code_pages_out|. The caller should provide a bigger buffer on the next 1521 * call in order to get all available code pages, but this is not required. 1522 */ 1523 size_t CopyCodePages(size_t capacity, MemoryRange* code_pages_out); 1524 1525 /** Set the callback to invoke in case of fatal errors. */ 1526 void SetFatalErrorHandler(FatalErrorCallback that); 1527 1528 /** Set the callback to invoke in case of OOM errors. */ 1529 void SetOOMErrorHandler(OOMErrorCallback that); 1530 1531 /** 1532 * Add a callback to invoke in case the heap size is close to the heap limit. 1533 * If multiple callbacks are added, only the most recently added callback is 1534 * invoked. 1535 */ 1536 void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data); 1537 1538 /** 1539 * Remove the given callback and restore the heap limit to the 1540 * given limit. If the given limit is zero, then it is ignored. 1541 * If the current heap size is greater than the given limit, 1542 * then the heap limit is restored to the minimal limit that 1543 * is possible for the current heap size. 1544 */ 1545 void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback, 1546 size_t heap_limit); 1547 1548 /** 1549 * If the heap limit was changed by the NearHeapLimitCallback, then the 1550 * initial heap limit will be restored once the heap size falls below the 1551 * given threshold percentage of the initial heap limit. 1552 * The threshold percentage is a number in (0.0, 1.0) range. 1553 */ 1554 void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5); 1555 1556 /** 1557 * Set the callback to invoke to check if code generation from 1558 * strings should be allowed. 1559 */ 1560 void SetModifyCodeGenerationFromStringsCallback( 1561 ModifyCodeGenerationFromStringsCallback2 callback); 1562 1563 /** 1564 * Set the callback to invoke to check if wasm code generation should 1565 * be allowed. 1566 */ 1567 void SetAllowWasmCodeGenerationCallback( 1568 AllowWasmCodeGenerationCallback callback); 1569 1570 /** 1571 * Embedder over{ride|load} injection points for wasm APIs. The expectation 1572 * is that the embedder sets them at most once. 1573 */ 1574 void SetWasmModuleCallback(ExtensionCallback callback); 1575 void SetWasmInstanceCallback(ExtensionCallback callback); 1576 1577 void SetWasmStreamingCallback(WasmStreamingCallback callback); 1578 1579 void SetWasmAsyncResolvePromiseCallback( 1580 WasmAsyncResolvePromiseCallback callback); 1581 1582 void SetWasmLoadSourceMapCallback(WasmLoadSourceMapCallback callback); 1583 1584 void SetWasmImportedStringsEnabledCallback( 1585 WasmImportedStringsEnabledCallback callback); 1586 1587 void SetSharedArrayBufferConstructorEnabledCallback( 1588 SharedArrayBufferConstructorEnabledCallback callback); 1589 1590 void SetWasmJSPIEnabledCallback(WasmJSPIEnabledCallback callback); 1591 1592 /** 1593 * Register callback to control whether compile hints magic comments are 1594 * enabled. 1595 */ 1596 void SetJavaScriptCompileHintsMagicEnabledCallback( 1597 JavaScriptCompileHintsMagicEnabledCallback callback); 1598 1599 /** 1600 * This function can be called by the embedder to signal V8 that the dynamic 1601 * enabling of features has finished. V8 can now set up dynamically added 1602 * features. 1603 */ 1604 void InstallConditionalFeatures(Local
context); 1605 1606 /** 1607 * Check if V8 is dead and therefore unusable. This is the case after 1608 * fatal errors such as out-of-memory situations. 1609 */ 1610 bool IsDead(); 1611 1612 /** 1613 * Adds a message listener (errors only). 1614 * 1615 * The same message listener can be added more than once and in that 1616 * case it will be called more than once for each message. 1617 * 1618 * If data is specified, it will be passed to the callback when it is called. 1619 * Otherwise, the exception object will be passed to the callback instead. 1620 */ 1621 bool AddMessageListener(MessageCallback that, 1622 Local
data = Local
()); 1623 1624 /** 1625 * Adds a message listener. 1626 * 1627 * The same message listener can be added more than once and in that 1628 * case it will be called more than once for each message. 1629 * 1630 * If data is specified, it will be passed to the callback when it is called. 1631 * Otherwise, the exception object will be passed to the callback instead. 1632 * 1633 * A listener can listen for particular error levels by providing a mask. 1634 */ 1635 bool AddMessageListenerWithErrorLevel(MessageCallback that, 1636 int message_levels, 1637 Local
data = Local
()); 1638 1639 /** 1640 * Remove all message listeners from the specified callback function. 1641 */ 1642 void RemoveMessageListeners(MessageCallback that); 1643 1644 /** Callback function for reporting failed access checks.*/ 1645 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback); 1646 1647 /** 1648 * Tells V8 to capture current stack trace when uncaught exception occurs 1649 * and report it to the message listeners. The option is off by default. 1650 */ 1651 void SetCaptureStackTraceForUncaughtExceptions( 1652 bool capture, int frame_limit = 10, 1653 StackTrace::StackTraceOptions options = StackTrace::kOverview); 1654 1655 /** 1656 * Iterates through all external resources referenced from current isolate 1657 * heap. GC is not invoked prior to iterating, therefore there is no 1658 * guarantee that visited objects are still alive. 1659 */ 1660 V8_DEPRECATE_SOON("Will be removed without replacement. crbug.com/v8/14172") 1661 void VisitExternalResources(ExternalResourceVisitor* visitor); 1662 1663 /** 1664 * Check if this isolate is in use. 1665 * True if at least one thread Enter'ed this isolate. 1666 */ 1667 bool IsInUse(); 1668 1669 /** 1670 * Set whether calling Atomics.wait (a function that may block) is allowed in 1671 * this isolate. This can also be configured via 1672 * CreateParams::allow_atomics_wait. 1673 */ 1674 void SetAllowAtomicsWait(bool allow); 1675 1676 /** 1677 * Time zone redetection indicator for 1678 * DateTimeConfigurationChangeNotification. 1679 * 1680 * kSkip indicates V8 that the notification should not trigger redetecting 1681 * host time zone. kRedetect indicates V8 that host time zone should be 1682 * redetected, and used to set the default time zone. 1683 * 1684 * The host time zone detection may require file system access or similar 1685 * operations unlikely to be available inside a sandbox. If v8 is run inside a 1686 * sandbox, the host time zone has to be detected outside the sandbox before 1687 * calling DateTimeConfigurationChangeNotification function. 1688 */ 1689 enum class TimeZoneDetection { kSkip, kRedetect }; 1690 1691 /** 1692 * Notification that the embedder has changed the time zone, daylight savings 1693 * time or other date / time configuration parameters. V8 keeps a cache of 1694 * various values used for date / time computation. This notification will 1695 * reset those cached values for the current context so that date / time 1696 * configuration changes would be reflected. 1697 * 1698 * This API should not be called more than needed as it will negatively impact 1699 * the performance of date operations. 1700 */ 1701 void DateTimeConfigurationChangeNotification( 1702 TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip); 1703 1704 /** 1705 * Notification that the embedder has changed the locale. V8 keeps a cache of 1706 * various values used for locale computation. This notification will reset 1707 * those cached values for the current context so that locale configuration 1708 * changes would be reflected. 1709 * 1710 * This API should not be called more than needed as it will negatively impact 1711 * the performance of locale operations. 1712 */ 1713 void LocaleConfigurationChangeNotification(); 1714 1715 /** 1716 * Returns the default locale in a string if Intl support is enabled. 1717 * Otherwise returns an empty string. 1718 */ 1719 std::string GetDefaultLocale(); 1720 1721 Isolate() = delete; 1722 ~Isolate() = delete; 1723 Isolate(const Isolate&) = delete; 1724 Isolate& operator=(const Isolate&) = delete; 1725 // Deleting operator new and delete here is allowed as ctor and dtor is also 1726 // deleted. 1727 void* operator new(size_t size) = delete; 1728 void* operator new[](size_t size) = delete; 1729 void operator delete(void*, size_t) = delete; 1730 void operator delete[](void*, size_t) = delete; 1731 1732 private: 1733 template
1734 friend class PersistentValueMapBase; 1735 1736 internal::Address* GetDataFromSnapshotOnce(size_t index); 1737 void ReportExternalAllocationLimitReached(); 1738 }; 1739 1740 void Isolate::SetData(uint32_t slot, void* data) { 1741 using I = internal::Internals; 1742 I::SetEmbedderData(this, slot, data); 1743 } 1744 1745 void* Isolate::GetData(uint32_t slot) { 1746 using I = internal::Internals; 1747 return I::GetEmbedderData(this, slot); 1748 } 1749 1750 uint32_t Isolate::GetNumberOfDataSlots() { 1751 using I = internal::Internals; 1752 return I::kNumIsolateDataSlots; 1753 } 1754 1755 template
1756 MaybeLocal
Isolate::GetDataFromSnapshotOnce(size_t index) { 1757 if (auto slot = GetDataFromSnapshotOnce(index); slot) { 1758 internal::PerformCastCheck( 1759 internal::ValueHelper::SlotAsValue
(slot)); 1760 return Local
::FromSlot(slot); 1761 } 1762 return {}; 1763 } 1764 1765 } // namespace v8 1766 1767 #endif // INCLUDE_V8_ISOLATE_H_
Contact us
|
About us
|
Term of use
|
Copyright © 2000-2025 MyWebUniversity.com ™