If you're reading this in the future because you had the same issue as me, the solution is that WASI p2 requires that you drop some objects in a certain order (in the guest):
drop(in_stream);
drop(out_stream);
drop(socket);You also need to drop the pollable objects before their respective streams.
So if you do:
let pollable = in_stream.subscribe();Then you have to drop that pollable object before the in_stream.
Minimal demo code that causes wasmtime WASI sockets code to crash.
cargo build --package host
cargo build --package guest --target wasm32-wasip2
First run a netcat listener on port 8080:
nc -l 127.0.0.1 8080
Then run the host.
./target/debug/host
It will load the guest Wasm in at runtime, which will connect over TCP to the netcat listener. It should look like this:
Hello, world! From the guest Wasm module.
Connected to server!
Once connected, quit out of the netcat listener with CTRL-C and you'll see this from the host binary:
Received data: Err(StreamError::Closed)
Received data: Err(StreamError::Closed)
finished run function
guest error: Some(error while executing at wasm backtrace:
0: 0x4a18 - guest-7a94999886812cfa.wasm!<wasi::bindings::wasi::sockets::tcp::TcpSocket as wasi::bindings::_rt::WasmResource>::drop::hbd600976671ef7ed
1: 0x35e9 - guest-7a94999886812cfa.wasm!<wasi::bindings::_rt::Resource<T> as core::ops::drop::Drop>::drop::hc26cd29c2e86015f
2: 0x3564 - guest-7a94999886812cfa.wasm!core::ptr::drop_in_place<wasi::bindings::_rt::Resource<wasi::bindings::wasi::sockets::tcp::TcpSocket>>::he71c56c6c7df9336
3: 0x3b89 - guest-7a94999886812cfa.wasm!core::ptr::drop_in_place<wasi::bindings::wasi::sockets::tcp::TcpSocket>::hc04eeeba95d43492
4: 0x2542 - guest-7a94999886812cfa.wasm!guest::run::hd31b4c5c8b2f2f83
5: 0x1e59 - guest-7a94999886812cfa.wasm!guest::main::hda5a2cfc9bf0b36d
6: 0x3463 - guest-7a94999886812cfa.wasm!core::ops::function::FnOnce::call_once::ha3371c02f905880a
7: 0x4308 - guest-7a94999886812cfa.wasm!std::sys::backtrace::__rust_begin_short_backtrace::h9a0efd7171e138ad
8: 0x40ca - guest-7a94999886812cfa.wasm!std::rt::lang_start::{{closure}}::h850807c2aa8d5152
9: 0x1069b - guest-7a94999886812cfa.wasm!std::rt::lang_start_internal::hd8f43a585ee7e12a
10: 0x407c - guest-7a94999886812cfa.wasm!std::rt::lang_start::hcc01919a26f87998
11: 0x2fcb - guest-7a94999886812cfa.wasm!__main_void
12: 0x1840 - guest-7a94999886812cfa.wasm!_start
13: 0x306b42 - wit-component:adapter:wasi_snapshot_preview1!wasi:cli/run@0.2.3#run
note: using the `WASMTIME_BACKTRACE_DETAILS=1` environment variable may show more debugging information
Caused by:
resource has children)
Note that the debug print here never runs. And also that we have a non-zero exit code.
pub fn main() {
run();
println!("This will never be printed. Because it crashes before we get here.");
}Ubuntu (vanilla) 24.04 x86_64