wasmi 0.36.0

WebAssembly interpreter
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Tests for the register-machine Wasmi engine translation implementation.

mod display_wasm;
pub mod driver;
mod fuzz;
mod op;
pub mod wasm_type;

use self::{
    display_wasm::DisplayWasm,
    driver::{ExpectedFunc, TranslationTest},
};
use crate::{
    core::UntypedVal,
    engine::bytecode::{AnyConst32, Const16, Const32, Instruction, Register},
    Config,
    Engine,
    Module,
};
use std::{fmt::Display, format};

/// Compiles the `wasm` encoded bytes into a [`Module`].
///
/// # Panics
///
/// If an error occurred upon module compilation, validation or translation.
fn create_module(config: &Config, bytes: &[u8]) -> Module {
    let engine = Engine::new(config);
    Module::new(&engine, bytes).unwrap()
}

/// Used to swap operands of a `rev` variant [`Instruction`] constructor.
macro_rules! swap_ops {
    ($fn_name:path) => {
        |result: Register, lhs: Const16<_>, rhs: Register| -> Instruction {
            $fn_name(result, rhs, lhs)
        }
    };
}
use swap_ops;

/// Asserts that the given `wasm` bytes yield functions with expected instructions.
///
/// Uses the given [`Config`] to configure the [`Engine`] that the tests are run on.
///
/// # Note
///
/// This enables the register machine bytecode translation.
///
/// # Panics
///
/// If any of the yielded functions consists of instruction different from the
/// expected instructions for that function.
fn assert_func_bodies<E, T>(wasm: &str, expected: E)
where
    E: IntoIterator<Item = T>,
    T: IntoIterator<Item = Instruction>,
    <T as IntoIterator>::IntoIter: ExactSizeIterator,
{
    let mut testcase = TranslationTest::from_wat(wasm);
    for instrs in expected {
        testcase.expect_func_instrs(instrs);
    }
    testcase.run();
}

/// Identifier for a Wasm operator.
///
/// # Note
///
/// This type is mainly used for test Wasm blob generation.
#[derive(Debug, Copy, Clone)]
pub enum WasmOp {
    /// For Wasm functions with signature: `fn(T, T) -> T`
    Binary { ty: WasmType, op: &'static str },
    /// For Wasm functions with signature: `fn(T, T) -> i32`
    Cmp { ty: WasmType, op: &'static str },
    /// For Wasm `load` instructions.
    Load { ty: WasmType, op: &'static str },
    /// For Wasm `store` instructions.
    Store { ty: WasmType, op: &'static str },
}

impl WasmOp {
    /// Create a new binary [`WasmOp`] for the given [`ValType`]: `fn(T, T) -> T`
    pub const fn binary(ty: WasmType, op: &'static str) -> Self {
        Self::Binary { ty, op }
    }

    /// Create a new compare [`WasmOp`] for the given [`ValType`]: `fn(T, T) -> i32`
    pub const fn cmp(ty: WasmType, op: &'static str) -> Self {
        Self::Cmp { ty, op }
    }

    /// Create a new `load` [`WasmOp`] for the given [`ValType`].
    pub const fn load(ty: WasmType, op: &'static str) -> Self {
        Self::Load { ty, op }
    }

    /// Create a new `store` [`WasmOp`] for the given [`ValType`].
    pub const fn store(ty: WasmType, op: &'static str) -> Self {
        Self::Store { ty, op }
    }

    /// Returns the parameter [`ValType`] of the [`WasmOp`].
    pub fn param_ty(&self) -> WasmType {
        match self {
            Self::Binary { ty, op: _ } => *ty,
            Self::Cmp { ty, op: _ } => *ty,
            Self::Load { .. } => panic!("load instructions have no parameters"),
            Self::Store { ty, op: _ } => *ty,
        }
    }

    /// Returns the result [`ValType`] of the [`WasmOp`].
    pub fn result_ty(&self) -> WasmType {
        match self {
            Self::Binary { ty, op: _ } => *ty,
            Self::Cmp { ty: _, op: _ } => WasmType::I32,
            Self::Load { ty, op: _ } => *ty,
            Self::Store { .. } => panic!("store instructions have no results"),
        }
    }

    /// Returns the display [`ValType`] of the [`WasmOp`].
    pub fn display_ty(&self) -> WasmType {
        match self {
            Self::Binary { .. } => self.param_ty(),
            Self::Cmp { .. } => self.param_ty(),
            Self::Load { .. } => self.result_ty(),
            Self::Store { .. } => self.param_ty(),
        }
    }

    /// Returns the operator identifier of the [`WasmOp`].
    pub fn op(&self) -> &'static str {
        match self {
            WasmOp::Binary { ty: _, op } => op,
            WasmOp::Cmp { ty: _, op } => op,
            WasmOp::Load { ty: _, op } => op,
            WasmOp::Store { ty: _, op } => op,
        }
    }
}

impl Display for WasmOp {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}.{}", self.display_ty(), self.op())
    }
}

/// A Wasm operator type.
///
/// # Note
///
/// This type is mainly used for test Wasm blob generation.
#[derive(Debug, Copy, Clone)]
pub enum WasmType {
    I32,
    I64,
    F32,
    F64,
}

impl Display for WasmType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::I32 => write!(f, "i32"),
            Self::I64 => write!(f, "i64"),
            Self::F32 => write!(f, "f32"),
            Self::F64 => write!(f, "f64"),
        }
    }
}

fn test_binary_reg_reg(
    wasm_op: WasmOp,
    make_instr: fn(result: Register, lhs: Register, rhs: Register) -> Instruction,
) {
    let param_ty = wasm_op.param_ty();
    let result_ty = wasm_op.result_ty();
    let wasm = format!(
        r#"
        (module
            (func (param {param_ty}) (param {param_ty}) (result {result_ty})
                local.get 0
                local.get 1
                {wasm_op}
            )
        )
    "#,
    );
    let expected = [
        make_instr(
            Register::from_i16(2),
            Register::from_i16(0),
            Register::from_i16(1),
        ),
        Instruction::return_reg(2),
    ];
    assert_func_bodies(&wasm, [expected]);
}

fn testcase_binary_reg_imm<T>(wasm_op: WasmOp, value: T) -> TranslationTest
where
    T: Copy,
    DisplayWasm<T>: Display,
{
    let param_ty = wasm_op.param_ty();
    let result_ty = wasm_op.result_ty();
    let display_value = DisplayWasm::from(value);
    let wasm = format!(
        r#"
        (module
            (func (param {param_ty}) (result {result_ty})
                local.get 0
                {param_ty}.const {display_value}
                {wasm_op}
            )
        )
    "#,
    );
    TranslationTest::from_wat(&wasm)
}

fn testcase_binary_imm_reg<T>(wasm_op: WasmOp, value: T) -> TranslationTest
where
    T: Copy,
    DisplayWasm<T>: Display,
{
    let param_ty = wasm_op.param_ty();
    let result_ty = wasm_op.result_ty();
    let display_value = DisplayWasm::from(value);
    let wasm = format!(
        r#"
        (module
            (func (param {param_ty}) (result {result_ty})
                {param_ty}.const {display_value}
                local.get 0
                {wasm_op}
            )
        )
    "#,
    );
    TranslationTest::from_wat(&wasm)
}

fn test_binary_reg_imm16<T>(
    wasm_op: WasmOp,
    value: T,
    make_instr: fn(result: Register, lhs: Register, rhs: Const16<T>) -> Instruction,
) where
    T: Copy + TryInto<Const16<T>>,
    DisplayWasm<T>: Display,
{
    let immediate: Const16<T> = value
        .try_into()
        .unwrap_or_else(|_| panic!("failed to convert {} to Const16", DisplayWasm::from(value)));
    let expected = [
        make_instr(Register::from_i16(1), Register::from_i16(0), immediate),
        Instruction::return_reg(1),
    ];
    test_binary_reg_imm_with(wasm_op, value, expected).run()
}

/// Variant of [`test_binary_reg_imm16`] where both operands are swapped.
fn test_binary_reg_imm16_rev<T>(
    wasm_op: WasmOp,
    value: T,
    make_instr: fn(result: Register, lhs: Const16<T>, rhs: Register) -> Instruction,
) where
    T: Copy + TryInto<Const16<T>>,
    DisplayWasm<T>: Display,
{
    let immediate: Const16<T> = value
        .try_into()
        .unwrap_or_else(|_| panic!("failed to convert {} to Const16", DisplayWasm::from(value)));
    let expected = [
        make_instr(Register::from_i16(1), immediate, Register::from_i16(0)),
        Instruction::return_reg(1),
    ];
    test_binary_reg_imm_rev_with(wasm_op, value, expected).run()
}

fn test_binary_reg_imm32<T>(
    wasm_op: WasmOp,
    value: T,
    make_instr: fn(result: Register, lhs: Register, rhs: Register) -> Instruction,
) where
    T: Copy + Into<UntypedVal>,
    DisplayWasm<T>: Display,
{
    let expected = [
        make_instr(
            Register::from_i16(1),
            Register::from_i16(0),
            Register::from_i16(-1),
        ),
        Instruction::return_reg(1),
    ];
    let mut testcase = testcase_binary_reg_imm(wasm_op, value);
    testcase.expect_func(ExpectedFunc::new(expected).consts([value.into()]));
    testcase.run()
}

/// Variant of [`test_binary_reg_imm32`] where both operands are swapped.
fn test_binary_reg_imm32_rev<T>(
    wasm_op: WasmOp,
    value: T,
    make_instr: fn(result: Register, lhs: Register, rhs: Register) -> Instruction,
) where
    T: Copy + Into<UntypedVal>,
    DisplayWasm<T>: Display,
{
    let expected = [
        make_instr(
            Register::from_i16(1),
            Register::from_i16(-1),
            Register::from_i16(0),
        ),
        Instruction::return_reg(1),
    ];
    let mut testcase = testcase_binary_imm_reg(wasm_op, value);
    testcase.expect_func(ExpectedFunc::new(expected).consts([value.into()]));
    testcase.run()
}

/// Variant of [`test_binary_reg_imm32`] where both operands are swapped.
fn test_binary_reg_imm32_rev_commutative<T>(
    wasm_op: WasmOp,
    value: T,
    make_instr: fn(result: Register, lhs: Register, rhs: Register) -> Instruction,
) where
    T: Copy + Into<UntypedVal>,
    DisplayWasm<T>: Display,
{
    let expected = [
        make_instr(
            Register::from_i16(1),
            Register::from_i16(0),
            Register::from_i16(-1),
        ),
        Instruction::return_reg(1),
    ];
    let mut testcase = testcase_binary_imm_reg(wasm_op, value);
    testcase.expect_func(ExpectedFunc::new(expected).consts([value.into()]));
    testcase.run()
}

fn test_binary_reg_imm_with<T, E>(wasm_op: WasmOp, value: T, expected: E) -> TranslationTest
where
    T: Copy,
    DisplayWasm<T>: Display,
    E: IntoIterator<Item = Instruction>,
    <E as IntoIterator>::IntoIter: ExactSizeIterator,
{
    let mut testcase = testcase_binary_reg_imm(wasm_op, value);
    testcase.expect_func_instrs(expected);
    testcase
}

fn test_binary_reg_imm_rev_with<T, E>(wasm_op: WasmOp, value: T, expected: E) -> TranslationTest
where
    T: Copy,
    DisplayWasm<T>: Display,
    E: IntoIterator<Item = Instruction>,
    <E as IntoIterator>::IntoIter: ExactSizeIterator,
{
    let mut testcase = testcase_binary_imm_reg(wasm_op, value);
    testcase.expect_func_instrs(expected);
    testcase
}

fn testcase_binary_consteval<T>(wasm_op: WasmOp, lhs: T, rhs: T) -> TranslationTest
where
    T: Copy,
    DisplayWasm<T>: Display,
{
    let param_ty = wasm_op.param_ty();
    let result_ty = wasm_op.result_ty();
    let display_lhs = DisplayWasm::from(lhs);
    let display_rhs = DisplayWasm::from(rhs);
    let wasm = format!(
        r#"
        (module
            (func (result {result_ty})
                {param_ty}.const {display_lhs}
                {param_ty}.const {display_rhs}
                {wasm_op}
            )
        )
    "#,
    );
    TranslationTest::from_wat(&wasm)
}

fn test_binary_consteval<T, E>(wasm_op: WasmOp, lhs: T, rhs: T, expected: E)
where
    T: Copy,
    DisplayWasm<T>: Display,
    E: IntoIterator<Item = Instruction>,
    <E as IntoIterator>::IntoIter: ExactSizeIterator,
{
    testcase_binary_consteval(wasm_op, lhs, rhs)
        .expect_func_instrs(expected)
        .run()
}

fn test_binary_same_reg<E>(wasm_op: WasmOp, expected: E)
where
    E: IntoIterator<Item = Instruction>,
    <E as IntoIterator>::IntoIter: ExactSizeIterator,
{
    let param_ty = wasm_op.param_ty();
    let result_ty = wasm_op.result_ty();
    let wasm = format!(
        r#"
        (module
            (func (param {param_ty}) (result {result_ty})
                local.get 0
                local.get 0
                {wasm_op}
            )
        )
    "#,
    );
    assert_func_bodies(&wasm, [expected]);
}