Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-03-29 08:24:41

0001 // Copyright 2021 the V8 project authors. All rights reserved.
0002 // Use of this source code is governed by a BSD-style license that can be
0003 // found in the LICENSE file.
0004 
0005 #ifndef INCLUDE_V8_ISOLATE_CALLBACKS_H_
0006 #define INCLUDE_V8_ISOLATE_CALLBACKS_H_
0007 
0008 #include <stddef.h>
0009 
0010 #include <functional>
0011 #include <string>
0012 
0013 #include "cppgc/common.h"
0014 #include "v8-data.h"          // NOLINT(build/include_directory)
0015 #include "v8-local-handle.h"  // NOLINT(build/include_directory)
0016 #include "v8-promise.h"       // NOLINT(build/include_directory)
0017 #include "v8config.h"         // NOLINT(build/include_directory)
0018 
0019 #if defined(V8_OS_WIN)
0020 struct _EXCEPTION_POINTERS;
0021 #endif
0022 
0023 namespace v8 {
0024 
0025 template <typename T>
0026 class FunctionCallbackInfo;
0027 class Isolate;
0028 class Message;
0029 class Module;
0030 class Object;
0031 class Promise;
0032 class ScriptOrModule;
0033 class String;
0034 class UnboundScript;
0035 class Value;
0036 
0037 /**
0038  * A JIT code event is issued each time code is added, moved or removed.
0039  *
0040  * \note removal events are not currently issued.
0041  */
0042 struct JitCodeEvent {
0043   enum EventType {
0044     CODE_ADDED,
0045     CODE_MOVED,
0046     CODE_REMOVED,
0047     CODE_ADD_LINE_POS_INFO,
0048     CODE_START_LINE_INFO_RECORDING,
0049     CODE_END_LINE_INFO_RECORDING
0050   };
0051   // Definition of the code position type. The "POSITION" type means the place
0052   // in the source code which are of interest when making stack traces to
0053   // pin-point the source location of a stack frame as close as possible.
0054   // The "STATEMENT_POSITION" means the place at the beginning of each
0055   // statement, and is used to indicate possible break locations.
0056   enum PositionType { POSITION, STATEMENT_POSITION };
0057 
0058   // There are three different kinds of CodeType, one for JIT code generated
0059   // by the optimizing compiler, one for byte code generated for the
0060   // interpreter, and one for code generated from Wasm. For JIT_CODE and
0061   // WASM_CODE, |code_start| points to the beginning of jitted assembly code,
0062   // while for BYTE_CODE events, |code_start| points to the first bytecode of
0063   // the interpreted function.
0064   enum CodeType { BYTE_CODE, JIT_CODE, WASM_CODE };
0065 
0066   // Type of event.
0067   EventType type;
0068   CodeType code_type;
0069   // Start of the instructions.
0070   void* code_start;
0071   // Size of the instructions.
0072   size_t code_len;
0073   // Script info for CODE_ADDED event.
0074   Local<UnboundScript> script;
0075   // User-defined data for *_LINE_INFO_* event. It's used to hold the source
0076   // code line information which is returned from the
0077   // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
0078   // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
0079   void* user_data;
0080 
0081   struct name_t {
0082     // Name of the object associated with the code, note that the string is not
0083     // zero-terminated.
0084     const char* str;
0085     // Number of chars in str.
0086     size_t len;
0087   };
0088 
0089   struct line_info_t {
0090     // PC offset
0091     size_t offset;
0092     // Code position
0093     size_t pos;
0094     // The position type.
0095     PositionType position_type;
0096   };
0097 
0098   struct wasm_source_info_t {
0099     // Source file name.
0100     const char* filename;
0101     // Length of filename.
0102     size_t filename_size;
0103     // Line number table, which maps offsets of JITted code to line numbers of
0104     // source file.
0105     const line_info_t* line_number_table;
0106     // Number of entries in the line number table.
0107     size_t line_number_table_size;
0108   };
0109 
0110   wasm_source_info_t* wasm_source_info = nullptr;
0111 
0112   union {
0113     // Only valid for CODE_ADDED.
0114     struct name_t name;
0115 
0116     // Only valid for CODE_ADD_LINE_POS_INFO
0117     struct line_info_t line_info;
0118 
0119     // New location of instructions. Only valid for CODE_MOVED.
0120     void* new_code_start;
0121   };
0122 
0123   Isolate* isolate;
0124 };
0125 
0126 /**
0127  * Option flags passed to the SetJitCodeEventHandler function.
0128  */
0129 enum JitCodeEventOptions {
0130   kJitCodeEventDefault = 0,
0131   // Generate callbacks for already existent code.
0132   kJitCodeEventEnumExisting = 1,
0133 
0134   kLastJitCodeEventOption = kJitCodeEventEnumExisting
0135 };
0136 
0137 /**
0138  * Callback function passed to SetJitCodeEventHandler.
0139  *
0140  * \param event code add, move or removal event.
0141  */
0142 using JitCodeEventHandler = void (*)(const JitCodeEvent* event);
0143 
0144 // --- Garbage Collection Callbacks ---
0145 
0146 /**
0147  * Applications can register callback functions which will be called before and
0148  * after certain garbage collection operations.  Allocations are not allowed in
0149  * the callback functions, you therefore cannot manipulate objects (set or
0150  * delete properties for example) since it is possible such operations will
0151  * result in the allocation of objects.
0152  * TODO(v8:12612): Deprecate kGCTypeMinorMarkSweep after updating blink.
0153  */
0154 enum GCType {
0155   kGCTypeScavenge = 1 << 0,
0156   kGCTypeMinorMarkSweep = 1 << 1,
0157   kGCTypeMarkSweepCompact = 1 << 2,
0158   kGCTypeIncrementalMarking = 1 << 3,
0159   kGCTypeProcessWeakCallbacks = 1 << 4,
0160   kGCTypeAll = kGCTypeScavenge | kGCTypeMinorMarkSweep |
0161                kGCTypeMarkSweepCompact | kGCTypeIncrementalMarking |
0162                kGCTypeProcessWeakCallbacks
0163 };
0164 
0165 /**
0166  * GCCallbackFlags is used to notify additional information about the GC
0167  * callback.
0168  *   - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
0169  *     constructing retained object infos.
0170  *   - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
0171  *   - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
0172  *     is called synchronously without getting posted to an idle task.
0173  *   - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
0174  *     in a phase where V8 is trying to collect all available garbage
0175  *     (e.g., handling a low memory notification).
0176  *   - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
0177  *     trigger an idle garbage collection.
0178  */
0179 enum GCCallbackFlags {
0180   kNoGCCallbackFlags = 0,
0181   kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
0182   kGCCallbackFlagForced = 1 << 2,
0183   kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3,
0184   kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4,
0185   kGCCallbackFlagCollectAllExternalMemory = 1 << 5,
0186   kGCCallbackScheduleIdleGarbageCollection = 1 << 6,
0187 };
0188 
0189 using GCCallback = void (*)(GCType type, GCCallbackFlags flags);
0190 
0191 using InterruptCallback = void (*)(Isolate* isolate, void* data);
0192 
0193 using PrintCurrentStackTraceFilterCallback =
0194     bool (*)(Isolate* isolate, Local<String> script_name);
0195 
0196 /**
0197  * This callback is invoked when the heap size is close to the heap limit and
0198  * V8 is likely to abort with out-of-memory error.
0199  * The callback can extend the heap limit by returning a value that is greater
0200  * than the current_heap_limit. The initial heap limit is the limit that was
0201  * set after heap setup.
0202  */
0203 using NearHeapLimitCallback = size_t (*)(void* data, size_t current_heap_limit,
0204                                          size_t initial_heap_limit);
0205 
0206 /**
0207  * Callback function passed to SetUnhandledExceptionCallback.
0208  */
0209 #if defined(V8_OS_WIN)
0210 using UnhandledExceptionCallback =
0211     int (*)(_EXCEPTION_POINTERS* exception_pointers);
0212 #endif
0213 
0214 // --- Counters Callbacks ---
0215 
0216 using CounterLookupCallback = int* (*)(const char* name);
0217 
0218 using CreateHistogramCallback = void* (*)(const char* name, int min, int max,
0219                                           size_t buckets);
0220 
0221 using AddHistogramSampleCallback = void (*)(void* histogram, int sample);
0222 
0223 // --- Exceptions ---
0224 
0225 using FatalErrorCallback = void (*)(const char* location, const char* message);
0226 
0227 struct OOMDetails {
0228   bool is_heap_oom = false;
0229   const char* detail = nullptr;
0230 };
0231 
0232 using OOMErrorCallback = void (*)(const char* location,
0233                                   const OOMDetails& details);
0234 
0235 using MessageCallback = void (*)(Local<Message> message, Local<Value> data);
0236 
0237 // --- Tracing ---
0238 
0239 enum LogEventStatus : int { kStart = 0, kEnd = 1, kLog = 2 };
0240 using LogEventCallback = void (*)(const char* name,
0241                                   int /* LogEventStatus */ status);
0242 
0243 // --- Crashkeys Callback ---
0244 enum class CrashKeyId {
0245   kIsolateAddress,
0246   kReadonlySpaceFirstPageAddress,
0247   kMapSpaceFirstPageAddress V8_ENUM_DEPRECATE_SOON("Map space got removed"),
0248   kOldSpaceFirstPageAddress,
0249   kCodeRangeBaseAddress,
0250   kCodeSpaceFirstPageAddress,
0251   kDumpType,
0252   kSnapshotChecksumCalculated,
0253   kSnapshotChecksumExpected,
0254 };
0255 
0256 using AddCrashKeyCallback = void (*)(CrashKeyId id, const std::string& value);
0257 
0258 // --- Enter/Leave Script Callback ---
0259 using BeforeCallEnteredCallback = void (*)(Isolate*);
0260 using CallCompletedCallback = void (*)(Isolate*);
0261 
0262 // --- Modify Code Generation From Strings Callback ---
0263 struct ModifyCodeGenerationFromStringsResult {
0264   // If true, proceed with the codegen algorithm. Otherwise, block it.
0265   bool codegen_allowed = false;
0266   // Overwrite the original source with this string, if present.
0267   // Use the original source if empty.
0268   // This field is considered only if codegen_allowed is true.
0269   MaybeLocal<String> modified_source;
0270 };
0271 
0272 /**
0273  * Callback to check if codegen is allowed from a source object, and convert
0274  * the source to string if necessary. See: ModifyCodeGenerationFromStrings.
0275  */
0276 using ModifyCodeGenerationFromStringsCallback =
0277     ModifyCodeGenerationFromStringsResult (*)(Local<Context> context,
0278                                               Local<Value> source);
0279 using ModifyCodeGenerationFromStringsCallback2 =
0280     ModifyCodeGenerationFromStringsResult (*)(Local<Context> context,
0281                                               Local<Value> source,
0282                                               bool is_code_like);
0283 
0284 // --- Failed Access Check Callback ---
0285 
0286 /**
0287  * Access type specification.
0288  */
0289 enum AccessType {
0290   ACCESS_GET,
0291   ACCESS_SET,
0292   ACCESS_HAS,
0293   ACCESS_DELETE,
0294   ACCESS_KEYS
0295 };
0296 
0297 using FailedAccessCheckCallback = void (*)(Local<Object> target,
0298                                            AccessType type, Local<Value> data);
0299 
0300 // --- WebAssembly compilation callbacks ---
0301 using ExtensionCallback = bool (*)(const FunctionCallbackInfo<Value>&);
0302 
0303 using AllowWasmCodeGenerationCallback = bool (*)(Local<Context> context,
0304                                                  Local<String> source);
0305 
0306 // --- Callback for APIs defined on v8-supported objects, but implemented
0307 // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
0308 using ApiImplementationCallback = void (*)(const FunctionCallbackInfo<Value>&);
0309 
0310 // --- Callback for WebAssembly.compileStreaming ---
0311 using WasmStreamingCallback = void (*)(const FunctionCallbackInfo<Value>&);
0312 
0313 enum class WasmAsyncSuccess { kSuccess, kFail };
0314 
0315 // --- Callback called when async WebAssembly operations finish ---
0316 using WasmAsyncResolvePromiseCallback = void (*)(
0317     Isolate* isolate, Local<Context> context, Local<Promise::Resolver> resolver,
0318     Local<Value> result, WasmAsyncSuccess success);
0319 
0320 // --- Callback for loading source map file for Wasm profiling support
0321 using WasmLoadSourceMapCallback = Local<String> (*)(Isolate* isolate,
0322                                                     const char* name);
0323 
0324 // --- Callback for checking if WebAssembly imported strings are enabled ---
0325 using WasmImportedStringsEnabledCallback = bool (*)(Local<Context> context);
0326 
0327 // --- Callback for checking if the SharedArrayBuffer constructor is enabled ---
0328 using SharedArrayBufferConstructorEnabledCallback =
0329     bool (*)(Local<Context> context);
0330 
0331 // --- Callback for checking if the compile hints magic comments are enabled ---
0332 using JavaScriptCompileHintsMagicEnabledCallback =
0333     bool (*)(Local<Context> context);
0334 
0335 // --- Callback for checking if WebAssembly JSPI is enabled ---
0336 using WasmJSPIEnabledCallback = bool (*)(Local<Context> context);
0337 
0338 /**
0339  * Import phases in import requests.
0340  */
0341 enum class ModuleImportPhase {
0342   kSource,
0343   kEvaluation,
0344 };
0345 
0346 /**
0347  * HostImportModuleDynamicallyCallback is called when we
0348  * require the embedder to load a module. This is used as part of the dynamic
0349  * import syntax.
0350  *
0351  * The referrer contains metadata about the script/module that calls
0352  * import.
0353  *
0354  * The specifier is the name of the module that should be imported.
0355  *
0356  * The import_attributes are import attributes for this request in the form:
0357  * [key1, value1, key2, value2, ...] where the keys and values are of type
0358  * v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
0359  * returned from ModuleRequest::GetImportAttributes(), this array does not
0360  * contain the source Locations of the attributes.
0361  *
0362  * The embedder must compile, instantiate, evaluate the Module, and
0363  * obtain its namespace object.
0364  *
0365  * The Promise returned from this function is forwarded to userland
0366  * JavaScript. The embedder must resolve this promise with the module
0367  * namespace object. In case of an exception, the embedder must reject
0368  * this promise with the exception. If the promise creation itself
0369  * fails (e.g. due to stack overflow), the embedder must propagate
0370  * that exception by returning an empty MaybeLocal.
0371  */
0372 using HostImportModuleDynamicallyCallback = MaybeLocal<Promise> (*)(
0373     Local<Context> context, Local<Data> host_defined_options,
0374     Local<Value> resource_name, Local<String> specifier,
0375     Local<FixedArray> import_attributes);
0376 
0377 /**
0378  * HostImportModuleWithPhaseDynamicallyCallback is called when we
0379  * require the embedder to load a module with a specific phase. This is used
0380  * as part of the dynamic import syntax.
0381  *
0382  * The referrer contains metadata about the script/module that calls
0383  * import.
0384  *
0385  * The specifier is the name of the module that should be imported.
0386  *
0387  * The phase is the phase of the import requested.
0388  *
0389  * The import_attributes are import attributes for this request in the form:
0390  * [key1, value1, key2, value2, ...] where the keys and values are of type
0391  * v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
0392  * returned from ModuleRequest::GetImportAttributes(), this array does not
0393  * contain the source Locations of the attributes.
0394  *
0395  * The Promise returned from this function is forwarded to userland
0396  * JavaScript. The embedder must resolve this promise according to the phase
0397  * requested:
0398  * - For ModuleImportPhase::kSource, the promise must be resolved with a
0399  *   compiled ModuleSource object, or rejected with a SyntaxError if the
0400  *   module does not support source representation.
0401  * - For ModuleImportPhase::kEvaluation, the promise must be resolved with a
0402  *   ModuleNamespace object of a module that has been compiled, instantiated,
0403  *   and evaluated.
0404  *
0405  * In case of an exception, the embedder must reject this promise with the
0406  * exception. If the promise creation itself fails (e.g. due to stack
0407  * overflow), the embedder must propagate that exception by returning an empty
0408  * MaybeLocal.
0409  *
0410  * This callback is still experimental and is only invoked for source phase
0411  * imports.
0412  */
0413 using HostImportModuleWithPhaseDynamicallyCallback = MaybeLocal<Promise> (*)(
0414     Local<Context> context, Local<Data> host_defined_options,
0415     Local<Value> resource_name, Local<String> specifier,
0416     ModuleImportPhase phase, Local<FixedArray> import_attributes);
0417 
0418 /**
0419  * Callback for requesting a compile hint for a function from the embedder. The
0420  * first parameter is the position of the function in source code and the second
0421  * parameter is embedder data to be passed back.
0422  */
0423 using CompileHintCallback = bool (*)(int, void*);
0424 
0425 /**
0426  * HostInitializeImportMetaObjectCallback is called the first time import.meta
0427  * is accessed for a module. Subsequent access will reuse the same value.
0428  *
0429  * The method combines two implementation-defined abstract operations into one:
0430  * HostGetImportMetaProperties and HostFinalizeImportMeta.
0431  *
0432  * The embedder should use v8::Object::CreateDataProperty to add properties on
0433  * the meta object.
0434  */
0435 using HostInitializeImportMetaObjectCallback = void (*)(Local<Context> context,
0436                                                         Local<Module> module,
0437                                                         Local<Object> meta);
0438 
0439 /**
0440  * HostCreateShadowRealmContextCallback is called each time a ShadowRealm is
0441  * being constructed in the initiator_context.
0442  *
0443  * The method combines Context creation and implementation defined abstract
0444  * operation HostInitializeShadowRealm into one.
0445  *
0446  * The embedder should use v8::Context::New or v8::Context:NewFromSnapshot to
0447  * create a new context. If the creation fails, the embedder must propagate
0448  * that exception by returning an empty MaybeLocal.
0449  */
0450 using HostCreateShadowRealmContextCallback =
0451     MaybeLocal<Context> (*)(Local<Context> initiator_context);
0452 
0453 /**
0454  * IsJSApiWrapperNativeErrorCallback is called on an JSApiWrapper object to
0455  * determine if Error.isError should return true or false. For instance, in an
0456  * HTML embedder, DOMExceptions return true when passed to Error.isError.
0457  */
0458 using IsJSApiWrapperNativeErrorCallback = bool (*)(Isolate* isolate,
0459                                                    Local<Object> obj);
0460 
0461 /**
0462  * PrepareStackTraceCallback is called when the stack property of an error is
0463  * first accessed. The return value will be used as the stack value. If this
0464  * callback is registed, the |Error.prepareStackTrace| API will be disabled.
0465  * |sites| is an array of call sites, specified in
0466  * https://v8.dev/docs/stack-trace-api
0467  */
0468 using PrepareStackTraceCallback = MaybeLocal<Value> (*)(Local<Context> context,
0469                                                         Local<Value> error,
0470                                                         Local<Array> sites);
0471 
0472 #if defined(V8_OS_WIN)
0473 /**
0474  * Callback to selectively enable ETW tracing based on the document URL.
0475  * Implemented by the embedder, it should never call back into V8.
0476  *
0477  * Windows allows passing additional data to the ETW EnableCallback:
0478  * https://learn.microsoft.com/en-us/windows/win32/api/evntprov/nc-evntprov-penablecallback
0479  *
0480  * This data can be configured in a WPR (Windows Performance Recorder)
0481  * profile, adding a CustomFilter to an EventProvider like the following:
0482  *
0483  * <EventProvider Id=".." Name="57277741-3638-4A4B-BDBA-0AC6E45DA56C" Level="5">
0484  *   <CustomFilter Type="0x80000000" Value="AQABAAAAAAA..." />
0485  * </EventProvider>
0486  *
0487  * Where:
0488  * - Name="57277741-3638-4A4B-BDBA-0AC6E45DA56C" is the GUID of the V8
0489  *     ETW provider, (see src/libplatform/etw/etw-provider-win.h),
0490  * - Type="0x80000000" is EVENT_FILTER_TYPE_SCHEMATIZED,
0491  * - Value="AQABAAAAAA..." is a base64-encoded byte array that is
0492  *     base64-decoded by Windows and passed to the ETW enable callback in
0493  *     the 'PEVENT_FILTER_DESCRIPTOR FilterData' argument; see:
0494  * https://learn.microsoft.com/en-us/windows/win32/api/evntprov/ns-evntprov-event_filter_descriptor.
0495  *
0496  * This array contains a struct EVENT_FILTER_HEADER followed by a
0497  * variable length payload, and as payload we pass a string in JSON format,
0498  * with a list of regular expressions that should match the document URL
0499  * in order to enable ETW tracing:
0500  *   {
0501  *     "version": "2.0",
0502  *     "filtered_urls": [
0503  *         "https:\/\/.*\.chromium\.org\/.*", "https://v8.dev/";, "..."
0504  *     ],
0505  *     "trace_interpreter_frames": true
0506  *  }
0507  */
0508 
0509 using FilterETWSessionByURLCallback =
0510     bool (*)(Local<Context> context, const std::string& etw_filter_payload);
0511 
0512 struct FilterETWSessionByURLResult {
0513   // If true, enable ETW tracing for the current isolate.
0514   bool enable_etw_tracing;
0515 
0516   // If true, also enables ETW tracing for interpreter stack frames.
0517   bool trace_interpreter_frames;
0518 };
0519 using FilterETWSessionByURL2Callback = FilterETWSessionByURLResult (*)(
0520     Local<Context> context, const std::string& etw_filter_payload);
0521 #endif  // V8_OS_WIN
0522 
0523 }  // namespace v8
0524 
0525 #endif  // INCLUDE_V8_ISOLATE_CALLBACKS_H_