Skip to main content

scripting/runtime/
engine.rs

1//! Engine configuration, module compilation and caching, and the plain i64 export call.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6use super::{EngineError, classify_runtime_error};
7
8use wasmtime::{Config, Engine, Linker, Module, Store};
9
10/// Optional profiling strategy. JitDump is the Linux `perf record`
11/// flow; it writes a `jit-<pid>.dump` file the OS-level profiler can
12/// read. PerfMap is the simpler symbol-name-only Linux variant. Both
13/// require the `wasmtime/profiling` cargo feature, which we pull in
14/// via the `jitdump` feature flag on the scripting crate; non-Linux
15/// builds should leave this as `None`.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum ProfilerStrategy {
18    #[default]
19    None,
20    JitDump,
21    PerfMap,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct EngineOpts {
26    pub fuel: bool,
27    pub profiler: ProfilerStrategy,
28}
29
30impl EngineOpts {
31    #[must_use]
32    pub const fn baseline() -> Self {
33        Self {
34            fuel: false,
35            profiler: ProfilerStrategy::None,
36        }
37    }
38
39    #[must_use]
40    pub const fn with_fuel(mut self) -> Self {
41        self.fuel = true;
42        self
43    }
44
45    #[must_use]
46    pub const fn with_profiler(mut self, strategy: ProfilerStrategy) -> Self {
47        self.profiler = strategy;
48        self
49    }
50}
51
52impl Default for EngineOpts {
53    fn default() -> Self {
54        Self::baseline()
55    }
56}
57
58pub fn build_engine(opts: EngineOpts) -> Result<Engine, EngineError> {
59    let mut config = Config::new();
60    config.wasm_gc(true);
61    config.wasm_function_references(true);
62    // Exception-handling proposal: `(error)` lowers to `throw $nomi_error`
63    // and `(handler-case)` / `(unwind-protect)` lower to `try_table`
64    // (Tier 3, ADR-0026). Engine traps (`OutOfFuel` / `EpochInterrupt`)
65    // are not wasm exceptions, so they bypass `try_table` and keep the
66    // per-Session deadline budget non-catchable.
67    config.wasm_exceptions(true);
68    config.epoch_interruption(true);
69    if opts.fuel {
70        config.consume_fuel(true);
71    }
72    match opts.profiler {
73        ProfilerStrategy::None => {}
74        ProfilerStrategy::JitDump => {
75            config.profiler(wasmtime::ProfilingStrategy::JitDump);
76        }
77        ProfilerStrategy::PerfMap => {
78            config.profiler(wasmtime::ProfilingStrategy::PerfMap);
79        }
80    }
81    Engine::new(&config).map_err(|e| EngineError::Config(e.to_string()))
82}
83
84pub fn compile_module(engine: &Engine, bytes: &[u8]) -> Result<Module, EngineError> {
85    Module::new(engine, bytes).map_err(|e| EngineError::Compile(e.to_string()))
86}
87
88pub fn compile_wat(engine: &Engine, source: &str) -> Result<Module, EngineError> {
89    Module::new(engine, source).map_err(|e| EngineError::Compile(e.to_string()))
90}
91
92/// Per-engine bytecode cache keyed by the full module bytes. Cloning a
93/// [`ModuleCache`] yields a handle into the same inner map; meant to be
94/// shared between long-lived hosts (Session, ScriptExecutor) and any per-form
95/// helpers that need the same cached compilation.
96#[derive(Debug, Default, Clone)]
97pub struct ModuleCache {
98    inner: Arc<Mutex<HashMap<Vec<u8>, Module>>>,
99}
100
101impl ModuleCache {
102    #[must_use]
103    pub fn new() -> Self {
104        Self::default()
105    }
106
107    pub fn get_or_compile(&self, engine: &Engine, bytecode: &[u8]) -> Result<Module, EngineError> {
108        if let Some(module) = self.lookup(bytecode)? {
109            return Ok(module);
110        }
111        let module = compile_module(engine, bytecode)?;
112        self.store(bytecode, module.clone())?;
113        Ok(module)
114    }
115
116    fn lookup(&self, bytecode: &[u8]) -> Result<Option<Module>, EngineError> {
117        let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
118        Ok(guard.get(bytecode).cloned())
119    }
120
121    fn store(&self, bytecode: &[u8], module: Module) -> Result<(), EngineError> {
122        let mut guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
123        guard.insert(bytecode.to_vec(), module);
124        Ok(())
125    }
126
127    pub fn is_empty(&self) -> Result<bool, EngineError> {
128        let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
129        Ok(guard.is_empty())
130    }
131
132    pub fn len(&self) -> Result<usize, EngineError> {
133        let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
134        Ok(guard.len())
135    }
136}
137
138/// Instantiates `module` against an empty linker and calls a zero-arg export
139/// returning a single `i64`. Constraints (fuel cap, epoch deadline) come from
140/// the caller-supplied `Store`.
141pub fn call_i64_export<T>(
142    engine: &Engine,
143    store: &mut Store<T>,
144    module: &Module,
145    export: &str,
146) -> Result<i64, EngineError> {
147    let linker = Linker::<T>::new(engine);
148    let instance = linker
149        .instantiate(&mut *store, module)
150        .map_err(|e| classify_runtime_error(&e))?;
151    let func = instance
152        .get_typed_func::<(), i64>(&mut *store, export)
153        .map_err(|_| EngineError::MissingExport(export.to_string()))?;
154    func.call(&mut *store, ())
155        .map_err(|e| classify_runtime_error(&e))
156}