File: wasmtime_sync.rs

package info (click to toggle)
rust-wasmtime 26.0.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 48,492 kB
  • sloc: ansic: 4,003; sh: 561; javascript: 542; cpp: 254; asm: 175; ml: 96; makefile: 55
file content (181 lines) | stat: -rw-r--r-- 5,419 bytes parent folder | download
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
use wasmtime::{Engine, Linker, Module, Store, Val};
use wiggle::GuestMemory;

wiggle::from_witx!({
    witx: ["$CARGO_MANIFEST_DIR/tests/atoms.witx"],
    block_on: {
        atoms::double_int_return_float
    }
});

pub struct Ctx;
impl wiggle::GuestErrorType for types::Errno {
    fn success() -> Self {
        types::Errno::Ok
    }
}

const TRIGGER_PENDING: u32 = 0;

#[wiggle::async_trait]
impl atoms::Atoms for Ctx {
    fn int_float_args(
        &mut self,
        _: &mut GuestMemory<'_>,
        an_int: u32,
        an_float: f32,
    ) -> Result<(), types::Errno> {
        println!("INT FLOAT ARGS: {an_int} {an_float}");
        Ok(())
    }
    async fn double_int_return_float(
        &mut self,
        _: &mut GuestMemory<'_>,
        an_int: u32,
    ) -> Result<types::AliasToFloat, types::Errno> {
        if an_int == TRIGGER_PENDING {
            // Define a Future that is pending forever. This is `futures::future::pending()`
            // without incurring the dep.
            use std::future::Future;
            use std::pin::Pin;
            use std::task::{Context, Poll};
            struct Pending;
            impl Future for Pending {
                type Output = ();
                fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
                    Poll::Pending
                }
            }
            // This await will pend, which should cause the dummy executor to Trap.
            Pending.await;
        }
        Ok((an_int as f32) * 2.0)
    }
}

#[test]
fn test_sync_host_func() {
    let engine = Engine::default();
    let mut linker = Linker::new(&engine);
    atoms::add_to_linker(&mut linker, |cx| cx).unwrap();
    let mut store = store(&engine);
    let shim_mod = shim_module(&engine);
    let shim_inst = linker.instantiate(&mut store, &shim_mod).unwrap();

    let mut results = [Val::I32(0)];
    shim_inst
        .get_func(&mut store, "int_float_args_shim")
        .unwrap()
        .call(&mut store, &[0i32.into(), 123.45f32.into()], &mut results)
        .unwrap();

    assert_eq!(
        results[0].unwrap_i32(),
        types::Errno::Ok as i32,
        "int_float_args errno"
    );
}

#[test]
fn test_async_host_func() {
    let engine = Engine::default();
    let mut linker = Linker::new(&engine);
    atoms::add_to_linker(&mut linker, |cx| cx).unwrap();
    let mut store = store(&engine);

    let shim_mod = shim_module(&engine);
    let shim_inst = linker.instantiate(&mut store, &shim_mod).unwrap();

    let input: i32 = 123;
    let result_location: i32 = 0;

    let mut results = [Val::I32(0)];
    shim_inst
        .get_func(&mut store, "double_int_return_float_shim")
        .unwrap()
        .call(
            &mut store,
            &[input.into(), result_location.into()],
            &mut results,
        )
        .unwrap();

    assert_eq!(
        results[0].unwrap_i32(),
        types::Errno::Ok as i32,
        "double_int_return_float errno"
    );

    // The actual result is in memory:
    let mem = shim_inst.get_memory(&mut store, "memory").unwrap();
    let mut result_bytes: [u8; 4] = [0, 0, 0, 0];
    mem.read(&store, result_location as usize, &mut result_bytes)
        .unwrap();
    let result = f32::from_le_bytes(result_bytes);
    assert_eq!((input * 2) as f32, result);
}

#[test]
fn test_async_host_func_pending() {
    let engine = Engine::default();
    let mut linker = Linker::new(&engine);
    atoms::add_to_linker(&mut linker, |cx| cx).unwrap();
    let mut store = store(&engine);

    let shim_mod = shim_module(&engine);
    let shim_inst = linker.instantiate(&mut store, &shim_mod).unwrap();

    let result_location: i32 = 0;

    // This input triggers the host func pending forever
    let input: i32 = TRIGGER_PENDING as i32;
    let trap = shim_inst
        .get_func(&mut store, "double_int_return_float_shim")
        .unwrap()
        .call(
            &mut store,
            &[input.into(), result_location.into()],
            &mut [Val::I32(0)],
        )
        .unwrap_err();
    assert!(
        format!("{trap:?}").contains("Cannot wait on pending future"),
        "expected get a pending future Trap from dummy executor, got: {trap}"
    );
}

fn store(engine: &Engine) -> Store<Ctx> {
    Store::new(engine, Ctx)
}

// Wiggle expects the caller to have an exported memory. Wasmtime can only
// provide this if the caller is a WebAssembly module, so we need to write
// a shim module:
fn shim_module(engine: &Engine) -> Module {
    Module::new(
        engine,
        r#"
        (module
            (import "atoms" "int_float_args" (func $int_float_args (param i32 f32) (result i32)))
            (import "atoms" "double_int_return_float" (func $double_int_return_float (param i32 i32) (result i32)))

            (memory 1)
            (export "memory" (memory 0))

            (func $int_float_args_shim (param i32 f32) (result i32)
                local.get 0
                local.get 1
                call $int_float_args
            )
            (func $double_int_return_float_shim (param i32 i32) (result i32)
                local.get 0
                local.get 1
                call $double_int_return_float
            )
            (export "int_float_args_shim" (func $int_float_args_shim))
            (export "double_int_return_float_shim" (func $double_int_return_float_shim))
        )
    "#,
    )
    .unwrap()
}