Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

fix(wasmtime-cli): generic eio error thrown for wasip2 (#14107)

Eduardo de Moura Rodrigues8cee831b118e
diff --git a/crates/test-programs/src/bin/p2_cli_stdin_eisdir.rs b/crates/test-programs/src/bin/p2_cli_stdin_eisdir.rs
new file mode 100644
index 0000000000..0538db3f7c
--- /dev/null
+++ b/crates/test-programs/src/bin/p2_cli_stdin_eisdir.rs
@@ -0,0 +1,36 @@
+//! Guest program that reads from stdin expecting an `IsADirectory` error.
+//!
+//! When stdin is redirected from a directory (e.g. `< /some/dir`), the host
+//! should surface the error as `StreamError::LastOperationFailed` with the
+//! original `io::Error` preserved, recoverable via `filesystem-error-code`.
+
+use test_programs::wasi::cli::stdin;
+use test_programs::wasi::filesystem::types::{self as filesystem, ErrorCode};
+use test_programs::wasi::io::streams::StreamError;
+
+fn main() {
+ let stdin = stdin::get_stdin();
+
+ // Keep polling until data or an error is available.
+ loop {
+ stdin.subscribe().block();
+ match stdin.read(1024) {
+ Ok(bytes) if bytes.is_empty() => continue,
+ Ok(_) => panic!("expected an error reading from a directory, got data"),
+ Err(StreamError::Closed) => {
+ panic!("expected LastOperationFailed(IsDirectory), got Closed")
+ }
+ Err(StreamError::LastOperationFailed(err)) => {
+ // Use filesystem-error-code to recover the specific error.
+ let code = filesystem::filesystem_error_code(&err);
+ assert_eq!(
+ code,
+ Some(ErrorCode::IsDirectory),
+ "expected IsDirectory, got {code:?}"
+ );
+ eprintln!("got expected ErrorCode::IsDirectory");
+ return;
+ }
+ }
+ }
+}
diff --git a/crates/test-programs/src/bin/p2_cli_stdout_epipe.rs b/crates/test-programs/src/bin/p2_cli_stdout_epipe.rs
new file mode 100644
index 0000000000..3e52fda485
--- /dev/null
+++ b/crates/test-programs/src/bin/p2_cli_stdout_epipe.rs
@@ -0,0 +1,29 @@
+//! Guest program that writes to stdout until the pipe is closed, then verifies
+//! it gets `StreamError::Closed` (which maps to EPIPE) rather than a trap or
+//! generic EIO.
+
+use test_programs::wasi::cli::stdout;
+use test_programs::wasi::io::streams::StreamError;
+
+fn main() {
+ let stdout = stdout::get_stdout();
+ let chunk = vec![b'x'; 4096];
+
+ loop {
+ match stdout.blocking_write_and_flush(&chunk) {
+ Ok(()) => continue,
+ Err(StreamError::Closed) => {
+ // This is the expected outcome: the pipe was closed by the
+ // reader, and wasmtime correctly reports it as Closed (EPIPE).
+ eprintln!("got expected StreamError::Closed");
+ return;
+ }
+ Err(StreamError::LastOperationFailed(err)) => {
+ panic!(
+ "unexpected LastOperationFailed (should have been Closed): {}",
+ err.to_debug_string()
+ );
+ }
+ }
+ }
+}
diff --git a/crates/wasi/src/cli.rs b/crates/wasi/src/cli.rs
index 090a656c4c..eff5089d1c 100644
--- a/crates/wasi/src/cli.rs
+++ b/crates/wasi/src/cli.rs
@@ -3,7 +3,7 @@ use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite, empty};
use wasmtime::component::{HasData, ResourceTable};
-use wasmtime_wasi_io::streams::{InputStream, OutputStream};
+use wasmtime_wasi_io::streams::{InputStream, OutputStream, StreamError};
mod empty;
mod file;
@@ -15,6 +15,27 @@ mod worker_thread_stdin;
pub use self::file::{InputFile, OutputFile};
pub use self::locked_async::{AsyncStdinStream, AsyncStdoutStream};
+/// Convert a host `io::Error` into a `StreamError`, matching the error-code
+/// recovery that wasip1 performs via `filesystem::ErrorCode::from`.
+///
+/// * `BrokenPipe` is mapped to `StreamError::Closed` so that downstream
+/// consumers (e.g. wasi-libc) can recover `EPIPE` rather than falling back
+/// to a generic `EIO`.
+///
+/// * All other errors (including `IsADirectory`, permission errors, etc.) are
+/// preserved as `LastOperationFailed` with the original `std::io::Error`
+/// intact. This allows guests to recover the specific error code via the
+/// `wasi:filesystem/types#filesystem-error-code` function, which downcasts
+/// the error back to `std::io::Error` and maps it through
+/// `ErrorCode::from`.
+fn stream_error_from(e: std::io::Error) -> StreamError {
+ if e.kind() == std::io::ErrorKind::BrokenPipe {
+ StreamError::Closed
+ } else {
+ StreamError::LastOperationFailed(e.into())
+ }
+}
+
// Convenience reexport for stdio types so tokio doesn't have to be imported
// itself.
#[doc(no_inline)]
@@ -366,4 +387,66 @@ mod test {
s.write_ready().await?;
Ok(())
}
+
+ // Verify that the stdio OutputStream implementation reports a usable
+ // write permit and can successfully write + flush (exercises the full
+ // trait impl including the error conversion path).
+ #[test]
+ fn stdio_output_stream_write_flush() {
+ let mut stream: Box<dyn wasmtime_wasi_io::streams::OutputStream> =
+ StdoutStream::p2_stream(&std::io::stderr());
+
+ let permit = stream.check_write().expect("check_write");
+ assert!(permit > 0, "permit should be nonzero");
+
+ // Writing empty bytes must succeed.
+ stream
+ .write(Bytes::new())
+ .expect("writing empty bytes should succeed");
+
+ // Flushing must succeed.
+ stream.flush().expect("flush should succeed");
+ }
+
+ #[test]
+ fn stream_error_from_broken_pipe_maps_to_closed() {
+ use std::io;
+ use wasmtime_wasi_io::streams::StreamError;
+
+ let err = super::stream_error_from(io::Error::from(io::ErrorKind::BrokenPipe));
+ assert!(matches!(err, StreamError::Closed));
+ }
+
+ #[test]
+ fn stream_error_from_preserves_io_error() {
+ use std::io;
+ use wasmtime_wasi_io::streams::StreamError;
+
+ let err = super::stream_error_from(io::Error::from(io::ErrorKind::IsADirectory));
+ match err {
+ StreamError::LastOperationFailed(e) => {
+ let io_err = e.downcast::<io::Error>().expect("should downcast");
+ assert_eq!(io_err.kind(), io::ErrorKind::IsADirectory);
+ }
+ other => panic!("expected LastOperationFailed, got: {other:?}"),
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn stream_error_from_raw_os_eisdir() {
+ use rustix::io::Errno;
+ use std::io;
+ use wasmtime_wasi_io::streams::StreamError;
+
+ let err =
+ super::stream_error_from(io::Error::from_raw_os_error(Errno::ISDIR.raw_os_error()));
+ match err {
+ StreamError::LastOperationFailed(e) => {
+ let io_err = e.downcast::<io::Error>().expect("should downcast");
+ assert_eq!(io_err.raw_os_error(), Some(Errno::ISDIR.raw_os_error()));
+ }
+ other => panic!("expected LastOperationFailed, got: {other:?}"),
+ }
+ }
}
diff --git a/crates/wasi/src/cli/stdout.rs b/crates/wasi/src/cli/stdout.rs
index 9d0a213e52..0ffe2ee976 100644
--- a/crates/wasi/src/cli/stdout.rs
+++ b/crates/wasi/src/cli/stdout.rs
@@ -1,4 +1,4 @@
-use crate::cli::{IsTerminal, StdoutStream};
+use crate::cli::{IsTerminal, StdoutStream, stream_error_from};
use crate::p2;
use bytes::Bytes;
use std::io::{self, Write};
@@ -78,7 +78,7 @@ impl OutputStream for StdioOutputStream {
StdioOutputStream::Stdout => std::io::stdout().write_all(&bytes),
StdioOutputStream::Stderr => std::io::stderr().write_all(&bytes),
}
- .map_err(|e| p2::StreamError::LastOperationFailed(wasmtime::format_err!(e)))
+ .map_err(|e| stream_error_from(e))
}
fn flush(&mut self) -> p2::StreamResult<()> {
@@ -86,7 +86,7 @@ impl OutputStream for StdioOutputStream {
StdioOutputStream::Stdout => std::io::stdout().flush(),
StdioOutputStream::Stderr => std::io::stderr().flush(),
}
- .map_err(|e| p2::StreamError::LastOperationFailed(wasmtime::format_err!(e)))
+ .map_err(|e| stream_error_from(e))
}
fn check_write(&mut self) -> p2::StreamResult<usize> {
diff --git a/crates/wasi/src/cli/worker_thread_stdin.rs b/crates/wasi/src/cli/worker_thread_stdin.rs
index 52229352e6..c9c8ea30da 100644
--- a/crates/wasi/src/cli/worker_thread_stdin.rs
+++ b/crates/wasi/src/cli/worker_thread_stdin.rs
@@ -23,7 +23,7 @@
//! This module is one that's likely to change over time though as new systems
//! are encountered along with preexisting bugs.
-use crate::cli::{IsTerminal, StdinStream};
+use crate::cli::{IsTerminal, StdinStream, stream_error_from};
use bytes::{Bytes, BytesMut};
use std::mem;
use std::pin::Pin;
@@ -213,7 +213,7 @@ impl InputStream for WasiStdin {
}
StdinState::Error(e) => {
*locked = StdinState::Closed;
- Err(StreamError::LastOperationFailed(e.into()))
+ Err(stream_error_from(e))
}
StdinState::Closed => {
*locked = StdinState::Closed;
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index fa3fee6c74..8f175b7077 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -1205,6 +1205,71 @@ mod test_programs {
Ok(())
}
+ #[test]
+ fn p2_cli_stdout_epipe() -> Result<()> {
+ let mut child = get_wasmtime_command()?
+ .args(&["run", "-Wcomponent-model", P2_CLI_STDOUT_EPIPE_COMPONENT])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .stdin(Stdio::null())
+ .spawn()?;
+
+ // Read a small amount from stdout then drop it to close the pipe,
+ // which should cause the guest to receive StreamError::Closed (EPIPE).
+ let mut stdout = child.stdout.take().unwrap();
+ let mut buf = [0u8; 64];
+ let _ = stdout.read(&mut buf)?;
+ drop(stdout);
+
+ let output = child.wait_with_output()?;
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ output.status.success(),
+ "guest should exit successfully after receiving Closed, stderr: {stderr}"
+ );
+ assert!(
+ stderr.contains("got expected StreamError::Closed"),
+ "guest should have reported StreamError::Closed, stderr: {stderr}"
+ );
+ Ok(())
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn p2_cli_stdin_eisdir() -> Result<()> {
+ let dir = tempfile::tempdir()?;
+ // Open the directory and transfer the fd to Stdio for use as stdin.
+ let dir_file = std::fs::File::open(dir.path())?;
+ let stdin_stdio: Stdio = dir_file.into();
+
+ let child = get_wasmtime_command()?
+ .args(&["run", "-Wcomponent-model", P2_CLI_STDIN_EISDIR_COMPONENT])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .stdin(stdin_stdio)
+ .spawn()?;
+
+ let output = child.wait_with_output()?;
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ output.status.success(),
+ "guest should exit successfully after receiving IsDirectory, stderr: {stderr}"
+ );
+ assert!(
+ stderr.contains("got expected ErrorCode::IsDirectory"),
+ "guest should have reported ErrorCode::IsDirectory, stderr: {stderr}"
+ );
+ Ok(())
+ }
+
+ // EISDIR is a Unix-specific concept; on Windows opening a directory for
+ // reading behaves differently, so this test only runs on Unix.
+ #[cfg(not(unix))]
+ #[test]
+ fn p2_cli_stdin_eisdir() -> Result<()> {
+ Ok(())
+ }
+
#[test]
fn p2_cli_env() -> Result<()> {
run_wasmtime(&[