1 use crate::os::windows::prelude::*;
3 use crate::borrow::Cow;
4 use crate::ffi::OsString;
6 use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
7 use crate::mem::{self, MaybeUninit};
8 use crate::os::windows::io::{AsHandle, BorrowedHandle};
9 use crate::path::{Path, PathBuf};
13 use crate::sys::handle::Handle;
14 use crate::sys::time::SystemTime;
15 use crate::sys::{c, cvt, Align8};
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
19 use super::path::maybe_verbatim;
29 creation_time: c::FILETIME,
30 last_access_time: c::FILETIME,
31 last_write_time: c::FILETIME,
33 reparse_tag: c::DWORD,
34 volume_serial_number: Option<u32>,
35 number_of_links: Option<u32>,
36 file_index: Option<u64>,
39 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
42 reparse_tag: c::DWORD,
46 handle: FindNextFileHandle,
48 first: Option<c::WIN32_FIND_DATAW>,
51 struct FindNextFileHandle(c::HANDLE);
53 unsafe impl Send for FindNextFileHandle {}
54 unsafe impl Sync for FindNextFileHandle {}
58 data: c::WIN32_FIND_DATAW,
61 unsafe impl Send for OpenOptions {}
62 unsafe impl Sync for OpenOptions {}
64 #[derive(Clone, Debug)]
65 pub struct OpenOptions {
75 access_mode: Option<c::DWORD>,
78 security_qos_flags: c::DWORD,
79 security_attributes: c::LPSECURITY_ATTRIBUTES,
82 #[derive(Clone, PartialEq, Eq, Debug)]
83 pub struct FilePermissions {
87 #[derive(Copy, Clone, Debug, Default)]
88 pub struct FileTimes {
89 accessed: Option<c::FILETIME>,
90 modified: Option<c::FILETIME>,
94 pub struct DirBuilder;
96 impl fmt::Debug for ReadDir {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
99 // Thus the result will be e g 'ReadDir("C:\")'
100 fmt::Debug::fmt(&*self.root, f)
104 impl Iterator for ReadDir {
105 type Item = io::Result<DirEntry>;
106 fn next(&mut self) -> Option<io::Result<DirEntry>> {
107 if let Some(first) = self.first.take() {
108 if let Some(e) = DirEntry::new(&self.root, &first) {
113 let mut wfd = mem::zeroed();
115 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
116 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
119 return Some(Err(Error::last_os_error()));
122 if let Some(e) = DirEntry::new(&self.root, &wfd) {
130 impl Drop for FindNextFileHandle {
132 let r = unsafe { c::FindClose(self.0) };
133 debug_assert!(r != 0);
138 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
139 match &wfd.cFileName[0..3] {
140 // check for '.' and '..'
141 &[46, 0, ..] | &[46, 46, 0, ..] => return None,
145 Some(DirEntry { root: root.clone(), data: *wfd })
148 pub fn path(&self) -> PathBuf {
149 self.root.join(&self.file_name())
152 pub fn file_name(&self) -> OsString {
153 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
154 OsString::from_wide(filename)
157 pub fn file_type(&self) -> io::Result<FileType> {
159 self.data.dwFileAttributes,
160 /* reparse_tag = */ self.data.dwReserved0,
164 pub fn metadata(&self) -> io::Result<FileAttr> {
170 pub fn new() -> OpenOptions {
182 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
184 security_qos_flags: 0,
185 security_attributes: ptr::null_mut(),
189 pub fn read(&mut self, read: bool) {
192 pub fn write(&mut self, write: bool) {
195 pub fn append(&mut self, append: bool) {
196 self.append = append;
198 pub fn truncate(&mut self, truncate: bool) {
199 self.truncate = truncate;
201 pub fn create(&mut self, create: bool) {
202 self.create = create;
204 pub fn create_new(&mut self, create_new: bool) {
205 self.create_new = create_new;
208 pub fn custom_flags(&mut self, flags: u32) {
209 self.custom_flags = flags;
211 pub fn access_mode(&mut self, access_mode: u32) {
212 self.access_mode = Some(access_mode);
214 pub fn share_mode(&mut self, share_mode: u32) {
215 self.share_mode = share_mode;
217 pub fn attributes(&mut self, attrs: u32) {
218 self.attributes = attrs;
220 pub fn security_qos_flags(&mut self, flags: u32) {
221 // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
222 // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
223 self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
225 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
226 self.security_attributes = attrs;
229 fn get_access_mode(&self) -> io::Result<c::DWORD> {
230 const ERROR_INVALID_PARAMETER: i32 = 87;
232 match (self.read, self.write, self.append, self.access_mode) {
233 (.., Some(mode)) => Ok(mode),
234 (true, false, false, None) => Ok(c::GENERIC_READ),
235 (false, true, false, None) => Ok(c::GENERIC_WRITE),
236 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
237 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
238 (true, _, true, None) => {
239 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
241 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
245 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
246 const ERROR_INVALID_PARAMETER: i32 = 87;
248 match (self.write, self.append) {
251 if self.truncate || self.create || self.create_new {
252 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
256 if self.truncate && !self.create_new {
257 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
262 Ok(match (self.create, self.truncate, self.create_new) {
263 (false, false, false) => c::OPEN_EXISTING,
264 (true, false, false) => c::OPEN_ALWAYS,
265 (false, true, false) => c::TRUNCATE_EXISTING,
266 (true, true, false) => c::CREATE_ALWAYS,
267 (_, _, true) => c::CREATE_NEW,
271 fn get_flags_and_attributes(&self) -> c::DWORD {
274 | self.security_qos_flags
275 | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
280 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
281 let path = maybe_verbatim(path)?;
282 let handle = unsafe {
285 opts.get_access_mode()?,
287 opts.security_attributes,
288 opts.get_creation_mode()?,
289 opts.get_flags_and_attributes(),
293 if let Ok(handle) = handle.try_into() {
294 Ok(File { handle: Handle::from_inner(handle) })
296 Err(Error::last_os_error())
300 pub fn fsync(&self) -> io::Result<()> {
301 cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
305 pub fn datasync(&self) -> io::Result<()> {
309 pub fn truncate(&self, size: u64) -> io::Result<()> {
310 let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
311 let size = mem::size_of_val(&info);
313 c::SetFileInformationByHandle(
314 self.handle.as_raw_handle(),
315 c::FileEndOfFileInfo,
316 &mut info as *mut _ as *mut _,
323 #[cfg(not(target_vendor = "uwp"))]
324 pub fn file_attr(&self) -> io::Result<FileAttr> {
326 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
327 cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
328 let mut reparse_tag = 0;
329 if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
330 let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
331 cvt(c::GetFileInformationByHandleEx(
332 self.handle.as_raw_handle(),
333 c::FileAttributeTagInfo,
334 ptr::addr_of_mut!(attr_tag).cast(),
335 mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
337 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
338 reparse_tag = attr_tag.ReparseTag;
342 attributes: info.dwFileAttributes,
343 creation_time: info.ftCreationTime,
344 last_access_time: info.ftLastAccessTime,
345 last_write_time: info.ftLastWriteTime,
346 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
348 volume_serial_number: Some(info.dwVolumeSerialNumber),
349 number_of_links: Some(info.nNumberOfLinks),
351 (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
357 #[cfg(target_vendor = "uwp")]
358 pub fn file_attr(&self) -> io::Result<FileAttr> {
360 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
361 let size = mem::size_of_val(&info);
362 cvt(c::GetFileInformationByHandleEx(
363 self.handle.as_raw_handle(),
365 &mut info as *mut _ as *mut libc::c_void,
368 let mut attr = FileAttr {
369 attributes: info.FileAttributes,
370 creation_time: c::FILETIME {
371 dwLowDateTime: info.CreationTime as c::DWORD,
372 dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
374 last_access_time: c::FILETIME {
375 dwLowDateTime: info.LastAccessTime as c::DWORD,
376 dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
378 last_write_time: c::FILETIME {
379 dwLowDateTime: info.LastWriteTime as c::DWORD,
380 dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
384 volume_serial_number: None,
385 number_of_links: None,
388 let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
389 let size = mem::size_of_val(&info);
390 cvt(c::GetFileInformationByHandleEx(
391 self.handle.as_raw_handle(),
393 &mut info as *mut _ as *mut libc::c_void,
396 attr.file_size = info.AllocationSize as u64;
397 attr.number_of_links = Some(info.NumberOfLinks);
398 if attr.file_type().is_reparse_point() {
399 let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
400 cvt(c::GetFileInformationByHandleEx(
401 self.handle.as_raw_handle(),
402 c::FileAttributeTagInfo,
403 ptr::addr_of_mut!(attr_tag).cast(),
404 mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
406 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
407 attr.reparse_tag = attr_tag.ReparseTag;
414 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
415 self.handle.read(buf)
418 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
419 self.handle.read_vectored(bufs)
423 pub fn is_read_vectored(&self) -> bool {
424 self.handle.is_read_vectored()
427 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
428 self.handle.read_at(buf, offset)
431 pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
432 self.handle.read_buf(cursor)
435 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
436 self.handle.write(buf)
439 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
440 self.handle.write_vectored(bufs)
444 pub fn is_write_vectored(&self) -> bool {
445 self.handle.is_write_vectored()
448 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
449 self.handle.write_at(buf, offset)
452 pub fn flush(&self) -> io::Result<()> {
456 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
457 let (whence, pos) = match pos {
458 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
460 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
461 SeekFrom::End(n) => (c::FILE_END, n),
462 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
464 let pos = pos as c::LARGE_INTEGER;
466 cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
470 pub fn duplicate(&self) -> io::Result<File> {
471 Ok(Self { handle: self.handle.try_clone()? })
474 // NB: returned pointer is derived from `space`, and has provenance to
475 // match. A raw pointer is returned rather than a reference in order to
476 // avoid narrowing provenance to the actual `REPARSE_DATA_BUFFER`.
479 space: &mut Align8<[MaybeUninit<u8>]>,
480 ) -> io::Result<(c::DWORD, *const c::REPARSE_DATA_BUFFER)> {
484 // Grab this in advance to avoid it invalidating the pointer
485 // we get from `space.0.as_mut_ptr()`.
486 let len = space.0.len();
488 self.handle.as_raw_handle(),
489 c::FSCTL_GET_REPARSE_POINT,
492 space.0.as_mut_ptr().cast(),
498 const _: () = assert!(core::mem::align_of::<c::REPARSE_DATA_BUFFER>() <= 8);
499 Ok((bytes, space.0.as_ptr().cast::<c::REPARSE_DATA_BUFFER>()))
503 fn readlink(&self) -> io::Result<PathBuf> {
504 let mut space = Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
505 let (_bytes, buf) = self.reparse_point(&mut space)?;
507 let (path_buffer, subst_off, subst_len, relative) = match (*buf).ReparseTag {
508 c::IO_REPARSE_TAG_SYMLINK => {
509 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
510 ptr::addr_of!((*buf).rest).cast();
511 assert!(info.is_aligned());
513 ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
514 (*info).SubstituteNameOffset / 2,
515 (*info).SubstituteNameLength / 2,
516 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
519 c::IO_REPARSE_TAG_MOUNT_POINT => {
520 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
521 ptr::addr_of!((*buf).rest).cast();
522 assert!(info.is_aligned());
524 ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
525 (*info).SubstituteNameOffset / 2,
526 (*info).SubstituteNameLength / 2,
531 return Err(io::const_io_error!(
532 io::ErrorKind::Uncategorized,
533 "Unsupported reparse point type",
537 let subst_ptr = path_buffer.add(subst_off.into());
538 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
539 // Absolute paths start with an NT internal namespace prefix `\??\`
540 // We should not let it leak through.
541 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
544 Ok(PathBuf::from(OsString::from_wide(subst)))
548 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
549 let mut info = c::FILE_BASIC_INFO {
554 FileAttributes: perm.attrs,
556 let size = mem::size_of_val(&info);
558 c::SetFileInformationByHandle(
559 self.handle.as_raw_handle(),
561 &mut info as *mut _ as *mut _,
568 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
569 let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0;
570 if times.accessed.map_or(false, is_zero) || times.modified.map_or(false, is_zero) {
571 return Err(io::const_io_error!(
572 io::ErrorKind::InvalidInput,
573 "Cannot set file timestamp to 0",
577 |t: c::FILETIME| t.dwLowDateTime == c::DWORD::MAX && t.dwHighDateTime == c::DWORD::MAX;
578 if times.accessed.map_or(false, is_max) || times.modified.map_or(false, is_max) {
579 return Err(io::const_io_error!(
580 io::ErrorKind::InvalidInput,
581 "Cannot set file timestamp to 0xFFFF_FFFF_FFFF_FFFF",
585 c::SetFileTime(self.as_handle(), None, times.accessed.as_ref(), times.modified.as_ref())
590 /// Get only basic file information such as attributes and file times.
591 fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
593 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
594 let size = mem::size_of_val(&info);
595 cvt(c::GetFileInformationByHandleEx(
596 self.handle.as_raw_handle(),
598 &mut info as *mut _ as *mut libc::c_void,
604 /// Delete using POSIX semantics.
606 /// Files will be deleted as soon as the handle is closed. This is supported
607 /// for Windows 10 1607 (aka RS1) and later. However some filesystem
608 /// drivers will not support it even then, e.g. FAT32.
610 /// If the operation is not supported for this filesystem or OS version
611 /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
612 fn posix_delete(&self) -> io::Result<()> {
613 let mut info = c::FILE_DISPOSITION_INFO_EX {
614 Flags: c::FILE_DISPOSITION_DELETE
615 | c::FILE_DISPOSITION_POSIX_SEMANTICS
616 | c::FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,
618 let size = mem::size_of_val(&info);
620 c::SetFileInformationByHandle(
621 self.handle.as_raw_handle(),
622 c::FileDispositionInfoEx,
623 &mut info as *mut _ as *mut _,
630 /// Delete a file using win32 semantics. The file won't actually be deleted
631 /// until all file handles are closed. However, marking a file for deletion
632 /// will prevent anyone from opening a new handle to the file.
633 fn win32_delete(&self) -> io::Result<()> {
634 let mut info = c::FILE_DISPOSITION_INFO { DeleteFile: c::TRUE as _ };
635 let size = mem::size_of_val(&info);
637 c::SetFileInformationByHandle(
638 self.handle.as_raw_handle(),
639 c::FileDispositionInfo,
640 &mut info as *mut _ as *mut _,
647 /// Fill the given buffer with as many directory entries as will fit.
648 /// This will remember its position and continue from the last call unless
649 /// `restart` is set to `true`.
651 /// The returned bool indicates if there are more entries or not.
652 /// It is an error if `self` is not a directory.
654 /// # Symlinks and other reparse points
656 /// On Windows a file is either a directory or a non-directory.
657 /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
658 /// So if you open a link (not its target) and iterate the directory,
659 /// you will always iterate an empty directory regardless of the target.
660 fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool> {
662 if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
665 let result = cvt(c::GetFileInformationByHandleEx(
666 self.handle.as_raw_handle(),
668 buffer.as_mut_ptr().cast(),
669 buffer.capacity() as _,
673 Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
680 /// A buffer for holding directory entries.
682 buffer: Box<Align8<[MaybeUninit<u8>; Self::BUFFER_SIZE]>>,
685 const BUFFER_SIZE: usize = 1024;
688 // Safety: `Align8<[MaybeUninit<u8>; N]>` does not need
690 buffer: unsafe { Box::new_uninit().assume_init() },
693 fn capacity(&self) -> usize {
696 fn as_mut_ptr(&mut self) -> *mut u8 {
697 self.buffer.0.as_mut_ptr().cast()
699 /// Returns a `DirBuffIter`.
700 fn iter(&self) -> DirBuffIter<'_> {
701 DirBuffIter::new(self)
704 impl AsRef<[MaybeUninit<u8>]> for DirBuff {
705 fn as_ref(&self) -> &[MaybeUninit<u8>] {
710 /// An iterator over entries stored in a `DirBuff`.
712 /// Currently only returns file names (UTF-16 encoded).
713 struct DirBuffIter<'a> {
714 buffer: Option<&'a [MaybeUninit<u8>]>,
717 impl<'a> DirBuffIter<'a> {
718 fn new(buffer: &'a DirBuff) -> Self {
719 Self { buffer: Some(buffer.as_ref()), cursor: 0 }
722 impl<'a> Iterator for DirBuffIter<'a> {
723 type Item = (Cow<'a, [u16]>, bool);
724 fn next(&mut self) -> Option<Self::Item> {
725 use crate::mem::size_of;
726 let buffer = &self.buffer?[self.cursor..];
728 // Get the name and next entry from the buffer.
730 // - The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the last
731 // field (the file name) is unsized. So an offset has to be used to
732 // get the file name slice.
733 // - The OS has guaranteed initialization of the fields of
734 // `FILE_ID_BOTH_DIR_INFO` and the trailing filename (for at least
735 // `FileNameLength` bytes)
736 let (name, is_directory, next_entry) = unsafe {
737 let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
738 // While this is guaranteed to be aligned in documentation for
739 // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_both_dir_info
740 // it does not seem that reality is so kind, and assuming this
741 // caused crashes in some cases (https://github.com/rust-lang/rust/issues/104530)
742 // presumably, this can be blamed on buggy filesystem drivers, but who knows.
743 let next_entry = ptr::addr_of!((*info).NextEntryOffset).read_unaligned() as usize;
744 let length = ptr::addr_of!((*info).FileNameLength).read_unaligned() as usize;
745 let attrs = ptr::addr_of!((*info).FileAttributes).read_unaligned();
746 let name = from_maybe_unaligned(
747 ptr::addr_of!((*info).FileName).cast::<u16>(),
748 length / size_of::<u16>(),
750 let is_directory = (attrs & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
752 (name, is_directory, next_entry)
758 self.cursor += next_entry
761 // Skip `.` and `..` pseudo entries.
762 const DOT: u16 = b'.' as u16;
764 [DOT] | [DOT, DOT] => self.next(),
765 _ => Some((name, is_directory)),
770 unsafe fn from_maybe_unaligned<'a>(p: *const u16, len: usize) -> Cow<'a, [u16]> {
772 Cow::Borrowed(crate::slice::from_raw_parts(p, len))
774 Cow::Owned((0..len).map(|i| p.add(i).read_unaligned()).collect())
778 /// Open a link relative to the parent directory, ensure no symlinks are followed.
779 fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File> {
780 // This is implemented using the lower level `NtCreateFile` function as
781 // unfortunately opening a file relative to a parent is not supported by
782 // win32 functions. It is however a fundamental feature of the NT kernel.
784 // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
786 let mut handle = ptr::null_mut();
787 let mut io_status = c::IO_STATUS_BLOCK::default();
788 let name_str = c::UNICODE_STRING::from_ref(name);
789 use crate::sync::atomic::{AtomicU32, Ordering};
790 // The `OBJ_DONT_REPARSE` attribute ensures that we haven't been
791 // tricked into following a symlink. However, it may not be available in
792 // earlier versions of Windows.
793 static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
794 let object = c::OBJECT_ATTRIBUTES {
795 ObjectName: &name_str,
796 RootDirectory: parent.as_raw_handle(),
797 Attributes: ATTRIBUTES.load(Ordering::Relaxed),
798 ..c::OBJECT_ATTRIBUTES::default()
800 let status = c::NtCreateFile(
805 crate::ptr::null_mut(),
807 c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
809 // If `name` is a symlink then open the link rather than the target.
810 c::FILE_OPEN_REPARSE_POINT,
811 crate::ptr::null_mut(),
814 // Convert an NTSTATUS to the more familiar Win32 error codes (aka "DosError")
815 if c::nt_success(status) {
816 Ok(File::from_raw_handle(handle))
817 } else if status == c::STATUS_DELETE_PENDING {
818 // We make a special exception for `STATUS_DELETE_PENDING` because
819 // otherwise this will be mapped to `ERROR_ACCESS_DENIED` which is
821 Err(io::Error::from_raw_os_error(c::ERROR_DELETE_PENDING as _))
822 } else if status == c::STATUS_INVALID_PARAMETER
823 && ATTRIBUTES.load(Ordering::Relaxed) == c::OBJ_DONT_REPARSE
825 // Try without `OBJ_DONT_REPARSE`. See above.
826 ATTRIBUTES.store(0, Ordering::Relaxed);
827 open_link_no_reparse(parent, name, access)
829 Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
834 impl AsInner<Handle> for File {
835 fn as_inner(&self) -> &Handle {
840 impl IntoInner<Handle> for File {
841 fn into_inner(self) -> Handle {
846 impl FromInner<Handle> for File {
847 fn from_inner(handle: Handle) -> File {
852 impl AsHandle for File {
853 fn as_handle(&self) -> BorrowedHandle<'_> {
854 self.as_inner().as_handle()
858 impl AsRawHandle for File {
859 fn as_raw_handle(&self) -> RawHandle {
860 self.as_inner().as_raw_handle()
864 impl IntoRawHandle for File {
865 fn into_raw_handle(self) -> RawHandle {
866 self.into_inner().into_raw_handle()
870 impl FromRawHandle for File {
871 unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
872 Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
876 impl fmt::Debug for File {
877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
878 // FIXME(#24570): add more info here (e.g., mode)
879 let mut b = f.debug_struct("File");
880 b.field("handle", &self.handle.as_raw_handle());
881 if let Ok(path) = get_path(&self) {
882 b.field("path", &path);
889 pub fn size(&self) -> u64 {
893 pub fn perm(&self) -> FilePermissions {
894 FilePermissions { attrs: self.attributes }
897 pub fn attrs(&self) -> u32 {
901 pub fn file_type(&self) -> FileType {
902 FileType::new(self.attributes, self.reparse_tag)
905 pub fn modified(&self) -> io::Result<SystemTime> {
906 Ok(SystemTime::from(self.last_write_time))
909 pub fn accessed(&self) -> io::Result<SystemTime> {
910 Ok(SystemTime::from(self.last_access_time))
913 pub fn created(&self) -> io::Result<SystemTime> {
914 Ok(SystemTime::from(self.creation_time))
917 pub fn modified_u64(&self) -> u64 {
918 to_u64(&self.last_write_time)
921 pub fn accessed_u64(&self) -> u64 {
922 to_u64(&self.last_access_time)
925 pub fn created_u64(&self) -> u64 {
926 to_u64(&self.creation_time)
929 pub fn volume_serial_number(&self) -> Option<u32> {
930 self.volume_serial_number
933 pub fn number_of_links(&self) -> Option<u32> {
937 pub fn file_index(&self) -> Option<u64> {
941 impl From<c::WIN32_FIND_DATAW> for FileAttr {
942 fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
944 attributes: wfd.dwFileAttributes,
945 creation_time: wfd.ftCreationTime,
946 last_access_time: wfd.ftLastAccessTime,
947 last_write_time: wfd.ftLastWriteTime,
948 file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
949 reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
950 // reserved unless this is a reparse point
955 volume_serial_number: None,
956 number_of_links: None,
962 fn to_u64(ft: &c::FILETIME) -> u64 {
963 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
966 impl FilePermissions {
967 pub fn readonly(&self) -> bool {
968 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
971 pub fn set_readonly(&mut self, readonly: bool) {
973 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
975 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
981 pub fn set_accessed(&mut self, t: SystemTime) {
982 self.accessed = Some(t.into_inner());
985 pub fn set_modified(&mut self, t: SystemTime) {
986 self.modified = Some(t.into_inner());
991 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
992 FileType { attributes: attrs, reparse_tag }
994 pub fn is_dir(&self) -> bool {
995 !self.is_symlink() && self.is_directory()
997 pub fn is_file(&self) -> bool {
998 !self.is_symlink() && !self.is_directory()
1000 pub fn is_symlink(&self) -> bool {
1001 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
1003 pub fn is_symlink_dir(&self) -> bool {
1004 self.is_symlink() && self.is_directory()
1006 pub fn is_symlink_file(&self) -> bool {
1007 self.is_symlink() && !self.is_directory()
1009 fn is_directory(&self) -> bool {
1010 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
1012 fn is_reparse_point(&self) -> bool {
1013 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
1015 fn is_reparse_tag_name_surrogate(&self) -> bool {
1016 self.reparse_tag & 0x20000000 != 0
1021 pub fn new() -> DirBuilder {
1025 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1026 let p = maybe_verbatim(p)?;
1027 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
1032 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1033 let root = p.to_path_buf();
1034 let star = p.join("*");
1035 let path = maybe_verbatim(&star)?;
1038 let mut wfd = mem::zeroed();
1039 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
1040 if find_handle != c::INVALID_HANDLE_VALUE {
1042 handle: FindNextFileHandle(find_handle),
1043 root: Arc::new(root),
1047 Err(Error::last_os_error())
1052 pub fn unlink(p: &Path) -> io::Result<()> {
1053 let p_u16s = maybe_verbatim(p)?;
1054 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
1058 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1059 let old = maybe_verbatim(old)?;
1060 let new = maybe_verbatim(new)?;
1061 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
1065 pub fn rmdir(p: &Path) -> io::Result<()> {
1066 let p = maybe_verbatim(p)?;
1067 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
1071 /// Open a file or directory without following symlinks.
1072 fn open_link(path: &Path, access_mode: u32) -> io::Result<File> {
1073 let mut opts = OpenOptions::new();
1074 opts.access_mode(access_mode);
1075 // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
1076 // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
1077 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1078 File::open(path, &opts)
1081 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
1082 let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
1084 // Test if the file is not a directory or a symlink to a directory.
1085 if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
1086 return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
1089 match remove_dir_all_iterative(&file, File::posix_delete) {
1091 if let Some(code) = e.raw_os_error() {
1093 // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
1094 c::ERROR_NOT_SUPPORTED
1095 | c::ERROR_INVALID_FUNCTION
1096 | c::ERROR_INVALID_PARAMETER => {
1097 remove_dir_all_iterative(&file, File::win32_delete)
1109 fn remove_dir_all_iterative(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()> {
1110 // When deleting files we may loop this many times when certain error conditions occur.
1111 // This allows remove_dir_all to succeed when the error is temporary.
1112 const MAX_RETRIES: u32 = 10;
1114 let mut buffer = DirBuff::new();
1115 let mut dirlist = vec![f.duplicate()?];
1117 // FIXME: This is a hack so we can push to the dirlist vec after borrowing from it.
1118 fn copy_handle(f: &File) -> mem::ManuallyDrop<File> {
1119 unsafe { mem::ManuallyDrop::new(File::from_raw_handle(f.as_raw_handle())) }
1122 let mut restart = true;
1123 while let Some(dir) = dirlist.last() {
1124 let dir = copy_handle(dir);
1126 // Fill the buffer and iterate the entries.
1127 let more_data = dir.fill_dir_buff(&mut buffer, restart)?;
1129 for (name, is_directory) in buffer.iter() {
1131 let child_dir = open_link_no_reparse(
1134 c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY,
1136 dirlist.push(child_dir);
1138 for i in 1..=MAX_RETRIES {
1139 let result = open_link_no_reparse(&dir, &name, c::SYNCHRONIZE | c::DELETE);
1141 Ok(f) => delete(&f)?,
1142 // Already deleted, so skip.
1143 Err(e) if e.kind() == io::ErrorKind::NotFound => break,
1144 // Retry a few times if the file is locked or a delete is already in progress.
1147 && (e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
1149 == Some(c::ERROR_SHARING_VIOLATION as _)) => {}
1150 // Otherwise return the error.
1151 Err(e) => return Err(e),
1153 thread::yield_now();
1157 // If there were no more files then delete the directory.
1159 if let Some(dir) = dirlist.pop() {
1160 // Retry deleting a few times in case we need to wait for a file to be deleted.
1161 for i in 1..=MAX_RETRIES {
1162 let result = delete(&dir);
1163 if let Err(e) = result {
1164 if i == MAX_RETRIES || e.kind() != io::ErrorKind::DirectoryNotEmpty {
1167 thread::yield_now();
1178 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
1179 // Open the link with no access mode, instead of generic read.
1180 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1181 // this is needed for a common case.
1182 let mut opts = OpenOptions::new();
1183 opts.access_mode(0);
1184 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1185 let file = File::open(&path, &opts)?;
1189 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1190 symlink_inner(original, link, false)
1193 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1194 let original = to_u16s(original)?;
1195 let link = maybe_verbatim(link)?;
1196 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1197 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1198 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1199 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1200 // added to dwFlags to opt into this behaviour.
1201 let result = cvt(unsafe {
1202 c::CreateSymbolicLinkW(
1205 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1208 if let Err(err) = result {
1209 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1210 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1211 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1213 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1222 #[cfg(not(target_vendor = "uwp"))]
1223 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1224 let original = maybe_verbatim(original)?;
1225 let link = maybe_verbatim(link)?;
1226 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1230 #[cfg(target_vendor = "uwp")]
1231 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
1232 return Err(io::const_io_error!(
1233 io::ErrorKind::Unsupported,
1234 "hard link are not supported on UWP",
1238 pub fn stat(path: &Path) -> io::Result<FileAttr> {
1239 metadata(path, ReparsePoint::Follow)
1242 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
1243 metadata(path, ReparsePoint::Open)
1247 #[derive(Clone, Copy, PartialEq, Eq)]
1250 Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
1253 fn as_flag(self) -> u32 {
1258 fn metadata(path: &Path, reparse: ReparsePoint) -> io::Result<FileAttr> {
1259 let mut opts = OpenOptions::new();
1260 // No read or write permissions are necessary
1261 opts.access_mode(0);
1262 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());
1264 // Attempt to open the file normally.
1265 // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileW`.
1266 // If the fallback fails for any reason we return the original error.
1267 match File::open(path, &opts) {
1268 Ok(file) => file.file_attr(),
1269 Err(e) if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {
1270 // `ERROR_SHARING_VIOLATION` will almost never be returned.
1271 // Usually if a file is locked you can still read some metadata.
1272 // However, there are special system files, such as
1273 // `C:\hiberfil.sys`, that are locked in a way that denies even that.
1275 let path = maybe_verbatim(path)?;
1277 // `FindFirstFileW` accepts wildcard file names.
1278 // Fortunately wildcards are not valid file names and
1279 // `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
1280 // therefore it's safe to assume the file name given does not
1281 // include wildcards.
1282 let mut wfd = mem::zeroed();
1283 let handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
1285 if handle == c::INVALID_HANDLE_VALUE {
1286 // This can fail if the user does not have read access to the
1290 // We no longer need the find handle.
1291 c::FindClose(handle);
1293 // `FindFirstFileW` reads the cached file information from the
1294 // directory. The downside is that this metadata may be outdated.
1295 let attrs = FileAttr::from(wfd);
1296 if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
1308 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1309 let p = maybe_verbatim(p)?;
1311 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1316 fn get_path(f: &File) -> io::Result<PathBuf> {
1317 super::fill_utf16_buf(
1319 c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1321 |buf| PathBuf::from(OsString::from_wide(buf)),
1325 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1326 let mut opts = OpenOptions::new();
1327 // No read or write permissions are necessary
1328 opts.access_mode(0);
1329 // This flag is so we can open directories too
1330 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1331 let f = File::open(p, &opts)?;
1335 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1336 unsafe extern "system" fn callback(
1337 _TotalFileSize: c::LARGE_INTEGER,
1338 _TotalBytesTransferred: c::LARGE_INTEGER,
1339 _StreamSize: c::LARGE_INTEGER,
1340 StreamBytesTransferred: c::LARGE_INTEGER,
1341 dwStreamNumber: c::DWORD,
1342 _dwCallbackReason: c::DWORD,
1343 _hSourceFile: c::HANDLE,
1344 _hDestinationFile: c::HANDLE,
1347 if dwStreamNumber == 1 {
1348 *(lpData as *mut i64) = StreamBytesTransferred;
1350 c::PROGRESS_CONTINUE
1352 let pfrom = maybe_verbatim(from)?;
1353 let pto = maybe_verbatim(to)?;
1354 let mut size = 0i64;
1360 &mut size as *mut _ as *mut _,
1369 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
1372 ) -> io::Result<()> {
1373 symlink_junction_inner(original.as_ref(), junction.as_ref())
1376 // Creating a directory junction on windows involves dealing with reparse
1377 // points and the DeviceIoControl function, and this code is a skeleton of
1378 // what can be found here:
1380 // http://www.flexhex.com/docs/articles/hard-links.phtml
1382 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
1383 let d = DirBuilder::new();
1384 d.mkdir(&junction)?;
1386 let mut opts = OpenOptions::new();
1388 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1389 let f = File::open(junction, &opts)?;
1390 let h = f.as_inner().as_raw_handle();
1393 let mut data = Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
1394 let data_ptr = data.0.as_mut_ptr();
1395 let db = data_ptr.cast::<c::REPARSE_MOUNTPOINT_DATA_BUFFER>();
1396 let buf = ptr::addr_of_mut!((*db).ReparseTarget).cast::<c::WCHAR>();
1398 // FIXME: this conversion is very hacky
1400 let v = v.iter().map(|x| *x as u16);
1401 for c in v.chain(original.as_os_str().encode_wide()) {
1407 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
1408 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
1409 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
1410 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
1413 cvt(c::DeviceIoControl(
1415 c::FSCTL_SET_REPARSE_POINT,
1417 (*db).ReparseDataLength + 8,
1427 // Try to see if a file exists but, unlike `exists`, report I/O errors.
1428 pub fn try_exists(path: &Path) -> io::Result<bool> {
1429 // Open the file to ensure any symlinks are followed to their target.
1430 let mut opts = OpenOptions::new();
1431 // No read, write, etc access rights are needed.
1432 opts.access_mode(0);
1433 // Backup semantics enables opening directories as well as files.
1434 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1435 match File::open(path, &opts) {
1436 Err(e) => match e.kind() {
1437 // The file definitely does not exist
1438 io::ErrorKind::NotFound => Ok(false),
1440 // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1441 // another process. This is often temporary so we simply report it
1442 // as the file existing.
1443 _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1445 // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1446 // file exists. However, these types of errors are usually more
1447 // permanent so we report them here.
1450 // The file was opened successfully therefore it must exist,