Skip to content

Truly independent web browser

11.6 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! Execution contexts, the execution context stack and the interpreter stack.
//!
//! A JSExecutionContext is the runtime's ExecutionContext. LibJS/Embedding/Layout.h gives the offset and size of each
//! of its fields as JS_LAYOUT_EXECUTION_CONTEXT_*, and its value slots, the arguments last, follow it directly. An
//! embedder reads and writes the fields there, among them the this value and the skip-when-determining-incumbent
//! counter. The realm and the ScriptOrModule of a context with a function come from the function: it reads the realm
//! of an ECMAScript function from its shape and that of another function with js_execution_context_realm(), and the
//! ScriptOrModule of an ECMAScript function from its shared data at
//! JS_LAYOUT_SHARED_FUNCTION_INSTANCE_DATA_SCRIPT_OR_MODULE_OFFSET. It also finds the running context at
//! JS_LAYOUT_VM_RUNNING_EXECUTION_CONTEXT_OFFSET in the VM, and with it the current realm and the arguments and this
//! value of the running code, without a call.
//!
//! Every function here must be called on the thread that runs the VM.

use core::ffi::c_void;
use core::ptr::NonNull;

use crate::bytecode::executable::Executable;
use crate::embedding::abi_types::{
    JSOwnedUtf16String, JSRealm, optional_cell_into_abi, owned_utf16_string_into_abi, vm_from_abi,
};
use crate::gc::capi::GCVisitor;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::execution_context::OwnedExecutionContext;
use crate::layout::execution_context::{ExecutionContext, ScriptOrModule, ScriptOrModuleSlot};
use crate::layout::host_class::JSVM;

/// An execution context, laid out as the JS_LAYOUT_EXECUTION_CONTEXT_* values of LibJS/Embedding/Layout.h describe.
pub struct JSExecutionContext {
    _opaque: [u8; 0],
}

/// A ScriptOrModule, laid out like the field of an execution context: zero for null, otherwise the pointer to the
/// Script or the Module, with JS_LAYOUT_SCRIPT_OR_MODULE_MODULE_BIT set for a module.
#[repr(transparent)]
pub struct JSScriptOrModule(u64);

const _: () = assert!(size_of::<JSScriptOrModule>() == size_of::<ScriptOrModuleSlot>());

/// # Safety
///
/// `script_or_module` must be empty or name a live Script or Module.
pub unsafe fn script_or_module_from_abi(script_or_module: JSScriptOrModule) -> ScriptOrModule {
    ScriptOrModuleSlot::from_word(script_or_module.0).get()
}

fn execution_context_from_abi(execution_context: *mut JSExecutionContext) -> NonNull<ExecutionContext> {
    NonNull::new(execution_context.cast()).expect("the embedder passes an execution context")
}

fn execution_context_to_abi(execution_context: Option<NonNull<ExecutionContext>>) -> *mut JSExecutionContext {
    execution_context.map_or(core::ptr::null_mut(), |execution_context| {
        execution_context.as_ptr().cast()
    })
}

/// ExecutionContext::create(): a new execution context with room for `registers_and_locals_count` registers and locals,
/// `constant_count` constants and `argument_count` arguments. The caller owns it and frees it with
/// js_execution_context_destroy(). Its argument slots are uninitialized, and the caller fills them before the context
/// is pushed or visited. The garbage collector only sees what the context holds while the context is on an execution
/// context stack, or when its owner visits it with js_execution_context_visit().
///
/// # Safety
///
/// Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_create(
    registers_and_locals_count: u32,
    constant_count: u32,
    argument_count: u32,
) -> *mut JSExecutionContext {
    let execution_context = OwnedExecutionContext::create(registers_and_locals_count, constant_count, argument_count);
    execution_context_to_abi(Some(execution_context.into_raw()))
}

/// ExecutionContext::copy(): a new execution context with the fields, the slot counts and the live slots of
/// `execution_context`, which the caller owns and frees with js_execution_context_destroy().
///
/// # Safety
///
/// `execution_context` must be a live execution context. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_copy(
    execution_context: *const JSExecutionContext,
) -> *mut JSExecutionContext {
    let execution_context = execution_context_from_abi(execution_context.cast_mut());
    // SAFETY: The caller passes a live execution context.
    let copy = unsafe { execution_context.as_ref() }.copy();
    execution_context_to_abi(Some(copy.into_raw()))
}

/// Frees an execution context that js_execution_context_create() or js_execution_context_copy() returned.
///
/// # Safety
///
/// `execution_context` must come from one of those functions, must not be freed already, and must not be on an
/// execution context stack, a saved one included. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_destroy(execution_context: *mut JSExecutionContext) {
    // SAFETY: The caller passes a context that one of the creating functions gave up ownership of.
    drop(unsafe { OwnedExecutionContext::from_raw(execution_context_from_abi(execution_context)) });
}

/// ExecutionContext::visit_edges(): visits every cell the execution context holds, as the owner of a context that
/// js_execution_context_create() or js_execution_context_copy() returned does from its own visit_edges().
///
/// # Safety
///
/// `execution_context` must be a live execution context, and `visitor` the visitor LibGC passed to the caller. Must be
/// called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_visit(
    execution_context: *const JSExecutionContext,
    visitor: *mut GCVisitor,
) {
    let execution_context = execution_context_from_abi(execution_context.cast_mut());
    // SAFETY: The caller passes the visitor LibGC is visiting with, which outlives this call.
    let mut visitor = unsafe { Visitor::from_raw(visitor) };
    // SAFETY: The caller passes a live execution context.
    unsafe { execution_context.as_ref() }.trace(&mut visitor);
}

/// InterpreterStack::allocate(): an execution context on the interpreter stack with room for
/// `registers_and_locals_count` registers and locals, `constant_count` constants and `argument_count` arguments, or
/// null if the stack is full. The context lives until js_execution_context_interpreter_stack_deallocate() is passed a
/// mark taken before it was allocated. Its argument slots are uninitialized, and the caller fills them before the
/// context is pushed.
///
/// # Safety
///
/// `vm` must be a live VM. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_interpreter_stack_allocate(
    vm: *mut JSVM,
    registers_and_locals_count: u32,
    constant_count: u32,
    argument_count: u32,
) -> *mut JSExecutionContext {
    // SAFETY: The caller passes a live VM.
    let vm = unsafe { vm_from_abi(vm) };
    execution_context_to_abi(vm.interpreter_stack().allocate(
        registers_and_locals_count,
        constant_count,
        argument_count,
    ))
}

/// InterpreterStack::deallocate(): frees every context allocated on the interpreter stack since `mark` was taken.
///
/// # Safety
///
/// `vm` must be a live VM, and `mark` a mark of the interpreter stack taken since, with none of the contexts it frees
/// on an execution context stack. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_interpreter_stack_deallocate(vm: *mut JSVM, mark: *mut c_void) {
    // SAFETY: The caller passes a live VM.
    let vm = unsafe { vm_from_abi(vm) };
    vm.interpreter_stack().deallocate(mark.cast());
}

/// VM::push_execution_context(): pushes `execution_context` onto the execution context stack, which makes it the
/// running execution context. The stack does not own it.
///
/// # Safety
///
/// `vm` must be a live VM, and `execution_context` a live execution context that stays live until it is popped. Must be
/// called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_push(vm: *mut JSVM, execution_context: *mut JSExecutionContext) {
    // SAFETY: The caller passes a live VM.
    let vm = unsafe { vm_from_abi(vm) };
    vm.push_execution_context(execution_context_from_abi(execution_context));
}

/// VM::save_execution_context_stack(): sets the execution context stack aside and leaves an empty one with nothing
/// running. The garbage collector keeps tracing the contexts on the saved stack until
/// js_execution_context_restore_stack() brings it back.
///
/// # Safety
///
/// `vm` must be a live VM. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_save_stack(vm: *mut JSVM) {
    // SAFETY: The caller passes a live VM.
    let vm = unsafe { vm_from_abi(vm) };
    vm.save_execution_context_stack();
}

/// VM::clear_execution_context_stack(): removes every context from the execution context stack.
///
/// # Safety
///
/// `vm` must be a live VM. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_clear_stack(vm: *mut JSVM) {
    // SAFETY: The caller passes a live VM.
    let vm = unsafe { vm_from_abi(vm) };
    vm.clear_execution_context_stack();
}

/// VM::restore_execution_context_stack(): replaces the execution context stack with the one the last unmatched
/// js_execution_context_save_stack() set aside.
///
/// # Safety
///
/// `vm` must be a live VM with a saved execution context stack. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_restore_stack(vm: *mut JSVM) {
    // SAFETY: The caller passes a live VM.
    let vm = unsafe { vm_from_abi(vm) };
    vm.restore_execution_context_stack();
}

/// ExecutionContext::realm(): the [[Realm]] of `execution_context`, or null. That of a context with a function is the
/// function's, and the field holds it only for a context without one.
///
/// # Safety
///
/// `execution_context` must be a live execution context. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_realm(execution_context: *const JSExecutionContext) -> *mut JSRealm {
    assert!(!execution_context.is_null(), "the embedder passes an execution context");
    // SAFETY: The caller passes a live execution context.
    let execution_context = unsafe { &*execution_context.cast::<ExecutionContext>() };
    optional_cell_into_abi::<JSRealm>(execution_context.realm())
}

/// ExecutionContext::function_name(): the name of the function whose bytecode the context runs, as an owned
/// AK::Utf16String the caller adopts with AK::Utf16String::adopt_raw(). It is empty for a context that runs no
/// bytecode, such as that of a native function, and for code that is not the body of a function.
///
/// # Safety
///
/// `execution_context` must be a live execution context. Must be called on the thread that runs the VM.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_execution_context_function_name(
    execution_context: *const JSExecutionContext,
) -> JSOwnedUtf16String {
    assert!(!execution_context.is_null(), "the embedder passes an execution context");
    // SAFETY: The caller passes a live execution context.
    let execution_context = unsafe { &*execution_context.cast::<ExecutionContext>() };
    let name = execution_context
        .executable
        .get()
        .map(|executable| Executable::from_head(executable).name())
        .unwrap_or_default();
    owned_utf16_string_into_abi(name.into())
}