Skip to content

Commit 6799fe9

Browse files
committed
Fix a panic when opening a directory with truncate(true)
This is intended to address bytecodealliance/wasmtime#10577
1 parent 638b3ad commit 6799fe9

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

cap-primitives/src/windows/fs/open_unchecked.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,14 @@ fn handle_open_result(
205205
}
206206

207207
// Windows truncates symlinks into normal files, so truncation
208-
// may be disabled above; do it manually if needed.
208+
// may be disabled above; do it manually if needed. Note that this
209+
// is expected to always succeed for normal files, but this will
210+
// fail if a directory was opened as directories don't support
211+
// truncation.
209212
if manually_trunc {
210-
// Unwrap is ok because 0 never overflows, and we'll only
211-
// have `manually_trunc` set when the file is opened for
212-
// writing.
213-
f.set_len(0).unwrap();
213+
if let Err(e) = f.set_len(0) {
214+
return Err(OpenUncheckedError::Other(e));
215+
}
214216
}
215217
Ok(f)
216218
}

tests/fs.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1645,3 +1645,19 @@ fn create_dir_long_paths() {
16451645
std::io::ErrorKind::NotFound
16461646
);
16471647
}
1648+
1649+
/// Ensure that opening a directory with the truncation flag set is an error,
1650+
/// not a panic inside of cap-std.
1651+
#[test]
1652+
fn open_directory_with_truncate_is_error() {
1653+
use cap_fs_ext::OpenOptionsMaybeDirExt;
1654+
let tmpdir = tmpdir();
1655+
let mut options = OpenOptions::new();
1656+
options
1657+
.truncate(true)
1658+
.maybe_dir(true)
1659+
.read(true)
1660+
.write(true);
1661+
tmpdir.create_dir("test").unwrap();
1662+
assert!(tmpdir.open_with("test", &options).is_err());
1663+
}

0 commit comments

Comments
 (0)