1 use crate::os::windows::prelude::*;
3 use crate::ffi::OsString;
5 use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
6 use crate::mem::{self, MaybeUninit};
7 use crate::os::windows::io::{AsHandle, BorrowedHandle};
8 use crate::path::{Path, PathBuf};
12 use crate::sys::handle::Handle;
13 use crate::sys::time::SystemTime;
14 use crate::sys::{c, cvt, Align8};
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
18 use super::path::maybe_verbatim;
28 creation_time: c::FILETIME,
29 last_access_time: c::FILETIME,
30 last_write_time: c::FILETIME,
32 reparse_tag: c::DWORD,
33 volume_serial_number: Option<u32>,
34 number_of_links: Option<u32>,
35 file_index: Option<u64>,
38 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
41 reparse_tag: c::DWORD,
45 handle: FindNextFileHandle,
47 first: Option<c::WIN32_FIND_DATAW>,
50 struct FindNextFileHandle(c::HANDLE);
52 unsafe impl Send for FindNextFileHandle {}
53 unsafe impl Sync for FindNextFileHandle {}
57 data: c::WIN32_FIND_DATAW,
60 unsafe impl Send for OpenOptions {}
61 unsafe impl Sync for OpenOptions {}
63 #[derive(Clone, Debug)]
64 pub struct OpenOptions {
74 access_mode: Option<c::DWORD>,
77 security_qos_flags: c::DWORD,
78 security_attributes: c::LPSECURITY_ATTRIBUTES,
81 #[derive(Clone, PartialEq, Eq, Debug)]
82 pub struct FilePermissions {
86 #[derive(Copy, Clone, Debug, Default)]
87 pub struct FileTimes {
88 accessed: Option<c::FILETIME>,
89 modified: Option<c::FILETIME>,
93 pub struct DirBuilder;
95 impl fmt::Debug for ReadDir {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
98 // Thus the result will be e g 'ReadDir("C:\")'
99 fmt::Debug::fmt(&*self.root, f)
103 impl Iterator for ReadDir {
104 type Item = io::Result<DirEntry>;
105 fn next(&mut self) -> Option<io::Result<DirEntry>> {
106 if let Some(first) = self.first.take() {
107 if let Some(e) = DirEntry::new(&self.root, &first) {
112 let mut wfd = mem::zeroed();
114 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
115 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
118 return Some(Err(Error::last_os_error()));
121 if let Some(e) = DirEntry::new(&self.root, &wfd) {
129 impl Drop for FindNextFileHandle {
131 let r = unsafe { c::FindClose(self.0) };
132 debug_assert!(r != 0);
137 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
138 match &wfd.cFileName[0..3] {
139 // check for '.' and '..'
140 &[46, 0, ..] | &[46, 46, 0, ..] => return None,
144 Some(DirEntry { root: root.clone(), data: *wfd })
147 pub fn path(&self) -> PathBuf {
148 self.root.join(&self.file_name())
151 pub fn file_name(&self) -> OsString {
152 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
153 OsString::from_wide(filename)
156 pub fn file_type(&self) -> io::Result<FileType> {
158 self.data.dwFileAttributes,
159 /* reparse_tag = */ self.data.dwReserved0,
163 pub fn metadata(&self) -> io::Result<FileAttr> {
169 pub fn new() -> OpenOptions {
181 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
183 security_qos_flags: 0,
184 security_attributes: ptr::null_mut(),
188 pub fn read(&mut self, read: bool) {
191 pub fn write(&mut self, write: bool) {
194 pub fn append(&mut self, append: bool) {
195 self.append = append;
197 pub fn truncate(&mut self, truncate: bool) {
198 self.truncate = truncate;
200 pub fn create(&mut self, create: bool) {
201 self.create = create;
203 pub fn create_new(&mut self, create_new: bool) {
204 self.create_new = create_new;
207 pub fn custom_flags(&mut self, flags: u32) {
208 self.custom_flags = flags;
210 pub fn access_mode(&mut self, access_mode: u32) {
211 self.access_mode = Some(access_mode);
213 pub fn share_mode(&mut self, share_mode: u32) {
214 self.share_mode = share_mode;
216 pub fn attributes(&mut self, attrs: u32) {
217 self.attributes = attrs;
219 pub fn security_qos_flags(&mut self, flags: u32) {
220 // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
221 // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
222 self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
224 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
225 self.security_attributes = attrs;
228 fn get_access_mode(&self) -> io::Result<c::DWORD> {
229 const ERROR_INVALID_PARAMETER: i32 = 87;
231 match (self.read, self.write, self.append, self.access_mode) {
232 (.., Some(mode)) => Ok(mode),
233 (true, false, false, None) => Ok(c::GENERIC_READ),
234 (false, true, false, None) => Ok(c::GENERIC_WRITE),
235 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
236 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
237 (true, _, true, None) => {
238 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
240 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
244 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
245 const ERROR_INVALID_PARAMETER: i32 = 87;
247 match (self.write, self.append) {
250 if self.truncate || self.create || self.create_new {
251 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
255 if self.truncate && !self.create_new {
256 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
261 Ok(match (self.create, self.truncate, self.create_new) {
262 (false, false, false) => c::OPEN_EXISTING,
263 (true, false, false) => c::OPEN_ALWAYS,
264 (false, true, false) => c::TRUNCATE_EXISTING,
265 (true, true, false) => c::CREATE_ALWAYS,
266 (_, _, true) => c::CREATE_NEW,
270 fn get_flags_and_attributes(&self) -> c::DWORD {
273 | self.security_qos_flags
274 | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
279 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
280 let path = maybe_verbatim(path)?;
281 let handle = unsafe {
284 opts.get_access_mode()?,
286 opts.security_attributes,
287 opts.get_creation_mode()?,
288 opts.get_flags_and_attributes(),
292 if let Ok(handle) = handle.try_into() {
293 Ok(File { handle: Handle::from_inner(handle) })
295 Err(Error::last_os_error())
299 pub fn fsync(&self) -> io::Result<()> {
300 cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
304 pub fn datasync(&self) -> io::Result<()> {
308 pub fn truncate(&self, size: u64) -> io::Result<()> {
309 let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
310 let size = mem::size_of_val(&info);
312 c::SetFileInformationByHandle(
313 self.handle.as_raw_handle(),
314 c::FileEndOfFileInfo,
315 &mut info as *mut _ as *mut _,
322 #[cfg(not(target_vendor = "uwp"))]
323 pub fn file_attr(&self) -> io::Result<FileAttr> {
325 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
326 cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
327 let mut reparse_tag = 0;
328 if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
329 let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
330 cvt(c::GetFileInformationByHandleEx(
331 self.handle.as_raw_handle(),
332 c::FileAttributeTagInfo,
333 ptr::addr_of_mut!(attr_tag).cast(),
334 mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
336 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
337 reparse_tag = attr_tag.ReparseTag;
341 attributes: info.dwFileAttributes,
342 creation_time: info.ftCreationTime,
343 last_access_time: info.ftLastAccessTime,
344 last_write_time: info.ftLastWriteTime,
345 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
347 volume_serial_number: Some(info.dwVolumeSerialNumber),
348 number_of_links: Some(info.nNumberOfLinks),
350 (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
356 #[cfg(target_vendor = "uwp")]
357 pub fn file_attr(&self) -> io::Result<FileAttr> {
359 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
360 let size = mem::size_of_val(&info);
361 cvt(c::GetFileInformationByHandleEx(
362 self.handle.as_raw_handle(),
364 &mut info as *mut _ as *mut libc::c_void,
367 let mut attr = FileAttr {
368 attributes: info.FileAttributes,
369 creation_time: c::FILETIME {
370 dwLowDateTime: info.CreationTime as c::DWORD,
371 dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
373 last_access_time: c::FILETIME {
374 dwLowDateTime: info.LastAccessTime as c::DWORD,
375 dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
377 last_write_time: c::FILETIME {
378 dwLowDateTime: info.LastWriteTime as c::DWORD,
379 dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
383 volume_serial_number: None,
384 number_of_links: None,
387 let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
388 let size = mem::size_of_val(&info);
389 cvt(c::GetFileInformationByHandleEx(
390 self.handle.as_raw_handle(),
392 &mut info as *mut _ as *mut libc::c_void,
395 attr.file_size = info.AllocationSize as u64;
396 attr.number_of_links = Some(info.NumberOfLinks);
397 if attr.file_type().is_reparse_point() {
398 let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
399 cvt(c::GetFileInformationByHandleEx(
400 self.handle.as_raw_handle(),
401 c::FileAttributeTagInfo,
402 ptr::addr_of_mut!(attr_tag).cast(),
403 mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
405 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
406 attr.reparse_tag = attr_tag.ReparseTag;
413 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
414 self.handle.read(buf)
417 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
418 self.handle.read_vectored(bufs)
422 pub fn is_read_vectored(&self) -> bool {
423 self.handle.is_read_vectored()
426 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
427 self.handle.read_at(buf, offset)
430 pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
431 self.handle.read_buf(cursor)
434 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
435 self.handle.write(buf)
438 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
439 self.handle.write_vectored(bufs)
443 pub fn is_write_vectored(&self) -> bool {
444 self.handle.is_write_vectored()
447 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
448 self.handle.write_at(buf, offset)
451 pub fn flush(&self) -> io::Result<()> {
455 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
456 let (whence, pos) = match pos {
457 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
459 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
460 SeekFrom::End(n) => (c::FILE_END, n),
461 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
463 let pos = pos as c::LARGE_INTEGER;
465 cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
469 pub fn duplicate(&self) -> io::Result<File> {
470 Ok(Self { handle: self.handle.try_clone()? })
473 // NB: returned pointer is derived from `space`, and has provenance to
474 // match. A raw pointer is returned rather than a reference in order to
475 // avoid narrowing provenance to the actual `REPARSE_DATA_BUFFER`.
478 space: &mut Align8<[MaybeUninit<u8>]>,
479 ) -> io::Result<(c::DWORD, *const c::REPARSE_DATA_BUFFER)> {
483 // Grab this in advance to avoid it invalidating the pointer
484 // we get from `space.0.as_mut_ptr()`.
485 let len = space.0.len();
487 self.handle.as_raw_handle(),
488 c::FSCTL_GET_REPARSE_POINT,
491 space.0.as_mut_ptr().cast(),
497 const _: () = assert!(core::mem::align_of::<c::REPARSE_DATA_BUFFER>() <= 8);
498 Ok((bytes, space.0.as_ptr().cast::<c::REPARSE_DATA_BUFFER>()))
502 fn readlink(&self) -> io::Result<PathBuf> {
503 let mut space = Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
504 let (_bytes, buf) = self.reparse_point(&mut space)?;
506 let (path_buffer, subst_off, subst_len, relative) = match (*buf).ReparseTag {
507 c::IO_REPARSE_TAG_SYMLINK => {
508 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
509 ptr::addr_of!((*buf).rest).cast();
510 assert!(info.is_aligned());
512 ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
513 (*info).SubstituteNameOffset / 2,
514 (*info).SubstituteNameLength / 2,
515 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
518 c::IO_REPARSE_TAG_MOUNT_POINT => {
519 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
520 ptr::addr_of!((*buf).rest).cast();
521 assert!(info.is_aligned());
523 ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
524 (*info).SubstituteNameOffset / 2,
525 (*info).SubstituteNameLength / 2,
530 return Err(io::const_io_error!(
531 io::ErrorKind::Uncategorized,
532 "Unsupported reparse point type",
536 let subst_ptr = path_buffer.add(subst_off.into());
537 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
538 // Absolute paths start with an NT internal namespace prefix `\??\`
539 // We should not let it leak through.
540 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
543 Ok(PathBuf::from(OsString::from_wide(subst)))
547 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
548 let mut info = c::FILE_BASIC_INFO {
553 FileAttributes: perm.attrs,
555 let size = mem::size_of_val(&info);
557 c::SetFileInformationByHandle(
558 self.handle.as_raw_handle(),
560 &mut info as *mut _ as *mut _,
567 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
568 let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0;
569 if times.accessed.map_or(false, is_zero) || times.modified.map_or(false, is_zero) {
570 return Err(io::const_io_error!(
571 io::ErrorKind::InvalidInput,
572 "Cannot set file timestamp to 0",
576 |t: c::FILETIME| t.dwLowDateTime == c::DWORD::MAX && t.dwHighDateTime == c::DWORD::MAX;
577 if times.accessed.map_or(false, is_max) || times.modified.map_or(false, is_max) {
578 return Err(io::const_io_error!(
579 io::ErrorKind::InvalidInput,
580 "Cannot set file timestamp to 0xFFFF_FFFF_FFFF_FFFF",
584 c::SetFileTime(self.as_handle(), None, times.accessed.as_ref(), times.modified.as_ref())
589 /// Get only basic file information such as attributes and file times.
590 fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
592 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
593 let size = mem::size_of_val(&info);
594 cvt(c::GetFileInformationByHandleEx(
595 self.handle.as_raw_handle(),
597 &mut info as *mut _ as *mut libc::c_void,
603 /// Delete using POSIX semantics.
605 /// Files will be deleted as soon as the handle is closed. This is supported
606 /// for Windows 10 1607 (aka RS1) and later. However some filesystem
607 /// drivers will not support it even then, e.g. FAT32.
609 /// If the operation is not supported for this filesystem or OS version
610 /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
611 fn posix_delete(&self) -> io::Result<()> {
612 let mut info = c::FILE_DISPOSITION_INFO_EX {
613 Flags: c::FILE_DISPOSITION_DELETE
614 | c::FILE_DISPOSITION_POSIX_SEMANTICS
615 | c::FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,
617 let size = mem::size_of_val(&info);
619 c::SetFileInformationByHandle(
620 self.handle.as_raw_handle(),
621 c::FileDispositionInfoEx,
622 &mut info as *mut _ as *mut _,
629 /// Delete a file using win32 semantics. The file won't actually be deleted
630 /// until all file handles are closed. However, marking a file for deletion
631 /// will prevent anyone from opening a new handle to the file.
632 fn win32_delete(&self) -> io::Result<()> {
633 let mut info = c::FILE_DISPOSITION_INFO { DeleteFile: c::TRUE as _ };
634 let size = mem::size_of_val(&info);
636 c::SetFileInformationByHandle(
637 self.handle.as_raw_handle(),
638 c::FileDispositionInfo,
639 &mut info as *mut _ as *mut _,
646 /// Fill the given buffer with as many directory entries as will fit.
647 /// This will remember its position and continue from the last call unless
648 /// `restart` is set to `true`.
650 /// The returned bool indicates if there are more entries or not.
651 /// It is an error if `self` is not a directory.
653 /// # Symlinks and other reparse points
655 /// On Windows a file is either a directory or a non-directory.
656 /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
657 /// So if you open a link (not its target) and iterate the directory,
658 /// you will always iterate an empty directory regardless of the target.
659 fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool> {
661 if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
664 let result = cvt(c::GetFileInformationByHandleEx(
665 self.handle.as_raw_handle(),
667 buffer.as_mut_ptr().cast(),
668 buffer.capacity() as _,
672 Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
679 /// A buffer for holding directory entries.
681 buffer: Box<Align8<[MaybeUninit<u8>; Self::BUFFER_SIZE]>>,
684 const BUFFER_SIZE: usize = 1024;
687 // Safety: `Align8<[MaybeUninit<u8>; N]>` does not need
689 buffer: unsafe { Box::new_uninit().assume_init() },
692 fn capacity(&self) -> usize {
695 fn as_mut_ptr(&mut self) -> *mut u8 {
696 self.buffer.0.as_mut_ptr().cast()
698 /// Returns a `DirBuffIter`.
699 fn iter(&self) -> DirBuffIter<'_> {
700 DirBuffIter::new(self)
703 impl AsRef<[MaybeUninit<u8>]> for DirBuff {
704 fn as_ref(&self) -> &[MaybeUninit<u8>] {
709 /// An iterator over entries stored in a `DirBuff`.
711 /// Currently only returns file names (UTF-16 encoded).
712 struct DirBuffIter<'a> {
713 buffer: Option<&'a [MaybeUninit<u8>]>,
716 impl<'a> DirBuffIter<'a> {
717 fn new(buffer: &'a DirBuff) -> Self {
718 Self { buffer: Some(buffer.as_ref()), cursor: 0 }
721 impl<'a> Iterator for DirBuffIter<'a> {
722 type Item = (&'a [u16], bool);
723 fn next(&mut self) -> Option<Self::Item> {
724 use crate::mem::size_of;
725 let buffer = &self.buffer?[self.cursor..];
727 // Get the name and next entry from the buffer.
729 // - The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the last
730 // field (the file name) is unsized. So an offset has to be used to
731 // get the file name slice.
732 // - The OS has guaranteed initialization of the fields of
733 // `FILE_ID_BOTH_DIR_INFO` and the trailing filename (for at least
734 // `FileNameLength` bytes)
735 let (name, is_directory, next_entry) = unsafe {
736 let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
737 // Guaranteed to be aligned in documentation for
738 // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_both_dir_info
739 assert!(info.is_aligned());
740 let next_entry = (*info).NextEntryOffset as usize;
741 let name = crate::slice::from_raw_parts(
742 ptr::addr_of!((*info).FileName).cast::<u16>(),
743 (*info).FileNameLength as usize / size_of::<u16>(),
745 let is_directory = ((*info).FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
747 (name, is_directory, next_entry)
753 self.cursor += next_entry
756 // Skip `.` and `..` pseudo entries.
757 const DOT: u16 = b'.' as u16;
759 [DOT] | [DOT, DOT] => self.next(),
760 _ => Some((name, is_directory)),
765 /// Open a link relative to the parent directory, ensure no symlinks are followed.
766 fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File> {
767 // This is implemented using the lower level `NtCreateFile` function as
768 // unfortunately opening a file relative to a parent is not supported by
769 // win32 functions. It is however a fundamental feature of the NT kernel.
771 // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
773 let mut handle = ptr::null_mut();
774 let mut io_status = c::IO_STATUS_BLOCK::default();
775 let name_str = c::UNICODE_STRING::from_ref(name);
776 use crate::sync::atomic::{AtomicU32, Ordering};
777 // The `OBJ_DONT_REPARSE` attribute ensures that we haven't been
778 // tricked into following a symlink. However, it may not be available in
779 // earlier versions of Windows.
780 static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
781 let object = c::OBJECT_ATTRIBUTES {
782 ObjectName: &name_str,
783 RootDirectory: parent.as_raw_handle(),
784 Attributes: ATTRIBUTES.load(Ordering::Relaxed),
785 ..c::OBJECT_ATTRIBUTES::default()
787 let status = c::NtCreateFile(
792 crate::ptr::null_mut(),
794 c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
796 // If `name` is a symlink then open the link rather than the target.
797 c::FILE_OPEN_REPARSE_POINT,
798 crate::ptr::null_mut(),
801 // Convert an NTSTATUS to the more familiar Win32 error codes (aka "DosError")
802 if c::nt_success(status) {
803 Ok(File::from_raw_handle(handle))
804 } else if status == c::STATUS_DELETE_PENDING {
805 // We make a special exception for `STATUS_DELETE_PENDING` because
806 // otherwise this will be mapped to `ERROR_ACCESS_DENIED` which is
808 Err(io::Error::from_raw_os_error(c::ERROR_DELETE_PENDING as _))
809 } else if status == c::STATUS_INVALID_PARAMETER
810 && ATTRIBUTES.load(Ordering::Relaxed) == c::OBJ_DONT_REPARSE
812 // Try without `OBJ_DONT_REPARSE`. See above.
813 ATTRIBUTES.store(0, Ordering::Relaxed);
814 open_link_no_reparse(parent, name, access)
816 Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
821 impl AsInner<Handle> for File {
822 fn as_inner(&self) -> &Handle {
827 impl IntoInner<Handle> for File {
828 fn into_inner(self) -> Handle {
833 impl FromInner<Handle> for File {
834 fn from_inner(handle: Handle) -> File {
839 impl AsHandle for File {
840 fn as_handle(&self) -> BorrowedHandle<'_> {
841 self.as_inner().as_handle()
845 impl AsRawHandle for File {
846 fn as_raw_handle(&self) -> RawHandle {
847 self.as_inner().as_raw_handle()
851 impl IntoRawHandle for File {
852 fn into_raw_handle(self) -> RawHandle {
853 self.into_inner().into_raw_handle()
857 impl FromRawHandle for File {
858 unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
859 Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
863 impl fmt::Debug for File {
864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 // FIXME(#24570): add more info here (e.g., mode)
866 let mut b = f.debug_struct("File");
867 b.field("handle", &self.handle.as_raw_handle());
868 if let Ok(path) = get_path(&self) {
869 b.field("path", &path);
876 pub fn size(&self) -> u64 {
880 pub fn perm(&self) -> FilePermissions {
881 FilePermissions { attrs: self.attributes }
884 pub fn attrs(&self) -> u32 {
888 pub fn file_type(&self) -> FileType {
889 FileType::new(self.attributes, self.reparse_tag)
892 pub fn modified(&self) -> io::Result<SystemTime> {
893 Ok(SystemTime::from(self.last_write_time))
896 pub fn accessed(&self) -> io::Result<SystemTime> {
897 Ok(SystemTime::from(self.last_access_time))
900 pub fn created(&self) -> io::Result<SystemTime> {
901 Ok(SystemTime::from(self.creation_time))
904 pub fn modified_u64(&self) -> u64 {
905 to_u64(&self.last_write_time)
908 pub fn accessed_u64(&self) -> u64 {
909 to_u64(&self.last_access_time)
912 pub fn created_u64(&self) -> u64 {
913 to_u64(&self.creation_time)
916 pub fn volume_serial_number(&self) -> Option<u32> {
917 self.volume_serial_number
920 pub fn number_of_links(&self) -> Option<u32> {
924 pub fn file_index(&self) -> Option<u64> {
928 impl From<c::WIN32_FIND_DATAW> for FileAttr {
929 fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
931 attributes: wfd.dwFileAttributes,
932 creation_time: wfd.ftCreationTime,
933 last_access_time: wfd.ftLastAccessTime,
934 last_write_time: wfd.ftLastWriteTime,
935 file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
936 reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
937 // reserved unless this is a reparse point
942 volume_serial_number: None,
943 number_of_links: None,
949 fn to_u64(ft: &c::FILETIME) -> u64 {
950 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
953 impl FilePermissions {
954 pub fn readonly(&self) -> bool {
955 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
958 pub fn set_readonly(&mut self, readonly: bool) {
960 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
962 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
968 pub fn set_accessed(&mut self, t: SystemTime) {
969 self.accessed = Some(t.into_inner());
972 pub fn set_modified(&mut self, t: SystemTime) {
973 self.modified = Some(t.into_inner());
978 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
979 FileType { attributes: attrs, reparse_tag }
981 pub fn is_dir(&self) -> bool {
982 !self.is_symlink() && self.is_directory()
984 pub fn is_file(&self) -> bool {
985 !self.is_symlink() && !self.is_directory()
987 pub fn is_symlink(&self) -> bool {
988 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
990 pub fn is_symlink_dir(&self) -> bool {
991 self.is_symlink() && self.is_directory()
993 pub fn is_symlink_file(&self) -> bool {
994 self.is_symlink() && !self.is_directory()
996 fn is_directory(&self) -> bool {
997 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
999 fn is_reparse_point(&self) -> bool {
1000 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
1002 fn is_reparse_tag_name_surrogate(&self) -> bool {
1003 self.reparse_tag & 0x20000000 != 0
1008 pub fn new() -> DirBuilder {
1012 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1013 let p = maybe_verbatim(p)?;
1014 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
1019 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1020 let root = p.to_path_buf();
1021 let star = p.join("*");
1022 let path = maybe_verbatim(&star)?;
1025 let mut wfd = mem::zeroed();
1026 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
1027 if find_handle != c::INVALID_HANDLE_VALUE {
1029 handle: FindNextFileHandle(find_handle),
1030 root: Arc::new(root),
1034 Err(Error::last_os_error())
1039 pub fn unlink(p: &Path) -> io::Result<()> {
1040 let p_u16s = maybe_verbatim(p)?;
1041 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
1045 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1046 let old = maybe_verbatim(old)?;
1047 let new = maybe_verbatim(new)?;
1048 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
1052 pub fn rmdir(p: &Path) -> io::Result<()> {
1053 let p = maybe_verbatim(p)?;
1054 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
1058 /// Open a file or directory without following symlinks.
1059 fn open_link(path: &Path, access_mode: u32) -> io::Result<File> {
1060 let mut opts = OpenOptions::new();
1061 opts.access_mode(access_mode);
1062 // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
1063 // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
1064 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1065 File::open(path, &opts)
1068 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
1069 let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
1071 // Test if the file is not a directory or a symlink to a directory.
1072 if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
1073 return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
1076 match remove_dir_all_iterative(&file, File::posix_delete) {
1078 if let Some(code) = e.raw_os_error() {
1080 // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
1081 c::ERROR_NOT_SUPPORTED
1082 | c::ERROR_INVALID_FUNCTION
1083 | c::ERROR_INVALID_PARAMETER => {
1084 remove_dir_all_iterative(&file, File::win32_delete)
1096 fn remove_dir_all_iterative(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()> {
1097 // When deleting files we may loop this many times when certain error conditions occur.
1098 // This allows remove_dir_all to succeed when the error is temporary.
1099 const MAX_RETRIES: u32 = 10;
1101 let mut buffer = DirBuff::new();
1102 let mut dirlist = vec![f.duplicate()?];
1104 // FIXME: This is a hack so we can push to the dirlist vec after borrowing from it.
1105 fn copy_handle(f: &File) -> mem::ManuallyDrop<File> {
1106 unsafe { mem::ManuallyDrop::new(File::from_raw_handle(f.as_raw_handle())) }
1109 let mut restart = true;
1110 while let Some(dir) = dirlist.last() {
1111 let dir = copy_handle(dir);
1113 // Fill the buffer and iterate the entries.
1114 let more_data = dir.fill_dir_buff(&mut buffer, restart)?;
1116 for (name, is_directory) in buffer.iter() {
1118 let child_dir = open_link_no_reparse(
1121 c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY,
1123 dirlist.push(child_dir);
1125 for i in 1..=MAX_RETRIES {
1126 let result = open_link_no_reparse(&dir, name, c::SYNCHRONIZE | c::DELETE);
1128 Ok(f) => delete(&f)?,
1129 // Already deleted, so skip.
1130 Err(e) if e.kind() == io::ErrorKind::NotFound => break,
1131 // Retry a few times if the file is locked or a delete is already in progress.
1134 && (e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
1136 == Some(c::ERROR_SHARING_VIOLATION as _)) => {}
1137 // Otherwise return the error.
1138 Err(e) => return Err(e),
1140 thread::yield_now();
1144 // If there were no more files then delete the directory.
1146 if let Some(dir) = dirlist.pop() {
1147 // Retry deleting a few times in case we need to wait for a file to be deleted.
1148 for i in 1..=MAX_RETRIES {
1149 let result = delete(&dir);
1150 if let Err(e) = result {
1151 if i == MAX_RETRIES || e.kind() != io::ErrorKind::DirectoryNotEmpty {
1154 thread::yield_now();
1165 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
1166 // Open the link with no access mode, instead of generic read.
1167 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1168 // this is needed for a common case.
1169 let mut opts = OpenOptions::new();
1170 opts.access_mode(0);
1171 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1172 let file = File::open(&path, &opts)?;
1176 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1177 symlink_inner(original, link, false)
1180 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1181 let original = to_u16s(original)?;
1182 let link = maybe_verbatim(link)?;
1183 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1184 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1185 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1186 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1187 // added to dwFlags to opt into this behaviour.
1188 let result = cvt(unsafe {
1189 c::CreateSymbolicLinkW(
1192 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1195 if let Err(err) = result {
1196 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1197 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1198 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1200 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1209 #[cfg(not(target_vendor = "uwp"))]
1210 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1211 let original = maybe_verbatim(original)?;
1212 let link = maybe_verbatim(link)?;
1213 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1217 #[cfg(target_vendor = "uwp")]
1218 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
1219 return Err(io::const_io_error!(
1220 io::ErrorKind::Unsupported,
1221 "hard link are not supported on UWP",
1225 pub fn stat(path: &Path) -> io::Result<FileAttr> {
1226 metadata(path, ReparsePoint::Follow)
1229 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
1230 metadata(path, ReparsePoint::Open)
1234 #[derive(Clone, Copy, PartialEq, Eq)]
1237 Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
1240 fn as_flag(self) -> u32 {
1245 fn metadata(path: &Path, reparse: ReparsePoint) -> io::Result<FileAttr> {
1246 let mut opts = OpenOptions::new();
1247 // No read or write permissions are necessary
1248 opts.access_mode(0);
1249 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());
1251 // Attempt to open the file normally.
1252 // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileW`.
1253 // If the fallback fails for any reason we return the original error.
1254 match File::open(path, &opts) {
1255 Ok(file) => file.file_attr(),
1256 Err(e) if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {
1257 // `ERROR_SHARING_VIOLATION` will almost never be returned.
1258 // Usually if a file is locked you can still read some metadata.
1259 // However, there are special system files, such as
1260 // `C:\hiberfil.sys`, that are locked in a way that denies even that.
1262 let path = maybe_verbatim(path)?;
1264 // `FindFirstFileW` accepts wildcard file names.
1265 // Fortunately wildcards are not valid file names and
1266 // `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
1267 // therefore it's safe to assume the file name given does not
1268 // include wildcards.
1269 let mut wfd = mem::zeroed();
1270 let handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
1272 if handle == c::INVALID_HANDLE_VALUE {
1273 // This can fail if the user does not have read access to the
1277 // We no longer need the find handle.
1278 c::FindClose(handle);
1280 // `FindFirstFileW` reads the cached file information from the
1281 // directory. The downside is that this metadata may be outdated.
1282 let attrs = FileAttr::from(wfd);
1283 if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
1295 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1296 let p = maybe_verbatim(p)?;
1298 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1303 fn get_path(f: &File) -> io::Result<PathBuf> {
1304 super::fill_utf16_buf(
1306 c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1308 |buf| PathBuf::from(OsString::from_wide(buf)),
1312 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1313 let mut opts = OpenOptions::new();
1314 // No read or write permissions are necessary
1315 opts.access_mode(0);
1316 // This flag is so we can open directories too
1317 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1318 let f = File::open(p, &opts)?;
1322 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1323 unsafe extern "system" fn callback(
1324 _TotalFileSize: c::LARGE_INTEGER,
1325 _TotalBytesTransferred: c::LARGE_INTEGER,
1326 _StreamSize: c::LARGE_INTEGER,
1327 StreamBytesTransferred: c::LARGE_INTEGER,
1328 dwStreamNumber: c::DWORD,
1329 _dwCallbackReason: c::DWORD,
1330 _hSourceFile: c::HANDLE,
1331 _hDestinationFile: c::HANDLE,
1334 if dwStreamNumber == 1 {
1335 *(lpData as *mut i64) = StreamBytesTransferred;
1337 c::PROGRESS_CONTINUE
1339 let pfrom = maybe_verbatim(from)?;
1340 let pto = maybe_verbatim(to)?;
1341 let mut size = 0i64;
1347 &mut size as *mut _ as *mut _,
1356 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
1359 ) -> io::Result<()> {
1360 symlink_junction_inner(original.as_ref(), junction.as_ref())
1363 // Creating a directory junction on windows involves dealing with reparse
1364 // points and the DeviceIoControl function, and this code is a skeleton of
1365 // what can be found here:
1367 // http://www.flexhex.com/docs/articles/hard-links.phtml
1369 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
1370 let d = DirBuilder::new();
1371 d.mkdir(&junction)?;
1373 let mut opts = OpenOptions::new();
1375 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1376 let f = File::open(junction, &opts)?;
1377 let h = f.as_inner().as_raw_handle();
1380 let mut data = Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
1381 let data_ptr = data.0.as_mut_ptr();
1382 let db = data_ptr.cast::<c::REPARSE_MOUNTPOINT_DATA_BUFFER>();
1383 let buf = ptr::addr_of_mut!((*db).ReparseTarget).cast::<c::WCHAR>();
1385 // FIXME: this conversion is very hacky
1387 let v = v.iter().map(|x| *x as u16);
1388 for c in v.chain(original.as_os_str().encode_wide()) {
1394 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
1395 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
1396 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
1397 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
1400 cvt(c::DeviceIoControl(
1402 c::FSCTL_SET_REPARSE_POINT,
1404 (*db).ReparseDataLength + 8,
1414 // Try to see if a file exists but, unlike `exists`, report I/O errors.
1415 pub fn try_exists(path: &Path) -> io::Result<bool> {
1416 // Open the file to ensure any symlinks are followed to their target.
1417 let mut opts = OpenOptions::new();
1418 // No read, write, etc access rights are needed.
1419 opts.access_mode(0);
1420 // Backup semantics enables opening directories as well as files.
1421 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1422 match File::open(path, &opts) {
1423 Err(e) => match e.kind() {
1424 // The file definitely does not exist
1425 io::ErrorKind::NotFound => Ok(false),
1427 // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1428 // another process. This is often temporary so we simply report it
1429 // as the file existing.
1430 _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1432 // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1433 // file exists. However, these types of errors are usually more
1434 // permanent so we report them here.
1437 // The file was opened successfully therefore it must exist,