submilli-wasm 0.1.11

A WebAssembly interpreter with a wasmtime-compatible API, built for fast compilation and startup
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! `Config` — engine/runtime configuration (wasmtime-compatible builder).

use crate::module::ModuleLimits;

/// Global configuration for an [`crate::Engine`]. Builder methods return `&mut Self`.
#[allow(clippy::struct_excessive_bools)] // independent on/off knobs, mirroring `wasmtime::Config`
#[derive(Clone, Debug)]
pub struct Config {
    consume_fuel: bool,
    epoch_interruption: bool,
    max_wasm_stack: Option<usize>,
    collector: Collector,
    gc_memory_threshold: Option<usize>,
    gc_heap_reservation: u64,
    max_module_bytes: usize,
    max_expanded_locals: usize,
    async_support: bool,
    wasm_backtrace: bool,
    wasm_backtrace_details: WasmBacktraceDetails,
    debug_info: bool,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            consume_fuel: false,
            epoch_interruption: false,
            max_wasm_stack: None,
            collector: Collector::default(),
            gc_memory_threshold: None,
            // A small pre-authorized GC budget by default, so a typical store's early allocation
            // doesn't suspend to the limiter on every batch; growth beyond it is limiter-gated.
            // Set to 0 for a limiter-strict store (every grow consults the limiter).
            gc_heap_reservation: 256 * 1024,
            // The untrusted-tier module-size ceiling (#32); a finite default, never unbounded.
            max_module_bytes: crate::module::DEFAULT_MAX_MODULE_BYTES,
            max_expanded_locals: crate::module::DEFAULT_MAX_EXPANDED_LOCALS,
            // Enabled by default (unlike wasmtime, where it's opt-in): this interpreter is
            // fiber-less, so an async-enabled store runs sync calls just as well, and defaulting
            // on lets embedders use `call_async`/`fuel_async_yield_interval` without an explicit
            // `async_support(true)`. Call `async_support(false)` to disable the async-only APIs.
            async_support: true,
            // wasmtime defaults: backtraces on, DWARF detail from the environment, no debug info.
            wasm_backtrace: true,
            wasm_backtrace_details: WasmBacktraceDetails::default(),
            debug_info: false,
        }
    }
}

impl Config {
    /// Creates a configuration with default settings.
    pub fn new() -> Self {
        Config::default()
    }

    /// Enables fuel consumption (metering). Off by default.
    pub fn consume_fuel(&mut self, enable: bool) -> &mut Self {
        self.consume_fuel = enable;
        self
    }

    /// Whether fuel metering is enabled.
    pub(crate) fn consume_fuel_enabled(&self) -> bool {
        self.consume_fuel
    }

    /// Enables epoch-based interruption. Off by default.
    pub fn epoch_interruption(&mut self, enable: bool) -> &mut Self {
        self.epoch_interruption = enable;
        self
    }

    /// Whether epoch-based interruption is enabled.
    pub(crate) fn epoch_interruption_enabled(&self) -> bool {
        self.epoch_interruption
    }

    /// Sets the maximum wasm operand-stack size, in bytes.
    pub fn max_wasm_stack(&mut self, size: usize) -> &mut Self {
        self.max_wasm_stack = Some(size);
        self
    }

    /// The configured max wasm stack size in bytes, if set.
    pub(crate) fn max_wasm_stack_bytes(&self) -> Option<usize> {
        self.max_wasm_stack
    }

    /// Sets the default maximum module binary size, in **bytes**, that [`Module::new`] will
    /// compile on this engine — the **untrusted-tier** validation-time ceiling that bounds
    /// compiler memory against a hostile module before it ever executes (#32). Trusted/curated
    /// packages can raise it per-module via [`Module::new_with_limits`].
    ///
    /// **Additive deviation from wasmtime** — there is no analog in `wasmtime::Config`. The
    /// default is a finite ceiling (256 MiB, never unbounded), per the multi-tenant threat model.
    ///
    /// [`Module::new`]: crate::Module::new
    /// [`Module::new_with_limits`]: crate::Module::new_with_limits
    pub fn max_module_bytes(&mut self, bytes: usize) -> &mut Self {
        self.max_module_bytes = bytes;
        self
    }

    /// Sets the default maximum number of locals, summed over every function after run-length
    /// expansion, that [`Module::new`] will compile on this engine. `wasmparser` caps locals per
    /// function (50 000) but not per module, so without this a small module of many such
    /// functions could demand gigabytes from the compiler. Raised per-module for trusted packages
    /// via [`Module::new_with_limits`].
    ///
    /// **Additive deviation from wasmtime** — there is no analog in `wasmtime::Config`. The
    /// default is finite (8M locals; ~4× what a 256 MiB real-world module declares).
    ///
    /// [`Module::new`]: crate::Module::new
    /// [`Module::new_with_limits`]: crate::Module::new_with_limits
    pub fn max_expanded_locals(&mut self, locals: usize) -> &mut Self {
        self.max_expanded_locals = locals;
        self
    }

    /// The configured untrusted-tier module limits, as a [`ModuleLimits`].
    pub(crate) fn module_limits(&self) -> ModuleLimits {
        ModuleLimits {
            max_module_bytes: self.max_module_bytes,
            max_expanded_locals: self.max_expanded_locals,
        }
    }

    pub fn wasm_multi_value(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn wasm_tail_call(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn wasm_bulk_memory(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn wasm_reference_types(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn wasm_function_references(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn wasm_gc(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn wasm_exceptions(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn memory_reservation(&mut self, bytes: u64) -> &mut Self {
        self
    }

    pub fn memory_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
        self
    }

    pub fn memory_may_move(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn memory_init_cow(&mut self, enable: bool) -> &mut Self {
        self
    }

    pub fn memory_guard_size(&mut self, bytes: u64) -> &mut Self {
        self
    }

    /// The GC heap's **pre-authorized reservation** (bytes): the byte budget a store may grow its
    /// GC heap to **without consulting the `ResourceLimiter`** (the embedder has authorized it up
    /// front), and the cap on a single reservation-growth step. Growth beyond it is limiter-gated.
    /// Defaults to `0` (every grow consults the limiter). Unlike wasmtime this reserves a *budget*,
    /// not address space (we hold no mmap'd region).
    pub fn gc_heap_reservation(&mut self, bytes: u64) -> &mut Self {
        self.gc_heap_reservation = bytes;
        self
    }

    /// The configured GC-heap reservation in bytes (saturated to `usize`).
    pub(crate) fn gc_heap_reservation_bytes(&self) -> usize {
        usize::try_from(self.gc_heap_reservation).unwrap_or(usize::MAX)
    }

    pub fn gc_heap_guard_size(&mut self, bytes: u64) -> &mut Self {
        self
    }

    pub fn gc_heap_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
        self
    }

    pub fn gc_heap_may_move(&mut self, enable: bool) -> &mut Self {
        self
    }

    /// Accepted for wasmtime parity; this interpreter has no Cranelift backend so the
    /// optimization level has no effect (compilation is a single linear pre-decode pass).
    pub fn cranelift_opt_level(&mut self, level: OptLevel) -> &mut Self {
        self
    }

    /// Whether to capture a wasm backtrace on traps/exceptions. On by default. Also gates the
    /// cheap per-`Op` offset table + `name`-section retention used to symbolicate frames.
    pub fn wasm_backtrace(&mut self, enable: bool) -> &mut Self {
        self.wasm_backtrace = enable;
        self
    }

    /// Whether wasm backtraces carry DWARF file/line detail. Defaults to
    /// [`WasmBacktraceDetails::Environment`].
    pub fn wasm_backtrace_details(&mut self, enable: WasmBacktraceDetails) -> &mut Self {
        self.wasm_backtrace_details = enable;
        self
    }

    /// Whether to retain the module's DWARF debug info. Off by default. The native-debugger aspect
    /// is a no-op for an interpreter, but the retained DWARF symbolicates backtraces (ARCHITECTURE
    /// §16), so enabling this gives source-level frames regardless of `wasm_backtrace_details`.
    pub fn debug_info(&mut self, enable: bool) -> &mut Self {
        self.debug_info = enable;
        self
    }

    /// Whether backtrace capture is enabled (`Config::wasm_backtrace`).
    pub(crate) fn wasm_backtrace_enabled(&self) -> bool {
        self.wasm_backtrace
    }

    /// Whether DWARF debug info is retained (`Config::debug_info`).
    pub(crate) fn debug_info_enabled(&self) -> bool {
        self.debug_info
    }

    /// Whether backtraces should resolve DWARF file/line, resolving `Environment` against
    /// `WASMTIME_BACKTRACE_DETAILS` (`"1"` enables).
    pub(crate) fn wasm_backtrace_details_enabled(&self) -> bool {
        match self.wasm_backtrace_details {
            WasmBacktraceDetails::Enable => true,
            WasmBacktraceDetails::Disable => false,
            WasmBacktraceDetails::Environment => {
                std::env::var("WASMTIME_BACKTRACE_DETAILS").is_ok_and(|v| v == "1")
            }
        }
    }

    /// Engine-wide GC-pressure high-water mark, in bytes.
    ///
    /// **Additive deviation from wasmtime** — there is no analog in `wasmtime::Config`.
    /// When total committed GC bytes across all stores of the engine cross this value,
    /// the engine requests collection from its stores (checked at the fuel/epoch
    /// back-edge safe point). Defaults to ~80% of detected physical RAM if unset.
    /// See `docs/ARCHITECTURE.md` §14.
    pub fn gc_memory_threshold(&mut self, bytes: usize) -> &mut Self {
        self.gc_memory_threshold = Some(bytes);
        self
    }

    pub fn collector(&mut self, collector: Collector) -> &mut Self {
        self.collector = collector;
        self
    }

    /// The selected garbage collector (resolved to the internal strategy by `Engine::new`).
    pub(crate) fn collector_kind(&self) -> Collector {
        self.collector
    }

    /// The configured engine-wide GC-pressure threshold in bytes, if set.
    pub(crate) fn gc_memory_threshold_bytes(&self) -> Option<usize> {
        self.gc_memory_threshold
    }

    /// Enables async execution (`Func::call_async`, async host fns, yields).
    /// Off by default. Once enabled, the sync entry points reject this store.
    #[cfg(feature = "async")]
    pub fn async_support(&mut self, enable: bool) -> &mut Self {
        self.async_support = enable;
        self
    }

    /// Whether async support is enabled (`Config::async_support`).
    pub(crate) fn async_support_enabled(&self) -> bool {
        self.async_support
    }

    /// Accepted for wasmtime API parity but a **no-op** for this interpreter:
    /// suspend/resume is just parking the `Execution` state machine (no native
    /// fiber stack to size — see ARCHITECTURE §2.4), so there is no async stack.
    #[cfg(feature = "async")]
    pub fn async_stack_size(&mut self, size: usize) -> &mut Self {
        self
    }
}

/// Garbage-collector selection, mostly mirroring `wasmtime::Collector`.
///
/// Our interpreter implements a single tracing strategy — non-moving stop-the-world
/// **mark-sweep**. `Auto` selects it; `Null` stays allocate-only (matching wasmtime). The
/// extra [`Collector::MarkSweep`] variant names that strategy explicitly (it has no wasmtime
/// analog — naming it keeps us a superset, so drop-in embedder code, which never references it,
/// still compiles). The two collectors we do **not** implement —
/// [`Collector::DeferredReferenceCounting`] and [`Collector::Copying`] — are **rejected** at
/// [`Engine::new`](crate::Engine::new), the same way wasmtime errors when a selected collector is
/// unavailable. See `docs/ARCHITECTURE.md` §14.
#[non_exhaustive]
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
pub enum Collector {
    /// Automatically select a collector — resolves to non-moving mark-sweep here.
    #[default]
    Auto,
    /// Deferred reference counting — **not implemented** (rejected at `Engine::new`).
    DeferredReferenceCounting,
    /// Allocate-only: never reclaims, traps on heap exhaustion.
    Null,
    /// Copying collector — **not implemented** (rejected at `Engine::new`).
    Copying,
    /// Non-moving stop-the-world mark-sweep (our own variant; no wasmtime analog).
    MarkSweep,
}

/// The internal collector strategy actually run, resolved from the public [`Collector`] at
/// `Engine::new`. Two-way so the heap/run loop switch on it without re-deriving from the
/// (`#[non_exhaustive]`, partly-rejected) public enum.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub(crate) enum CollectorKind {
    /// Allocate-only; reclaims nothing (`Collector::Null`).
    Null,
    /// Non-moving stop-the-world mark-sweep (`Collector::Auto`/`MarkSweep`).
    MarkSweep,
}

impl Collector {
    /// Resolves the public selection to the internal strategy, **rejecting** the collectors we
    /// don't implement (wasmtime likewise errors at `Engine::new` for an unavailable collector).
    pub(crate) fn resolve(self) -> crate::Result<CollectorKind> {
        match self {
            Collector::Auto | Collector::MarkSweep => Ok(CollectorKind::MarkSweep),
            Collector::Null => Ok(CollectorKind::Null),
            Collector::DeferredReferenceCounting => Err(crate::Error::msg(
                "the deferred reference-counting collector is not supported \
                 (use Collector::Auto, Collector::MarkSweep, or Collector::Null)",
            )),
            Collector::Copying => Err(crate::Error::msg(
                "the copying collector is not supported \
                 (use Collector::Auto, Collector::MarkSweep, or Collector::Null)",
            )),
        }
    }
}

/// Cranelift optimization level, mirroring `wasmtime::OptLevel`. Accepted for API
/// parity only — this interpreter has no optimizing backend, so all variants behave
/// identically (see [`Config::cranelift_opt_level`]).
#[non_exhaustive]
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
pub enum OptLevel {
    #[default]
    None,
    Speed,
    SpeedAndSize,
}

/// Whether captured backtraces carry DWARF file/line detail, mirroring
/// `wasmtime::WasmBacktraceDetails`. `Environment` (the default) reads the
/// `WASMTIME_BACKTRACE_DETAILS` env var (`"1"` enables).
#[non_exhaustive]
#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
pub enum WasmBacktraceDetails {
    Enable,
    Disable,
    #[default]
    Environment,
}

#[cfg(test)]
mod tests {
    use super::{Config, WasmBacktraceDetails};

    #[test]
    fn backtrace_knob_defaults() {
        let c = Config::new();
        assert!(c.wasm_backtrace_enabled(), "backtrace on by default");
        assert!(!c.debug_info_enabled(), "debug_info off by default");
    }

    #[test]
    fn details_enable_disable_resolve_without_env() {
        assert!(Config::new()
            .wasm_backtrace_details(WasmBacktraceDetails::Enable)
            .wasm_backtrace_details_enabled());
        assert!(!Config::new()
            .wasm_backtrace_details(WasmBacktraceDetails::Disable)
            .wasm_backtrace_details_enabled());
    }

    #[test]
    fn knobs_round_trip() {
        let mut c = Config::new();
        c.wasm_backtrace(false).debug_info(true);
        assert!(!c.wasm_backtrace_enabled());
        assert!(c.debug_info_enabled());
    }
}