Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/crates/wasi/tests/all/store.rs
3124 views
1
use tempfile::TempDir;
2
use wasmtime::Result;
3
use wasmtime::component::ResourceTable;
4
use wasmtime::{Engine, Store};
5
use wasmtime_wasi::{
6
DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe,
7
};
8
9
pub struct Ctx<T> {
10
stdout: MemoryOutputPipe,
11
stderr: MemoryOutputPipe,
12
pub wasi: T,
13
}
14
15
fn prepare_workspace(exe_name: &str) -> Result<TempDir> {
16
let prefix = format!("wasi_components_{exe_name}_");
17
let tempdir = tempfile::Builder::new().prefix(&prefix).tempdir()?;
18
Ok(tempdir)
19
}
20
21
impl<T> Ctx<T> {
22
pub fn new(
23
engine: &Engine,
24
name: &str,
25
configure: impl FnOnce(&mut WasiCtxBuilder) -> T,
26
) -> Result<(Store<Ctx<T>>, TempDir)> {
27
const MAX_OUTPUT_SIZE: usize = 10 << 20;
28
let stdout = MemoryOutputPipe::new(MAX_OUTPUT_SIZE);
29
let stderr = MemoryOutputPipe::new(MAX_OUTPUT_SIZE);
30
let workspace = prepare_workspace(name)?;
31
32
// Create our wasi context.
33
let mut builder = WasiCtxBuilder::new();
34
builder.stdout(stdout.clone()).stderr(stderr.clone());
35
36
builder
37
.args(&[name, "."])
38
.inherit_network()
39
.allow_ip_name_lookup(true);
40
println!("preopen: {workspace:?}");
41
builder.preopened_dir(workspace.path(), ".", DirPerms::all(), FilePerms::all())?;
42
for (var, val) in test_programs_artifacts::wasi_tests_environment() {
43
builder.env(var, val);
44
}
45
46
let supports_ipv6 = std::net::TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, 0)).is_ok();
47
if !supports_ipv6 {
48
builder.env("DISABLE_IPV6", "1");
49
}
50
51
let ctx = Ctx {
52
wasi: configure(&mut builder),
53
stderr,
54
stdout,
55
};
56
57
Ok((Store::new(&engine, ctx), workspace))
58
}
59
}
60
61
impl<T> Drop for Ctx<T> {
62
fn drop(&mut self) {
63
let stdout = self.stdout.contents();
64
if !stdout.is_empty() {
65
println!("[guest] stdout:\n{}\n===", String::from_utf8_lossy(&stdout));
66
}
67
let stderr = self.stderr.contents();
68
if !stderr.is_empty() {
69
println!("[guest] stderr:\n{}\n===", String::from_utf8_lossy(&stderr));
70
}
71
}
72
}
73
74
pub struct MyWasiCtx {
75
pub wasi: WasiCtx,
76
pub table: ResourceTable,
77
}
78
79
impl WasiView for Ctx<MyWasiCtx> {
80
fn ctx(&mut self) -> WasiCtxView<'_> {
81
WasiCtxView {
82
ctx: &mut self.wasi.wasi,
83
table: &mut self.wasi.table,
84
}
85
}
86
}
87
88