Skip to content
/ rust Public
forked from rust-lang/rust

Commit 229d38a

Browse files
authored
Rollup merge of rust-lang#137528 - ChrisDenton:rename-win, r=joboet
Windows: Fix error in `fs::rename` on Windows 1607 Fixes rust-lang#137499 There's a bug in our Windows implementation of `fs::rename` that only manifests on a specific version of Windows. Both newer and older versions of Windows work. I took the safest route to fixing this by using the old `MoveFileExW` function to implement this and only falling back to the new behaviour if that fails. This is similar to what is done in `unlink` (just above this function). try-job: dist-x86_64-mingw try-job: dist-x86_64-msvc
2 parents bcc7dca + 3a726b1 commit 229d38a

File tree

2 files changed

+57
-126
lines changed

2 files changed

+57
-126
lines changed

library/std/src/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2446,7 +2446,7 @@ pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
24462446
/// # Platform-specific behavior
24472447
///
24482448
/// This function currently corresponds to the `rename` function on Unix
2449-
/// and the `SetFileInformationByHandle` function on Windows.
2449+
/// and the `MoveFileExW` or `SetFileInformationByHandle` function on Windows.
24502450
///
24512451
/// Because of this, the behavior when both `from` and `to` exist differs. On
24522452
/// Unix, if `from` is a directory, `to` must also be an (empty) directory. If

library/std/src/sys/pal/windows/fs.rs

+56-125
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use super::api::{self, WinError, set_file_information_by_handle};
22
use super::{IoResult, to_u16s};
3-
use crate::alloc::{alloc, handle_alloc_error};
3+
use crate::alloc::{Layout, alloc, dealloc};
44
use crate::borrow::Cow;
55
use crate::ffi::{OsStr, OsString, c_void};
66
use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
7-
use crate::mem::{self, MaybeUninit};
7+
use crate::mem::{self, MaybeUninit, offset_of};
88
use crate::os::windows::io::{AsHandle, BorrowedHandle};
99
use crate::os::windows::prelude::*;
1010
use crate::path::{Path, PathBuf};
@@ -1242,141 +1242,72 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
12421242
let old = maybe_verbatim(old)?;
12431243
let new = maybe_verbatim(new)?;
12441244

1245-
let new_len_without_nul_in_bytes = (new.len() - 1).try_into().unwrap();
1246-
1247-
// The last field of FILE_RENAME_INFO, the file name, is unsized,
1248-
// and FILE_RENAME_INFO has two padding bytes.
1249-
// Therefore we need to make sure to not allocate less than
1250-
// size_of::<c::FILE_RENAME_INFO>() bytes, which would be the case with
1251-
// 0 or 1 character paths + a null byte.
1252-
let struct_size = mem::size_of::<c::FILE_RENAME_INFO>()
1253-
.max(mem::offset_of!(c::FILE_RENAME_INFO, FileName) + new.len() * mem::size_of::<u16>());
1254-
1255-
let struct_size: u32 = struct_size.try_into().unwrap();
1256-
1257-
let create_file = |extra_access, extra_flags| {
1258-
let handle = unsafe {
1259-
HandleOrInvalid::from_raw_handle(c::CreateFileW(
1260-
old.as_ptr(),
1261-
c::SYNCHRONIZE | c::DELETE | extra_access,
1262-
c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
1263-
ptr::null(),
1264-
c::OPEN_EXISTING,
1265-
c::FILE_ATTRIBUTE_NORMAL | c::FILE_FLAG_BACKUP_SEMANTICS | extra_flags,
1266-
ptr::null_mut(),
1267-
))
1268-
};
1269-
1270-
OwnedHandle::try_from(handle).map_err(|_| io::Error::last_os_error())
1271-
};
1272-
1273-
// The following code replicates `MoveFileEx`'s behavior as reverse-engineered from its disassembly.
1274-
// If `old` refers to a mount point, we move it instead of the target.
1275-
let handle = match create_file(c::FILE_READ_ATTRIBUTES, c::FILE_FLAG_OPEN_REPARSE_POINT) {
1276-
Ok(handle) => {
1277-
let mut file_attribute_tag_info: MaybeUninit<c::FILE_ATTRIBUTE_TAG_INFO> =
1278-
MaybeUninit::uninit();
1279-
1280-
let result = unsafe {
1281-
cvt(c::GetFileInformationByHandleEx(
1282-
handle.as_raw_handle(),
1283-
c::FileAttributeTagInfo,
1284-
file_attribute_tag_info.as_mut_ptr().cast(),
1285-
mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
1286-
))
1245+
if unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) } == 0 {
1246+
let err = api::get_last_error();
1247+
// if `MoveFileExW` fails with ERROR_ACCESS_DENIED then try to move
1248+
// the file while ignoring the readonly attribute.
1249+
// This is accomplished by calling `SetFileInformationByHandle` with `FileRenameInfoEx`.
1250+
if err == WinError::ACCESS_DENIED {
1251+
let mut opts = OpenOptions::new();
1252+
opts.access_mode(c::DELETE);
1253+
opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1254+
let Ok(f) = File::open_native(&old, &opts) else { return Err(err).io_result() };
1255+
1256+
// Calculate the layout of the `FILE_RENAME_INFO` we pass to `SetFileInformation`
1257+
// This is a dynamically sized struct so we need to get the position of the last field to calculate the actual size.
1258+
let Ok(new_len_without_nul_in_bytes): Result<u32, _> = ((new.len() - 1) * 2).try_into()
1259+
else {
1260+
return Err(err).io_result();
12871261
};
1288-
1289-
if let Err(err) = result {
1290-
if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _)
1291-
|| err.raw_os_error() == Some(c::ERROR_INVALID_FUNCTION as _)
1292-
{
1293-
// `GetFileInformationByHandleEx` documents that not all underlying drivers support all file information classes.
1294-
// Since we know we passed the correct arguments, this means the underlying driver didn't understand our request;
1295-
// `MoveFileEx` proceeds by reopening the file without inhibiting reparse point behavior.
1296-
None
1297-
} else {
1298-
Some(Err(err))
1299-
}
1300-
} else {
1301-
// SAFETY: The struct has been initialized by GetFileInformationByHandleEx
1302-
let file_attribute_tag_info = unsafe { file_attribute_tag_info.assume_init() };
1303-
let file_type = FileType::new(
1304-
file_attribute_tag_info.FileAttributes,
1305-
file_attribute_tag_info.ReparseTag,
1306-
);
1307-
1308-
if file_type.is_symlink() {
1309-
// The file is a mount point, junction point or symlink so
1310-
// don't reopen the file so that the link gets renamed.
1311-
Some(Ok(handle))
1312-
} else {
1313-
// Otherwise reopen the file without inhibiting reparse point behavior.
1314-
None
1262+
let offset: u32 = offset_of!(c::FILE_RENAME_INFO, FileName).try_into().unwrap();
1263+
let struct_size = offset + new_len_without_nul_in_bytes + 2;
1264+
let layout =
1265+
Layout::from_size_align(struct_size as usize, align_of::<c::FILE_RENAME_INFO>())
1266+
.unwrap();
1267+
1268+
// SAFETY: We allocate enough memory for a full FILE_RENAME_INFO struct and a filename.
1269+
let file_rename_info;
1270+
unsafe {
1271+
file_rename_info = alloc(layout).cast::<c::FILE_RENAME_INFO>();
1272+
if file_rename_info.is_null() {
1273+
return Err(io::ErrorKind::OutOfMemory.into());
13151274
}
1316-
}
1317-
}
1318-
// The underlying driver may not support `FILE_FLAG_OPEN_REPARSE_POINT`: Retry without it.
1319-
Err(err) if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _) => None,
1320-
Err(err) => Some(Err(err)),
1321-
}
1322-
.unwrap_or_else(|| create_file(0, 0))?;
1323-
1324-
let layout = core::alloc::Layout::from_size_align(
1325-
struct_size as _,
1326-
mem::align_of::<c::FILE_RENAME_INFO>(),
1327-
)
1328-
.unwrap();
1329-
1330-
let file_rename_info = unsafe { alloc(layout) } as *mut c::FILE_RENAME_INFO;
1331-
1332-
if file_rename_info.is_null() {
1333-
handle_alloc_error(layout);
1334-
}
13351275

1336-
// SAFETY: file_rename_info is a non-null pointer pointing to memory allocated by the global allocator.
1337-
let mut file_rename_info = unsafe { Box::from_raw(file_rename_info) };
1276+
(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1277+
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS
1278+
| c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1279+
});
13381280

1339-
// SAFETY: We have allocated enough memory for a full FILE_RENAME_INFO struct and a filename.
1340-
unsafe {
1341-
(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1342-
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS | c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1343-
});
1344-
1345-
(&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1346-
(&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
1347-
1348-
new.as_ptr()
1349-
.copy_to_nonoverlapping((&raw mut (*file_rename_info).FileName) as *mut u16, new.len());
1350-
}
1351-
1352-
// We don't use `set_file_information_by_handle` here as `FILE_RENAME_INFO` is used for both `FileRenameInfo` and `FileRenameInfoEx`.
1353-
let result = unsafe {
1354-
cvt(c::SetFileInformationByHandle(
1355-
handle.as_raw_handle(),
1356-
c::FileRenameInfoEx,
1357-
(&raw const *file_rename_info).cast::<c_void>(),
1358-
struct_size,
1359-
))
1360-
};
1281+
(&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1282+
// Don't include the NULL in the size
1283+
(&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
13611284

1362-
if let Err(err) = result {
1363-
if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _) {
1364-
// FileRenameInfoEx and FILE_RENAME_FLAG_POSIX_SEMANTICS were added in Windows 10 1607; retry with FileRenameInfo.
1365-
file_rename_info.Anonymous.ReplaceIfExists = true;
1285+
new.as_ptr().copy_to_nonoverlapping(
1286+
(&raw mut (*file_rename_info).FileName).cast::<u16>(),
1287+
new.len(),
1288+
);
1289+
}
13661290

1367-
cvt(unsafe {
1291+
let result = unsafe {
13681292
c::SetFileInformationByHandle(
1369-
handle.as_raw_handle(),
1370-
c::FileRenameInfo,
1371-
(&raw const *file_rename_info).cast::<c_void>(),
1293+
f.as_raw_handle(),
1294+
c::FileRenameInfoEx,
1295+
file_rename_info.cast::<c_void>(),
13721296
struct_size,
13731297
)
1374-
})?;
1298+
};
1299+
unsafe { dealloc(file_rename_info.cast::<u8>(), layout) };
1300+
if result == 0 {
1301+
if api::get_last_error() == WinError::DIR_NOT_EMPTY {
1302+
return Err(WinError::DIR_NOT_EMPTY).io_result();
1303+
} else {
1304+
return Err(err).io_result();
1305+
}
1306+
}
13751307
} else {
1376-
return Err(err);
1308+
return Err(err).io_result();
13771309
}
13781310
}
1379-
13801311
Ok(())
13811312
}
13821313

0 commit comments

Comments
 (0)