From bfadeeb45cf25b996a50e3393967dac460d5cd53 Mon Sep 17 00:00:00 2001 From: George Tokmaji Date: Tue, 29 Oct 2024 14:14:06 +0100 Subject: Win: rename: Use offset_of! in struct size calculation --- library/std/src/sys/pal/windows/fs.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'library/std/src') diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 272d1091d94..62f784f1e8e 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1099,8 +1099,13 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let new_len_without_nul_in_bytes = (new.len() - 1).try_into().unwrap(); - let struct_size = mem::size_of::() - mem::size_of::() - + new.len() * mem::size_of::(); + // The last field of FILE_RENAME_INFO, the file name, is unsized, + // and FILE_RENAME_INFO has two padding bytes. + // Therefore we need to make sure to not allocate less than + // size_of::() bytes, which would be the case with + // 0 or 1 character paths + a null byte. + let struct_size = mem::size_of::() + .max(mem::offset_of!(c::FILE_RENAME_INFO, FileName) + new.len() * mem::size_of::()); let struct_size: u32 = struct_size.try_into().unwrap(); @@ -1168,8 +1173,6 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> { } .unwrap_or_else(|| create_file(0, 0))?; - // The last field of FILE_RENAME_INFO, the file name, is unsized. - // Therefore we need to subtract the size of one wide char. let layout = core::alloc::Layout::from_size_align( struct_size as _, mem::align_of::(), -- cgit 1.4.1-3-g733a5