Coverage Report

Created: 2025-10-31 09:06

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