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