From 5b35c738878797b781b0715b710fb3dc49fa59e7 Mon Sep 17 00:00:00 2001 From: Peter Huene Date: Thu, 28 Jan 2021 12:39:40 -0800 Subject: [PATCH] Fix `fd_readdir` to properly truncate directory entry names. Previously, `fd_readdir` was truncating directory entry names based on the calculation of `min(name_len, buf_len - bufused)`, but `bufused` was not being updated after writing in the `dirent` structure to the buffer. This allowed `bufused` to be incremented beyond `buf_len` and returned as the number of bytes written to the buffer, which is invalid. This fix adjusts `bufused` when the buffer is written to for the `dirent` so that name truncation happens as expected. Fixes #2618. --- crates/wasi-common/src/snapshots/wasi_snapshot_preview1.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/wasi-common/src/snapshots/wasi_snapshot_preview1.rs b/crates/wasi-common/src/snapshots/wasi_snapshot_preview1.rs index 794be79c9fc6..2f74b98aa88e 100644 --- a/crates/wasi-common/src/snapshots/wasi_snapshot_preview1.rs +++ b/crates/wasi-common/src/snapshots/wasi_snapshot_preview1.rs @@ -304,7 +304,6 @@ impl<'a> WasiSnapshotPreview1 for WasiCtx { let dirent_len: types::Size = dirent_raw.len().try_into()?; let name_raw = name.as_bytes(); let name_len = name_raw.len().try_into()?; - let offset = dirent_len.checked_add(name_len).ok_or(Error::Overflow)?; // Copy as many bytes of the dirent as we can, up to the end of the buffer. let dirent_copy_len = min(dirent_len, buf_len - bufused); @@ -318,6 +317,7 @@ impl<'a> WasiSnapshotPreview1 for WasiCtx { } buf = buf.add(dirent_copy_len)?; + bufused = bufused.checked_add(dirent_copy_len).ok_or(Error::Overflow)?; // Copy as many bytes of the name as we can, up to the end of the buffer. let name_copy_len = min(name_len, buf_len - bufused); @@ -331,8 +331,7 @@ impl<'a> WasiSnapshotPreview1 for WasiCtx { } buf = buf.add(name_copy_len)?; - - bufused += offset; + bufused = bufused.checked_add(name_copy_len).ok_or(Error::Overflow)?; } Ok(bufused)