1
//! Engine configuration, module compilation and caching, and the plain i64 export call.
2

            
3
use std::collections::HashMap;
4
use std::sync::{Arc, Mutex};
5

            
6
use super::{EngineError, classify_runtime_error};
7

            
8
use 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)]
17
pub enum ProfilerStrategy {
18
    #[default]
19
    None,
20
    JitDump,
21
    PerfMap,
22
}
23

            
24
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25
pub struct EngineOpts {
26
    pub fuel: bool,
27
    pub profiler: ProfilerStrategy,
28
}
29

            
30
impl EngineOpts {
31
    #[must_use]
32
726013
    pub const fn baseline() -> Self {
33
726013
        Self {
34
726013
            fuel: false,
35
726013
            profiler: ProfilerStrategy::None,
36
726013
        }
37
726013
    }
38

            
39
    #[must_use]
40
331907
    pub const fn with_fuel(mut self) -> Self {
41
331907
        self.fuel = true;
42
331907
        self
43
331907
    }
44

            
45
    #[must_use]
46
352640
    pub const fn with_profiler(mut self, strategy: ProfilerStrategy) -> Self {
47
352640
        self.profiler = strategy;
48
352640
        self
49
352640
    }
50
}
51

            
52
impl Default for EngineOpts {
53
    fn default() -> Self {
54
        Self::baseline()
55
    }
56
}
57

            
58
726013
pub fn build_engine(opts: EngineOpts) -> Result<Engine, EngineError> {
59
726013
    let mut config = Config::new();
60
726013
    config.wasm_gc(true);
61
726013
    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
726013
    config.wasm_exceptions(true);
68
726013
    config.epoch_interruption(true);
69
726013
    if opts.fuel {
70
331907
        config.consume_fuel(true);
71
394106
    }
72
726013
    match opts.profiler {
73
725823
        ProfilerStrategy::None => {}
74
        ProfilerStrategy::JitDump => {
75
            config.profiler(wasmtime::ProfilingStrategy::JitDump);
76
        }
77
        ProfilerStrategy::PerfMap => {
78
190
            config.profiler(wasmtime::ProfilingStrategy::PerfMap);
79
        }
80
    }
81
726013
    Engine::new(&config).map_err(|e| EngineError::Config(e.to_string()))
82
726013
}
83

            
84
1149301
pub fn compile_module(engine: &Engine, bytes: &[u8]) -> Result<Module, EngineError> {
85
1149301
    Module::new(engine, bytes).map_err(|e| EngineError::Compile(e.to_string()))
86
1149301
}
87

            
88
971
pub fn compile_wat(engine: &Engine, source: &str) -> Result<Module, EngineError> {
89
971
    Module::new(engine, source).map_err(|e| EngineError::Compile(e.to_string()))
90
971
}
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)]
97
pub struct ModuleCache {
98
    inner: Arc<Mutex<HashMap<Vec<u8>, Module>>>,
99
}
100

            
101
impl ModuleCache {
102
    #[must_use]
103
702815
    pub fn new() -> Self {
104
702815
        Self::default()
105
702815
    }
106

            
107
2162203
    pub fn get_or_compile(&self, engine: &Engine, bytecode: &[u8]) -> Result<Module, EngineError> {
108
2162203
        if let Some(module) = self.lookup(bytecode)? {
109
1067801
            return Ok(module);
110
1094402
        }
111
1094402
        let module = compile_module(engine, bytecode)?;
112
1094022
        self.store(bytecode, module.clone())?;
113
1094022
        Ok(module)
114
2162203
    }
115

            
116
2162203
    fn lookup(&self, bytecode: &[u8]) -> Result<Option<Module>, EngineError> {
117
2162203
        let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
118
2162203
        Ok(guard.get(bytecode).cloned())
119
2162203
    }
120

            
121
1094022
    fn store(&self, bytecode: &[u8], module: Module) -> Result<(), EngineError> {
122
1094022
        let mut guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
123
1094022
        guard.insert(bytecode.to_vec(), module);
124
1094022
        Ok(())
125
1094022
    }
126

            
127
2
    pub fn is_empty(&self) -> Result<bool, EngineError> {
128
2
        let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
129
2
        Ok(guard.is_empty())
130
2
    }
131

            
132
1334
    pub fn len(&self) -> Result<usize, EngineError> {
133
1334
        let guard = self.inner.lock().map_err(|_| EngineError::CachePoisoned)?;
134
1334
        Ok(guard.len())
135
1334
    }
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`.
141
4
pub fn call_i64_export<T>(
142
4
    engine: &Engine,
143
4
    store: &mut Store<T>,
144
4
    module: &Module,
145
4
    export: &str,
146
4
) -> Result<i64, EngineError> {
147
4
    let linker = Linker::<T>::new(engine);
148
4
    let instance = linker
149
4
        .instantiate(&mut *store, module)
150
        .map_err(|e| classify_runtime_error(&e))?;
151
4
    let func = instance
152
4
        .get_typed_func::<(), i64>(&mut *store, export)
153
1
        .map_err(|_| EngineError::MissingExport(export.to_string()))?;
154
3
    func.call(&mut *store, ())
155
2
        .map_err(|e| classify_runtime_error(&e))
156
4
}