Path: blob/main/crates/wizer/tests/all/make_linker.rs
2459 views
use anyhow::{Context, Result, anyhow};1use wasmtime_wasi::WasiCtxBuilder;2use wasmtime_wizer::Wizer;3use wat::parse_str as wat_to_wasm;45async fn run_wasm(args: &[wasmtime::Val], expected: i32, wasm: &[u8]) -> Result<()> {6let _ = env_logger::try_init();78let mut config = wasmtime::Config::new();9config.async_support(true);10wasmtime::Cache::from_file(None)11.map(|cache| config.cache(Some(cache)))12.unwrap();13config.wasm_multi_memory(true);14config.wasm_multi_value(true);1516let engine = wasmtime::Engine::new(&config)?;17let wasi_ctx = WasiCtxBuilder::new().build_p1();18let mut store = wasmtime::Store::new(&engine, wasi_ctx);19let wasm = Wizer::new()20.run(&mut store, &wasm, async |store, module| {21let mut linker = wasmtime::Linker::new(module.engine());22linker.func_wrap("foo", "bar", |x: i32| x + 1)?;23linker.instantiate_async(store, module).await24})25.await?;26log::debug!(27"=== Wizened Wasm ==========================================================\n\28{}\n\29===========================================================================",30wasmprinter::print_bytes(&wasm).unwrap()31);32if log::log_enabled!(log::Level::Debug) {33std::fs::write("test.wasm", &wasm).unwrap();34}3536let wasi_ctx = WasiCtxBuilder::new().build_p1();37let mut store = wasmtime::Store::new(&engine, wasi_ctx);38let module =39wasmtime::Module::new(store.engine(), wasm).context("Wasm test case failed to compile")?;4041let mut linker = wasmtime::Linker::new(&engine);42linker.func_wrap("foo", "bar", |_: i32| -> Result<i32> {43Err(anyhow!("shouldn't be called"))44})?;4546let instance = linker.instantiate_async(&mut store, &module).await?;4748let run = instance49.get_func(&mut store, "run")50.ok_or_else(|| anyhow::anyhow!("the test Wasm module does not export a `run` function"))?;5152let mut actual = vec![wasmtime::Val::I32(0)];53run.call_async(&mut store, args, &mut actual).await?;54anyhow::ensure!(actual.len() == 1, "expected one result");55let actual = match actual[0] {56wasmtime::Val::I32(x) => x,57_ => anyhow::bail!("expected an i32 result"),58};59anyhow::ensure!(60expected == actual,61"expected `{expected}`, found `{actual}`",62);6364Ok(())65}6667async fn run_wat(args: &[wasmtime::Val], expected: i32, wat: &str) -> Result<()> {68let _ = env_logger::try_init();69let wasm = wat_to_wasm(wat)?;70run_wasm(args, expected, &wasm).await71}7273#[tokio::test]74async fn custom_linker() -> Result<()> {75run_wat(76&[],771,78r#"79(module80(type (func (param i32) (result i32)))81(import "foo" "bar" (func (type 0)))82(global $g (mut i32) (i32.const 0))83(func (export "wizer-initialize")84global.get $g85call 086global.set $g87)88(func (export "run") (result i32)89(global.get $g)90)91)"#,92)93.await94}959697