Skip to content

Commit 8a10301

Browse files
committed
Make File::create work on Windows hidden files
Previously it failed on Windows if the file had the `FILE_ATTRIBUTE_HIDDEN` attribute set. This was inconsistent with `OpenOptions::new().write(true).truncate(true)` which can truncate an existing hidden file.
1 parent afe67fa commit 8a10301

File tree

4 files changed

+61
-5
lines changed

4 files changed

+61
-5
lines changed

library/std/src/fs/tests.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use crate::os::unix::fs::symlink as symlink_file;
2222
#[cfg(unix)]
2323
use crate::os::unix::fs::symlink as symlink_junction;
2424
#[cfg(windows)]
25-
use crate::os::windows::fs::{symlink_dir, symlink_file};
25+
use crate::os::windows::fs::{symlink_dir, symlink_file, OpenOptionsExt};
2626
#[cfg(windows)]
2727
use crate::sys::fs::symlink_junction;
2828
#[cfg(target_os = "macos")]
@@ -1707,3 +1707,28 @@ fn test_file_times() {
17071707
assert_eq!(metadata.created().unwrap(), created);
17081708
}
17091709
}
1710+
1711+
#[cfg(windows)]
1712+
#[test]
1713+
fn test_hidden_file_truncation() {
1714+
// Make sure that File::create works on an existing hidden file. See #115745.
1715+
let tmpdir = tmpdir();
1716+
let path = tmpdir.join("hidden_file.txt");
1717+
1718+
// Create a hidden file.
1719+
const FILE_ATTRIBUTE_HIDDEN: u32 = 2;
1720+
let mut file = OpenOptions::new()
1721+
.write(true)
1722+
.create_new(true)
1723+
.attributes(FILE_ATTRIBUTE_HIDDEN)
1724+
.open(&path)
1725+
.unwrap();
1726+
file.write("hidden world!".as_bytes()).unwrap();
1727+
file.flush().unwrap();
1728+
drop(file);
1729+
1730+
// Create a new file by truncating the existing one.
1731+
let file = File::create(&path).unwrap();
1732+
let metadata = file.metadata().unwrap();
1733+
assert_eq!(metadata.len(), 0);
1734+
}

library/std/src/sys/windows/c/windows_sys.lst

+1
Original file line numberDiff line numberDiff line change
@@ -2222,6 +2222,7 @@ Windows.Win32.Storage.FileSystem.FILE_ACCESS_RIGHTS
22222222
Windows.Win32.Storage.FileSystem.FILE_ADD_FILE
22232223
Windows.Win32.Storage.FileSystem.FILE_ADD_SUBDIRECTORY
22242224
Windows.Win32.Storage.FileSystem.FILE_ALL_ACCESS
2225+
Windows.Win32.Storage.FileSystem.FILE_ALLOCATION_INFO
22252226
Windows.Win32.Storage.FileSystem.FILE_APPEND_DATA
22262227
Windows.Win32.Storage.FileSystem.FILE_ATTRIBUTE_ARCHIVE
22272228
Windows.Win32.Storage.FileSystem.FILE_ATTRIBUTE_COMPRESSED

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

+10
Original file line numberDiff line numberDiff line change
@@ -3106,6 +3106,16 @@ impl ::core::clone::Clone for FILETIME {
31063106
pub type FILE_ACCESS_RIGHTS = u32;
31073107
pub const FILE_ADD_FILE: FILE_ACCESS_RIGHTS = 2u32;
31083108
pub const FILE_ADD_SUBDIRECTORY: FILE_ACCESS_RIGHTS = 4u32;
3109+
#[repr(C)]
3110+
pub struct FILE_ALLOCATION_INFO {
3111+
pub AllocationSize: i64,
3112+
}
3113+
impl ::core::marker::Copy for FILE_ALLOCATION_INFO {}
3114+
impl ::core::clone::Clone for FILE_ALLOCATION_INFO {
3115+
fn clone(&self) -> Self {
3116+
*self
3117+
}
3118+
}
31093119
pub const FILE_ALL_ACCESS: FILE_ACCESS_RIGHTS = 2032127u32;
31103120
pub const FILE_APPEND_DATA: FILE_ACCESS_RIGHTS = 4u32;
31113121
pub const FILE_ATTRIBUTE_ARCHIVE: FILE_FLAGS_AND_ATTRIBUTES = 32u32;

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

+24-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::os::windows::prelude::*;
22

33
use crate::borrow::Cow;
4-
use crate::ffi::OsString;
4+
use crate::ffi::{c_void, OsString};
55
use crate::fmt;
66
use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
77
use crate::mem::{self, MaybeUninit};
@@ -271,7 +271,9 @@ impl OpenOptions {
271271
(false, false, false) => c::OPEN_EXISTING,
272272
(true, false, false) => c::OPEN_ALWAYS,
273273
(false, true, false) => c::TRUNCATE_EXISTING,
274-
(true, true, false) => c::CREATE_ALWAYS,
274+
// `CREATE_ALWAYS` has weird semantics so we emulate it using
275+
// `OPEN_ALWAYS` and a manual truncation step. See #115745.
276+
(true, true, false) => c::OPEN_ALWAYS,
275277
(_, _, true) => c::CREATE_NEW,
276278
})
277279
}
@@ -287,19 +289,37 @@ impl OpenOptions {
287289
impl File {
288290
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
289291
let path = maybe_verbatim(path)?;
292+
let creation = opts.get_creation_mode()?;
290293
let handle = unsafe {
291294
c::CreateFileW(
292295
path.as_ptr(),
293296
opts.get_access_mode()?,
294297
opts.share_mode,
295298
opts.security_attributes,
296-
opts.get_creation_mode()?,
299+
creation,
297300
opts.get_flags_and_attributes(),
298301
ptr::null_mut(),
299302
)
300303
};
301304
let handle = unsafe { HandleOrInvalid::from_raw_handle(handle) };
302-
if let Ok(handle) = handle.try_into() {
305+
if let Ok(handle) = OwnedHandle::try_from(handle) {
306+
// Manual truncation. See #115745.
307+
if opts.truncate && creation == c::OPEN_ALWAYS {
308+
unsafe {
309+
// Setting the allocation size to zero also sets the
310+
// EOF position to zero.
311+
let alloc = c::FILE_ALLOCATION_INFO { AllocationSize: 0 };
312+
let result = c::SetFileInformationByHandle(
313+
handle.as_raw_handle(),
314+
c::FileAllocationInfo,
315+
ptr::addr_of!(alloc).cast::<c_void>(),
316+
mem::size_of::<c::FILE_ALLOCATION_INFO>() as u32,
317+
);
318+
if result == 0 {
319+
return Err(io::Error::last_os_error());
320+
}
321+
}
322+
}
303323
Ok(File { handle: Handle::from_inner(handle) })
304324
} else {
305325
Err(Error::last_os_error())

0 commit comments

Comments
 (0)