Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-15 09:02:43

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 <string>
0013 #include <utility>
0014 
0015 #include "cppgc/common.h"
0016 #include "v8-array-buffer.h"       // NOLINT(build/include_directory)
0017 #include "v8-callbacks.h"          // NOLINT(build/include_directory)
0018 #include "v8-data.h"               // NOLINT(build/include_directory)
0019 #include "v8-debug.h"              // NOLINT(build/include_directory)
0020 #include "v8-embedder-heap.h"      // NOLINT(build/include_directory)
0021 #include "v8-function-callback.h"  // NOLINT(build/include_directory)
0022 #include "v8-internal.h"           // NOLINT(build/include_directory)
0023 #include "v8-local-handle.h"       // NOLINT(build/include_directory)
0024 #include "v8-microtask.h"          // NOLINT(build/include_directory)
0025 #include "v8-persistent-handle.h"  // NOLINT(build/include_directory)
0026 #include "v8-primitive.h"          // NOLINT(build/include_directory)
0027 #include "v8-statistics.h"         // NOLINT(build/include_directory)
0028 #include "v8-unwinder.h"           // NOLINT(build/include_directory)
0029 #include "v8config.h"              // NOLINT(build/include_directory)
0030 
0031 namespace v8 {
0032 
0033 class CppHeap;
0034 class HeapProfiler;
0035 class MicrotaskQueue;
0036 class StartupData;
0037 class ScriptOrModule;
0038 class SharedArrayBuffer;
0039 
0040 namespace internal {
0041 class MicrotaskQueue;
0042 class ThreadLocalTop;
0043 }  // namespace internal
0044 
0045 namespace metrics {
0046 class Recorder;
0047 }  // namespace metrics
0048 
0049 /**
0050  * A set of constraints that specifies the limits of the runtime's memory use.
0051  * You must set the heap size before initializing the VM - the size cannot be
0052  * adjusted after the VM is initialized.
0053  *
0054  * If you are using threads then you should hold the V8::Locker lock while
0055  * setting the stack limit and you must set a non-default stack limit separately
0056  * for each thread.
0057  *
0058  * The arguments for set_max_semi_space_size, set_max_old_space_size,
0059  * set_max_executable_size, set_code_range_size specify limits in MB.
0060  *
0061  * The argument for set_max_semi_space_size_in_kb is in KB.
0062  */
0063 class V8_EXPORT ResourceConstraints {
0064  public:
0065   /**
0066    * Configures the constraints with reasonable default values based on the
0067    * provided heap size limit. The heap size includes both the young and
0068    * the old generation.
0069    *
0070    * \param initial_heap_size_in_bytes The initial heap size or zero.
0071    *    By default V8 starts with a small heap and dynamically grows it to
0072    *    match the set of live objects. This may lead to ineffective
0073    *    garbage collections at startup if the live set is large.
0074    *    Setting the initial heap size avoids such garbage collections.
0075    *    Note that this does not affect young generation garbage collections.
0076    *
0077    * \param maximum_heap_size_in_bytes The hard limit for the heap size.
0078    *    When the heap size approaches this limit, V8 will perform series of
0079    *    garbage collections and invoke the NearHeapLimitCallback. If the garbage
0080    *    collections do not help and the callback does not increase the limit,
0081    *    then V8 will crash with V8::FatalProcessOutOfMemory.
0082    */
0083   void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes,
0084                                      size_t maximum_heap_size_in_bytes);
0085 
0086   /**
0087    * Configures the constraints with reasonable default values based on the
0088    * capabilities of the current device the VM is running on.
0089    *
0090    * \param physical_memory The total amount of physical memory on the current
0091    *   device, in bytes.
0092    * \param virtual_memory_limit The amount of virtual memory on the current
0093    *   device, in bytes, or zero, if there is no limit.
0094    */
0095   void ConfigureDefaults(uint64_t physical_memory,
0096                          uint64_t virtual_memory_limit);
0097 
0098   /**
0099    * The address beyond which the VM's stack may not grow.
0100    */
0101   uint32_t* stack_limit() const { return stack_limit_; }
0102   void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
0103 
0104   /**
0105    * The amount of virtual memory reserved for generated code. This is relevant
0106    * for 64-bit architectures that rely on code range for calls in code.
0107    *
0108    * When V8_COMPRESS_POINTERS_IN_SHARED_CAGE is defined, there is a shared
0109    * process-wide code range that is lazily initialized. This value is used to
0110    * configure that shared code range when the first Isolate is
0111    * created. Subsequent Isolates ignore this value.
0112    */
0113   size_t code_range_size_in_bytes() const { return code_range_size_; }
0114   void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; }
0115 
0116   /**
0117    * The maximum size of the old generation.
0118    * When the old generation approaches this limit, V8 will perform series of
0119    * garbage collections and invoke the NearHeapLimitCallback.
0120    * If the garbage collections do not help and the callback does not
0121    * increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory.
0122    */
0123   size_t max_old_generation_size_in_bytes() const {
0124     return max_old_generation_size_;
0125   }
0126   void set_max_old_generation_size_in_bytes(size_t limit) {
0127     max_old_generation_size_ = limit;
0128   }
0129 
0130   /**
0131    * The maximum size of the young generation, which consists of two semi-spaces
0132    * and a large object space. This affects frequency of Scavenge garbage
0133    * collections and should be typically much smaller that the old generation.
0134    */
0135   size_t max_young_generation_size_in_bytes() const {
0136     return max_young_generation_size_;
0137   }
0138   void set_max_young_generation_size_in_bytes(size_t limit) {
0139     max_young_generation_size_ = limit;
0140   }
0141 
0142   size_t initial_old_generation_size_in_bytes() const {
0143     return initial_old_generation_size_;
0144   }
0145   void set_initial_old_generation_size_in_bytes(size_t initial_size) {
0146     initial_old_generation_size_ = initial_size;
0147   }
0148 
0149   size_t initial_young_generation_size_in_bytes() const {
0150     return initial_young_generation_size_;
0151   }
0152   void set_initial_young_generation_size_in_bytes(size_t initial_size) {
0153     initial_young_generation_size_ = initial_size;
0154   }
0155 
0156  private:
0157   static constexpr size_t kMB = 1048576u;
0158   size_t code_range_size_ = 0;
0159   size_t max_old_generation_size_ = 0;
0160   size_t max_young_generation_size_ = 0;
0161   size_t initial_old_generation_size_ = 0;
0162   size_t initial_young_generation_size_ = 0;
0163   uint32_t* stack_limit_ = nullptr;
0164 };
0165 
0166 /**
0167  * Option flags passed to the SetRAILMode function.
0168  * See documentation https://developers.google.com/web/tools/chrome-devtools/
0169  * profile/evaluate-performance/rail
0170  */
0171 enum RAILMode : unsigned {
0172   // Response performance mode: In this mode very low virtual machine latency
0173   // is provided. V8 will try to avoid JavaScript execution interruptions.
0174   // Throughput may be throttled.
0175   PERFORMANCE_RESPONSE,
0176   // Animation performance mode: In this mode low virtual machine latency is
0177   // provided. V8 will try to avoid as many JavaScript execution interruptions
0178   // as possible. Throughput may be throttled. This is the default mode.
0179   PERFORMANCE_ANIMATION,
0180   // Idle performance mode: The embedder is idle. V8 can complete deferred work
0181   // in this mode.
0182   PERFORMANCE_IDLE,
0183   // Load performance mode: In this mode high throughput is provided. V8 may
0184   // turn off latency optimizations.
0185   PERFORMANCE_LOAD
0186 };
0187 
0188 /**
0189  * Memory pressure level for the MemoryPressureNotification.
0190  * kNone hints V8 that there is no memory pressure.
0191  * kModerate hints V8 to speed up incremental garbage collection at the cost of
0192  * of higher latency due to garbage collection pauses.
0193  * kCritical hints V8 to free memory as soon as possible. Garbage collection
0194  * pauses at this level will be large.
0195  */
0196 enum class MemoryPressureLevel { kNone, kModerate, kCritical };
0197 
0198 /**
0199  * Indicator for the stack state.
0200  */
0201 using StackState = cppgc::EmbedderStackState;
0202 
0203 /**
0204  * Isolate represents an isolated instance of the V8 engine.  V8 isolates have
0205  * completely separate states.  Objects from one isolate must not be used in
0206  * other isolates.  The embedder can create multiple isolates and use them in
0207  * parallel in multiple threads.  An isolate can be entered by at most one
0208  * thread at any given time.  The Locker/Unlocker API must be used to
0209  * synchronize.
0210  */
0211 class V8_EXPORT Isolate {
0212  public:
0213   /**
0214    * Initial configuration parameters for a new Isolate.
0215    */
0216   struct V8_EXPORT CreateParams {
0217     CreateParams();
0218     ~CreateParams();
0219 
0220     ALLOW_COPY_AND_MOVE_WITH_DEPRECATED_FIELDS(CreateParams)
0221 
0222     /**
0223      * Allows the host application to provide the address of a function that is
0224      * notified each time code is added, moved or removed.
0225      */
0226     JitCodeEventHandler code_event_handler = nullptr;
0227 
0228     /**
0229      * ResourceConstraints to use for the new Isolate.
0230      */
0231     ResourceConstraints constraints;
0232 
0233     /**
0234      * Explicitly specify a startup snapshot blob. The embedder owns the blob.
0235      * The embedder *must* ensure that the snapshot is from a trusted source.
0236      */
0237     const StartupData* snapshot_blob = nullptr;
0238 
0239     /**
0240      * Enables the host application to provide a mechanism for recording
0241      * statistics counters.
0242      */
0243     CounterLookupCallback counter_lookup_callback = nullptr;
0244 
0245     /**
0246      * Enables the host application to provide a mechanism for recording
0247      * histograms. The CreateHistogram function returns a
0248      * histogram which will later be passed to the AddHistogramSample
0249      * function.
0250      */
0251     CreateHistogramCallback create_histogram_callback = nullptr;
0252     AddHistogramSampleCallback add_histogram_sample_callback = nullptr;
0253 
0254     /**
0255      * The ArrayBuffer::Allocator to use for allocating and freeing the backing
0256      * store of ArrayBuffers.
0257      *
0258      * If the shared_ptr version is used, the Isolate instance and every
0259      * |BackingStore| allocated using this allocator hold a std::shared_ptr
0260      * to the allocator, in order to facilitate lifetime
0261      * management for the allocator instance.
0262      */
0263     ArrayBuffer::Allocator* array_buffer_allocator = nullptr;
0264     std::shared_ptr<ArrayBuffer::Allocator> array_buffer_allocator_shared;
0265 
0266     /**
0267      * Specifies an optional nullptr-terminated array of raw addresses in the
0268      * embedder that V8 can match against during serialization and use for
0269      * deserialization. This array and its content must stay valid for the
0270      * entire lifetime of the isolate.
0271      */
0272     const intptr_t* external_references = nullptr;
0273 
0274     /**
0275      * Whether calling Atomics.wait (a function that may block) is allowed in
0276      * this isolate. This can also be configured via SetAllowAtomicsWait.
0277      */
0278     bool allow_atomics_wait = true;
0279 
0280     /**
0281      * Termination is postponed when there is no active SafeForTerminationScope.
0282      */
0283     bool only_terminate_in_safe_scope = false;
0284 
0285     /**
0286      * The following parameters describe the offsets for addressing type info
0287      * for wrapped API objects and are used by the fast C API
0288      * (for details see v8-fast-api-calls.h).
0289      */
0290     int embedder_wrapper_type_index = -1;
0291     int embedder_wrapper_object_index = -1;
0292 
0293     /**
0294      * Callbacks to invoke in case of fatal or OOM errors.
0295      */
0296     FatalErrorCallback fatal_error_callback = nullptr;
0297     OOMErrorCallback oom_error_callback = nullptr;
0298 
0299     /**
0300      * A CppHeap used to construct the Isolate. V8 takes ownership of the
0301      * CppHeap passed this way.
0302      */
0303     CppHeap* cpp_heap = nullptr;
0304   };
0305 
0306   /**
0307    * Stack-allocated class which sets the isolate for all operations
0308    * executed within a local scope.
0309    */
0310   class V8_EXPORT V8_NODISCARD Scope {
0311    public:
0312     explicit Scope(Isolate* isolate) : v8_isolate_(isolate) {
0313       v8_isolate_->Enter();
0314     }
0315 
0316     ~Scope() { v8_isolate_->Exit(); }
0317 
0318     // Prevent copying of Scope objects.
0319     Scope(const Scope&) = delete;
0320     Scope& operator=(const Scope&) = delete;
0321 
0322    private:
0323     Isolate* const v8_isolate_;
0324   };
0325 
0326   /**
0327    * Assert that no Javascript code is invoked.
0328    */
0329   class V8_EXPORT V8_NODISCARD DisallowJavascriptExecutionScope {
0330    public:
0331     enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE, DUMP_ON_FAILURE };
0332 
0333     DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
0334     ~DisallowJavascriptExecutionScope();
0335 
0336     // Prevent copying of Scope objects.
0337     DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
0338         delete;
0339     DisallowJavascriptExecutionScope& operator=(
0340         const DisallowJavascriptExecutionScope&) = delete;
0341 
0342    private:
0343     v8::Isolate* const v8_isolate_;
0344     const OnFailure on_failure_;
0345     bool was_execution_allowed_;
0346   };
0347 
0348   /**
0349    * Introduce exception to DisallowJavascriptExecutionScope.
0350    */
0351   class V8_EXPORT V8_NODISCARD AllowJavascriptExecutionScope {
0352    public:
0353     explicit AllowJavascriptExecutionScope(Isolate* isolate);
0354     ~AllowJavascriptExecutionScope();
0355 
0356     // Prevent copying of Scope objects.
0357     AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
0358         delete;
0359     AllowJavascriptExecutionScope& operator=(
0360         const AllowJavascriptExecutionScope&) = delete;
0361 
0362    private:
0363     Isolate* const v8_isolate_;
0364     bool was_execution_allowed_assert_;
0365     bool was_execution_allowed_throws_;
0366     bool was_execution_allowed_dump_;
0367   };
0368 
0369   /**
0370    * Do not run microtasks while this scope is active, even if microtasks are
0371    * automatically executed otherwise.
0372    */
0373   class V8_EXPORT V8_NODISCARD SuppressMicrotaskExecutionScope {
0374    public:
0375     explicit SuppressMicrotaskExecutionScope(
0376         Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr);
0377     ~SuppressMicrotaskExecutionScope();
0378 
0379     // Prevent copying of Scope objects.
0380     SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
0381         delete;
0382     SuppressMicrotaskExecutionScope& operator=(
0383         const SuppressMicrotaskExecutionScope&) = delete;
0384 
0385    private:
0386     internal::Isolate* const i_isolate_;
0387     internal::MicrotaskQueue* const microtask_queue_;
0388     internal::Address previous_stack_height_;
0389 
0390     friend class internal::ThreadLocalTop;
0391   };
0392 
0393   /**
0394    * This scope allows terminations inside direct V8 API calls and forbid them
0395    * inside any recursive API calls without explicit SafeForTerminationScope.
0396    */
0397   class V8_EXPORT V8_NODISCARD SafeForTerminationScope {
0398    public:
0399     V8_DEPRECATE_SOON("All code should be safe for termination")
0400     explicit SafeForTerminationScope(v8::Isolate* v8_isolate) {}
0401     ~SafeForTerminationScope() {}
0402 
0403     // Prevent copying of Scope objects.
0404     SafeForTerminationScope(const SafeForTerminationScope&) = delete;
0405     SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete;
0406   };
0407 
0408   /**
0409    * Types of garbage collections that can be requested via
0410    * RequestGarbageCollectionForTesting.
0411    */
0412   enum GarbageCollectionType {
0413     kFullGarbageCollection,
0414     kMinorGarbageCollection
0415   };
0416 
0417   /**
0418    * Features reported via the SetUseCounterCallback callback. Do not change
0419    * assigned numbers of existing items; add new features to the end of this
0420    * list.
0421    * Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and
0422    * then finally be renamed to `kOBSOLETE_...` to stop embedders from using
0423    * them.
0424    */
0425   enum UseCounterFeature {
0426     kUseAsm = 0,
0427     kBreakIterator = 1,
0428     kOBSOLETE_LegacyConst = 2,
0429     kOBSOLETE_MarkDequeOverflow = 3,
0430     kOBSOLETE_StoreBufferOverflow = 4,
0431     kOBSOLETE_SlotsBufferOverflow = 5,
0432     kOBSOLETE_ObjectObserve = 6,
0433     kForcedGC = 7,
0434     kSloppyMode = 8,
0435     kStrictMode = 9,
0436     kOBSOLETE_StrongMode = 10,
0437     kRegExpPrototypeStickyGetter = 11,
0438     kRegExpPrototypeToString = 12,
0439     kRegExpPrototypeUnicodeGetter = 13,
0440     kOBSOLETE_IntlV8Parse = 14,
0441     kOBSOLETE_IntlPattern = 15,
0442     kOBSOLETE_IntlResolved = 16,
0443     kOBSOLETE_PromiseChain = 17,
0444     kOBSOLETE_PromiseAccept = 18,
0445     kOBSOLETE_PromiseDefer = 19,
0446     kHtmlCommentInExternalScript = 20,
0447     kHtmlComment = 21,
0448     kSloppyModeBlockScopedFunctionRedefinition = 22,
0449     kForInInitializer = 23,
0450     kOBSOLETE_ArrayProtectorDirtied = 24,
0451     kArraySpeciesModified = 25,
0452     kArrayPrototypeConstructorModified = 26,
0453     kOBSOLETE_ArrayInstanceProtoModified = 27,
0454     kArrayInstanceConstructorModified = 28,
0455     kOBSOLETE_LegacyFunctionDeclaration = 29,
0456     kOBSOLETE_RegExpPrototypeSourceGetter = 30,
0457     kOBSOLETE_RegExpPrototypeOldFlagGetter = 31,
0458     kDecimalWithLeadingZeroInStrictMode = 32,
0459     kLegacyDateParser = 33,
0460     kDefineGetterOrSetterWouldThrow = 34,
0461     kFunctionConstructorReturnedUndefined = 35,
0462     kAssigmentExpressionLHSIsCallInSloppy = 36,
0463     kAssigmentExpressionLHSIsCallInStrict = 37,
0464     kPromiseConstructorReturnedUndefined = 38,
0465     kOBSOLETE_ConstructorNonUndefinedPrimitiveReturn = 39,
0466     kOBSOLETE_LabeledExpressionStatement = 40,
0467     kOBSOLETE_LineOrParagraphSeparatorAsLineTerminator = 41,
0468     kIndexAccessor = 42,
0469     kErrorCaptureStackTrace = 43,
0470     kErrorPrepareStackTrace = 44,
0471     kErrorStackTraceLimit = 45,
0472     kWebAssemblyInstantiation = 46,
0473     kDeoptimizerDisableSpeculation = 47,
0474     kOBSOLETE_ArrayPrototypeSortJSArrayModifiedPrototype = 48,
0475     kFunctionTokenOffsetTooLongForToString = 49,
0476     kWasmSharedMemory = 50,
0477     kWasmThreadOpcodes = 51,
0478     kOBSOLETE_AtomicsNotify = 52,
0479     kOBSOLETE_AtomicsWake = 53,
0480     kCollator = 54,
0481     kNumberFormat = 55,
0482     kDateTimeFormat = 56,
0483     kPluralRules = 57,
0484     kRelativeTimeFormat = 58,
0485     kLocale = 59,
0486     kListFormat = 60,
0487     kSegmenter = 61,
0488     kStringLocaleCompare = 62,
0489     kOBSOLETE_StringToLocaleUpperCase = 63,
0490     kStringToLocaleLowerCase = 64,
0491     kNumberToLocaleString = 65,
0492     kDateToLocaleString = 66,
0493     kDateToLocaleDateString = 67,
0494     kDateToLocaleTimeString = 68,
0495     kAttemptOverrideReadOnlyOnPrototypeSloppy = 69,
0496     kAttemptOverrideReadOnlyOnPrototypeStrict = 70,
0497     kOBSOLETE_OptimizedFunctionWithOneShotBytecode = 71,
0498     kRegExpMatchIsTrueishOnNonJSRegExp = 72,
0499     kRegExpMatchIsFalseishOnJSRegExp = 73,
0500     kOBSOLETE_DateGetTimezoneOffset = 74,
0501     kStringNormalize = 75,
0502     kCallSiteAPIGetFunctionSloppyCall = 76,
0503     kCallSiteAPIGetThisSloppyCall = 77,
0504     kOBSOLETE_RegExpMatchAllWithNonGlobalRegExp = 78,
0505     kRegExpExecCalledOnSlowRegExp = 79,
0506     kRegExpReplaceCalledOnSlowRegExp = 80,
0507     kDisplayNames = 81,
0508     kSharedArrayBufferConstructed = 82,
0509     kArrayPrototypeHasElements = 83,
0510     kObjectPrototypeHasElements = 84,
0511     kNumberFormatStyleUnit = 85,
0512     kDateTimeFormatRange = 86,
0513     kDateTimeFormatDateTimeStyle = 87,
0514     kBreakIteratorTypeWord = 88,
0515     kBreakIteratorTypeLine = 89,
0516     kInvalidatedArrayBufferDetachingProtector = 90,
0517     kInvalidatedArrayConstructorProtector = 91,
0518     kInvalidatedArrayIteratorLookupChainProtector = 92,
0519     kInvalidatedArraySpeciesLookupChainProtector = 93,
0520     kInvalidatedIsConcatSpreadableLookupChainProtector = 94,
0521     kInvalidatedMapIteratorLookupChainProtector = 95,
0522     kInvalidatedNoElementsProtector = 96,
0523     kInvalidatedPromiseHookProtector = 97,
0524     kInvalidatedPromiseResolveLookupChainProtector = 98,
0525     kInvalidatedPromiseSpeciesLookupChainProtector = 99,
0526     kInvalidatedPromiseThenLookupChainProtector = 100,
0527     kInvalidatedRegExpSpeciesLookupChainProtector = 101,
0528     kInvalidatedSetIteratorLookupChainProtector = 102,
0529     kInvalidatedStringIteratorLookupChainProtector = 103,
0530     kInvalidatedStringLengthOverflowLookupChainProtector = 104,
0531     kInvalidatedTypedArraySpeciesLookupChainProtector = 105,
0532     kWasmSimdOpcodes = 106,
0533     kVarRedeclaredCatchBinding = 107,
0534     kWasmRefTypes = 108,
0535     kOBSOLETE_WasmBulkMemory = 109,
0536     kOBSOLETE_WasmMultiValue = 110,
0537     kWasmExceptionHandling = 111,
0538     kInvalidatedMegaDOMProtector = 112,
0539     kFunctionPrototypeArguments = 113,
0540     kFunctionPrototypeCaller = 114,
0541     kTurboFanOsrCompileStarted = 115,
0542     kAsyncStackTaggingCreateTaskCall = 116,
0543     kDurationFormat = 117,
0544     kInvalidatedNumberStringNotRegexpLikeProtector = 118,
0545     kOBSOLETE_RegExpUnicodeSetIncompatibilitiesWithUnicodeMode = 119,
0546     kImportAssertionDeprecatedSyntax = 120,
0547     kLocaleInfoObsoletedGetters = 121,
0548     kLocaleInfoFunctions = 122,
0549     kCompileHintsMagicAll = 123,
0550     kInvalidatedNoProfilingProtector = 124,
0551     kWasmMemory64 = 125,
0552     kWasmMultiMemory = 126,
0553     kWasmGC = 127,
0554     kWasmImportedStrings = 128,
0555     kSourceMappingUrlMagicCommentAtSign = 129,
0556     kTemporalObject = 130,
0557     kWasmModuleCompilation = 131,
0558     kInvalidatedNoUndetectableObjectsProtector = 132,
0559     kWasmJavaScriptPromiseIntegration = 133,
0560     kWasmReturnCall = 134,
0561     kWasmExtendedConst = 135,
0562     kWasmRelaxedSimd = 136,
0563     kWasmTypeReflection = 137,
0564     kWasmExnRef = 138,
0565     kWasmTypedFuncRef = 139,
0566     kInvalidatedStringWrapperToPrimitiveProtector = 140,
0567 
0568     // If you add new values here, you'll also need to update Chromium's:
0569     // web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to
0570     // this list need to be landed first, then changes on the Chromium side.
0571     kUseCounterFeatureCount  // This enum value must be last.
0572   };
0573 
0574   enum MessageErrorLevel {
0575     kMessageLog = (1 << 0),
0576     kMessageDebug = (1 << 1),
0577     kMessageInfo = (1 << 2),
0578     kMessageError = (1 << 3),
0579     kMessageWarning = (1 << 4),
0580     kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
0581                   kMessageWarning,
0582   };
0583 
0584   using UseCounterCallback = void (*)(Isolate* isolate,
0585                                       UseCounterFeature feature);
0586 
0587   /**
0588    * Allocates a new isolate but does not initialize it. Does not change the
0589    * currently entered isolate.
0590    *
0591    * Only Isolate::GetData() and Isolate::SetData(), which access the
0592    * embedder-controlled parts of the isolate, are allowed to be called on the
0593    * uninitialized isolate. To initialize the isolate, call
0594    * `Isolate::Initialize()` or initialize a `SnapshotCreator`.
0595    *
0596    * When an isolate is no longer used its resources should be freed
0597    * by calling Dispose().  Using the delete operator is not allowed.
0598    *
0599    * V8::Initialize() must have run prior to this.
0600    */
0601   static Isolate* Allocate();
0602 
0603   /**
0604    * Initialize an Isolate previously allocated by Isolate::Allocate().
0605    */
0606   static void Initialize(Isolate* isolate, const CreateParams& params);
0607 
0608   /**
0609    * Creates a new isolate.  Does not change the currently entered
0610    * isolate.
0611    *
0612    * When an isolate is no longer used its resources should be freed
0613    * by calling Dispose().  Using the delete operator is not allowed.
0614    *
0615    * V8::Initialize() must have run prior to this.
0616    */
0617   static Isolate* New(const CreateParams& params);
0618 
0619   /**
0620    * Returns the entered isolate for the current thread or NULL in
0621    * case there is no current isolate.
0622    *
0623    * This method must not be invoked before V8::Initialize() was invoked.
0624    */
0625   static Isolate* GetCurrent();
0626 
0627   /**
0628    * Returns the entered isolate for the current thread or NULL in
0629    * case there is no current isolate.
0630    *
0631    * No checks are performed by this method.
0632    */
0633   static Isolate* TryGetCurrent();
0634 
0635   /**
0636    * Return true if this isolate is currently active.
0637    **/
0638   bool IsCurrent() const;
0639 
0640   /**
0641    * Clears the set of objects held strongly by the heap. This set of
0642    * objects are originally built when a WeakRef is created or
0643    * successfully dereferenced.
0644    *
0645    * This is invoked automatically after microtasks are run. See
0646    * MicrotasksPolicy for when microtasks are run.
0647    *
0648    * This needs to be manually invoked only if the embedder is manually running
0649    * microtasks via a custom MicrotaskQueue class's PerformCheckpoint. In that
0650    * case, it is the embedder's responsibility to make this call at a time which
0651    * does not interrupt synchronous ECMAScript code execution.
0652    */
0653   void ClearKeptObjects();
0654 
0655   /**
0656    * Custom callback used by embedders to help V8 determine if it should abort
0657    * when it throws and no internal handler is predicted to catch the
0658    * exception. If --abort-on-uncaught-exception is used on the command line,
0659    * then V8 will abort if either:
0660    * - no custom callback is set.
0661    * - the custom callback set returns true.
0662    * Otherwise, the custom callback will not be called and V8 will not abort.
0663    */
0664   using AbortOnUncaughtExceptionCallback = bool (*)(Isolate*);
0665   void SetAbortOnUncaughtExceptionCallback(
0666       AbortOnUncaughtExceptionCallback callback);
0667 
0668   /**
0669    * This specifies the callback called by the upcoming dynamic
0670    * import() language feature to load modules.
0671    */
0672   void SetHostImportModuleDynamicallyCallback(
0673       HostImportModuleDynamicallyCallback callback);
0674 
0675   /**
0676    * This specifies the callback called by the upcoming import.meta
0677    * language feature to retrieve host-defined meta data for a module.
0678    */
0679   void SetHostInitializeImportMetaObjectCallback(
0680       HostInitializeImportMetaObjectCallback callback);
0681 
0682   /**
0683    * This specifies the callback called by the upcoming ShadowRealm
0684    * construction language feature to retrieve host created globals.
0685    */
0686   void SetHostCreateShadowRealmContextCallback(
0687       HostCreateShadowRealmContextCallback callback);
0688 
0689   /**
0690    * This specifies the callback called when the stack property of Error
0691    * is accessed.
0692    */
0693   void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
0694 
0695 #if defined(V8_OS_WIN)
0696   /**
0697    * This specifies the callback called when an ETW tracing session starts.
0698    */
0699   void SetFilterETWSessionByURLCallback(FilterETWSessionByURLCallback callback);
0700 #endif  // V8_OS_WIN
0701 
0702   /**
0703    * Optional notification that the system is running low on memory.
0704    * V8 uses these notifications to guide heuristics.
0705    * It is allowed to call this function from another thread while
0706    * the isolate is executing long running JavaScript code.
0707    */
0708   void MemoryPressureNotification(MemoryPressureLevel level);
0709 
0710   /**
0711    * Optional request from the embedder to tune v8 towards energy efficiency
0712    * rather than speed if `battery_saver_mode_enabled` is true, because the
0713    * embedder is in battery saver mode. If false, the correct tuning is left
0714    * to v8 to decide.
0715    */
0716   void SetBatterySaverMode(bool battery_saver_mode_enabled);
0717 
0718   /**
0719    * Drop non-essential caches. Should only be called from testing code.
0720    * The method can potentially block for a long time and does not necessarily
0721    * trigger GC.
0722    */
0723   void ClearCachesForTesting();
0724 
0725   /**
0726    * Methods below this point require holding a lock (using Locker) in
0727    * a multi-threaded environment.
0728    */
0729 
0730   /**
0731    * Sets this isolate as the entered one for the current thread.
0732    * Saves the previously entered one (if any), so that it can be
0733    * restored when exiting.  Re-entering an isolate is allowed.
0734    */
0735   void Enter();
0736 
0737   /**
0738    * Exits this isolate by restoring the previously entered one in the
0739    * current thread.  The isolate may still stay the same, if it was
0740    * entered more than once.
0741    *
0742    * Requires: this == Isolate::GetCurrent().
0743    */
0744   void Exit();
0745 
0746   /**
0747    * Disposes the isolate.  The isolate must not be entered by any
0748    * thread to be disposable.
0749    */
0750   void Dispose();
0751 
0752   /**
0753    * Dumps activated low-level V8 internal stats. This can be used instead
0754    * of performing a full isolate disposal.
0755    */
0756   void DumpAndResetStats();
0757 
0758   /**
0759    * Discards all V8 thread-specific data for the Isolate. Should be used
0760    * if a thread is terminating and it has used an Isolate that will outlive
0761    * the thread -- all thread-specific data for an Isolate is discarded when
0762    * an Isolate is disposed so this call is pointless if an Isolate is about
0763    * to be Disposed.
0764    */
0765   void DiscardThreadSpecificMetadata();
0766 
0767   /**
0768    * Associate embedder-specific data with the isolate. |slot| has to be
0769    * between 0 and GetNumberOfDataSlots() - 1.
0770    */
0771   V8_INLINE void SetData(uint32_t slot, void* data);
0772 
0773   /**
0774    * Retrieve embedder-specific data from the isolate.
0775    * Returns NULL if SetData has never been called for the given |slot|.
0776    */
0777   V8_INLINE void* GetData(uint32_t slot);
0778 
0779   /**
0780    * Returns the maximum number of available embedder data slots. Valid slots
0781    * are in the range of 0 - GetNumberOfDataSlots() - 1.
0782    */
0783   V8_INLINE static uint32_t GetNumberOfDataSlots();
0784 
0785   /**
0786    * Return data that was previously attached to the isolate snapshot via
0787    * SnapshotCreator, and removes the reference to it.
0788    * Repeated call with the same index returns an empty MaybeLocal.
0789    */
0790   template <class T>
0791   V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
0792 
0793   /**
0794    * Returns the value that was set or restored by
0795    * SetContinuationPreservedEmbedderData(), if any.
0796    */
0797   Local<Value> GetContinuationPreservedEmbedderData();
0798 
0799   /**
0800    * Sets a value that will be stored on continuations and reset while the
0801    * continuation runs.
0802    */
0803   void SetContinuationPreservedEmbedderData(Local<Value> data);
0804 
0805   /**
0806    * Get statistics about the heap memory usage.
0807    */
0808   void GetHeapStatistics(HeapStatistics* heap_statistics);
0809 
0810   /**
0811    * Returns the number of spaces in the heap.
0812    */
0813   size_t NumberOfHeapSpaces();
0814 
0815   /**
0816    * Get the memory usage of a space in the heap.
0817    *
0818    * \param space_statistics The HeapSpaceStatistics object to fill in
0819    *   statistics.
0820    * \param index The index of the space to get statistics from, which ranges
0821    *   from 0 to NumberOfHeapSpaces() - 1.
0822    * \returns true on success.
0823    */
0824   bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
0825                               size_t index);
0826 
0827   /**
0828    * Returns the number of types of objects tracked in the heap at GC.
0829    */
0830   size_t NumberOfTrackedHeapObjectTypes();
0831 
0832   /**
0833    * Get statistics about objects in the heap.
0834    *
0835    * \param object_statistics The HeapObjectStatistics object to fill in
0836    *   statistics of objects of given type, which were live in the previous GC.
0837    * \param type_index The index of the type of object to fill details about,
0838    *   which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
0839    * \returns true on success.
0840    */
0841   bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
0842                                        size_t type_index);
0843 
0844   /**
0845    * Get statistics about code and its metadata in the heap.
0846    *
0847    * \param object_statistics The HeapCodeStatistics object to fill in
0848    *   statistics of code, bytecode and their metadata.
0849    * \returns true on success.
0850    */
0851   bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
0852 
0853   /**
0854    * This API is experimental and may change significantly.
0855    *
0856    * Enqueues a memory measurement request and invokes the delegate with the
0857    * results.
0858    *
0859    * \param delegate the delegate that defines which contexts to measure and
0860    *   reports the results.
0861    *
0862    * \param execution promptness executing the memory measurement.
0863    *   The kEager value is expected to be used only in tests.
0864    */
0865   bool MeasureMemory(
0866       std::unique_ptr<MeasureMemoryDelegate> delegate,
0867       MeasureMemoryExecution execution = MeasureMemoryExecution::kDefault);
0868 
0869   /**
0870    * Get a call stack sample from the isolate.
0871    * \param state Execution state.
0872    * \param frames Caller allocated buffer to store stack frames.
0873    * \param frames_limit Maximum number of frames to capture. The buffer must
0874    *                     be large enough to hold the number of frames.
0875    * \param sample_info The sample info is filled up by the function
0876    *                    provides number of actual captured stack frames and
0877    *                    the current VM state.
0878    * \note GetStackSample should only be called when the JS thread is paused or
0879    *       interrupted. Otherwise the behavior is undefined.
0880    */
0881   void GetStackSample(const RegisterState& state, void** frames,
0882                       size_t frames_limit, SampleInfo* sample_info);
0883 
0884   /**
0885    * Adjusts the amount of registered external memory. Used to give V8 an
0886    * indication of the amount of externally allocated memory that is kept alive
0887    * by JavaScript objects. V8 uses this to decide when to perform global
0888    * garbage collections. Registering externally allocated memory will trigger
0889    * global garbage collections more often than it would otherwise in an attempt
0890    * to garbage collect the JavaScript objects that keep the externally
0891    * allocated memory alive.
0892    *
0893    * \param change_in_bytes the change in externally allocated memory that is
0894    *   kept alive by JavaScript objects.
0895    * \returns the adjusted value.
0896    */
0897   int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
0898 
0899   /**
0900    * Returns heap profiler for this isolate. Will return NULL until the isolate
0901    * is initialized.
0902    */
0903   HeapProfiler* GetHeapProfiler();
0904 
0905   /**
0906    * Tells the VM whether the embedder is idle or not.
0907    */
0908   void SetIdle(bool is_idle);
0909 
0910   /** Returns the ArrayBuffer::Allocator used in this isolate. */
0911   ArrayBuffer::Allocator* GetArrayBufferAllocator();
0912 
0913   /** Returns true if this isolate has a current context. */
0914   bool InContext();
0915 
0916   /**
0917    * Returns the context of the currently running JavaScript, or the context
0918    * on the top of the stack if no JavaScript is running.
0919    */
0920   Local<Context> GetCurrentContext();
0921 
0922   /**
0923    * Returns either the last context entered through V8's C++ API, or the
0924    * context of the currently running microtask while processing microtasks.
0925    * If a context is entered while executing a microtask, that context is
0926    * returned.
0927    */
0928   Local<Context> GetEnteredOrMicrotaskContext();
0929 
0930   /**
0931    * Returns the Context that corresponds to the Incumbent realm in HTML spec.
0932    * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
0933    */
0934   Local<Context> GetIncumbentContext();
0935 
0936   /**
0937    * Schedules a v8::Exception::Error with the given message.
0938    * See ThrowException for more details. Templatized to provide compile-time
0939    * errors in case of too long strings (see v8::String::NewFromUtf8Literal).
0940    */
0941   template <int N>
0942   Local<Value> ThrowError(const char (&message)[N]) {
0943     return ThrowError(String::NewFromUtf8Literal(this, message));
0944   }
0945   Local<Value> ThrowError(Local<String> message);
0946 
0947   /**
0948    * Schedules an exception to be thrown when returning to JavaScript.  When an
0949    * exception has been scheduled it is illegal to invoke any JavaScript
0950    * operation; the caller must return immediately and only after the exception
0951    * has been handled does it become legal to invoke JavaScript operations.
0952    */
0953   Local<Value> ThrowException(Local<Value> exception);
0954 
0955   using GCCallback = void (*)(Isolate* isolate, GCType type,
0956                               GCCallbackFlags flags);
0957   using GCCallbackWithData = void (*)(Isolate* isolate, GCType type,
0958                                       GCCallbackFlags flags, void* data);
0959 
0960   /**
0961    * Enables the host application to receive a notification before a
0962    * garbage collection.
0963    *
0964    * \param callback The callback to be invoked. The callback is allowed to
0965    *     allocate but invocation is not re-entrant: a callback triggering
0966    *     garbage collection will not be called again. JS execution is prohibited
0967    *     from these callbacks. A single callback may only be registered once.
0968    * \param gc_type_filter A filter in case it should be applied.
0969    */
0970   void AddGCPrologueCallback(GCCallback callback,
0971                              GCType gc_type_filter = kGCTypeAll);
0972 
0973   /**
0974    * \copydoc AddGCPrologueCallback(GCCallback, GCType)
0975    *
0976    * \param data Additional data that should be passed to the callback.
0977    */
0978   void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
0979                              GCType gc_type_filter = kGCTypeAll);
0980 
0981   /**
0982    * This function removes a callback which was added by
0983    * `AddGCPrologueCallback`.
0984    *
0985    * \param callback the callback to remove.
0986    */
0987   void RemoveGCPrologueCallback(GCCallback callback);
0988 
0989   /**
0990    * \copydoc AddGCPrologueCallback(GCCallback)
0991    *
0992    * \param data Additional data that was used to install the callback.
0993    */
0994   void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
0995 
0996   /**
0997    * Enables the host application to receive a notification after a
0998    * garbage collection.
0999    *
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<SharedArrayBuffer> 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<Function> 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>& 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> 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<Value> data = Local<Value>());
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<Value> data = Local<Value>());
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 <class K, class V, class Traits>
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 <class T>
1756 MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
1757   if (auto slot = GetDataFromSnapshotOnce(index); slot) {
1758     internal::PerformCastCheck(
1759         internal::ValueHelper::SlotAsValue<T, false>(slot));
1760     return Local<T>::FromSlot(slot);
1761   }
1762   return {};
1763 }
1764 
1765 }  // namespace v8
1766 
1767 #endif  // INCLUDE_V8_ISOLATE_H_