Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-02-21 10:05:24

0001 // Copyright 2021 the V8 project authors. All rights reserved.
0002 // Use of this source code is governed by a BSD-style license that can be
0003 // found in the LICENSE file.
0004 
0005 #ifndef INCLUDE_V8_ISOLATE_H_
0006 #define INCLUDE_V8_ISOLATE_H_
0007 
0008 #include <stddef.h>
0009 #include <stdint.h>
0010 
0011 #include <memory>
0012 #include <utility>
0013 
0014 #include "cppgc/common.h"
0015 #include "v8-array-buffer.h"       // NOLINT(build/include_directory)
0016 #include "v8-callbacks.h"          // NOLINT(build/include_directory)
0017 #include "v8-data.h"               // NOLINT(build/include_directory)
0018 #include "v8-debug.h"              // NOLINT(build/include_directory)
0019 #include "v8-embedder-heap.h"      // NOLINT(build/include_directory)
0020 #include "v8-function-callback.h"  // NOLINT(build/include_directory)
0021 #include "v8-internal.h"           // NOLINT(build/include_directory)
0022 #include "v8-local-handle.h"       // NOLINT(build/include_directory)
0023 #include "v8-microtask.h"          // NOLINT(build/include_directory)
0024 #include "v8-persistent-handle.h"  // NOLINT(build/include_directory)
0025 #include "v8-primitive.h"          // NOLINT(build/include_directory)
0026 #include "v8-statistics.h"         // NOLINT(build/include_directory)
0027 #include "v8-unwinder.h"           // NOLINT(build/include_directory)
0028 #include "v8config.h"              // NOLINT(build/include_directory)
0029 
0030 namespace v8 {
0031 
0032 class CppHeap;
0033 class HeapProfiler;
0034 class MicrotaskQueue;
0035 class StartupData;
0036 class ScriptOrModule;
0037 class SharedArrayBuffer;
0038 
0039 namespace internal {
0040 class MicrotaskQueue;
0041 class ThreadLocalTop;
0042 }  // namespace internal
0043 
0044 namespace metrics {
0045 class Recorder;
0046 }  // namespace metrics
0047 
0048 /**
0049  * A set of constraints that specifies the limits of the runtime's memory use.
0050  * You must set the heap size before initializing the VM - the size cannot be
0051  * adjusted after the VM is initialized.
0052  *
0053  * If you are using threads then you should hold the V8::Locker lock while
0054  * setting the stack limit and you must set a non-default stack limit separately
0055  * for each thread.
0056  *
0057  * The arguments for set_max_semi_space_size, set_max_old_space_size,
0058  * set_max_executable_size, set_code_range_size specify limits in MB.
0059  *
0060  * The argument for set_max_semi_space_size_in_kb is in KB.
0061  */
0062 class V8_EXPORT ResourceConstraints {
0063  public:
0064   /**
0065    * Configures the constraints with reasonable default values based on the
0066    * provided heap size limit. The heap size includes both the young and
0067    * the old generation.
0068    *
0069    * \param initial_heap_size_in_bytes The initial heap size or zero.
0070    *    By default V8 starts with a small heap and dynamically grows it to
0071    *    match the set of live objects. This may lead to ineffective
0072    *    garbage collections at startup if the live set is large.
0073    *    Setting the initial heap size avoids such garbage collections.
0074    *    Note that this does not affect young generation garbage collections.
0075    *
0076    * \param maximum_heap_size_in_bytes The hard limit for the heap size.
0077    *    When the heap size approaches this limit, V8 will perform series of
0078    *    garbage collections and invoke the NearHeapLimitCallback. If the garbage
0079    *    collections do not help and the callback does not increase the limit,
0080    *    then V8 will crash with V8::FatalProcessOutOfMemory.
0081    */
0082   void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes,
0083                                      size_t maximum_heap_size_in_bytes);
0084 
0085   /**
0086    * Configures the constraints with reasonable default values based on the
0087    * capabilities of the current device the VM is running on.
0088    *
0089    * \param physical_memory The total amount of physical memory on the current
0090    *   device, in bytes.
0091    * \param virtual_memory_limit The amount of virtual memory on the current
0092    *   device, in bytes, or zero, if there is no limit.
0093    */
0094   void ConfigureDefaults(uint64_t physical_memory,
0095                          uint64_t virtual_memory_limit);
0096 
0097   /**
0098    * The address beyond which the VM's stack may not grow.
0099    */
0100   uint32_t* stack_limit() const { return stack_limit_; }
0101   void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
0102 
0103   /**
0104    * The amount of virtual memory reserved for generated code. This is relevant
0105    * for 64-bit architectures that rely on code range for calls in code.
0106    *
0107    * When V8_COMPRESS_POINTERS_IN_SHARED_CAGE is defined, there is a shared
0108    * process-wide code range that is lazily initialized. This value is used to
0109    * configure that shared code range when the first Isolate is
0110    * created. Subsequent Isolates ignore this value.
0111    */
0112   size_t code_range_size_in_bytes() const { return code_range_size_; }
0113   void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; }
0114 
0115   /**
0116    * The maximum size of the old generation.
0117    * When the old generation approaches this limit, V8 will perform series of
0118    * garbage collections and invoke the NearHeapLimitCallback.
0119    * If the garbage collections do not help and the callback does not
0120    * increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory.
0121    */
0122   size_t max_old_generation_size_in_bytes() const {
0123     return max_old_generation_size_;
0124   }
0125   void set_max_old_generation_size_in_bytes(size_t limit) {
0126     max_old_generation_size_ = limit;
0127   }
0128 
0129   /**
0130    * The maximum size of the young generation, which consists of two semi-spaces
0131    * and a large object space. This affects frequency of Scavenge garbage
0132    * collections and should be typically much smaller that the old generation.
0133    */
0134   size_t max_young_generation_size_in_bytes() const {
0135     return max_young_generation_size_;
0136   }
0137   void set_max_young_generation_size_in_bytes(size_t limit) {
0138     max_young_generation_size_ = limit;
0139   }
0140 
0141   size_t initial_old_generation_size_in_bytes() const {
0142     return initial_old_generation_size_;
0143   }
0144   void set_initial_old_generation_size_in_bytes(size_t initial_size) {
0145     initial_old_generation_size_ = initial_size;
0146   }
0147 
0148   size_t initial_young_generation_size_in_bytes() const {
0149     return initial_young_generation_size_;
0150   }
0151   void set_initial_young_generation_size_in_bytes(size_t initial_size) {
0152     initial_young_generation_size_ = initial_size;
0153   }
0154 
0155  private:
0156   static constexpr size_t kMB = 1048576u;
0157   size_t code_range_size_ = 0;
0158   size_t max_old_generation_size_ = 0;
0159   size_t max_young_generation_size_ = 0;
0160   size_t initial_old_generation_size_ = 0;
0161   size_t initial_young_generation_size_ = 0;
0162   uint32_t* stack_limit_ = nullptr;
0163 };
0164 
0165 /**
0166  * Option flags passed to the SetRAILMode function.
0167  * See documentation https://developers.google.com/web/tools/chrome-devtools/
0168  * profile/evaluate-performance/rail
0169  */
0170 enum RAILMode : unsigned {
0171   // Response performance mode: In this mode very low virtual machine latency
0172   // is provided. V8 will try to avoid JavaScript execution interruptions.
0173   // Throughput may be throttled.
0174   PERFORMANCE_RESPONSE,
0175   // Animation performance mode: In this mode low virtual machine latency is
0176   // provided. V8 will try to avoid as many JavaScript execution interruptions
0177   // as possible. Throughput may be throttled. This is the default mode.
0178   PERFORMANCE_ANIMATION,
0179   // Idle performance mode: The embedder is idle. V8 can complete deferred work
0180   // in this mode.
0181   PERFORMANCE_IDLE,
0182   // Load performance mode: In this mode high throughput is provided. V8 may
0183   // turn off latency optimizations.
0184   PERFORMANCE_LOAD
0185 };
0186 
0187 /**
0188  * Memory pressure level for the MemoryPressureNotification.
0189  * kNone hints V8 that there is no memory pressure.
0190  * kModerate hints V8 to speed up incremental garbage collection at the cost of
0191  * of higher latency due to garbage collection pauses.
0192  * kCritical hints V8 to free memory as soon as possible. Garbage collection
0193  * pauses at this level will be large.
0194  */
0195 enum class MemoryPressureLevel { kNone, kModerate, kCritical };
0196 
0197 /**
0198  * Indicator for the stack state.
0199  */
0200 using StackState = cppgc::EmbedderStackState;
0201 
0202 /**
0203  * Isolate represents an isolated instance of the V8 engine.  V8 isolates have
0204  * completely separate states.  Objects from one isolate must not be used in
0205  * other isolates.  The embedder can create multiple isolates and use them in
0206  * parallel in multiple threads.  An isolate can be entered by at most one
0207  * thread at any given time.  The Locker/Unlocker API must be used to
0208  * synchronize.
0209  */
0210 class V8_EXPORT Isolate {
0211  public:
0212   /**
0213    * Initial configuration parameters for a new Isolate.
0214    */
0215   struct V8_EXPORT CreateParams {
0216     CreateParams();
0217     ~CreateParams();
0218 
0219     ALLOW_COPY_AND_MOVE_WITH_DEPRECATED_FIELDS(CreateParams)
0220 
0221     /**
0222      * Allows the host application to provide the address of a function that is
0223      * notified each time code is added, moved or removed.
0224      */
0225     JitCodeEventHandler code_event_handler = nullptr;
0226 
0227     /**
0228      * ResourceConstraints to use for the new Isolate.
0229      */
0230     ResourceConstraints constraints;
0231 
0232     /**
0233      * Explicitly specify a startup snapshot blob. The embedder owns the blob.
0234      * The embedder *must* ensure that the snapshot is from a trusted source.
0235      */
0236     const StartupData* snapshot_blob = nullptr;
0237 
0238     /**
0239      * Enables the host application to provide a mechanism for recording
0240      * statistics counters.
0241      */
0242     CounterLookupCallback counter_lookup_callback = nullptr;
0243 
0244     /**
0245      * Enables the host application to provide a mechanism for recording
0246      * histograms. The CreateHistogram function returns a
0247      * histogram which will later be passed to the AddHistogramSample
0248      * function.
0249      */
0250     CreateHistogramCallback create_histogram_callback = nullptr;
0251     AddHistogramSampleCallback add_histogram_sample_callback = nullptr;
0252 
0253     /**
0254      * The ArrayBuffer::Allocator to use for allocating and freeing the backing
0255      * store of ArrayBuffers.
0256      *
0257      * If the shared_ptr version is used, the Isolate instance and every
0258      * |BackingStore| allocated using this allocator hold a std::shared_ptr
0259      * to the allocator, in order to facilitate lifetime
0260      * management for the allocator instance.
0261      */
0262     ArrayBuffer::Allocator* array_buffer_allocator = nullptr;
0263     std::shared_ptr<ArrayBuffer::Allocator> array_buffer_allocator_shared;
0264 
0265     /**
0266      * Specifies an optional nullptr-terminated array of raw addresses in the
0267      * embedder that V8 can match against during serialization and use for
0268      * deserialization. This array and its content must stay valid for the
0269      * entire lifetime of the isolate.
0270      */
0271     const intptr_t* external_references = nullptr;
0272 
0273     /**
0274      * Whether calling Atomics.wait (a function that may block) is allowed in
0275      * this isolate. This can also be configured via SetAllowAtomicsWait.
0276      */
0277     bool allow_atomics_wait = true;
0278 
0279     /**
0280      * Termination is postponed when there is no active SafeForTerminationScope.
0281      */
0282     bool only_terminate_in_safe_scope = false;
0283 
0284     /**
0285      * The following parameters describe the offsets for addressing type info
0286      * for wrapped API objects and are used by the fast C API
0287      * (for details see v8-fast-api-calls.h).
0288      */
0289     int embedder_wrapper_type_index = -1;
0290     int embedder_wrapper_object_index = -1;
0291 
0292     /**
0293      * Callbacks to invoke in case of fatal or OOM errors.
0294      */
0295     FatalErrorCallback fatal_error_callback = nullptr;
0296     OOMErrorCallback oom_error_callback = nullptr;
0297 
0298     /**
0299      * A CppHeap used to construct the Isolate. V8 takes ownership of the
0300      * CppHeap passed this way.
0301      */
0302     CppHeap* cpp_heap = nullptr;
0303   };
0304 
0305   /**
0306    * Stack-allocated class which sets the isolate for all operations
0307    * executed within a local scope.
0308    */
0309   class V8_EXPORT V8_NODISCARD Scope {
0310    public:
0311     explicit Scope(Isolate* isolate) : v8_isolate_(isolate) {
0312       v8_isolate_->Enter();
0313     }
0314 
0315     ~Scope() { v8_isolate_->Exit(); }
0316 
0317     // Prevent copying of Scope objects.
0318     Scope(const Scope&) = delete;
0319     Scope& operator=(const Scope&) = delete;
0320 
0321    private:
0322     Isolate* const v8_isolate_;
0323   };
0324 
0325   /**
0326    * Assert that no Javascript code is invoked.
0327    */
0328   class V8_EXPORT V8_NODISCARD DisallowJavascriptExecutionScope {
0329    public:
0330     enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE, DUMP_ON_FAILURE };
0331 
0332     DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
0333     ~DisallowJavascriptExecutionScope();
0334 
0335     // Prevent copying of Scope objects.
0336     DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
0337         delete;
0338     DisallowJavascriptExecutionScope& operator=(
0339         const DisallowJavascriptExecutionScope&) = delete;
0340 
0341    private:
0342     v8::Isolate* const v8_isolate_;
0343     const OnFailure on_failure_;
0344     bool was_execution_allowed_;
0345   };
0346 
0347   /**
0348    * Introduce exception to DisallowJavascriptExecutionScope.
0349    */
0350   class V8_EXPORT V8_NODISCARD AllowJavascriptExecutionScope {
0351    public:
0352     explicit AllowJavascriptExecutionScope(Isolate* isolate);
0353     ~AllowJavascriptExecutionScope();
0354 
0355     // Prevent copying of Scope objects.
0356     AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
0357         delete;
0358     AllowJavascriptExecutionScope& operator=(
0359         const AllowJavascriptExecutionScope&) = delete;
0360 
0361    private:
0362     Isolate* const v8_isolate_;
0363     bool was_execution_allowed_assert_;
0364     bool was_execution_allowed_throws_;
0365     bool was_execution_allowed_dump_;
0366   };
0367 
0368   /**
0369    * Do not run microtasks while this scope is active, even if microtasks are
0370    * automatically executed otherwise.
0371    */
0372   class V8_EXPORT V8_NODISCARD SuppressMicrotaskExecutionScope {
0373    public:
0374     explicit SuppressMicrotaskExecutionScope(
0375         Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr);
0376     ~SuppressMicrotaskExecutionScope();
0377 
0378     // Prevent copying of Scope objects.
0379     SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
0380         delete;
0381     SuppressMicrotaskExecutionScope& operator=(
0382         const SuppressMicrotaskExecutionScope&) = delete;
0383 
0384    private:
0385     internal::Isolate* const i_isolate_;
0386     internal::MicrotaskQueue* const microtask_queue_;
0387     internal::Address previous_stack_height_;
0388 
0389     friend class internal::ThreadLocalTop;
0390   };
0391 
0392   /**
0393    * This scope allows terminations inside direct V8 API calls and forbid them
0394    * inside any recursive API calls without explicit SafeForTerminationScope.
0395    */
0396   class V8_EXPORT V8_NODISCARD SafeForTerminationScope {
0397    public:
0398     V8_DEPRECATE_SOON("All code should be safe for termination")
0399     explicit SafeForTerminationScope(v8::Isolate* v8_isolate) {}
0400     ~SafeForTerminationScope() {}
0401 
0402     // Prevent copying of Scope objects.
0403     SafeForTerminationScope(const SafeForTerminationScope&) = delete;
0404     SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete;
0405   };
0406 
0407   /**
0408    * Types of garbage collections that can be requested via
0409    * RequestGarbageCollectionForTesting.
0410    */
0411   enum GarbageCollectionType {
0412     kFullGarbageCollection,
0413     kMinorGarbageCollection
0414   };
0415 
0416   /**
0417    * Features reported via the SetUseCounterCallback callback. Do not change
0418    * assigned numbers of existing items; add new features to the end of this
0419    * list.
0420    * Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and
0421    * then finally be renamed to `kOBSOLETE_...` to stop embedders from using
0422    * them.
0423    */
0424   enum UseCounterFeature {
0425     kUseAsm = 0,
0426     kBreakIterator = 1,
0427     kOBSOLETE_LegacyConst = 2,
0428     kOBSOLETE_MarkDequeOverflow = 3,
0429     kOBSOLETE_StoreBufferOverflow = 4,
0430     kOBSOLETE_SlotsBufferOverflow = 5,
0431     kOBSOLETE_ObjectObserve = 6,
0432     kForcedGC = 7,
0433     kSloppyMode = 8,
0434     kStrictMode = 9,
0435     kOBSOLETE_StrongMode = 10,
0436     kRegExpPrototypeStickyGetter = 11,
0437     kRegExpPrototypeToString = 12,
0438     kRegExpPrototypeUnicodeGetter = 13,
0439     kOBSOLETE_IntlV8Parse = 14,
0440     kOBSOLETE_IntlPattern = 15,
0441     kOBSOLETE_IntlResolved = 16,
0442     kOBSOLETE_PromiseChain = 17,
0443     kOBSOLETE_PromiseAccept = 18,
0444     kOBSOLETE_PromiseDefer = 19,
0445     kHtmlCommentInExternalScript = 20,
0446     kHtmlComment = 21,
0447     kSloppyModeBlockScopedFunctionRedefinition = 22,
0448     kForInInitializer = 23,
0449     kOBSOLETE_ArrayProtectorDirtied = 24,
0450     kArraySpeciesModified = 25,
0451     kArrayPrototypeConstructorModified = 26,
0452     kOBSOLETE_ArrayInstanceProtoModified = 27,
0453     kArrayInstanceConstructorModified = 28,
0454     kOBSOLETE_LegacyFunctionDeclaration = 29,
0455     kOBSOLETE_RegExpPrototypeSourceGetter = 30,
0456     kOBSOLETE_RegExpPrototypeOldFlagGetter = 31,
0457     kDecimalWithLeadingZeroInStrictMode = 32,
0458     kLegacyDateParser = 33,
0459     kDefineGetterOrSetterWouldThrow = 34,
0460     kFunctionConstructorReturnedUndefined = 35,
0461     kAssigmentExpressionLHSIsCallInSloppy = 36,
0462     kAssigmentExpressionLHSIsCallInStrict = 37,
0463     kPromiseConstructorReturnedUndefined = 38,
0464     kOBSOLETE_ConstructorNonUndefinedPrimitiveReturn = 39,
0465     kOBSOLETE_LabeledExpressionStatement = 40,
0466     kOBSOLETE_LineOrParagraphSeparatorAsLineTerminator = 41,
0467     kIndexAccessor = 42,
0468     kErrorCaptureStackTrace = 43,
0469     kErrorPrepareStackTrace = 44,
0470     kErrorStackTraceLimit = 45,
0471     kWebAssemblyInstantiation = 46,
0472     kDeoptimizerDisableSpeculation = 47,
0473     kOBSOLETE_ArrayPrototypeSortJSArrayModifiedPrototype = 48,
0474     kFunctionTokenOffsetTooLongForToString = 49,
0475     kWasmSharedMemory = 50,
0476     kWasmThreadOpcodes = 51,
0477     kOBSOLETE_AtomicsNotify = 52,
0478     kOBSOLETE_AtomicsWake = 53,
0479     kCollator = 54,
0480     kNumberFormat = 55,
0481     kDateTimeFormat = 56,
0482     kPluralRules = 57,
0483     kRelativeTimeFormat = 58,
0484     kLocale = 59,
0485     kListFormat = 60,
0486     kSegmenter = 61,
0487     kStringLocaleCompare = 62,
0488     kOBSOLETE_StringToLocaleUpperCase = 63,
0489     kStringToLocaleLowerCase = 64,
0490     kNumberToLocaleString = 65,
0491     kDateToLocaleString = 66,
0492     kDateToLocaleDateString = 67,
0493     kDateToLocaleTimeString = 68,
0494     kAttemptOverrideReadOnlyOnPrototypeSloppy = 69,
0495     kAttemptOverrideReadOnlyOnPrototypeStrict = 70,
0496     kOBSOLETE_OptimizedFunctionWithOneShotBytecode = 71,
0497     kRegExpMatchIsTrueishOnNonJSRegExp = 72,
0498     kRegExpMatchIsFalseishOnJSRegExp = 73,
0499     kOBSOLETE_DateGetTimezoneOffset = 74,
0500     kStringNormalize = 75,
0501     kCallSiteAPIGetFunctionSloppyCall = 76,
0502     kCallSiteAPIGetThisSloppyCall = 77,
0503     kOBSOLETE_RegExpMatchAllWithNonGlobalRegExp = 78,
0504     kRegExpExecCalledOnSlowRegExp = 79,
0505     kRegExpReplaceCalledOnSlowRegExp = 80,
0506     kDisplayNames = 81,
0507     kSharedArrayBufferConstructed = 82,
0508     kArrayPrototypeHasElements = 83,
0509     kObjectPrototypeHasElements = 84,
0510     kNumberFormatStyleUnit = 85,
0511     kDateTimeFormatRange = 86,
0512     kDateTimeFormatDateTimeStyle = 87,
0513     kBreakIteratorTypeWord = 88,
0514     kBreakIteratorTypeLine = 89,
0515     kInvalidatedArrayBufferDetachingProtector = 90,
0516     kInvalidatedArrayConstructorProtector = 91,
0517     kInvalidatedArrayIteratorLookupChainProtector = 92,
0518     kInvalidatedArraySpeciesLookupChainProtector = 93,
0519     kInvalidatedIsConcatSpreadableLookupChainProtector = 94,
0520     kInvalidatedMapIteratorLookupChainProtector = 95,
0521     kInvalidatedNoElementsProtector = 96,
0522     kInvalidatedPromiseHookProtector = 97,
0523     kInvalidatedPromiseResolveLookupChainProtector = 98,
0524     kInvalidatedPromiseSpeciesLookupChainProtector = 99,
0525     kInvalidatedPromiseThenLookupChainProtector = 100,
0526     kInvalidatedRegExpSpeciesLookupChainProtector = 101,
0527     kInvalidatedSetIteratorLookupChainProtector = 102,
0528     kInvalidatedStringIteratorLookupChainProtector = 103,
0529     kInvalidatedStringLengthOverflowLookupChainProtector = 104,
0530     kInvalidatedTypedArraySpeciesLookupChainProtector = 105,
0531     kWasmSimdOpcodes = 106,
0532     kVarRedeclaredCatchBinding = 107,
0533     kWasmRefTypes = 108,
0534     kOBSOLETE_WasmBulkMemory = 109,
0535     kOBSOLETE_WasmMultiValue = 110,
0536     kWasmExceptionHandling = 111,
0537     kInvalidatedMegaDOMProtector = 112,
0538     kFunctionPrototypeArguments = 113,
0539     kFunctionPrototypeCaller = 114,
0540     kTurboFanOsrCompileStarted = 115,
0541     kAsyncStackTaggingCreateTaskCall = 116,
0542     kDurationFormat = 117,
0543     kInvalidatedNumberStringNotRegexpLikeProtector = 118,
0544     kOBSOLETE_RegExpUnicodeSetIncompatibilitiesWithUnicodeMode = 119,
0545     kImportAssertionDeprecatedSyntax = 120,
0546     kLocaleInfoObsoletedGetters = 121,
0547     kLocaleInfoFunctions = 122,
0548     kCompileHintsMagicAll = 123,
0549     kInvalidatedNoProfilingProtector = 124,
0550     kWasmMemory64 = 125,
0551     kWasmMultiMemory = 126,
0552     kWasmGC = 127,
0553     kWasmImportedStrings = 128,
0554     kSourceMappingUrlMagicCommentAtSign = 129,
0555     kTemporalObject = 130,
0556     kWasmModuleCompilation = 131,
0557     kInvalidatedNoUndetectableObjectsProtector = 132,
0558     kWasmJavaScriptPromiseIntegration = 133,
0559     kWasmReturnCall = 134,
0560     kWasmExtendedConst = 135,
0561     kWasmRelaxedSimd = 136,
0562     kWasmTypeReflection = 137,
0563     kWasmExnRef = 138,
0564     kWasmTypedFuncRef = 139,
0565     kInvalidatedStringWrapperToPrimitiveProtector = 140,
0566 
0567     // If you add new values here, you'll also need to update Chromium's:
0568     // web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to
0569     // this list need to be landed first, then changes on the Chromium side.
0570     kUseCounterFeatureCount  // This enum value must be last.
0571   };
0572 
0573   enum MessageErrorLevel {
0574     kMessageLog = (1 << 0),
0575     kMessageDebug = (1 << 1),
0576     kMessageInfo = (1 << 2),
0577     kMessageError = (1 << 3),
0578     kMessageWarning = (1 << 4),
0579     kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
0580                   kMessageWarning,
0581   };
0582 
0583   using UseCounterCallback = void (*)(Isolate* isolate,
0584                                       UseCounterFeature feature);
0585 
0586   /**
0587    * Allocates a new isolate but does not initialize it. Does not change the
0588    * currently entered isolate.
0589    *
0590    * Only Isolate::GetData() and Isolate::SetData(), which access the
0591    * embedder-controlled parts of the isolate, are allowed to be called on the
0592    * uninitialized isolate. To initialize the isolate, call
0593    * `Isolate::Initialize()` or initialize a `SnapshotCreator`.
0594    *
0595    * When an isolate is no longer used its resources should be freed
0596    * by calling Dispose().  Using the delete operator is not allowed.
0597    *
0598    * V8::Initialize() must have run prior to this.
0599    */
0600   static Isolate* Allocate();
0601 
0602   /**
0603    * Initialize an Isolate previously allocated by Isolate::Allocate().
0604    */
0605   static void Initialize(Isolate* isolate, const CreateParams& params);
0606 
0607   /**
0608    * Creates a new isolate.  Does not change the currently entered
0609    * isolate.
0610    *
0611    * When an isolate is no longer used its resources should be freed
0612    * by calling Dispose().  Using the delete operator is not allowed.
0613    *
0614    * V8::Initialize() must have run prior to this.
0615    */
0616   static Isolate* New(const CreateParams& params);
0617 
0618   /**
0619    * Returns the entered isolate for the current thread or NULL in
0620    * case there is no current isolate.
0621    *
0622    * This method must not be invoked before V8::Initialize() was invoked.
0623    */
0624   static Isolate* GetCurrent();
0625 
0626   /**
0627    * Returns the entered isolate for the current thread or NULL in
0628    * case there is no current isolate.
0629    *
0630    * No checks are performed by this method.
0631    */
0632   static Isolate* TryGetCurrent();
0633 
0634   /**
0635    * Return true if this isolate is currently active.
0636    **/
0637   bool IsCurrent() const;
0638 
0639   /**
0640    * Clears the set of objects held strongly by the heap. This set of
0641    * objects are originally built when a WeakRef is created or
0642    * successfully dereferenced.
0643    *
0644    * This is invoked automatically after microtasks are run. See
0645    * MicrotasksPolicy for when microtasks are run.
0646    *
0647    * This needs to be manually invoked only if the embedder is manually running
0648    * microtasks via a custom MicrotaskQueue class's PerformCheckpoint. In that
0649    * case, it is the embedder's responsibility to make this call at a time which
0650    * does not interrupt synchronous ECMAScript code execution.
0651    */
0652   void ClearKeptObjects();
0653 
0654   /**
0655    * Custom callback used by embedders to help V8 determine if it should abort
0656    * when it throws and no internal handler is predicted to catch the
0657    * exception. If --abort-on-uncaught-exception is used on the command line,
0658    * then V8 will abort if either:
0659    * - no custom callback is set.
0660    * - the custom callback set returns true.
0661    * Otherwise, the custom callback will not be called and V8 will not abort.
0662    */
0663   using AbortOnUncaughtExceptionCallback = bool (*)(Isolate*);
0664   void SetAbortOnUncaughtExceptionCallback(
0665       AbortOnUncaughtExceptionCallback callback);
0666 
0667   /**
0668    * This specifies the callback called by the upcoming dynamic
0669    * import() language feature to load modules.
0670    */
0671   void SetHostImportModuleDynamicallyCallback(
0672       HostImportModuleDynamicallyCallback callback);
0673 
0674   /**
0675    * This specifies the callback called by the upcoming import.meta
0676    * language feature to retrieve host-defined meta data for a module.
0677    */
0678   void SetHostInitializeImportMetaObjectCallback(
0679       HostInitializeImportMetaObjectCallback callback);
0680 
0681   /**
0682    * This specifies the callback called by the upcoming ShadowRealm
0683    * construction language feature to retrieve host created globals.
0684    */
0685   void SetHostCreateShadowRealmContextCallback(
0686       HostCreateShadowRealmContextCallback callback);
0687 
0688   /**
0689    * This specifies the callback called when the stack property of Error
0690    * is accessed.
0691    */
0692   void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
0693 
0694 #if defined(V8_OS_WIN)
0695   /**
0696    * This specifies the callback called when an ETW tracing session starts.
0697    */
0698   void SetFilterETWSessionByURLCallback(FilterETWSessionByURLCallback callback);
0699 #endif  // V8_OS_WIN
0700 
0701   /**
0702    * Optional notification that the system is running low on memory.
0703    * V8 uses these notifications to guide heuristics.
0704    * It is allowed to call this function from another thread while
0705    * the isolate is executing long running JavaScript code.
0706    */
0707   void MemoryPressureNotification(MemoryPressureLevel level);
0708 
0709   /**
0710    * Optional request from the embedder to tune v8 towards energy efficiency
0711    * rather than speed if `battery_saver_mode_enabled` is true, because the
0712    * embedder is in battery saver mode. If false, the correct tuning is left
0713    * to v8 to decide.
0714    */
0715   void SetBatterySaverMode(bool battery_saver_mode_enabled);
0716 
0717   /**
0718    * Drop non-essential caches. Should only be called from testing code.
0719    * The method can potentially block for a long time and does not necessarily
0720    * trigger GC.
0721    */
0722   void ClearCachesForTesting();
0723 
0724   /**
0725    * Methods below this point require holding a lock (using Locker) in
0726    * a multi-threaded environment.
0727    */
0728 
0729   /**
0730    * Sets this isolate as the entered one for the current thread.
0731    * Saves the previously entered one (if any), so that it can be
0732    * restored when exiting.  Re-entering an isolate is allowed.
0733    */
0734   void Enter();
0735 
0736   /**
0737    * Exits this isolate by restoring the previously entered one in the
0738    * current thread.  The isolate may still stay the same, if it was
0739    * entered more than once.
0740    *
0741    * Requires: this == Isolate::GetCurrent().
0742    */
0743   void Exit();
0744 
0745   /**
0746    * Disposes the isolate.  The isolate must not be entered by any
0747    * thread to be disposable.
0748    */
0749   void Dispose();
0750 
0751   /**
0752    * Dumps activated low-level V8 internal stats. This can be used instead
0753    * of performing a full isolate disposal.
0754    */
0755   void DumpAndResetStats();
0756 
0757   /**
0758    * Discards all V8 thread-specific data for the Isolate. Should be used
0759    * if a thread is terminating and it has used an Isolate that will outlive
0760    * the thread -- all thread-specific data for an Isolate is discarded when
0761    * an Isolate is disposed so this call is pointless if an Isolate is about
0762    * to be Disposed.
0763    */
0764   void DiscardThreadSpecificMetadata();
0765 
0766   /**
0767    * Associate embedder-specific data with the isolate. |slot| has to be
0768    * between 0 and GetNumberOfDataSlots() - 1.
0769    */
0770   V8_INLINE void SetData(uint32_t slot, void* data);
0771 
0772   /**
0773    * Retrieve embedder-specific data from the isolate.
0774    * Returns NULL if SetData has never been called for the given |slot|.
0775    */
0776   V8_INLINE void* GetData(uint32_t slot);
0777 
0778   /**
0779    * Returns the maximum number of available embedder data slots. Valid slots
0780    * are in the range of 0 - GetNumberOfDataSlots() - 1.
0781    */
0782   V8_INLINE static uint32_t GetNumberOfDataSlots();
0783 
0784   /**
0785    * Return data that was previously attached to the isolate snapshot via
0786    * SnapshotCreator, and removes the reference to it.
0787    * Repeated call with the same index returns an empty MaybeLocal.
0788    */
0789   template <class T>
0790   V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
0791 
0792   /**
0793    * Returns the value that was set or restored by
0794    * SetContinuationPreservedEmbedderData(), if any.
0795    */
0796   Local<Value> GetContinuationPreservedEmbedderData();
0797 
0798   /**
0799    * Sets a value that will be stored on continuations and reset while the
0800    * continuation runs.
0801    */
0802   void SetContinuationPreservedEmbedderData(Local<Value> data);
0803 
0804   /**
0805    * Get statistics about the heap memory usage.
0806    */
0807   void GetHeapStatistics(HeapStatistics* heap_statistics);
0808 
0809   /**
0810    * Returns the number of spaces in the heap.
0811    */
0812   size_t NumberOfHeapSpaces();
0813 
0814   /**
0815    * Get the memory usage of a space in the heap.
0816    *
0817    * \param space_statistics The HeapSpaceStatistics object to fill in
0818    *   statistics.
0819    * \param index The index of the space to get statistics from, which ranges
0820    *   from 0 to NumberOfHeapSpaces() - 1.
0821    * \returns true on success.
0822    */
0823   bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
0824                               size_t index);
0825 
0826   /**
0827    * Returns the number of types of objects tracked in the heap at GC.
0828    */
0829   size_t NumberOfTrackedHeapObjectTypes();
0830 
0831   /**
0832    * Get statistics about objects in the heap.
0833    *
0834    * \param object_statistics The HeapObjectStatistics object to fill in
0835    *   statistics of objects of given type, which were live in the previous GC.
0836    * \param type_index The index of the type of object to fill details about,
0837    *   which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
0838    * \returns true on success.
0839    */
0840   bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
0841                                        size_t type_index);
0842 
0843   /**
0844    * Get statistics about code and its metadata in the heap.
0845    *
0846    * \param object_statistics The HeapCodeStatistics object to fill in
0847    *   statistics of code, bytecode and their metadata.
0848    * \returns true on success.
0849    */
0850   bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
0851 
0852   /**
0853    * This API is experimental and may change significantly.
0854    *
0855    * Enqueues a memory measurement request and invokes the delegate with the
0856    * results.
0857    *
0858    * \param delegate the delegate that defines which contexts to measure and
0859    *   reports the results.
0860    *
0861    * \param execution promptness executing the memory measurement.
0862    *   The kEager value is expected to be used only in tests.
0863    */
0864   bool MeasureMemory(
0865       std::unique_ptr<MeasureMemoryDelegate> delegate,
0866       MeasureMemoryExecution execution = MeasureMemoryExecution::kDefault);
0867 
0868   /**
0869    * Get a call stack sample from the isolate.
0870    * \param state Execution state.
0871    * \param frames Caller allocated buffer to store stack frames.
0872    * \param frames_limit Maximum number of frames to capture. The buffer must
0873    *                     be large enough to hold the number of frames.
0874    * \param sample_info The sample info is filled up by the function
0875    *                    provides number of actual captured stack frames and
0876    *                    the current VM state.
0877    * \note GetStackSample should only be called when the JS thread is paused or
0878    *       interrupted. Otherwise the behavior is undefined.
0879    */
0880   void GetStackSample(const RegisterState& state, void** frames,
0881                       size_t frames_limit, SampleInfo* sample_info);
0882 
0883   /**
0884    * Adjusts the amount of registered external memory. Used to give V8 an
0885    * indication of the amount of externally allocated memory that is kept alive
0886    * by JavaScript objects. V8 uses this to decide when to perform global
0887    * garbage collections. Registering externally allocated memory will trigger
0888    * global garbage collections more often than it would otherwise in an attempt
0889    * to garbage collect the JavaScript objects that keep the externally
0890    * allocated memory alive.
0891    *
0892    * \param change_in_bytes the change in externally allocated memory that is
0893    *   kept alive by JavaScript objects.
0894    * \returns the adjusted value.
0895    */
0896   int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
0897 
0898   /**
0899    * Returns heap profiler for this isolate. Will return NULL until the isolate
0900    * is initialized.
0901    */
0902   HeapProfiler* GetHeapProfiler();
0903 
0904   /**
0905    * Tells the VM whether the embedder is idle or not.
0906    */
0907   void SetIdle(bool is_idle);
0908 
0909   /** Returns the ArrayBuffer::Allocator used in this isolate. */
0910   ArrayBuffer::Allocator* GetArrayBufferAllocator();
0911 
0912   /** Returns true if this isolate has a current context. */
0913   bool InContext();
0914 
0915   /**
0916    * Returns the context of the currently running JavaScript, or the context
0917    * on the top of the stack if no JavaScript is running.
0918    */
0919   Local<Context> GetCurrentContext();
0920 
0921   /**
0922    * Returns either the last context entered through V8's C++ API, or the
0923    * context of the currently running microtask while processing microtasks.
0924    * If a context is entered while executing a microtask, that context is
0925    * returned.
0926    */
0927   Local<Context> GetEnteredOrMicrotaskContext();
0928 
0929   /**
0930    * Returns the Context that corresponds to the Incumbent realm in HTML spec.
0931    * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
0932    */
0933   Local<Context> GetIncumbentContext();
0934 
0935   /**
0936    * Schedules a v8::Exception::Error with the given message.
0937    * See ThrowException for more details. Templatized to provide compile-time
0938    * errors in case of too long strings (see v8::String::NewFromUtf8Literal).
0939    */
0940   template <int N>
0941   Local<Value> ThrowError(const char (&message)[N]) {
0942     return ThrowError(String::NewFromUtf8Literal(this, message));
0943   }
0944   Local<Value> ThrowError(Local<String> message);
0945 
0946   /**
0947    * Schedules an exception to be thrown when returning to JavaScript.  When an
0948    * exception has been scheduled it is illegal to invoke any JavaScript
0949    * operation; the caller must return immediately and only after the exception
0950    * has been handled does it become legal to invoke JavaScript operations.
0951    */
0952   Local<Value> ThrowException(Local<Value> exception);
0953 
0954   using GCCallback = void (*)(Isolate* isolate, GCType type,
0955                               GCCallbackFlags flags);
0956   using GCCallbackWithData = void (*)(Isolate* isolate, GCType type,
0957                                       GCCallbackFlags flags, void* data);
0958 
0959   /**
0960    * Enables the host application to receive a notification before a
0961    * garbage collection.
0962    *
0963    * \param callback The callback to be invoked. The callback is allowed to
0964    *     allocate but invocation is not re-entrant: a callback triggering
0965    *     garbage collection will not be called again. JS execution is prohibited
0966    *     from these callbacks. A single callback may only be registered once.
0967    * \param gc_type_filter A filter in case it should be applied.
0968    */
0969   void AddGCPrologueCallback(GCCallback callback,
0970                              GCType gc_type_filter = kGCTypeAll);
0971 
0972   /**
0973    * \copydoc AddGCPrologueCallback(GCCallback, GCType)
0974    *
0975    * \param data Additional data that should be passed to the callback.
0976    */
0977   void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
0978                              GCType gc_type_filter = kGCTypeAll);
0979 
0980   /**
0981    * This function removes a callback which was added by
0982    * `AddGCPrologueCallback`.
0983    *
0984    * \param callback the callback to remove.
0985    */
0986   void RemoveGCPrologueCallback(GCCallback callback);
0987 
0988   /**
0989    * \copydoc AddGCPrologueCallback(GCCallback)
0990    *
0991    * \param data Additional data that was used to install the callback.
0992    */
0993   void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
0994 
0995   /**
0996    * Enables the host application to receive a notification after a
0997    * garbage collection.
0998    *
0999    * \copydetails AddGCPrologueCallback(GCCallback, GCType)
1000    */
1001   void AddGCEpilogueCallback(GCCallback callback,
1002                              GCType gc_type_filter = kGCTypeAll);
1003 
1004   /**
1005    * \copydoc AddGCEpilogueCallback(GCCallback, GCType)
1006    *
1007    * \param data Additional data that should be passed to the callback.
1008    */
1009   void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
1010                              GCType gc_type_filter = kGCTypeAll);
1011 
1012   /**
1013    * This function removes a callback which was added by
1014    * `AddGCEpilogueCallback`.
1015    *
1016    * \param callback the callback to remove.
1017    */
1018   void RemoveGCEpilogueCallback(GCCallback callback);
1019 
1020   /**
1021    * \copydoc RemoveGCEpilogueCallback(GCCallback)
1022    *
1023    * \param data Additional data that was used to install the callback.
1024    */
1025   void RemoveGCEpilogueCallback(GCCallbackWithData callback,
1026                                 void* data = nullptr);
1027 
1028   /**
1029    * Sets an embedder roots handle that V8 should consider when performing
1030    * non-unified heap garbage collections. The intended use case is for setting
1031    * a custom handler after invoking `AttachCppHeap()`.
1032    *
1033    * V8 does not take ownership of the handler.
1034    */
1035   void SetEmbedderRootsHandler(EmbedderRootsHandler* handler);
1036 
1037   /**
1038    * Attaches a managed C++ heap as an extension to the JavaScript heap. The
1039    * embedder maintains ownership of the CppHeap. At most one C++ heap can be
1040    * attached to V8.
1041    *
1042    * Multi-threaded use requires the use of v8::Locker/v8::Unlocker, see
1043    * CppHeap.
1044    *
1045    * If a CppHeap is set via CreateParams, then this call is a noop.
1046    */
1047   V8_DEPRECATE_SOON(
1048       "Set the heap on Isolate creation using CreateParams instead.")
1049   void AttachCppHeap(CppHeap*);
1050 
1051   /**
1052    * Detaches a managed C++ heap if one was attached using `AttachCppHeap()`.
1053    *
1054    * If a CppHeap is set via CreateParams, then this call is a noop.
1055    */
1056   V8_DEPRECATE_SOON(
1057       "Set the heap on Isolate creation using CreateParams instead.")
1058   void DetachCppHeap();
1059 
1060   /**
1061    * \returns the C++ heap managed by V8. Only available if such a heap has been
1062    *   attached using `AttachCppHeap()`.
1063    */
1064   CppHeap* GetCppHeap() const;
1065 
1066   /**
1067    * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
1068    */
1069   enum class AtomicsWaitEvent {
1070     /** Indicates that this call is happening before waiting. */
1071     kStartWait,
1072     /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
1073     kWokenUp,
1074     /** `Atomics.wait()` finished because it timed out. */
1075     kTimedOut,
1076     /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
1077     kTerminatedExecution,
1078     /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
1079     kAPIStopped,
1080     /** `Atomics.wait()` did not wait, as the initial condition was not met. */
1081     kNotEqual
1082   };
1083 
1084   /**
1085    * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
1086    * `Atomics.wait` call.
1087    */
1088   class V8_EXPORT AtomicsWaitWakeHandle {
1089    public:
1090     /**
1091      * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
1092      * with |kAPIStopped|.
1093      *
1094      * This function may be called from another thread. The caller has to ensure
1095      * through proper synchronization that it is not called after
1096      * the finishing |AtomicsWaitCallback|.
1097      *
1098      * Note that the ECMAScript specification does not plan for the possibility
1099      * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
1100      * call, so this may invalidate assumptions made by existing code.
1101      * The embedder may accordingly wish to schedule an exception in the
1102      * finishing |AtomicsWaitCallback|.
1103      */
1104     void Wake();
1105   };
1106 
1107   /**
1108    * Embedder callback for `Atomics.wait()` that can be added through
1109    * |SetAtomicsWaitCallback|.
1110    *
1111    * This will be called just before starting to wait with the |event| value
1112    * |kStartWait| and after finishing waiting with one of the other
1113    * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
1114    *
1115    * |array_buffer| will refer to the underlying SharedArrayBuffer,
1116    * |offset_in_bytes| to the location of the waited-on memory address inside
1117    * the SharedArrayBuffer.
1118    *
1119    * |value| and |timeout_in_ms| will be the values passed to
1120    * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
1121    * will be `INFINITY`.
1122    *
1123    * In the |kStartWait| callback, |stop_handle| will be an object that
1124    * is only valid until the corresponding finishing callback and that
1125    * can be used to stop the wait process while it is happening.
1126    *
1127    * This callback may schedule exceptions, *unless* |event| is equal to
1128    * |kTerminatedExecution|.
1129    */
1130   using AtomicsWaitCallback = void (*)(AtomicsWaitEvent event,
1131                                        Local<SharedArrayBuffer> array_buffer,
1132                                        size_t offset_in_bytes, int64_t value,
1133                                        double timeout_in_ms,
1134                                        AtomicsWaitWakeHandle* stop_handle,
1135                                        void* data);
1136 
1137   /**
1138    * Set a new |AtomicsWaitCallback|. This overrides an earlier
1139    * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
1140    * this unsets the callback. |data| will be passed to the callback
1141    * as its last parameter.
1142    */
1143   void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
1144 
1145   using GetExternallyAllocatedMemoryInBytesCallback = size_t (*)();
1146 
1147   /**
1148    * Set the callback that tells V8 how much memory is currently allocated
1149    * externally of the V8 heap. Ideally this memory is somehow connected to V8
1150    * objects and may get freed-up when the corresponding V8 objects get
1151    * collected by a V8 garbage collection.
1152    */
1153   void SetGetExternallyAllocatedMemoryInBytesCallback(
1154       GetExternallyAllocatedMemoryInBytesCallback callback);
1155 
1156   /**
1157    * Forcefully terminate the current thread of JavaScript execution
1158    * in the given isolate.
1159    *
1160    * This method can be used by any thread even if that thread has not
1161    * acquired the V8 lock with a Locker object.
1162    */
1163   void TerminateExecution();
1164 
1165   /**
1166    * Is V8 terminating JavaScript execution.
1167    *
1168    * Returns true if JavaScript execution is currently terminating
1169    * because of a call to TerminateExecution.  In that case there are
1170    * still JavaScript frames on the stack and the termination
1171    * exception is still active.
1172    */
1173   bool IsExecutionTerminating();
1174 
1175   /**
1176    * Resume execution capability in the given isolate, whose execution
1177    * was previously forcefully terminated using TerminateExecution().
1178    *
1179    * When execution is forcefully terminated using TerminateExecution(),
1180    * the isolate can not resume execution until all JavaScript frames
1181    * have propagated the uncatchable exception which is generated.  This
1182    * method allows the program embedding the engine to handle the
1183    * termination event and resume execution capability, even if
1184    * JavaScript frames remain on the stack.
1185    *
1186    * This method can be used by any thread even if that thread has not
1187    * acquired the V8 lock with a Locker object.
1188    */
1189   void CancelTerminateExecution();
1190 
1191   /**
1192    * Request V8 to interrupt long running JavaScript code and invoke
1193    * the given |callback| passing the given |data| to it. After |callback|
1194    * returns control will be returned to the JavaScript code.
1195    * There may be a number of interrupt requests in flight.
1196    * Can be called from another thread without acquiring a |Locker|.
1197    * Registered |callback| must not reenter interrupted Isolate.
1198    */
1199   void RequestInterrupt(InterruptCallback callback, void* data);
1200 
1201   /**
1202    * Returns true if there is ongoing background work within V8 that will
1203    * eventually post a foreground task, like asynchronous WebAssembly
1204    * compilation.
1205    */
1206   bool HasPendingBackgroundTasks();
1207 
1208   /**
1209    * Request garbage collection in this Isolate. It is only valid to call this
1210    * function if --expose_gc was specified.
1211    *
1212    * This should only be used for testing purposes and not to enforce a garbage
1213    * collection schedule. It has strong negative impact on the garbage
1214    * collection performance. Use MemoryPressureNotification() instead to
1215    * influence the garbage collection schedule.
1216    */
1217   void RequestGarbageCollectionForTesting(GarbageCollectionType type);
1218 
1219   /**
1220    * Request garbage collection with a specific embedderstack state in this
1221    * Isolate. It is only valid to call this function if --expose_gc was
1222    * specified.
1223    *
1224    * This should only be used for testing purposes and not to enforce a garbage
1225    * collection schedule. It has strong negative impact on the garbage
1226    * collection performance. Use MemoryPressureNotification() instead to
1227    * influence the garbage collection schedule.
1228    */
1229   void RequestGarbageCollectionForTesting(GarbageCollectionType type,
1230                                           StackState stack_state);
1231 
1232   /**
1233    * Set the callback to invoke for logging event.
1234    */
1235   void SetEventLogger(LogEventCallback that);
1236 
1237   /**
1238    * Adds a callback to notify the host application right before a script
1239    * is about to run. If a script re-enters the runtime during executing, the
1240    * BeforeCallEnteredCallback is invoked for each re-entrance.
1241    * Executing scripts inside the callback will re-trigger the callback.
1242    */
1243   void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1244 
1245   /**
1246    * Removes callback that was installed by AddBeforeCallEnteredCallback.
1247    */
1248   void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1249 
1250   /**
1251    * Adds a callback to notify the host application when a script finished
1252    * running.  If a script re-enters the runtime during executing, the
1253    * CallCompletedCallback is only invoked when the outer-most script
1254    * execution ends.  Executing scripts inside the callback do not trigger
1255    * further callbacks.
1256    */
1257   void AddCallCompletedCallback(CallCompletedCallback callback);
1258 
1259   /**
1260    * Removes callback that was installed by AddCallCompletedCallback.
1261    */
1262   void RemoveCallCompletedCallback(CallCompletedCallback callback);
1263 
1264   /**
1265    * Set the PromiseHook callback for various promise lifecycle
1266    * events.
1267    */
1268   void SetPromiseHook(PromiseHook hook);
1269 
1270   /**
1271    * Set callback to notify about promise reject with no handler, or
1272    * revocation of such a previous notification once the handler is added.
1273    */
1274   void SetPromiseRejectCallback(PromiseRejectCallback callback);
1275 
1276   /**
1277    * Runs the default MicrotaskQueue until it gets empty and perform other
1278    * microtask checkpoint steps, such as calling ClearKeptObjects. Asserts that
1279    * the MicrotasksPolicy is not kScoped. Any exceptions thrown by microtask
1280    * callbacks are swallowed.
1281    */
1282   void PerformMicrotaskCheckpoint();
1283 
1284   /**
1285    * Enqueues the callback to the default MicrotaskQueue
1286    */
1287   void EnqueueMicrotask(Local<Function> microtask);
1288 
1289   /**
1290    * Enqueues the callback to the default MicrotaskQueue
1291    */
1292   void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
1293 
1294   /**
1295    * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
1296    */
1297   void SetMicrotasksPolicy(MicrotasksPolicy policy);
1298 
1299   /**
1300    * Returns the policy controlling how Microtasks are invoked.
1301    */
1302   MicrotasksPolicy GetMicrotasksPolicy() const;
1303 
1304   /**
1305    * Adds a callback to notify the host application after
1306    * microtasks were run on the default MicrotaskQueue. The callback is
1307    * triggered by explicit RunMicrotasks call or automatic microtasks execution
1308    * (see SetMicrotaskPolicy).
1309    *
1310    * Callback will trigger even if microtasks were attempted to run,
1311    * but the microtasks queue was empty and no single microtask was actually
1312    * executed.
1313    *
1314    * Executing scripts inside the callback will not re-trigger microtasks and
1315    * the callback.
1316    */
1317   void AddMicrotasksCompletedCallback(
1318       MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
1319 
1320   /**
1321    * Removes callback that was installed by AddMicrotasksCompletedCallback.
1322    */
1323   void RemoveMicrotasksCompletedCallback(
1324       MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
1325 
1326   /**
1327    * Sets a callback for counting the number of times a feature of V8 is used.
1328    */
1329   void SetUseCounterCallback(UseCounterCallback callback);
1330 
1331   /**
1332    * Enables the host application to provide a mechanism for recording
1333    * statistics counters.
1334    */
1335   void SetCounterFunction(CounterLookupCallback);
1336 
1337   /**
1338    * Enables the host application to provide a mechanism for recording
1339    * histograms. The CreateHistogram function returns a
1340    * histogram which will later be passed to the AddHistogramSample
1341    * function.
1342    */
1343   void SetCreateHistogramFunction(CreateHistogramCallback);
1344   void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
1345 
1346   /**
1347    * Enables the host application to provide a mechanism for recording
1348    * event based metrics. In order to use this interface
1349    *   include/v8-metrics.h
1350    * needs to be included and the recorder needs to be derived from the
1351    * Recorder base class defined there.
1352    * This method can only be called once per isolate and must happen during
1353    * isolate initialization before background threads are spawned.
1354    */
1355   void SetMetricsRecorder(
1356       const std::shared_ptr<metrics::Recorder>& metrics_recorder);
1357 
1358   /**
1359    * Enables the host application to provide a mechanism for recording a
1360    * predefined set of data as crash keys to be used in postmortem debugging in
1361    * case of a crash.
1362    */
1363   void SetAddCrashKeyCallback(AddCrashKeyCallback);
1364 
1365   /**
1366    * Optional notification that the embedder is idle.
1367    * V8 uses the notification to perform garbage collection.
1368    * This call can be used repeatedly if the embedder remains idle.
1369    * Returns true if the embedder should stop calling IdleNotificationDeadline
1370    * until real work has been done.  This indicates that V8 has done
1371    * as much cleanup as it will be able to do.
1372    *
1373    * The deadline_in_seconds argument specifies the deadline V8 has to finish
1374    * garbage collection work. deadline_in_seconds is compared with
1375    * MonotonicallyIncreasingTime() and should be based on the same timebase as
1376    * that function. There is no guarantee that the actual work will be done
1377    * within the time limit.
1378    */
1379   V8_DEPRECATE_SOON(
1380       "Use MemoryPressureNotification() to influence the GC schedule.")
1381   bool IdleNotificationDeadline(double deadline_in_seconds);
1382 
1383   /**
1384    * Optional notification that the system is running low on memory.
1385    * V8 uses these notifications to attempt to free memory.
1386    */
1387   void LowMemoryNotification();
1388 
1389   /**
1390    * Optional notification that a context has been disposed. V8 uses these
1391    * notifications to guide the GC heuristic and cancel FinalizationRegistry
1392    * cleanup tasks. Returns the number of context disposals - including this one
1393    * - since the last time V8 had a chance to clean up.
1394    *
1395    * The optional parameter |dependant_context| specifies whether the disposed
1396    * context was depending on state from other contexts or not.
1397    */
1398   int ContextDisposedNotification(bool dependant_context = true);
1399 
1400   /**
1401    * Optional notification that the isolate switched to the foreground.
1402    * V8 uses these notifications to guide heuristics.
1403    */
1404   void IsolateInForegroundNotification();
1405 
1406   /**
1407    * Optional notification that the isolate switched to the background.
1408    * V8 uses these notifications to guide heuristics.
1409    */
1410   void IsolateInBackgroundNotification();
1411 
1412   /**
1413    * Optional notification to tell V8 the current performance requirements
1414    * of the embedder based on RAIL.
1415    * V8 uses these notifications to guide heuristics.
1416    * This is an unfinished experimental feature. Semantics and implementation
1417    * may change frequently.
1418    */
1419   void SetRAILMode(RAILMode rail_mode);
1420 
1421   /**
1422    * Update load start time of the RAIL mode
1423    */
1424   void UpdateLoadStartTime();
1425 
1426   /**
1427    * Optional notification to tell V8 the current isolate is used for debugging
1428    * and requires higher heap limit.
1429    */
1430   void IncreaseHeapLimitForDebugging();
1431 
1432   /**
1433    * Restores the original heap limit after IncreaseHeapLimitForDebugging().
1434    */
1435   void RestoreOriginalHeapLimit();
1436 
1437   /**
1438    * Returns true if the heap limit was increased for debugging and the
1439    * original heap limit was not restored yet.
1440    */
1441   bool IsHeapLimitIncreasedForDebugging();
1442 
1443   /**
1444    * Allows the host application to provide the address of a function that is
1445    * notified each time code is added, moved or removed.
1446    *
1447    * \param options options for the JIT code event handler.
1448    * \param event_handler the JIT code event handler, which will be invoked
1449    *     each time code is added, moved or removed.
1450    * \note \p event_handler won't get notified of existent code.
1451    * \note since code removal notifications are not currently issued, the
1452    *     \p event_handler may get notifications of code that overlaps earlier
1453    *     code notifications. This happens when code areas are reused, and the
1454    *     earlier overlapping code areas should therefore be discarded.
1455    * \note the events passed to \p event_handler and the strings they point to
1456    *     are not guaranteed to live past each call. The \p event_handler must
1457    *     copy strings and other parameters it needs to keep around.
1458    * \note the set of events declared in JitCodeEvent::EventType is expected to
1459    *     grow over time, and the JitCodeEvent structure is expected to accrue
1460    *     new members. The \p event_handler function must ignore event codes
1461    *     it does not recognize to maintain future compatibility.
1462    * \note Use Isolate::CreateParams to get events for code executed during
1463    *     Isolate setup.
1464    */
1465   void SetJitCodeEventHandler(JitCodeEventOptions options,
1466                               JitCodeEventHandler event_handler);
1467 
1468   /**
1469    * Modifies the stack limit for this Isolate.
1470    *
1471    * \param stack_limit An address beyond which the Vm's stack may not grow.
1472    *
1473    * \note  If you are using threads then you should hold the V8::Locker lock
1474    *     while setting the stack limit and you must set a non-default stack
1475    *     limit separately for each thread.
1476    */
1477   void SetStackLimit(uintptr_t stack_limit);
1478 
1479   /**
1480    * Returns a memory range that can potentially contain jitted code. Code for
1481    * V8's 'builtins' will not be in this range if embedded builtins is enabled.
1482    *
1483    * On Win64, embedders are advised to install function table callbacks for
1484    * these ranges, as default SEH won't be able to unwind through jitted code.
1485    * The first page of the code range is reserved for the embedder and is
1486    * committed, writable, and executable, to be used to store unwind data, as
1487    * documented in
1488    * https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64.
1489    *
1490    * Might be empty on other platforms.
1491    *
1492    * https://code.google.com/p/v8/issues/detail?id=3598
1493    */
1494   void GetCodeRange(void** start, size_t* length_in_bytes);
1495 
1496   /**
1497    * As GetCodeRange, but for embedded builtins (these live in a distinct
1498    * memory region from other V8 Code objects).
1499    */
1500   void GetEmbeddedCodeRange(const void** start, size_t* length_in_bytes);
1501 
1502   /**
1503    * Returns the JSEntryStubs necessary for use with the Unwinder API.
1504    */
1505   JSEntryStubs GetJSEntryStubs();
1506 
1507   static constexpr size_t kMinCodePagesBufferSize = 32;
1508 
1509   /**
1510    * Copies the code heap pages currently in use by V8 into |code_pages_out|.
1511    * |code_pages_out| must have at least kMinCodePagesBufferSize capacity and
1512    * must be empty.
1513    *
1514    * Signal-safe, does not allocate, does not access the V8 heap.
1515    * No code on the stack can rely on pages that might be missing.
1516    *
1517    * Returns the number of pages available to be copied, which might be greater
1518    * than |capacity|. In this case, only |capacity| pages will be copied into
1519    * |code_pages_out|. The caller should provide a bigger buffer on the next
1520    * call in order to get all available code pages, but this is not required.
1521    */
1522   size_t CopyCodePages(size_t capacity, MemoryRange* code_pages_out);
1523 
1524   /** Set the callback to invoke in case of fatal errors. */
1525   void SetFatalErrorHandler(FatalErrorCallback that);
1526 
1527   /** Set the callback to invoke in case of OOM errors. */
1528   void SetOOMErrorHandler(OOMErrorCallback that);
1529 
1530   /**
1531    * Add a callback to invoke in case the heap size is close to the heap limit.
1532    * If multiple callbacks are added, only the most recently added callback is
1533    * invoked.
1534    */
1535   void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
1536 
1537   /**
1538    * Remove the given callback and restore the heap limit to the
1539    * given limit. If the given limit is zero, then it is ignored.
1540    * If the current heap size is greater than the given limit,
1541    * then the heap limit is restored to the minimal limit that
1542    * is possible for the current heap size.
1543    */
1544   void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
1545                                    size_t heap_limit);
1546 
1547   /**
1548    * If the heap limit was changed by the NearHeapLimitCallback, then the
1549    * initial heap limit will be restored once the heap size falls below the
1550    * given threshold percentage of the initial heap limit.
1551    * The threshold percentage is a number in (0.0, 1.0) range.
1552    */
1553   void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5);
1554 
1555   /**
1556    * Set the callback to invoke to check if code generation from
1557    * strings should be allowed.
1558    */
1559   void SetModifyCodeGenerationFromStringsCallback(
1560       ModifyCodeGenerationFromStringsCallback2 callback);
1561 
1562   /**
1563    * Set the callback to invoke to check if wasm code generation should
1564    * be allowed.
1565    */
1566   void SetAllowWasmCodeGenerationCallback(
1567       AllowWasmCodeGenerationCallback callback);
1568 
1569   /**
1570    * Embedder over{ride|load} injection points for wasm APIs. The expectation
1571    * is that the embedder sets them at most once.
1572    */
1573   void SetWasmModuleCallback(ExtensionCallback callback);
1574   void SetWasmInstanceCallback(ExtensionCallback callback);
1575 
1576   void SetWasmStreamingCallback(WasmStreamingCallback callback);
1577 
1578   void SetWasmAsyncResolvePromiseCallback(
1579       WasmAsyncResolvePromiseCallback callback);
1580 
1581   void SetWasmLoadSourceMapCallback(WasmLoadSourceMapCallback callback);
1582 
1583   void SetWasmImportedStringsEnabledCallback(
1584       WasmImportedStringsEnabledCallback callback);
1585 
1586   void SetSharedArrayBufferConstructorEnabledCallback(
1587       SharedArrayBufferConstructorEnabledCallback callback);
1588 
1589   void SetWasmJSPIEnabledCallback(WasmJSPIEnabledCallback callback);
1590 
1591   /**
1592    * Register callback to control whether compile hints magic comments are
1593    * enabled.
1594    */
1595   void SetJavaScriptCompileHintsMagicEnabledCallback(
1596       JavaScriptCompileHintsMagicEnabledCallback callback);
1597 
1598   /**
1599    * This function can be called by the embedder to signal V8 that the dynamic
1600    * enabling of features has finished. V8 can now set up dynamically added
1601    * features.
1602    */
1603   void InstallConditionalFeatures(Local<Context> context);
1604 
1605   /**
1606    * Check if V8 is dead and therefore unusable.  This is the case after
1607    * fatal errors such as out-of-memory situations.
1608    */
1609   bool IsDead();
1610 
1611   /**
1612    * Adds a message listener (errors only).
1613    *
1614    * The same message listener can be added more than once and in that
1615    * case it will be called more than once for each message.
1616    *
1617    * If data is specified, it will be passed to the callback when it is called.
1618    * Otherwise, the exception object will be passed to the callback instead.
1619    */
1620   bool AddMessageListener(MessageCallback that,
1621                           Local<Value> data = Local<Value>());
1622 
1623   /**
1624    * Adds a message listener.
1625    *
1626    * The same message listener can be added more than once and in that
1627    * case it will be called more than once for each message.
1628    *
1629    * If data is specified, it will be passed to the callback when it is called.
1630    * Otherwise, the exception object will be passed to the callback instead.
1631    *
1632    * A listener can listen for particular error levels by providing a mask.
1633    */
1634   bool AddMessageListenerWithErrorLevel(MessageCallback that,
1635                                         int message_levels,
1636                                         Local<Value> data = Local<Value>());
1637 
1638   /**
1639    * Remove all message listeners from the specified callback function.
1640    */
1641   void RemoveMessageListeners(MessageCallback that);
1642 
1643   /** Callback function for reporting failed access checks.*/
1644   void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
1645 
1646   /**
1647    * Tells V8 to capture current stack trace when uncaught exception occurs
1648    * and report it to the message listeners. The option is off by default.
1649    */
1650   void SetCaptureStackTraceForUncaughtExceptions(
1651       bool capture, int frame_limit = 10,
1652       StackTrace::StackTraceOptions options = StackTrace::kOverview);
1653 
1654   /**
1655    * Iterates through all external resources referenced from current isolate
1656    * heap.  GC is not invoked prior to iterating, therefore there is no
1657    * guarantee that visited objects are still alive.
1658    */
1659   V8_DEPRECATE_SOON("Will be removed without replacement. crbug.com/v8/14172")
1660   void VisitExternalResources(ExternalResourceVisitor* visitor);
1661 
1662   /**
1663    * Check if this isolate is in use.
1664    * True if at least one thread Enter'ed this isolate.
1665    */
1666   bool IsInUse();
1667 
1668   /**
1669    * Set whether calling Atomics.wait (a function that may block) is allowed in
1670    * this isolate. This can also be configured via
1671    * CreateParams::allow_atomics_wait.
1672    */
1673   void SetAllowAtomicsWait(bool allow);
1674 
1675   /**
1676    * Time zone redetection indicator for
1677    * DateTimeConfigurationChangeNotification.
1678    *
1679    * kSkip indicates V8 that the notification should not trigger redetecting
1680    * host time zone. kRedetect indicates V8 that host time zone should be
1681    * redetected, and used to set the default time zone.
1682    *
1683    * The host time zone detection may require file system access or similar
1684    * operations unlikely to be available inside a sandbox. If v8 is run inside a
1685    * sandbox, the host time zone has to be detected outside the sandbox before
1686    * calling DateTimeConfigurationChangeNotification function.
1687    */
1688   enum class TimeZoneDetection { kSkip, kRedetect };
1689 
1690   /**
1691    * Notification that the embedder has changed the time zone, daylight savings
1692    * time or other date / time configuration parameters. V8 keeps a cache of
1693    * various values used for date / time computation. This notification will
1694    * reset those cached values for the current context so that date / time
1695    * configuration changes would be reflected.
1696    *
1697    * This API should not be called more than needed as it will negatively impact
1698    * the performance of date operations.
1699    */
1700   void DateTimeConfigurationChangeNotification(
1701       TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip);
1702 
1703   /**
1704    * Notification that the embedder has changed the locale. V8 keeps a cache of
1705    * various values used for locale computation. This notification will reset
1706    * those cached values for the current context so that locale configuration
1707    * changes would be reflected.
1708    *
1709    * This API should not be called more than needed as it will negatively impact
1710    * the performance of locale operations.
1711    */
1712   void LocaleConfigurationChangeNotification();
1713 
1714   Isolate() = delete;
1715   ~Isolate() = delete;
1716   Isolate(const Isolate&) = delete;
1717   Isolate& operator=(const Isolate&) = delete;
1718   // Deleting operator new and delete here is allowed as ctor and dtor is also
1719   // deleted.
1720   void* operator new(size_t size) = delete;
1721   void* operator new[](size_t size) = delete;
1722   void operator delete(void*, size_t) = delete;
1723   void operator delete[](void*, size_t) = delete;
1724 
1725  private:
1726   template <class K, class V, class Traits>
1727   friend class PersistentValueMapBase;
1728 
1729   internal::Address* GetDataFromSnapshotOnce(size_t index);
1730   void ReportExternalAllocationLimitReached();
1731 };
1732 
1733 void Isolate::SetData(uint32_t slot, void* data) {
1734   using I = internal::Internals;
1735   I::SetEmbedderData(this, slot, data);
1736 }
1737 
1738 void* Isolate::GetData(uint32_t slot) {
1739   using I = internal::Internals;
1740   return I::GetEmbedderData(this, slot);
1741 }
1742 
1743 uint32_t Isolate::GetNumberOfDataSlots() {
1744   using I = internal::Internals;
1745   return I::kNumIsolateDataSlots;
1746 }
1747 
1748 template <class T>
1749 MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
1750   if (auto slot = GetDataFromSnapshotOnce(index); slot) {
1751     internal::PerformCastCheck(
1752         internal::ValueHelper::SlotAsValue<T, false>(slot));
1753     return Local<T>::FromSlot(slot);
1754   }
1755   return {};
1756 }
1757 
1758 }  // namespace v8
1759 
1760 #endif  // INCLUDE_V8_ISOLATE_H_