Path: blob/main/crates/wasi-nn/tests/exec/witx.rs
1693 views
use super::PREOPENED_DIR_NAME;1use crate::check::artifacts_dir;2use anyhow::Result;3use std::path::Path;4use wasmtime::{Config, Engine, Linker, Module, Store};5use wasmtime_wasi::p1::WasiP1Ctx;6use wasmtime_wasi::{DirPerms, FilePerms, WasiCtxBuilder};7use wasmtime_wasi_nn::{Backend, InMemoryRegistry, witx::WasiNnCtx};89/// Run a wasi-nn test program. This is modeled after10/// `crates/wasi/tests/all/main.rs` but still uses the older p1 API11/// for file reads.12pub fn run(path: &str, backend: Backend, preload_model: bool) -> Result<()> {13let path = Path::new(path);14let engine = Engine::new(&Config::new())?;15let mut linker = Linker::new(&engine);16wasmtime_wasi_nn::witx::add_to_linker(&mut linker, |s: &mut Ctx| &mut s.wasi_nn)?;17wasmtime_wasi::p1::add_to_linker_sync(&mut linker, |s: &mut Ctx| &mut s.wasi)?;18let module = Module::from_file(&engine, path)?;19let mut store = Store::new(&engine, Ctx::new(&artifacts_dir(), preload_model, backend)?);20let instance = linker.instantiate(&mut store, &module)?;21let start = instance.get_typed_func::<(), ()>(&mut store, "_start")?;22start.call(&mut store, ())?;23Ok(())24}2526/// The host state for running wasi-nn tests.27struct Ctx {28wasi: WasiP1Ctx,29wasi_nn: WasiNnCtx,30}3132impl Ctx {33fn new(preopen_dir: &Path, preload_model: bool, mut backend: Backend) -> Result<Self> {34let mut builder = WasiCtxBuilder::new();35builder.inherit_stdio().preopened_dir(36preopen_dir,37PREOPENED_DIR_NAME,38DirPerms::READ,39FilePerms::READ,40)?;41let wasi = builder.build_p1();4243let mut registry = InMemoryRegistry::new();44let mobilenet_dir = artifacts_dir();45if preload_model {46registry.load((backend).as_dir_loadable().unwrap(), &mobilenet_dir)?;47}48let wasi_nn = WasiNnCtx::new([backend], registry.into());4950Ok(Self { wasi, wasi_nn })51}52}535455