Coverage Report

Created: 2026-10-19 09:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/src/lib.rs
Line
Count
Source
1
//! An in-place interpreter for WebAssembly 2.0
2
//!
3
//! # General Usage
4
//!
5
//! WebAssembly (Wasm) modules must first be decoded and validated through [`decode_and_validate`],
6
//! producing a [`Module`]. This module can then be instantiated in a [`Store`] via
7
//! [`Store::module_instantiate`], creating a module instance and returning its module address,
8
//! uniquely identifying this module instance within that store.
9
//!
10
//! When a [`Store`] is initially created through [`Store::new`], it is empty. This store exposes
11
//! many other functions besides module instantiation to interact with it and objects allocated
12
//! within it. Most notably, the [`Store::invoke_simple`] and [`Store::invoke`] methods are used to
13
//! interpret Wasm code. Refer to the examples in `examples/` for more information.
14
//!
15
//! # Example
16
//!
17
//! This is an example for how to run a function exposed from a simple Wasm module (full code in
18
//! `examples/function_invocation.rs`):
19
//!
20
//! ```
21
//! # use dlr_wasm_interpreter::{BytecodeProvider, ExternVal, FuncAddr, InstantiationOutcome, Module, Store, Value, decode_and_validate};
22
//!struct SingleBytecodeRef<'a>(&'a [u8]);
23
//! impl BytecodeProvider for SingleBytecodeRef<'_> {
24
//!    fn get_bytecode(&self, _id: usize) -> &[u8] {
25
//!        self.0
26
//!    }
27
//!}
28
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
29
//! const WAT_CODE: &str = r#"
30
//! (module
31
//!     (func (export "add_one") (param $n i32) (result i32)
32
//!         local.get $n
33
//!         i32.const 1
34
//!         i32.add))
35
//! "#;
36
//!
37
//! // Use the `wat` crate to convert from the text format to bytecode
38
//! let wasm_bytecode = wat::parse_str(WAT_CODE)?;
39
//!
40
//! // Decode and validate the module
41
//! let module = decode_and_validate(&wasm_bytecode, &mut ())?;
42
//!
43
//! // Create a new empty store
44
//! let mut store = Store::new(());
45
//!
46
//! let bytecode_provider = SingleBytecodeRef(&wasm_bytecode);
47
//! // Instantiate the module to create a module instance, returning its address
48
//! // SAFETY:
49
//! // 1. There are no extern values.
50
//! // 2. `bytecode_provider` always returns the same bytecode, which is associated with this
51
//! //    module.
52
//! // 3. There are no previous instantiations.
53
//! let module_addr = unsafe { store.module_instantiate(&module, 0, vec![], None, &bytecode_provider) }?.module_addr;
54
//!
55
//! // Get the function address of the exported add_one function
56
//! // SAFETY:
57
//! // 1. The module address was returned from the same store.
58
//! // 2. `bytecode_provider` is unchanged.
59
//! let add_one_extern = unsafe { store.instance_export(module_addr, "add_one", &bytecode_provider) }?;
60
//! let add_one = add_one_extern.as_func().ok_or("add_one is not a function")?;
61
//!
62
//! // Invoke the function
63
//! // SAFETY:
64
//! // 1. The function address was returned from the same store. There are also no address
65
//! //    type parameters.
66
//! // 2. `bytecode_provider` is unchanged.
67
//! let return_values = unsafe { store.invoke_simple(add_one, vec![Value::I32(16)], &bytecode_provider) }?;
68
//! assert_eq!(*return_values, [Value::I32(17)]);
69
//! # Ok(())
70
//! # }
71
//! ```
72
73
#![no_std]
74
#![cfg_attr(
75
    feature = "nightly",
76
    expect(incomplete_features),
77
    feature(explicit_tail_calls),
78
    feature(rust_preserve_none_cc)
79
)]
80
81
extern crate alloc;
82
83
pub use crate::{
84
    core::{
85
        decoding::{error::DecodingError, modules::custom_section::CustomSection},
86
        rw_spinlock,
87
        structure::instructions,
88
        structure::modules::{exports::Export, imports::Import},
89
        structure::types::{
90
            ExternType, FuncType, GlobalType, Limits, MemType, NumType, RefType, ResultType,
91
            TableType, ValType,
92
        },
93
        utils::BytecodeProvider,
94
    },
95
    execution::{
96
        config::{Config, stack_memory_bytes_total},
97
        error::{RuntimeError, TrapError},
98
        instructions::dispatch::DispatchMechanism,
99
        resumable::*,
100
        runtime_structure::{
101
            addresses::*,
102
            external_values::ExternVal,
103
            memory_instances::shared_linear_memory::{Ordering, SharedLinearMemory},
104
            store::{Hostcode, InstantiationOutcome, Store},
105
            values::{ExternAddr, F32, F64, Ref, Value, ValueTypeMismatchError},
106
        },
107
    },
108
    validation::{Module, config::ValidationConfig, decode_and_validate, error::ValidationError},
109
};
110
111
pub(crate) mod core;
112
pub(crate) mod execution;
113
pub(crate) mod validation;
114
115
/// A definition for a [`Result`] using the optional [`Error`] type.
116
pub type Result<T> = ::core::result::Result<T, Error>;
117
118
/// An opt-in error type useful for merging all error types of this crate into a single type.
119
///
120
/// Note: This crate does not use this type in any public interfaces, making it optional for downstream users.
121
#[derive(Debug, PartialEq, Eq)]
122
pub enum Error {
123
    Validation(ValidationError),
124
    RuntimeError(RuntimeError),
125
}
126
127
impl From<ValidationError> for Error {
128
1
    fn from(value: ValidationError) -> Self {
129
1
        Self::Validation(value)
130
1
    }
131
}
132
133
impl From<RuntimeError> for Error {
134
1
    fn from(value: RuntimeError) -> Self {
135
1
        Self::RuntimeError(value)
136
1
    }
137
}
138
139
#[cfg(test)]
140
mod test {
141
    use crate::{Error, RuntimeError, ValidationError, core::decoding::error::DecodingError};
142
143
    #[test]
144
1
    fn error_conversion_validation_error() {
145
1
        let validation_error = ValidationError::Decoding(DecodingError::InvalidMagic);
146
1
        let error: Error = validation_error.into();
147
148
1
        assert_eq!(
149
            error,
150
            Error::Validation(ValidationError::Decoding(DecodingError::InvalidMagic))
151
        )
152
1
    }
153
154
    #[test]
155
1
    fn error_conversion_runtime_error() {
156
1
        let runtime_error = RuntimeError::ModuleNotFound;
157
1
        let error: Error = runtime_error.into();
158
159
1
        assert_eq!(error, Error::RuntimeError(RuntimeError::ModuleNotFound))
160
1
    }
161
}