chromium/v8/include/v8-callbacks.h

// Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef INCLUDE_V8_ISOLATE_CALLBACKS_H_
#define INCLUDE_V8_ISOLATE_CALLBACKS_H_

#include <stddef.h>

#include <functional>
#include <string>

#include "cppgc/common.h"
#include "v8-data.h"          // NOLINT(build/include_directory)
#include "v8-local-handle.h"  // NOLINT(build/include_directory)
#include "v8-promise.h"       // NOLINT(build/include_directory)
#include "v8config.h"         // NOLINT(build/include_directory)

#if defined(V8_OS_WIN)
struct _EXCEPTION_POINTERS;
#endif

namespace v8 {

template <typename T>
class FunctionCallbackInfo;
class Isolate;
class Message;
class Module;
class Object;
class Promise;
class ScriptOrModule;
class String;
class UnboundScript;
class Value;

/**
 * A JIT code event is issued each time code is added, moved or removed.
 *
 * \note removal events are not currently issued.
 */
struct JitCodeEvent {};

/**
 * Option flags passed to the SetJitCodeEventHandler function.
 */
enum JitCodeEventOptions {};

/**
 * Callback function passed to SetJitCodeEventHandler.
 *
 * \param event code add, move or removal event.
 */
JitCodeEventHandler;

// --- Garbage Collection Callbacks ---

/**
 * Applications can register callback functions which will be called before and
 * after certain garbage collection operations.  Allocations are not allowed in
 * the callback functions, you therefore cannot manipulate objects (set or
 * delete properties for example) since it is possible such operations will
 * result in the allocation of objects.
 * TODO(v8:12612): Deprecate kGCTypeMinorMarkSweep after updating blink.
 */
enum GCType {};

/**
 * GCCallbackFlags is used to notify additional information about the GC
 * callback.
 *   - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
 *     constructing retained object infos.
 *   - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
 *   - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
 *     is called synchronously without getting posted to an idle task.
 *   - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
 *     in a phase where V8 is trying to collect all available garbage
 *     (e.g., handling a low memory notification).
 *   - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
 *     trigger an idle garbage collection.
 */
enum GCCallbackFlags {};

GCCallback;

InterruptCallback;

/**
 * This callback is invoked when the heap size is close to the heap limit and
 * V8 is likely to abort with out-of-memory error.
 * The callback can extend the heap limit by returning a value that is greater
 * than the current_heap_limit. The initial heap limit is the limit that was
 * set after heap setup.
 */
NearHeapLimitCallback;

/**
 * Callback function passed to SetUnhandledExceptionCallback.
 */
#if defined(V8_OS_WIN)
using UnhandledExceptionCallback =
    int (*)(_EXCEPTION_POINTERS* exception_pointers);
#endif

// --- Counters Callbacks ---

CounterLookupCallback;

CreateHistogramCallback;

AddHistogramSampleCallback;

// --- Exceptions ---

FatalErrorCallback;

struct OOMDetails {};

OOMErrorCallback;

MessageCallback;

// --- Tracing ---

enum LogEventStatus : int {};
LogEventCallback;

// --- Crashkeys Callback ---
enum class CrashKeyId {};

AddCrashKeyCallback;

// --- Enter/Leave Script Callback ---
BeforeCallEnteredCallback;
CallCompletedCallback;

// --- AllowCodeGenerationFromStrings callbacks ---

/**
 * Callback to check if code generation from strings is allowed. See
 * Context::AllowCodeGenerationFromStrings.
 */
AllowCodeGenerationFromStringsCallback;

struct ModifyCodeGenerationFromStringsResult {};

/**
 * Access type specification.
 */
enum AccessType {};

// --- Failed Access Check Callback ---

FailedAccessCheckCallback;

/**
 * Callback to check if codegen is allowed from a source object, and convert
 * the source to string if necessary. See: ModifyCodeGenerationFromStrings.
 */
ModifyCodeGenerationFromStringsCallback;
ModifyCodeGenerationFromStringsCallback2;

// --- WebAssembly compilation callbacks ---
ExtensionCallback;

AllowWasmCodeGenerationCallback;

// --- Callback for APIs defined on v8-supported objects, but implemented
// by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
ApiImplementationCallback;

// --- Callback for WebAssembly.compileStreaming ---
WasmStreamingCallback;

enum class WasmAsyncSuccess {};

// --- Callback called when async WebAssembly operations finish ---
WasmAsyncResolvePromiseCallback;

// --- Callback for loading source map file for Wasm profiling support
WasmLoadSourceMapCallback;

// --- Callback for checking if WebAssembly imported strings are enabled ---
WasmImportedStringsEnabledCallback;

// --- Callback for checking if the SharedArrayBuffer constructor is enabled ---
SharedArrayBufferConstructorEnabledCallback;

// --- Callback for checking if the compile hints magic comments are enabled ---
JavaScriptCompileHintsMagicEnabledCallback;

// --- Callback for checking if WebAssembly JSPI is enabled ---
WasmJSPIEnabledCallback;

/**
 * Import phases in import requests.
 */
enum class ModuleImportPhase {};

/**
 * HostImportModuleDynamicallyCallback is called when we
 * require the embedder to load a module. This is used as part of the dynamic
 * import syntax.
 *
 * The referrer contains metadata about the script/module that calls
 * import.
 *
 * The specifier is the name of the module that should be imported.
 *
 * The import_attributes are import attributes for this request in the form:
 * [key1, value1, key2, value2, ...] where the keys and values are of type
 * v8::String. Note, unlike the FixedArray passed to ResolveModuleCallback and
 * returned from ModuleRequest::GetImportAttributes(), this array does not
 * contain the source Locations of the attributes.
 *
 * The embedder must compile, instantiate, evaluate the Module, and
 * obtain its namespace object.
 *
 * The Promise returned from this function is forwarded to userland
 * JavaScript. The embedder must resolve this promise with the module
 * namespace object. In case of an exception, the embedder must reject
 * this promise with the exception. If the promise creation itself
 * fails (e.g. due to stack overflow), the embedder must propagate
 * that exception by returning an empty MaybeLocal.
 */
HostImportModuleDynamicallyCallback;

/**
 * Callback for requesting a compile hint for a function from the embedder. The
 * first parameter is the position of the function in source code and the second
 * parameter is embedder data to be passed back.
 */
CompileHintCallback;

/**
 * HostInitializeImportMetaObjectCallback is called the first time import.meta
 * is accessed for a module. Subsequent access will reuse the same value.
 *
 * The method combines two implementation-defined abstract operations into one:
 * HostGetImportMetaProperties and HostFinalizeImportMeta.
 *
 * The embedder should use v8::Object::CreateDataProperty to add properties on
 * the meta object.
 */
HostInitializeImportMetaObjectCallback;

/**
 * HostCreateShadowRealmContextCallback is called each time a ShadowRealm is
 * being constructed in the initiator_context.
 *
 * The method combines Context creation and implementation defined abstract
 * operation HostInitializeShadowRealm into one.
 *
 * The embedder should use v8::Context::New or v8::Context:NewFromSnapshot to
 * create a new context. If the creation fails, the embedder must propagate
 * that exception by returning an empty MaybeLocal.
 */
HostCreateShadowRealmContextCallback;

/**
 * PrepareStackTraceCallback is called when the stack property of an error is
 * first accessed. The return value will be used as the stack value. If this
 * callback is registed, the |Error.prepareStackTrace| API will be disabled.
 * |sites| is an array of call sites, specified in
 * https://v8.dev/docs/stack-trace-api
 */
PrepareStackTraceCallback;

#if defined(V8_OS_WIN)
/**
 * Callback to selectively enable ETW tracing based on the document URL.
 * Implemented by the embedder, it should never call back into V8.
 *
 * Windows allows passing additional data to the ETW EnableCallback:
 * https://learn.microsoft.com/en-us/windows/win32/api/evntprov/nc-evntprov-penablecallback
 *
 * This data can be configured in a WPR (Windows Performance Recorder)
 * profile, adding a CustomFilter to an EventProvider like the following:
 *
 * <EventProvider Id=".." Name="57277741-3638-4A4B-BDBA-0AC6E45DA56C" Level="5">
 *   <CustomFilter Type="0x80000000" Value="AQABAAAAAAA..." />
 * </EventProvider>
 *
 * Where:
 * - Name="57277741-3638-4A4B-BDBA-0AC6E45DA56C" is the GUID of the V8
 *     ETW provider, (see src/libplatform/etw/etw-provider-win.h),
 * - Type="0x80000000" is EVENT_FILTER_TYPE_SCHEMATIZED,
 * - Value="AQABAAAAAA..." is a base64-encoded byte array that is
 *     base64-decoded by Windows and passed to the ETW enable callback in
 *     the 'PEVENT_FILTER_DESCRIPTOR FilterData' argument; see:
 * https://learn.microsoft.com/en-us/windows/win32/api/evntprov/ns-evntprov-event_filter_descriptor.
 *
 * This array contains a struct EVENT_FILTER_HEADER followed by a
 * variable length payload, and as payload we pass a string in JSON format,
 * with a list of regular expressions that should match the document URL
 * in order to enable ETW tracing:
 *   {
 *     "version": "1.0",
 *     "filtered_urls": [
 *         "https:\/\/.*\.chromium\.org\/.*", "https://v8.dev/";, "..."
 *     ]
 *  }
 */
using FilterETWSessionByURLCallback =
    bool (*)(Local<Context> context, const std::string& etw_filter_payload);
#endif  // V8_OS_WIN

}  // namespace v8

#endif  // INCLUDE_V8_ISOLATE_CALLBACKS_H_