1 use crate::os::windows::prelude::*;
3 use crate::ffi::OsString;
5 use crate::io::{self, Error, IoSlice, IoSliceMut, ReadBuf, SeekFrom};
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};
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
17 use super::path::maybe_verbatim;
27 creation_time: c::FILETIME,
28 last_access_time: c::FILETIME,
29 last_write_time: c::FILETIME,
31 reparse_tag: c::DWORD,
32 volume_serial_number: Option<u32>,
33 number_of_links: Option<u32>,
34 file_index: Option<u64>,
37 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
40 reparse_tag: c::DWORD,
44 handle: FindNextFileHandle,
46 first: Option<c::WIN32_FIND_DATAW>,
49 struct FindNextFileHandle(c::HANDLE);
51 unsafe impl Send for FindNextFileHandle {}
52 unsafe impl Sync for FindNextFileHandle {}
56 data: c::WIN32_FIND_DATAW,
59 #[derive(Clone, Debug)]
60 pub struct OpenOptions {
70 access_mode: Option<c::DWORD>,
73 security_qos_flags: c::DWORD,
74 security_attributes: usize, // FIXME: should be a reference
77 #[derive(Clone, PartialEq, Eq, Debug)]
78 pub struct FilePermissions {
83 pub struct DirBuilder;
85 impl fmt::Debug for ReadDir {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
88 // Thus the result will be e g 'ReadDir("C:\")'
89 fmt::Debug::fmt(&*self.root, f)
93 impl Iterator for ReadDir {
94 type Item = io::Result<DirEntry>;
95 fn next(&mut self) -> Option<io::Result<DirEntry>> {
96 if let Some(first) = self.first.take() {
97 if let Some(e) = DirEntry::new(&self.root, &first) {
102 let mut wfd = mem::zeroed();
104 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
105 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
108 return Some(Err(Error::last_os_error()));
111 if let Some(e) = DirEntry::new(&self.root, &wfd) {
119 impl Drop for FindNextFileHandle {
121 let r = unsafe { c::FindClose(self.0) };
122 debug_assert!(r != 0);
127 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
128 match &wfd.cFileName[0..3] {
129 // check for '.' and '..'
130 &[46, 0, ..] | &[46, 46, 0, ..] => return None,
134 Some(DirEntry { root: root.clone(), data: *wfd })
137 pub fn path(&self) -> PathBuf {
138 self.root.join(&self.file_name())
141 pub fn file_name(&self) -> OsString {
142 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
143 OsString::from_wide(filename)
146 pub fn file_type(&self) -> io::Result<FileType> {
148 self.data.dwFileAttributes,
149 /* reparse_tag = */ self.data.dwReserved0,
153 pub fn metadata(&self) -> io::Result<FileAttr> {
155 attributes: self.data.dwFileAttributes,
156 creation_time: self.data.ftCreationTime,
157 last_access_time: self.data.ftLastAccessTime,
158 last_write_time: self.data.ftLastWriteTime,
159 file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
160 reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
161 // reserved unless this is a reparse point
162 self.data.dwReserved0
166 volume_serial_number: None,
167 number_of_links: None,
174 pub fn new() -> OpenOptions {
186 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
188 security_qos_flags: 0,
189 security_attributes: 0,
193 pub fn read(&mut self, read: bool) {
196 pub fn write(&mut self, write: bool) {
199 pub fn append(&mut self, append: bool) {
200 self.append = append;
202 pub fn truncate(&mut self, truncate: bool) {
203 self.truncate = truncate;
205 pub fn create(&mut self, create: bool) {
206 self.create = create;
208 pub fn create_new(&mut self, create_new: bool) {
209 self.create_new = create_new;
212 pub fn custom_flags(&mut self, flags: u32) {
213 self.custom_flags = flags;
215 pub fn access_mode(&mut self, access_mode: u32) {
216 self.access_mode = Some(access_mode);
218 pub fn share_mode(&mut self, share_mode: u32) {
219 self.share_mode = share_mode;
221 pub fn attributes(&mut self, attrs: u32) {
222 self.attributes = attrs;
224 pub fn security_qos_flags(&mut self, flags: u32) {
225 // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
226 // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
227 self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
229 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
230 self.security_attributes = attrs as usize;
233 fn get_access_mode(&self) -> io::Result<c::DWORD> {
234 const ERROR_INVALID_PARAMETER: i32 = 87;
236 match (self.read, self.write, self.append, self.access_mode) {
237 (.., Some(mode)) => Ok(mode),
238 (true, false, false, None) => Ok(c::GENERIC_READ),
239 (false, true, false, None) => Ok(c::GENERIC_WRITE),
240 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
241 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
242 (true, _, true, None) => {
243 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
245 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
249 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
250 const ERROR_INVALID_PARAMETER: i32 = 87;
252 match (self.write, self.append) {
255 if self.truncate || self.create || self.create_new {
256 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
260 if self.truncate && !self.create_new {
261 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
266 Ok(match (self.create, self.truncate, self.create_new) {
267 (false, false, false) => c::OPEN_EXISTING,
268 (true, false, false) => c::OPEN_ALWAYS,
269 (false, true, false) => c::TRUNCATE_EXISTING,
270 (true, true, false) => c::CREATE_ALWAYS,
271 (_, _, true) => c::CREATE_NEW,
275 fn get_flags_and_attributes(&self) -> c::DWORD {
278 | self.security_qos_flags
279 | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
284 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
285 let path = maybe_verbatim(path)?;
286 let handle = unsafe {
289 opts.get_access_mode()?,
291 opts.security_attributes as *mut _,
292 opts.get_creation_mode()?,
293 opts.get_flags_and_attributes(),
297 if handle == c::INVALID_HANDLE_VALUE {
298 Err(Error::last_os_error())
300 unsafe { Ok(File { handle: Handle::from_raw_handle(handle) }) }
304 pub fn fsync(&self) -> io::Result<()> {
305 cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
309 pub fn datasync(&self) -> io::Result<()> {
313 pub fn truncate(&self, size: u64) -> io::Result<()> {
314 let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
315 let size = mem::size_of_val(&info);
317 c::SetFileInformationByHandle(
318 self.handle.as_raw_handle(),
319 c::FileEndOfFileInfo,
320 &mut info as *mut _ as *mut _,
327 #[cfg(not(target_vendor = "uwp"))]
328 pub fn file_attr(&self) -> io::Result<FileAttr> {
330 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
331 cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
332 let mut reparse_tag = 0;
333 if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
334 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
335 if let Ok((_, buf)) = self.reparse_point(&mut b) {
336 reparse_tag = buf.ReparseTag;
340 attributes: info.dwFileAttributes,
341 creation_time: info.ftCreationTime,
342 last_access_time: info.ftLastAccessTime,
343 last_write_time: info.ftLastWriteTime,
344 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
346 volume_serial_number: Some(info.dwVolumeSerialNumber),
347 number_of_links: Some(info.nNumberOfLinks),
349 (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
355 #[cfg(target_vendor = "uwp")]
356 pub fn file_attr(&self) -> io::Result<FileAttr> {
358 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
359 let size = mem::size_of_val(&info);
360 cvt(c::GetFileInformationByHandleEx(
361 self.handle.as_raw_handle(),
363 &mut info as *mut _ as *mut libc::c_void,
366 let mut attr = FileAttr {
367 attributes: info.FileAttributes,
368 creation_time: c::FILETIME {
369 dwLowDateTime: info.CreationTime as c::DWORD,
370 dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
372 last_access_time: c::FILETIME {
373 dwLowDateTime: info.LastAccessTime as c::DWORD,
374 dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
376 last_write_time: c::FILETIME {
377 dwLowDateTime: info.LastWriteTime as c::DWORD,
378 dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
382 volume_serial_number: None,
383 number_of_links: None,
386 let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
387 let size = mem::size_of_val(&info);
388 cvt(c::GetFileInformationByHandleEx(
389 self.handle.as_raw_handle(),
391 &mut info as *mut _ as *mut libc::c_void,
394 attr.file_size = info.AllocationSize as u64;
395 attr.number_of_links = Some(info.NumberOfLinks);
396 if attr.file_type().is_reparse_point() {
397 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
398 if let Ok((_, buf)) = self.reparse_point(&mut b) {
399 attr.reparse_tag = buf.ReparseTag;
406 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
407 self.handle.read(buf)
410 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
411 self.handle.read_vectored(bufs)
415 pub fn is_read_vectored(&self) -> bool {
416 self.handle.is_read_vectored()
419 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
420 self.handle.read_at(buf, offset)
423 pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
424 self.handle.read_buf(buf)
427 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
428 self.handle.write(buf)
431 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
432 self.handle.write_vectored(bufs)
436 pub fn is_write_vectored(&self) -> bool {
437 self.handle.is_write_vectored()
440 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
441 self.handle.write_at(buf, offset)
444 pub fn flush(&self) -> io::Result<()> {
448 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
449 let (whence, pos) = match pos {
450 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
452 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
453 SeekFrom::End(n) => (c::FILE_END, n),
454 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
456 let pos = pos as c::LARGE_INTEGER;
458 cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
462 pub fn duplicate(&self) -> io::Result<File> {
463 Ok(Self { handle: self.handle.try_clone()? })
466 fn reparse_point<'a>(
468 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
469 ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
474 self.handle.as_raw_handle(),
475 c::FSCTL_GET_REPARSE_POINT,
478 space.as_mut_ptr() as *mut _,
479 space.len() as c::DWORD,
484 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
488 fn readlink(&self) -> io::Result<PathBuf> {
489 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
490 let (_bytes, buf) = self.reparse_point(&mut space)?;
492 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
493 c::IO_REPARSE_TAG_SYMLINK => {
494 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
495 &buf.rest as *const _ as *const _;
497 &(*info).PathBuffer as *const _ as *const u16,
498 (*info).SubstituteNameOffset / 2,
499 (*info).SubstituteNameLength / 2,
500 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
503 c::IO_REPARSE_TAG_MOUNT_POINT => {
504 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
505 &buf.rest as *const _ as *const _;
507 &(*info).PathBuffer as *const _ as *const u16,
508 (*info).SubstituteNameOffset / 2,
509 (*info).SubstituteNameLength / 2,
514 return Err(io::const_io_error!(
515 io::ErrorKind::Uncategorized,
516 "Unsupported reparse point type",
520 let subst_ptr = path_buffer.offset(subst_off as isize);
521 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
522 // Absolute paths start with an NT internal namespace prefix `\??\`
523 // We should not let it leak through.
524 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
527 Ok(PathBuf::from(OsString::from_wide(subst)))
531 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
532 let mut info = c::FILE_BASIC_INFO {
537 FileAttributes: perm.attrs,
539 let size = mem::size_of_val(&info);
541 c::SetFileInformationByHandle(
542 self.handle.as_raw_handle(),
544 &mut info as *mut _ as *mut _,
550 /// Get only basic file information such as attributes and file times.
551 fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
553 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
554 let size = mem::size_of_val(&info);
555 cvt(c::GetFileInformationByHandleEx(
556 self.handle.as_raw_handle(),
558 &mut info as *mut _ as *mut libc::c_void,
564 /// Delete using POSIX semantics.
566 /// Files will be deleted as soon as the handle is closed. This is supported
567 /// for Windows 10 1607 (aka RS1) and later. However some filesystem
568 /// drivers will not support it even then, e.g. FAT32.
570 /// If the operation is not supported for this filesystem or OS version
571 /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
572 fn posix_delete(&self) -> io::Result<()> {
573 let mut info = c::FILE_DISPOSITION_INFO_EX {
574 Flags: c::FILE_DISPOSITION_DELETE
575 | c::FILE_DISPOSITION_POSIX_SEMANTICS
576 | c::FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,
578 let size = mem::size_of_val(&info);
580 c::SetFileInformationByHandle(
581 self.handle.as_raw_handle(),
582 c::FileDispositionInfoEx,
583 &mut info as *mut _ as *mut _,
590 /// Delete a file using win32 semantics. The file won't actually be deleted
591 /// until all file handles are closed. However, marking a file for deletion
592 /// will prevent anyone from opening a new handle to the file.
593 fn win32_delete(&self) -> io::Result<()> {
594 let mut info = c::FILE_DISPOSITION_INFO { DeleteFile: c::TRUE as _ };
595 let size = mem::size_of_val(&info);
597 c::SetFileInformationByHandle(
598 self.handle.as_raw_handle(),
599 c::FileDispositionInfo,
600 &mut info as *mut _ as *mut _,
607 /// Fill the given buffer with as many directory entries as will fit.
608 /// This will remember its position and continue from the last call unless
609 /// `restart` is set to `true`.
611 /// The returned bool indicates if there are more entries or not.
612 /// It is an error if `self` is not a directory.
614 /// # Symlinks and other reparse points
616 /// On Windows a file is either a directory or a non-directory.
617 /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
618 /// So if you open a link (not its target) and iterate the directory,
619 /// you will always iterate an empty directory regardless of the target.
620 fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool> {
622 if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
625 let result = cvt(c::GetFileInformationByHandleEx(
626 self.handle.as_raw_handle(),
628 buffer.as_mut_ptr().cast(),
629 buffer.capacity() as _,
633 Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
640 /// A buffer for holding directory entries.
646 const BUFFER_SIZE: usize = 1024;
647 Self { buffer: vec![0_u8; BUFFER_SIZE] }
649 fn capacity(&self) -> usize {
652 fn as_mut_ptr(&mut self) -> *mut u8 {
653 self.buffer.as_mut_ptr().cast()
655 /// Returns a `DirBuffIter`.
656 fn iter(&self) -> DirBuffIter<'_> {
657 DirBuffIter::new(self)
660 impl AsRef<[u8]> for DirBuff {
661 fn as_ref(&self) -> &[u8] {
666 /// An iterator over entries stored in a `DirBuff`.
668 /// Currently only returns file names (UTF-16 encoded).
669 struct DirBuffIter<'a> {
670 buffer: Option<&'a [u8]>,
673 impl<'a> DirBuffIter<'a> {
674 fn new(buffer: &'a DirBuff) -> Self {
675 Self { buffer: Some(buffer.as_ref()), cursor: 0 }
678 impl<'a> Iterator for DirBuffIter<'a> {
679 type Item = &'a [u16];
680 fn next(&mut self) -> Option<Self::Item> {
681 use crate::mem::size_of;
682 let buffer = &self.buffer?[self.cursor..];
684 // Get the name and next entry from the buffer.
685 // SAFETY: The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the
686 // last field (the file name) is unsized. So an offset has to be
687 // used to get the file name slice.
688 let (name, next_entry) = unsafe {
689 let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
690 let next_entry = (*info).NextEntryOffset as usize;
691 let name = crate::slice::from_raw_parts(
692 (*info).FileName.as_ptr().cast::<u16>(),
693 (*info).FileNameLength as usize / size_of::<u16>(),
701 self.cursor += next_entry
704 // Skip `.` and `..` pseudo entries.
705 const DOT: u16 = b'.' as u16;
707 [DOT] | [DOT, DOT] => self.next(),
713 /// Open a link relative to the parent directory, ensure no symlinks are followed.
714 fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File> {
715 // This is implemented using the lower level `NtCreateFile` function as
716 // unfortunately opening a file relative to a parent is not supported by
717 // win32 functions. It is however a fundamental feature of the NT kernel.
719 // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
721 let mut handle = ptr::null_mut();
722 let mut io_status = c::IO_STATUS_BLOCK::default();
723 let name_str = c::UNICODE_STRING::from_ref(name);
724 use crate::sync::atomic::{AtomicU32, Ordering};
725 // The `OBJ_DONT_REPARSE` attribute ensures that we haven't been
726 // tricked into following a symlink. However, it may not be available in
727 // earlier versions of Windows.
728 static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
729 let object = c::OBJECT_ATTRIBUTES {
730 ObjectName: &name_str,
731 RootDirectory: parent.as_raw_handle(),
732 Attributes: ATTRIBUTES.load(Ordering::Relaxed),
733 ..c::OBJECT_ATTRIBUTES::default()
735 let status = c::NtCreateFile(
740 crate::ptr::null_mut(),
742 c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
744 // If `name` is a symlink then open the link rather than the target.
745 c::FILE_OPEN_REPARSE_POINT,
746 crate::ptr::null_mut(),
749 // Convert an NTSTATUS to the more familiar Win32 error codes (aka "DosError")
750 if c::nt_success(status) {
751 Ok(File::from_raw_handle(handle))
752 } else if status == c::STATUS_DELETE_PENDING {
753 // We make a special exception for `STATUS_DELETE_PENDING` because
754 // otherwise this will be mapped to `ERROR_ACCESS_DENIED` which is
756 Err(io::Error::from_raw_os_error(c::ERROR_DELETE_PENDING as _))
757 } else if status == c::STATUS_INVALID_PARAMETER
758 && ATTRIBUTES.load(Ordering::Relaxed) == c::OBJ_DONT_REPARSE
760 // Try without `OBJ_DONT_REPARSE`. See above.
761 ATTRIBUTES.store(0, Ordering::Relaxed);
762 open_link_no_reparse(parent, name, access)
764 Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
769 impl AsInner<Handle> for File {
770 fn as_inner(&self) -> &Handle {
775 impl IntoInner<Handle> for File {
776 fn into_inner(self) -> Handle {
781 impl FromInner<Handle> for File {
782 fn from_inner(handle: Handle) -> File {
787 impl AsHandle for File {
788 fn as_handle(&self) -> BorrowedHandle<'_> {
789 self.as_inner().as_handle()
793 impl AsRawHandle for File {
794 fn as_raw_handle(&self) -> RawHandle {
795 self.as_inner().as_raw_handle()
799 impl IntoRawHandle for File {
800 fn into_raw_handle(self) -> RawHandle {
801 self.into_inner().into_raw_handle()
805 impl FromRawHandle for File {
806 unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
807 Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
811 impl fmt::Debug for File {
812 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
813 // FIXME(#24570): add more info here (e.g., mode)
814 let mut b = f.debug_struct("File");
815 b.field("handle", &self.handle.as_raw_handle());
816 if let Ok(path) = get_path(&self) {
817 b.field("path", &path);
824 pub fn size(&self) -> u64 {
828 pub fn perm(&self) -> FilePermissions {
829 FilePermissions { attrs: self.attributes }
832 pub fn attrs(&self) -> u32 {
836 pub fn file_type(&self) -> FileType {
837 FileType::new(self.attributes, self.reparse_tag)
840 pub fn modified(&self) -> io::Result<SystemTime> {
841 Ok(SystemTime::from(self.last_write_time))
844 pub fn accessed(&self) -> io::Result<SystemTime> {
845 Ok(SystemTime::from(self.last_access_time))
848 pub fn created(&self) -> io::Result<SystemTime> {
849 Ok(SystemTime::from(self.creation_time))
852 pub fn modified_u64(&self) -> u64 {
853 to_u64(&self.last_write_time)
856 pub fn accessed_u64(&self) -> u64 {
857 to_u64(&self.last_access_time)
860 pub fn created_u64(&self) -> u64 {
861 to_u64(&self.creation_time)
864 pub fn volume_serial_number(&self) -> Option<u32> {
865 self.volume_serial_number
868 pub fn number_of_links(&self) -> Option<u32> {
872 pub fn file_index(&self) -> Option<u64> {
877 fn to_u64(ft: &c::FILETIME) -> u64 {
878 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
881 impl FilePermissions {
882 pub fn readonly(&self) -> bool {
883 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
886 pub fn set_readonly(&mut self, readonly: bool) {
888 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
890 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
896 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
897 FileType { attributes: attrs, reparse_tag }
899 pub fn is_dir(&self) -> bool {
900 !self.is_symlink() && self.is_directory()
902 pub fn is_file(&self) -> bool {
903 !self.is_symlink() && !self.is_directory()
905 pub fn is_symlink(&self) -> bool {
906 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
908 pub fn is_symlink_dir(&self) -> bool {
909 self.is_symlink() && self.is_directory()
911 pub fn is_symlink_file(&self) -> bool {
912 self.is_symlink() && !self.is_directory()
914 fn is_directory(&self) -> bool {
915 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
917 fn is_reparse_point(&self) -> bool {
918 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
920 fn is_reparse_tag_name_surrogate(&self) -> bool {
921 self.reparse_tag & 0x20000000 != 0
926 pub fn new() -> DirBuilder {
930 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
931 let p = maybe_verbatim(p)?;
932 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
937 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
938 let root = p.to_path_buf();
939 let star = p.join("*");
940 let path = maybe_verbatim(&star)?;
943 let mut wfd = mem::zeroed();
944 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
945 if find_handle != c::INVALID_HANDLE_VALUE {
947 handle: FindNextFileHandle(find_handle),
948 root: Arc::new(root),
952 Err(Error::last_os_error())
957 pub fn unlink(p: &Path) -> io::Result<()> {
958 let p_u16s = maybe_verbatim(p)?;
959 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
963 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
964 let old = maybe_verbatim(old)?;
965 let new = maybe_verbatim(new)?;
966 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
970 pub fn rmdir(p: &Path) -> io::Result<()> {
971 let p = maybe_verbatim(p)?;
972 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
976 /// Open a file or directory without following symlinks.
977 fn open_link(path: &Path, access_mode: u32) -> io::Result<File> {
978 let mut opts = OpenOptions::new();
979 opts.access_mode(access_mode);
980 // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
981 // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
982 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
983 File::open(path, &opts)
986 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
987 let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
989 // Test if the file is not a directory or a symlink to a directory.
990 if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
991 return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
993 let mut delete: fn(&File) -> io::Result<()> = File::posix_delete;
994 let result = match delete(&file) {
995 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {
996 match remove_dir_all_recursive(&file, delete) {
997 // Return unexpected errors.
998 Err(e) if e.kind() != io::ErrorKind::DirectoryNotEmpty => return Err(e),
1002 // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
1004 if e.raw_os_error() == Some(c::ERROR_NOT_SUPPORTED as i32)
1005 || e.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) =>
1007 delete = File::win32_delete;
1015 // This is a fallback to make sure the directory is actually deleted.
1016 // Otherwise this function is prone to failing with `DirectoryNotEmpty`
1017 // due to possible delays between marking a file for deletion and the
1018 // file actually being deleted from the filesystem.
1020 // So we retry a few times before giving up.
1022 match remove_dir_all_recursive(&file, delete) {
1023 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {}
1024 result => return result,
1027 // Try one last time.
1032 fn remove_dir_all_recursive(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()> {
1033 let mut buffer = DirBuff::new();
1034 let mut restart = true;
1035 // Fill the buffer and iterate the entries.
1036 while f.fill_dir_buff(&mut buffer, restart)? {
1037 for name in buffer.iter() {
1038 // Open the file without following symlinks and try deleting it.
1039 // We try opening will all needed permissions and if that is denied
1040 // fallback to opening without `FILE_LIST_DIRECTORY` permission.
1041 // Note `SYNCHRONIZE` permission is needed for synchronous access.
1043 open_link_no_reparse(&f, name, c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY);
1044 if matches!(&result, Err(e) if e.kind() == io::ErrorKind::PermissionDenied) {
1045 result = open_link_no_reparse(&f, name, c::SYNCHRONIZE | c::DELETE);
1048 Ok(file) => match delete(&file) {
1049 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {
1050 // Iterate the directory's files.
1051 // Ignore `DirectoryNotEmpty` errors here. They will be
1052 // caught when `remove_dir_all` tries to delete the top
1053 // level directory. It can then decide if to retry or not.
1054 match remove_dir_all_recursive(&file, delete) {
1055 Err(e) if e.kind() == io::ErrorKind::DirectoryNotEmpty => {}
1061 // Ignore error if a delete is already in progress or the file
1062 // has already been deleted. It also ignores sharing violations
1063 // (where a file is locked by another process) as these are
1064 // usually temporary.
1066 if e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
1067 || e.kind() == io::ErrorKind::NotFound
1068 || e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {}
1069 Err(e) => return Err(e),
1072 // Continue reading directory entries without restarting from the beginning,
1078 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
1079 // Open the link with no access mode, instead of generic read.
1080 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1081 // this is needed for a common case.
1082 let mut opts = OpenOptions::new();
1083 opts.access_mode(0);
1084 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1085 let file = File::open(&path, &opts)?;
1089 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1090 symlink_inner(original, link, false)
1093 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1094 let original = to_u16s(original)?;
1095 let link = maybe_verbatim(link)?;
1096 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1097 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1098 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1099 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1100 // added to dwFlags to opt into this behaviour.
1101 let result = cvt(unsafe {
1102 c::CreateSymbolicLinkW(
1105 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1108 if let Err(err) = result {
1109 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1110 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1111 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1113 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1122 #[cfg(not(target_vendor = "uwp"))]
1123 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1124 let original = maybe_verbatim(original)?;
1125 let link = maybe_verbatim(link)?;
1126 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1130 #[cfg(target_vendor = "uwp")]
1131 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
1132 return Err(io::const_io_error!(
1133 io::ErrorKind::Unsupported,
1134 "hard link are not supported on UWP",
1138 pub fn stat(path: &Path) -> io::Result<FileAttr> {
1139 let mut opts = OpenOptions::new();
1140 // No read or write permissions are necessary
1141 opts.access_mode(0);
1142 // This flag is so we can open directories too
1143 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1144 let file = File::open(path, &opts)?;
1148 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
1149 let mut opts = OpenOptions::new();
1150 // No read or write permissions are necessary
1151 opts.access_mode(0);
1152 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1153 let file = File::open(path, &opts)?;
1157 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1158 let p = maybe_verbatim(p)?;
1160 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1165 fn get_path(f: &File) -> io::Result<PathBuf> {
1166 super::fill_utf16_buf(
1168 c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1170 |buf| PathBuf::from(OsString::from_wide(buf)),
1174 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1175 let mut opts = OpenOptions::new();
1176 // No read or write permissions are necessary
1177 opts.access_mode(0);
1178 // This flag is so we can open directories too
1179 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1180 let f = File::open(p, &opts)?;
1184 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1185 unsafe extern "system" fn callback(
1186 _TotalFileSize: c::LARGE_INTEGER,
1187 _TotalBytesTransferred: c::LARGE_INTEGER,
1188 _StreamSize: c::LARGE_INTEGER,
1189 StreamBytesTransferred: c::LARGE_INTEGER,
1190 dwStreamNumber: c::DWORD,
1191 _dwCallbackReason: c::DWORD,
1192 _hSourceFile: c::HANDLE,
1193 _hDestinationFile: c::HANDLE,
1196 if dwStreamNumber == 1 {
1197 *(lpData as *mut i64) = StreamBytesTransferred;
1199 c::PROGRESS_CONTINUE
1201 let pfrom = maybe_verbatim(from)?;
1202 let pto = maybe_verbatim(to)?;
1203 let mut size = 0i64;
1209 &mut size as *mut _ as *mut _,
1218 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
1221 ) -> io::Result<()> {
1222 symlink_junction_inner(original.as_ref(), junction.as_ref())
1225 // Creating a directory junction on windows involves dealing with reparse
1226 // points and the DeviceIoControl function, and this code is a skeleton of
1227 // what can be found here:
1229 // http://www.flexhex.com/docs/articles/hard-links.phtml
1231 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
1232 let d = DirBuilder::new();
1233 d.mkdir(&junction)?;
1235 let mut opts = OpenOptions::new();
1237 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1238 let f = File::open(junction, &opts)?;
1239 let h = f.as_inner().as_raw_handle();
1242 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1243 let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
1244 let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
1246 // FIXME: this conversion is very hacky
1248 let v = v.iter().map(|x| *x as u16);
1249 for c in v.chain(original.as_os_str().encode_wide()) {
1255 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
1256 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
1257 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
1258 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
1261 cvt(c::DeviceIoControl(
1263 c::FSCTL_SET_REPARSE_POINT,
1264 data.as_ptr() as *mut _,
1265 (*db).ReparseDataLength + 8,
1275 // Try to see if a file exists but, unlike `exists`, report I/O errors.
1276 pub fn try_exists(path: &Path) -> io::Result<bool> {
1277 // Open the file to ensure any symlinks are followed to their target.
1278 let mut opts = OpenOptions::new();
1279 // No read, write, etc access rights are needed.
1280 opts.access_mode(0);
1281 // Backup semantics enables opening directories as well as files.
1282 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1283 match File::open(path, &opts) {
1284 Err(e) => match e.kind() {
1285 // The file definitely does not exist
1286 io::ErrorKind::NotFound => Ok(false),
1288 // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1289 // another process. This is often temporary so we simply report it
1290 // as the file existing.
1291 _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1293 // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1294 // file exists. However, these types of errors are usually more
1295 // permanent so we report them here.
1298 // The file was opened successfully therefore it must exist,