Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/crates/wasi/tests/all/store.rs
1693 views
1
use anyhow::Result;
2
use tempfile::TempDir;
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 ctx = Ctx {
47
wasi: configure(&mut builder),
48
stderr,
49
stdout,
50
};
51
52
Ok((Store::new(&engine, ctx), workspace))
53
}
54
}
55
56
impl<T> Drop for Ctx<T> {
57
fn drop(&mut self) {
58
let stdout = self.stdout.contents();
59
if !stdout.is_empty() {
60
println!("[guest] stdout:\n{}\n===", String::from_utf8_lossy(&stdout));
61
}
62
let stderr = self.stderr.contents();
63
if !stderr.is_empty() {
64
println!("[guest] stderr:\n{}\n===", String::from_utf8_lossy(&stderr));
65
}
66
}
67
}
68
69
pub struct MyWasiCtx {
70
pub wasi: WasiCtx,
71
pub table: ResourceTable,
72
}
73
74
impl WasiView for Ctx<MyWasiCtx> {
75
fn ctx(&mut self) -> WasiCtxView<'_> {
76
WasiCtxView {
77
ctx: &mut self.wasi.wasi,
78
table: &mut self.wasi.table,
79
}
80
}
81
}
82
83