Skip to content

Commit 4911ab1

Browse files
authored
Unrolled build for rust-lang#137528
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 cdd8af2 + 3cb53df commit 4911ab1

File tree

2 files changed

+57
-124
lines changed

2 files changed

+57
-124
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-123
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};
@@ -1241,139 +1241,72 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
12411241
let old = maybe_verbatim(old)?;
12421242
let new = maybe_verbatim(new)?;
12431243

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

1307-
if file_type.is_symlink() {
1308-
// The file is a mount point, junction point or symlink so
1309-
// don't reopen the file so that the link gets renamed.
1310-
Some(Ok(handle))
1311-
} else {
1312-
// Otherwise reopen the file without inhibiting reparse point behavior.
1313-
None
1314-
}
1315-
}
1316-
}
1317-
// The underlying driver may not support `FILE_FLAG_OPEN_REPARSE_POINT`: Retry without it.
1318-
Err(err) if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _) => None,
1319-
Err(err) => Some(Err(err)),
1320-
}
1321-
.unwrap_or_else(|| create_file(0, 0))?;
1322-
1323-
let layout =
1324-
core::alloc::Layout::from_size_align(struct_size as _, align_of::<c::FILE_RENAME_INFO>())
1325-
.unwrap();
1326-
1327-
let file_rename_info = unsafe { alloc(layout) } as *mut c::FILE_RENAME_INFO;
1328-
1329-
if file_rename_info.is_null() {
1330-
handle_alloc_error(layout);
1331-
}
1332-
1333-
// SAFETY: file_rename_info is a non-null pointer pointing to memory allocated by the global allocator.
1334-
let mut file_rename_info = unsafe { Box::from_raw(file_rename_info) };
1335-
1336-
// SAFETY: We have allocated enough memory for a full FILE_RENAME_INFO struct and a filename.
1337-
unsafe {
1338-
(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1339-
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS | c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1340-
});
1275+
(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1276+
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS
1277+
| c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1278+
});
13411279

1342-
(&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1343-
(&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
1344-
1345-
new.as_ptr()
1346-
.copy_to_nonoverlapping((&raw mut (*file_rename_info).FileName) as *mut u16, new.len());
1347-
}
1348-
1349-
// We don't use `set_file_information_by_handle` here as `FILE_RENAME_INFO` is used for both `FileRenameInfo` and `FileRenameInfoEx`.
1350-
let result = unsafe {
1351-
cvt(c::SetFileInformationByHandle(
1352-
handle.as_raw_handle(),
1353-
c::FileRenameInfoEx,
1354-
(&raw const *file_rename_info).cast::<c_void>(),
1355-
struct_size,
1356-
))
1357-
};
1280+
(&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1281+
// Don't include the NULL in the size
1282+
(&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
13581283

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

1364-
cvt(unsafe {
1290+
let result = unsafe {
13651291
c::SetFileInformationByHandle(
1366-
handle.as_raw_handle(),
1367-
c::FileRenameInfo,
1368-
(&raw const *file_rename_info).cast::<c_void>(),
1292+
f.as_raw_handle(),
1293+
c::FileRenameInfoEx,
1294+
file_rename_info.cast::<c_void>(),
13691295
struct_size,
13701296
)
1371-
})?;
1297+
};
1298+
unsafe { dealloc(file_rename_info.cast::<u8>(), layout) };
1299+
if result == 0 {
1300+
if api::get_last_error() == WinError::DIR_NOT_EMPTY {
1301+
return Err(WinError::DIR_NOT_EMPTY).io_result();
1302+
} else {
1303+
return Err(err).io_result();
1304+
}
1305+
}
13721306
} else {
1373-
return Err(err);
1307+
return Err(err).io_result();
13741308
}
13751309
}
1376-
13771310
Ok(())
13781311
}
13791312

0 commit comments

Comments
 (0)