Skip to content

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

wasi:io: do not trap on a zero-length write (#14533)

Xia Chao5d5cbca3e631
diff --git a/crates/test-programs/src/bin/p2_empty_write.rs b/crates/test-programs/src/bin/p2_empty_write.rs
new file mode 100644
index 0000000000..96874e75aa
--- /dev/null
+++ b/crates/test-programs/src/bin/p2_empty_write.rs
@@ -0,0 +1,27 @@
+use test_programs::wasi::filesystem::preopens;
+use test_programs::wasi::filesystem::types::{DescriptorFlags, OpenFlags, PathFlags};
+
+/// A zero-length `write` is within any `check-write` grant (`0 <= n`), so it is
+/// a no-op and must not trap, even while a previous write is still in flight.
+fn main() {
+ let (dir, _) = preopens::get_directories().into_iter().next().unwrap();
+ let file = dir
+ .open_at(
+ PathFlags::empty(),
+ "empty-write",
+ OpenFlags::CREATE,
+ DescriptorFlags::READ | DescriptorFlags::WRITE,
+ )
+ .unwrap();
+ let out = file.write_via_stream(0).unwrap();
+
+ let permit = out.check_write().unwrap();
+ assert!(permit > 0);
+
+ // Occupy the permit so `check-write` reports 0 and a write is in flight.
+ out.write(&[0]).unwrap();
+ assert_eq!(out.check_write().unwrap(), 0);
+
+ out.write(&[]).unwrap();
+ out.write_zeroes(0).unwrap();
+}
diff --git a/crates/wasi/src/p2/filesystem.rs b/crates/wasi/src/p2/filesystem.rs
index d6d9b43111..0802b913b1 100644
--- a/crates/wasi/src/p2/filesystem.rs
+++ b/crates/wasi/src/p2/filesystem.rs
@@ -285,6 +285,7 @@ impl OutputStream for FileOutputStream {
return Err(StreamError::Trap(format_err!("write exceeded budget")));
}
OutputState::Closed => return Err(StreamError::Closed),
+ OutputState::Waiting(_) if buf.is_empty() => return Ok(()),
OutputState::Waiting(_) | OutputState::Error(_) => {
// a write is pending - this call was not permitted
return Err(StreamError::Trap(format_err!(
diff --git a/crates/wasi/tests/all/p2/async_.rs b/crates/wasi/tests/all/p2/async_.rs
index cc8b9edf3c..fb196faaf8 100644
--- a/crates/wasi/tests/all/p2/async_.rs
+++ b/crates/wasi/tests/all/p2/async_.rs
@@ -399,6 +399,10 @@ async fn p2_write_too_much() {
)
}
#[test_log::test(tokio::test(flavor = "multi_thread"))]
+async fn p2_empty_write() {
+ run(P2_EMPTY_WRITE_COMPONENT, |_| {}).await.unwrap()
+}
+#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p2_file_settime_overflow() {
run(P2_FILE_SETTIME_OVERFLOW_COMPONENT, |_| {})
.await
diff --git a/crates/wasi/tests/all/p2/sync.rs b/crates/wasi/tests/all/p2/sync.rs
index 78cd1bbcea..cf65ce8f0c 100644
--- a/crates/wasi/tests/all/p2/sync.rs
+++ b/crates/wasi/tests/all/p2/sync.rs
@@ -375,6 +375,10 @@ fn p2_write_too_much() {
)
}
#[test_log::test]
+fn p2_empty_write() {
+ run(P2_EMPTY_WRITE_COMPONENT, |_| {}).unwrap()
+}
+#[test_log::test]
fn p2_file_settime_overflow() {
run(P2_FILE_SETTIME_OVERFLOW_COMPONENT, |_| {}).unwrap()
}