Skip to content

Commit 64f5201

Browse files
Fulgen301gitbot
authored and
gitbot
committed
Win: Use FILE_RENAME_FLAG_POSIX_SEMANTICS for std::fs::rename if available
Windows 10 1601 introduced `FileRenameInfoEx` as well as `FILE_RENAME_FLAG_POSIX_SEMANTICS`, allowing for atomic renaming. If it isn't supported, we fall back to `FileRenameInfo`. This commit also replicates `MoveFileExW`'s behavior of checking whether the source file is a mount point and moving the mount point instead of resolving the target path.
1 parent da73525 commit 64f5201

File tree

4 files changed

+168
-4
lines changed

4 files changed

+168
-4
lines changed

std/src/fs.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -2397,12 +2397,14 @@ pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
23972397
/// # Platform-specific behavior
23982398
///
23992399
/// This function currently corresponds to the `rename` function on Unix
2400-
/// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
2400+
/// and the `SetFileInformationByHandle` function on Windows.
24012401
///
24022402
/// Because of this, the behavior when both `from` and `to` exist differs. On
24032403
/// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
2404-
/// `from` is not a directory, `to` must also be not a directory. In contrast,
2405-
/// on Windows, `from` can be anything, but `to` must *not* be a directory.
2404+
/// `from` is not a directory, `to` must also be not a directory. The behavior
2405+
/// on Windows is the same on Windows 10 1607 and higher if `FileRenameInfoEx`
2406+
/// is supported by the filesystem; otherwise, `from` can be anything, but
2407+
/// `to` must *not* be a directory.
24062408
///
24072409
/// Note that, this [may change in the future][changes].
24082410
///

std/src/sys/pal/windows/c/bindings.txt

+3
Original file line numberDiff line numberDiff line change
@@ -2295,6 +2295,7 @@ Windows.Win32.Storage.FileSystem.FILE_NAME_OPENED
22952295
Windows.Win32.Storage.FileSystem.FILE_READ_ATTRIBUTES
22962296
Windows.Win32.Storage.FileSystem.FILE_READ_DATA
22972297
Windows.Win32.Storage.FileSystem.FILE_READ_EA
2298+
Windows.Win32.Storage.FileSystem.FILE_RENAME_INFO
22982299
Windows.Win32.Storage.FileSystem.FILE_SHARE_DELETE
22992300
Windows.Win32.Storage.FileSystem.FILE_SHARE_MODE
23002301
Windows.Win32.Storage.FileSystem.FILE_SHARE_NONE
@@ -2603,5 +2604,7 @@ Windows.Win32.System.Threading.WaitForMultipleObjects
26032604
Windows.Win32.System.Threading.WaitForSingleObject
26042605
Windows.Win32.System.Threading.WakeAllConditionVariable
26052606
Windows.Win32.System.Threading.WakeConditionVariable
2607+
Windows.Win32.System.WindowsProgramming.FILE_RENAME_FLAG_POSIX_SEMANTICS
2608+
Windows.Win32.System.WindowsProgramming.FILE_RENAME_FLAG_REPLACE_IF_EXISTS
26062609
Windows.Win32.System.WindowsProgramming.PROGRESS_CONTINUE
26072610
Windows.Win32.UI.Shell.GetUserProfileDirectoryW

std/src/sys/pal/windows/c/windows_sys.rs

+16
Original file line numberDiff line numberDiff line change
@@ -2472,6 +2472,22 @@ pub const FILE_RANDOM_ACCESS: NTCREATEFILE_CREATE_OPTIONS = 2048u32;
24722472
pub const FILE_READ_ATTRIBUTES: FILE_ACCESS_RIGHTS = 128u32;
24732473
pub const FILE_READ_DATA: FILE_ACCESS_RIGHTS = 1u32;
24742474
pub const FILE_READ_EA: FILE_ACCESS_RIGHTS = 8u32;
2475+
pub const FILE_RENAME_FLAG_POSIX_SEMANTICS: u32 = 2u32;
2476+
pub const FILE_RENAME_FLAG_REPLACE_IF_EXISTS: u32 = 1u32;
2477+
#[repr(C)]
2478+
#[derive(Clone, Copy)]
2479+
pub struct FILE_RENAME_INFO {
2480+
pub Anonymous: FILE_RENAME_INFO_0,
2481+
pub RootDirectory: HANDLE,
2482+
pub FileNameLength: u32,
2483+
pub FileName: [u16; 1],
2484+
}
2485+
#[repr(C)]
2486+
#[derive(Clone, Copy)]
2487+
pub union FILE_RENAME_INFO_0 {
2488+
pub ReplaceIfExists: BOOLEAN,
2489+
pub Flags: u32,
2490+
}
24752491
pub const FILE_RESERVE_OPFILTER: NTCREATEFILE_CREATE_OPTIONS = 1048576u32;
24762492
pub const FILE_SEQUENTIAL_ONLY: NTCREATEFILE_CREATE_OPTIONS = 4u32;
24772493
pub const FILE_SESSION_AWARE: NTCREATEFILE_CREATE_OPTIONS = 262144u32;

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

+144-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::api::{self, WinError};
22
use super::{IoResult, to_u16s};
3+
use crate::alloc::{alloc, handle_alloc_error};
34
use crate::borrow::Cow;
45
use crate::ffi::{OsStr, OsString, c_void};
56
use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
@@ -1223,7 +1224,149 @@ pub fn unlink(p: &Path) -> io::Result<()> {
12231224
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
12241225
let old = maybe_verbatim(old)?;
12251226
let new = maybe_verbatim(new)?;
1226-
cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
1227+
1228+
let new_len_without_nul_in_bytes = (new.len() - 1).try_into().unwrap();
1229+
1230+
let struct_size = mem::size_of::<c::FILE_RENAME_INFO>() - mem::size_of::<u16>()
1231+
+ new.len() * mem::size_of::<u16>();
1232+
1233+
let struct_size: u32 = struct_size.try_into().unwrap();
1234+
1235+
let create_file = |extra_access, extra_flags| {
1236+
let handle = unsafe {
1237+
HandleOrInvalid::from_raw_handle(c::CreateFileW(
1238+
old.as_ptr(),
1239+
c::SYNCHRONIZE | c::DELETE | extra_access,
1240+
c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
1241+
ptr::null(),
1242+
c::OPEN_EXISTING,
1243+
c::FILE_ATTRIBUTE_NORMAL | c::FILE_FLAG_BACKUP_SEMANTICS | extra_flags,
1244+
ptr::null_mut(),
1245+
))
1246+
};
1247+
1248+
OwnedHandle::try_from(handle).map_err(|_| io::Error::last_os_error())
1249+
};
1250+
1251+
// The following code replicates `MoveFileEx`'s behavior as reverse-engineered from its disassembly.
1252+
// If `old` refers to a mount point, we move it instead of the target.
1253+
let handle = match create_file(c::FILE_READ_ATTRIBUTES, c::FILE_FLAG_OPEN_REPARSE_POINT) {
1254+
Ok(handle) => {
1255+
let mut file_attribute_tag_info: MaybeUninit<c::FILE_ATTRIBUTE_TAG_INFO> =
1256+
MaybeUninit::uninit();
1257+
1258+
let result = unsafe {
1259+
cvt(c::GetFileInformationByHandleEx(
1260+
handle.as_raw_handle(),
1261+
c::FileAttributeTagInfo,
1262+
file_attribute_tag_info.as_mut_ptr().cast(),
1263+
mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
1264+
))
1265+
};
1266+
1267+
if let Err(err) = result {
1268+
if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _)
1269+
|| err.raw_os_error() == Some(c::ERROR_INVALID_FUNCTION as _)
1270+
{
1271+
// `GetFileInformationByHandleEx` documents that not all underlying drivers support all file information classes.
1272+
// Since we know we passed the correct arguments, this means the underlying driver didn't understand our request;
1273+
// `MoveFileEx` proceeds by reopening the file without inhibiting reparse point behavior.
1274+
None
1275+
} else {
1276+
Some(Err(err))
1277+
}
1278+
} else {
1279+
// SAFETY: The struct has been initialized by GetFileInformationByHandleEx
1280+
let file_attribute_tag_info = unsafe { file_attribute_tag_info.assume_init() };
1281+
1282+
if file_attribute_tag_info.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
1283+
&& file_attribute_tag_info.ReparseTag != c::IO_REPARSE_TAG_MOUNT_POINT
1284+
{
1285+
// The file is not a mount point: Reopen the file without inhibiting reparse point behavior.
1286+
None
1287+
} else {
1288+
// The file is a mount point: Don't reopen the file so that the mount point gets renamed.
1289+
Some(Ok(handle))
1290+
}
1291+
}
1292+
}
1293+
// The underlying driver may not support `FILE_FLAG_OPEN_REPARSE_POINT`: Retry without it.
1294+
Err(err) if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _) => None,
1295+
Err(err) => Some(Err(err)),
1296+
}
1297+
.unwrap_or_else(|| create_file(0, 0))?;
1298+
1299+
// The last field of FILE_RENAME_INFO, the file name, is unsized.
1300+
// Therefore we need to subtract the size of one wide char.
1301+
let layout = core::alloc::Layout::from_size_align(
1302+
struct_size as _,
1303+
mem::align_of::<c::FILE_RENAME_INFO>(),
1304+
)
1305+
.unwrap();
1306+
1307+
let file_rename_info = unsafe { alloc(layout) } as *mut c::FILE_RENAME_INFO;
1308+
1309+
if file_rename_info.is_null() {
1310+
handle_alloc_error(layout);
1311+
}
1312+
1313+
// SAFETY: file_rename_info is a non-null pointer pointing to memory allocated by the global allocator.
1314+
let mut file_rename_info = unsafe { Box::from_raw(file_rename_info) };
1315+
1316+
// SAFETY: We have allocated enough memory for a full FILE_RENAME_INFO struct and a filename.
1317+
unsafe {
1318+
(&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1319+
// Don't bother with FileRenameInfo on Windows 7 since it doesn't exist.
1320+
#[cfg(not(target_vendor = "win7"))]
1321+
Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS | c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1322+
#[cfg(target_vendor = "win7")]
1323+
ReplaceIfExists: 1,
1324+
});
1325+
1326+
(&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1327+
(&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
1328+
1329+
new.as_ptr()
1330+
.copy_to_nonoverlapping((&raw mut (*file_rename_info).FileName) as *mut u16, new.len());
1331+
}
1332+
1333+
#[cfg(not(target_vendor = "win7"))]
1334+
const FileInformationClass: c::FILE_INFO_BY_HANDLE_CLASS = c::FileRenameInfoEx;
1335+
#[cfg(target_vendor = "win7")]
1336+
const FileInformationClass: c::FILE_INFO_BY_HANDLE_CLASS = c::FileRenameInfo;
1337+
1338+
// We don't use `set_file_information_by_handle` here as `FILE_RENAME_INFO` is used for both `FileRenameInfo` and `FileRenameInfoEx`.
1339+
let result = unsafe {
1340+
cvt(c::SetFileInformationByHandle(
1341+
handle.as_raw_handle(),
1342+
FileInformationClass,
1343+
(&raw const *file_rename_info).cast::<c_void>(),
1344+
struct_size,
1345+
))
1346+
};
1347+
1348+
#[cfg(not(target_vendor = "win7"))]
1349+
if let Err(err) = result {
1350+
if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as _) {
1351+
// FileRenameInfoEx and FILE_RENAME_FLAG_POSIX_SEMANTICS were added in Windows 10 1607; retry with FileRenameInfo.
1352+
file_rename_info.Anonymous.ReplaceIfExists = 1;
1353+
1354+
cvt(unsafe {
1355+
c::SetFileInformationByHandle(
1356+
handle.as_raw_handle(),
1357+
c::FileRenameInfo,
1358+
(&raw const *file_rename_info).cast::<c_void>(),
1359+
struct_size,
1360+
)
1361+
})?;
1362+
} else {
1363+
return Err(err);
1364+
}
1365+
}
1366+
1367+
#[cfg(target_vendor = "win7")]
1368+
result?;
1369+
12271370
Ok(())
12281371
}
12291372

0 commit comments

Comments
 (0)