Path: blob/main/crates/wasi/tests/all/store.rs
3124 views
use tempfile::TempDir;1use wasmtime::Result;2use wasmtime::component::ResourceTable;3use wasmtime::{Engine, Store};4use wasmtime_wasi::{5DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe,6};78pub struct Ctx<T> {9stdout: MemoryOutputPipe,10stderr: MemoryOutputPipe,11pub wasi: T,12}1314fn prepare_workspace(exe_name: &str) -> Result<TempDir> {15let prefix = format!("wasi_components_{exe_name}_");16let tempdir = tempfile::Builder::new().prefix(&prefix).tempdir()?;17Ok(tempdir)18}1920impl<T> Ctx<T> {21pub fn new(22engine: &Engine,23name: &str,24configure: impl FnOnce(&mut WasiCtxBuilder) -> T,25) -> Result<(Store<Ctx<T>>, TempDir)> {26const MAX_OUTPUT_SIZE: usize = 10 << 20;27let stdout = MemoryOutputPipe::new(MAX_OUTPUT_SIZE);28let stderr = MemoryOutputPipe::new(MAX_OUTPUT_SIZE);29let workspace = prepare_workspace(name)?;3031// Create our wasi context.32let mut builder = WasiCtxBuilder::new();33builder.stdout(stdout.clone()).stderr(stderr.clone());3435builder36.args(&[name, "."])37.inherit_network()38.allow_ip_name_lookup(true);39println!("preopen: {workspace:?}");40builder.preopened_dir(workspace.path(), ".", DirPerms::all(), FilePerms::all())?;41for (var, val) in test_programs_artifacts::wasi_tests_environment() {42builder.env(var, val);43}4445let supports_ipv6 = std::net::TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, 0)).is_ok();46if !supports_ipv6 {47builder.env("DISABLE_IPV6", "1");48}4950let ctx = Ctx {51wasi: configure(&mut builder),52stderr,53stdout,54};5556Ok((Store::new(&engine, ctx), workspace))57}58}5960impl<T> Drop for Ctx<T> {61fn drop(&mut self) {62let stdout = self.stdout.contents();63if !stdout.is_empty() {64println!("[guest] stdout:\n{}\n===", String::from_utf8_lossy(&stdout));65}66let stderr = self.stderr.contents();67if !stderr.is_empty() {68println!("[guest] stderr:\n{}\n===", String::from_utf8_lossy(&stderr));69}70}71}7273pub struct MyWasiCtx {74pub wasi: WasiCtx,75pub table: ResourceTable,76}7778impl WasiView for Ctx<MyWasiCtx> {79fn ctx(&mut self) -> WasiCtxView<'_> {80WasiCtxView {81ctx: &mut self.wasi.wasi,82table: &mut self.wasi.table,83}84}85}868788