Lines
93.9 %
Functions
67.5 %
Branches
100 %
//! Engine configuration, module compilation and caching, and the plain i64 export call.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use super::{EngineError, classify_runtime_error};
use wasmtime::{Config, Engine, Linker, Module, Store};
/// Optional profiling strategy. JitDump is the Linux `perf record`
/// flow; it writes a `jit-<pid>.dump` file the OS-level profiler can
/// read. PerfMap is the simpler symbol-name-only Linux variant. Both
/// require the `wasmtime/profiling` cargo feature, which we pull in
/// via the `jitdump` feature flag on the scripting crate; non-Linux
/// builds should leave this as `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProfilerStrategy {
#[default]
None,
JitDump,
PerfMap,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EngineOpts {
pub fuel: bool,
pub profiler: ProfilerStrategy,
impl EngineOpts {
#[must_use]
pub const fn baseline() -> Self {
Self {
fuel: false,
profiler: ProfilerStrategy::None,
pub const fn with_fuel(mut self) -> Self {
self.fuel = true;
self
pub const fn with_profiler(mut self, strategy: ProfilerStrategy) -> Self {
self.profiler = strategy;
impl Default for EngineOpts {
fn default() -> Self {
Self::baseline()
pub fn build_engine(opts: EngineOpts) -> Result<Engine, EngineError> {
let mut config = Config::new();
config.wasm_gc(true);
config.wasm_function_references(true);
// Exception-handling proposal: `(error)` lowers to `throw $nomi_error`
// and `(handler-case)` / `(unwind-protect)` lower to `try_table`
// (Tier 3, ADR-0026). Engine traps (`OutOfFuel` / `EpochInterrupt`)
// are not wasm exceptions, so they bypass `try_table` and keep the
// per-Session deadline budget non-catchable.
config.wasm_exceptions(true);
config.epoch_interruption(true);
if opts.fuel {
config.consume_fuel(true);
match opts.profiler {
ProfilerStrategy::None => {}
ProfilerStrategy::JitDump => {
config.profiler(wasmtime::ProfilingStrategy::JitDump);
ProfilerStrategy::PerfMap => {
config.profiler(wasmtime::ProfilingStrategy::PerfMap);
Engine::new(&config).map_err(|e| EngineError::Config(e.to_string()))
pub fn compile_module(engine: &Engine, bytes: &[u8]) -> Result<Module, EngineError> {
Module::new(engine, bytes).map_err(|e| EngineError::Compile(e.to_string()))
pub fn compile_wat(engine: &Engine, source: &str) -> Result<Module, EngineError> {
Module::new(engine, source).map_err(|e| EngineError::Compile(e.to_string()))
/// Per-engine bytecode cache keyed by the full module bytes. Cloning a
/// [`ModuleCache`] yields a handle into the same inner map; meant to be
/// shared between long-lived hosts (Session, ScriptExecutor) and any per-form
/// helpers that need the same cached compilation.
#[derive(Debug, Default, Clone)]
pub struct ModuleCache {
inner: Arc<Mutex<HashMap<Vec<u8>, Module>>>,
impl ModuleCache {
pub fn new() -> Self {
Self::default()
pub fn get_or_compile(&self, engine: &Engine, bytecode: &[u8]) -> Result<Module, EngineError> {
if let Some(module) = self.lookup(bytecode)? {
return Ok(module);
let module = compile_module(engine, bytecode)?;
self.store(bytecode, module.clone())?;
Ok(module)
fn lookup(&self, bytecode: &[u8]) -> Result<Option<Module>, EngineError> {
let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
Ok(guard.get(bytecode).cloned())
fn store(&self, bytecode: &[u8], module: Module) -> Result<(), EngineError> {
let mut guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
guard.insert(bytecode.to_vec(), module);
Ok(())
pub fn is_empty(&self) -> Result<bool, EngineError> {
Ok(guard.is_empty())
pub fn len(&self) -> Result<usize, EngineError> {
Ok(guard.len())
/// Instantiates `module` against an empty linker and calls a zero-arg export
/// returning a single `i64`. Constraints (fuel cap, epoch deadline) come from
/// the caller-supplied `Store`.
pub fn call_i64_export<T>(
engine: &Engine,
store: &mut Store<T>,
module: &Module,
export: &str,
) -> Result<i64, EngineError> {
let linker = Linker::<T>::new(engine);
let instance = linker
.instantiate(&mut *store, module)
.map_err(|e| classify_runtime_error(&e))?;
let func = instance
.get_typed_func::<(), i64>(&mut *store, export)
.map_err(|_| EngineError::MissingExport(export.to_string()))?;
func.call(&mut *store, ())
.map_err(|e| classify_runtime_error(&e))