Coverage Report

Created: 2025-07-04 09:33

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