v8 14.1.146 (node 25.0.0)
V8 is Google's open source JavaScript engine
Loading...
Searching...
No Matches
v8-callbacks.h
Go to the documentation of this file.
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_CALLBACKS_H_
6#define INCLUDE_V8_ISOLATE_CALLBACKS_H_
7
8#include <stddef.h>
9
10#include <functional>
11#include <string>
12
13#include "cppgc/common.h"
14#include "v8-data.h" // NOLINT(build/include_directory)
15#include "v8-local-handle.h" // NOLINT(build/include_directory)
16#include "v8-promise.h" // NOLINT(build/include_directory)
17#include "v8config.h" // NOLINT(build/include_directory)
18
19#if defined(V8_OS_WIN)
20struct _EXCEPTION_POINTERS;
21#endif
22
23namespace v8 {
24
25template <typename T>
27class Isolate;
28class Message;
29class Module;
30class Object;
31class Promise;
32class ScriptOrModule;
33class String;
34class UnboundScript;
35class Value;
36
37/**
38 * A JIT code event is issued each time code is added, moved or removed.
39 *
40 * \note removal events are not currently issued.
41 */
43 enum EventType {
50 };
51 // Definition of the code position type. The "POSITION" type means the place
52 // in the source code which are of interest when making stack traces to
53 // pin-point the source location of a stack frame as close as possible.
54 // The "STATEMENT_POSITION" means the place at the beginning of each
55 // statement, and is used to indicate possible break locations.
57
58 // There are three different kinds of CodeType, one for JIT code generated
59 // by the optimizing compiler, one for byte code generated for the
60 // interpreter, and one for code generated from Wasm. For JIT_CODE and
61 // WASM_CODE, |code_start| points to the beginning of jitted assembly code,
62 // while for BYTE_CODE events, |code_start| points to the first bytecode of
63 // the interpreted function.
65
66 // Type of event.
69 // Start of the instructions.
71 // Size of the instructions.
73 // Script info for CODE_ADDED event.
75 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
76 // code line information which is returned from the
77 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
78 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
79 void* user_data;
80
81 struct name_t {
82 // Name of the object associated with the code, note that the string is not
83 // zero-terminated.
84 const char* str;
85 // Number of chars in str.
87 };
88
89 struct line_info_t {
90 // PC offset
92 // Code position
94 // The position type.
96 };
97
99 // Source file name.
100 const char* filename;
101 // Length of filename.
103 // Line number table, which maps offsets of JITted code to line numbers of
104 // source file.
106 // Number of entries in the line number table.
108 };
109
111
112 union {
113 // Only valid for CODE_ADDED.
114 struct name_t name;
115
116 // Only valid for CODE_ADD_LINE_POS_INFO
118
119 // New location of instructions. Only valid for CODE_MOVED.
121 };
122
124};
125
126/**
127 * Option flags passed to the SetJitCodeEventHandler function.
128 */
131 // Generate callbacks for already existent code.
133
136
137/**
138 * Callback function passed to SetJitCodeEventHandler.
139 *
140 * \param event code add, move or removal event.
141 */
142using JitCodeEventHandler = void (*)(const JitCodeEvent* event);
143
144// --- Garbage Collection Callbacks ---
145
146/**
147 * Applications can register callback functions which will be called before and
148 * after certain garbage collection operations. Allocations are not allowed in
149 * the callback functions, you therefore cannot manipulate objects (set or
150 * delete properties for example) since it is possible such operations will
151 * result in the allocation of objects.
152 * TODO(v8:12612): Deprecate kGCTypeMinorMarkSweep after updating blink.
153 */
154enum GCType {
164
165/**
166 * GCCallbackFlags is used to notify additional information about the GC
167 * callback.
168 * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
169 * constructing retained object infos.
170 * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
171 * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
172 * is called synchronously without getting posted to an idle task.
173 * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
174 * in a phase where V8 is trying to collect all available garbage
175 * (e.g., handling a low memory notification).
176 * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
177 * trigger an idle garbage collection.
178 */
187};
188
189using GCCallback = void (*)(GCType type, GCCallbackFlags flags);
190
191using InterruptCallback = void (*)(Isolate* isolate, void* data);
192
193using PrintCurrentStackTraceFilterCallback =
194 bool (*)(Isolate* isolate, Local<String> script_name);
195
196/**
197 * This callback is invoked when the heap size is close to the heap limit and
198 * V8 is likely to abort with out-of-memory error.
199 * The callback can extend the heap limit by returning a value that is greater
200 * than the current_heap_limit. The initial heap limit is the limit that was
201 * set after heap setup.
202 */
205
206/**
207 * Callback function passed to SetUnhandledExceptionCallback.
208 */
209#if defined(V8_OS_WIN)
212#endif
213
214// --- Counters Callbacks ---
215
216using CounterLookupCallback = int* (*)(const char* name);
217
218using CreateHistogramCallback = void* (*)(const char* name, int min, int max,
219 size_t buckets);
220
221using AddHistogramSampleCallback = void (*)(void* histogram, int sample);
222
223// --- Exceptions ---
224
225using FatalErrorCallback = void (*)(const char* location, const char* message);
226
228 bool is_heap_oom = false;
229 const char* detail = nullptr;
230};
231
232using OOMErrorCallback = void (*)(const char* location,
233 const OOMDetails& details);
234
235using MessageCallback = void (*)(Local<Message> message, Local<Value> data);
236
237// --- Tracing ---
238
239enum LogEventStatus : int { kStart = 0, kEnd = 1, kLog = 2 };
240using LogEventCallback = void (*)(const char* name,
241 int /* LogEventStatus */ status);
242
243// --- Crashkeys Callback ---
244enum class CrashKeyId {
247 kMapSpaceFirstPageAddress V8_ENUM_DEPRECATE_SOON("Map space got removed"),
251 kDumpType,
254};
255
256using AddCrashKeyCallback = void (*)(CrashKeyId id, const std::string& value);
257
258// --- Enter/Leave Script Callback ---
259using BeforeCallEnteredCallback = void (*)(Isolate*);
260using CallCompletedCallback = void (*)(Isolate*);
261
262// --- Modify Code Generation From Strings Callback ---
264 // If true, proceed with the codegen algorithm. Otherwise, block it.
265 bool codegen_allowed = false;
266 // Overwrite the original source with this string, if present.
267 // Use the original source if empty.
268 // This field is considered only if codegen_allowed is true.
270};
271
272/**
273 * Callback to check if codegen is allowed from a source object, and convert
274 * the source to string if necessary. See: ModifyCodeGenerationFromStrings.
275 */
276using ModifyCodeGenerationFromStringsCallback =
278 Local<Value> source);
279using ModifyCodeGenerationFromStringsCallback2 =
281 Local<Value> source,
282 bool is_code_like);
283
284// --- Failed Access Check Callback ---
285
286/**
287 * Access type specification.
288 */
296
297using FailedAccessCheckCallback = void (*)(Local<Object> target,
298 AccessType type, Local<Value> data);
299
300// --- WebAssembly compilation callbacks ---
301using ExtensionCallback = bool (*)(const FunctionCallbackInfo<Value>&);
302
303using AllowWasmCodeGenerationCallback = bool (*)(Local<Context> context,
304 Local<String> source);
305
306// --- Callback for APIs defined on v8-supported objects, but implemented
307// by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
308using ApiImplementationCallback = void (*)(const FunctionCallbackInfo<Value>&);
309
310// --- Callback for WebAssembly.compileStreaming ---
311using WasmStreamingCallback = void (*)(const FunctionCallbackInfo<Value>&);
312
314
315// --- Callback called when async WebAssembly operations finish ---
316using WasmAsyncResolvePromiseCallback = void (*)(
317 Isolate* isolate, Local<Context> context, Local<Promise::Resolver> resolver,
318 Local<Value> result, WasmAsyncSuccess success);
319
320// --- Callback for loading source map file for Wasm profiling support
321using WasmLoadSourceMapCallback = Local<String> (*)(Isolate* isolate,
322 const char* name);
323
324// --- Callback for checking if WebAssembly imported strings are enabled ---
325using WasmImportedStringsEnabledCallback = bool (*)(Local<Context> context);
326
327// --- Callback for checking if WebAssembly Custom Descriptors are enabled ---
328using WasmCustomDescriptorsEnabledCallback = bool (*)(Local<Context> context);
329
330// --- Callback for checking if the SharedArrayBuffer constructor is enabled ---
331using SharedArrayBufferConstructorEnabledCallback =
332 bool (*)(Local<Context> context);
333
334// --- Callback for checking if WebAssembly JSPI is enabled ---
335using WasmJSPIEnabledCallback = bool (*)(Local<Context> context);
336
337/**
338 * Import phases in import requests.
339 */
341 kSource,
343};
344
345/**
346 * HostImportModuleDynamicallyCallback is called when we
347 * require the embedder to load a module. This is used as part of the dynamic
348 * import syntax.
349 *
350 * The referrer contains metadata about the script/module that calls
351 * import.
352 *
353 * The specifier is the name of the module that should be imported.
354 *
355 * The import_attributes are import attributes for this request in the form:
356 * [key1, value1, key2, value2, ...] where the keys and values are of type
357 * v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
358 * returned from ModuleRequest::GetImportAttributes(), this array does not
359 * contain the source Locations of the attributes.
360 *
361 * The embedder must compile, instantiate, evaluate the Module, and
362 * obtain its namespace object.
363 *
364 * The Promise returned from this function is forwarded to userland
365 * JavaScript. The embedder must resolve this promise with the module
366 * namespace object. In case of an exception, the embedder must reject
367 * this promise with the exception. If the promise creation itself
368 * fails (e.g. due to stack overflow), the embedder must propagate
369 * that exception by returning an empty MaybeLocal.
370 */
371using HostImportModuleDynamicallyCallback = MaybeLocal<Promise> (*)(
372 Local<Context> context, Local<Data> host_defined_options,
373 Local<Value> resource_name, Local<String> specifier,
374 Local<FixedArray> import_attributes);
375
376/**
377 * HostImportModuleWithPhaseDynamicallyCallback is called when we
378 * require the embedder to load a module with a specific phase. This is used
379 * as part of the dynamic import syntax.
380 *
381 * The referrer contains metadata about the script/module that calls
382 * import.
383 *
384 * The specifier is the name of the module that should be imported.
385 *
386 * The phase is the phase of the import requested.
387 *
388 * The import_attributes are import attributes for this request in the form:
389 * [key1, value1, key2, value2, ...] where the keys and values are of type
390 * v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
391 * returned from ModuleRequest::GetImportAttributes(), this array does not
392 * contain the source Locations of the attributes.
393 *
394 * The Promise returned from this function is forwarded to userland
395 * JavaScript. The embedder must resolve this promise according to the phase
396 * requested:
397 * - For ModuleImportPhase::kSource, the promise must be resolved with a
398 * compiled ModuleSource object, or rejected with a SyntaxError if the
399 * module does not support source representation.
400 * - For ModuleImportPhase::kEvaluation, the promise must be resolved with a
401 * ModuleNamespace object of a module that has been compiled, instantiated,
402 * and evaluated.
403 *
404 * In case of an exception, the embedder must reject this promise with the
405 * exception. If the promise creation itself fails (e.g. due to stack
406 * overflow), the embedder must propagate that exception by returning an empty
407 * MaybeLocal.
408 *
409 * This callback is still experimental and is only invoked for source phase
410 * imports.
411 */
412using HostImportModuleWithPhaseDynamicallyCallback = MaybeLocal<Promise> (*)(
413 Local<Context> context, Local<Data> host_defined_options,
414 Local<Value> resource_name, Local<String> specifier,
415 ModuleImportPhase phase, Local<FixedArray> import_attributes);
416
417/**
418 * Callback for requesting a compile hint for a function from the embedder. The
419 * first parameter is the position of the function in source code and the second
420 * parameter is embedder data to be passed back.
421 */
422using CompileHintCallback = bool (*)(int, void*);
423
424/**
425 * HostInitializeImportMetaObjectCallback is called the first time import.meta
426 * is accessed for a module. Subsequent access will reuse the same value.
427 *
428 * The method combines two implementation-defined abstract operations into one:
429 * HostGetImportMetaProperties and HostFinalizeImportMeta.
430 *
431 * The embedder should use v8::Object::CreateDataProperty to add properties on
432 * the meta object.
433 */
434using HostInitializeImportMetaObjectCallback = void (*)(Local<Context> context,
435 Local<Module> module,
436 Local<Object> meta);
437
438/**
439 * HostCreateShadowRealmContextCallback is called each time a ShadowRealm is
440 * being constructed in the initiator_context.
441 *
442 * The method combines Context creation and implementation defined abstract
443 * operation HostInitializeShadowRealm into one.
444 *
445 * The embedder should use v8::Context::New or v8::Context:NewFromSnapshot to
446 * create a new context. If the creation fails, the embedder must propagate
447 * that exception by returning an empty MaybeLocal.
448 */
449using HostCreateShadowRealmContextCallback =
450 MaybeLocal<Context> (*)(Local<Context> initiator_context);
451
452/**
453 * IsJSApiWrapperNativeErrorCallback is called on an JSApiWrapper object to
454 * determine if Error.isError should return true or false. For instance, in an
455 * HTML embedder, DOMExceptions return true when passed to Error.isError.
456 */
457using IsJSApiWrapperNativeErrorCallback = bool (*)(Isolate* isolate,
458 Local<Object> obj);
459
460/**
461 * PrepareStackTraceCallback is called when the stack property of an error is
462 * first accessed. The return value will be used as the stack value. If this
463 * callback is registed, the |Error.prepareStackTrace| API will be disabled.
464 * |sites| is an array of call sites, specified in
465 * https://v8.dev/docs/stack-trace-api
466 */
467using PrepareStackTraceCallback = MaybeLocal<Value> (*)(Local<Context> context,
468 Local<Value> error,
469 Local<Array> sites);
470
471#if defined(V8_OS_WIN)
472/**
473 * Callback to selectively enable ETW tracing based on the document URL.
474 * Implemented by the embedder, it should never call back into V8.
475 *
476 * Windows allows passing additional data to the ETW EnableCallback:
477 * https://learn.microsoft.com/en-us/windows/win32/api/evntprov/nc-evntprov-penablecallback
478 *
479 * This data can be configured in a WPR (Windows Performance Recorder)
480 * profile, adding a CustomFilter to an EventProvider like the following:
481 *
482 * <EventProvider Id=".." Name="57277741-3638-4A4B-BDBA-0AC6E45DA56C" Level="5">
483 * <CustomFilter Type="0x80000000" Value="AQABAAAAAAA..." />
484 * </EventProvider>
485 *
486 * Where:
487 * - Name="57277741-3638-4A4B-BDBA-0AC6E45DA56C" is the GUID of the V8
488 * ETW provider, (see src/libplatform/etw/etw-provider-win.h),
489 * - Type="0x80000000" is EVENT_FILTER_TYPE_SCHEMATIZED,
490 * - Value="AQABAAAAAA..." is a base64-encoded byte array that is
491 * base64-decoded by Windows and passed to the ETW enable callback in
492 * the 'PEVENT_FILTER_DESCRIPTOR FilterData' argument; see:
493 * https://learn.microsoft.com/en-us/windows/win32/api/evntprov/ns-evntprov-event_filter_descriptor.
494 *
495 * This array contains a struct EVENT_FILTER_HEADER followed by a
496 * variable length payload, and as payload we pass a string in JSON format,
497 * with a list of regular expressions that should match the document URL
498 * in order to enable ETW tracing:
499 * {
500 * "version": "2.0",
501 * "filtered_urls": [
502 * "https:\/\/.*\.chromium\.org\/.*", "https://v8.dev/";, "..."
503 * ],
504 * "trace_interpreter_frames": true
505 * }
506 */
507
509 bool (*)(Local<Context> context, const std::string& etw_filter_payload);
510
512 // If true, enable ETW tracing for the current isolate.
514
515 // If true, also enables ETW tracing for interpreter stack frames.
517};
520#endif // V8_OS_WIN
521
522} // namespace v8
523
524#endif // INCLUDE_V8_ISOLATE_CALLBACKS_H_
friend class Local
friend class MaybeLocal
friend class FunctionCallbackInfo
WasmAsyncSuccess
GCCallbackFlags
@ kNoGCCallbackFlags
@ kGCCallbackFlagSynchronousPhantomCallbackProcessing
@ kGCCallbackFlagForced
@ kGCCallbackFlagConstructRetainedObjectInfos
@ kGCCallbackFlagCollectAllExternalMemory
@ kGCCallbackFlagCollectAllAvailableGarbage
@ kGCCallbackScheduleIdleGarbageCollection
@ kGCTypeProcessWeakCallbacks
@ kGCTypeIncrementalMarking
@ kGCTypeMarkSweepCompact
@ kGCTypeScavenge
@ kGCTypeAll
@ kGCTypeMinorMarkSweep
JitCodeEventOptions
@ kLastJitCodeEventOption
@ kJitCodeEventEnumExisting
@ kJitCodeEventDefault
ModuleImportPhase
@ ACCESS_KEYS
@ ACCESS_HAS
@ ACCESS_DELETE
@ ACCESS_GET
@ ACCESS_SET
LogEventStatus
@ kStart
@ kSnapshotChecksumCalculated
@ kCodeSpaceFirstPageAddress
@ kReadonlySpaceFirstPageAddress
Local< UnboundScript > script
struct line_info_t line_info
wasm_source_info_t * wasm_source_info
struct name_t name
const char * detail
#define V8_ENUM_DEPRECATE_SOON(message)
Definition v8config.h:664