1 use crate::os::windows::prelude::*;
3 use crate::ffi::OsString;
5 use crate::io::{self, Error, IoSlice, IoSliceMut, 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 write(&self, buf: &[u8]) -> io::Result<usize> {
424 self.handle.write(buf)
427 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
428 self.handle.write_vectored(bufs)
432 pub fn is_write_vectored(&self) -> bool {
433 self.handle.is_write_vectored()
436 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
437 self.handle.write_at(buf, offset)
440 pub fn flush(&self) -> io::Result<()> {
444 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
445 let (whence, pos) = match pos {
446 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
448 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
449 SeekFrom::End(n) => (c::FILE_END, n),
450 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
452 let pos = pos as c::LARGE_INTEGER;
454 cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
458 pub fn duplicate(&self) -> io::Result<File> {
459 Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
462 fn reparse_point<'a>(
464 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
465 ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
470 self.handle.as_raw_handle(),
471 c::FSCTL_GET_REPARSE_POINT,
474 space.as_mut_ptr() as *mut _,
475 space.len() as c::DWORD,
480 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
484 fn readlink(&self) -> io::Result<PathBuf> {
485 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
486 let (_bytes, buf) = self.reparse_point(&mut space)?;
488 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
489 c::IO_REPARSE_TAG_SYMLINK => {
490 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
491 &buf.rest as *const _ as *const _;
493 &(*info).PathBuffer as *const _ as *const u16,
494 (*info).SubstituteNameOffset / 2,
495 (*info).SubstituteNameLength / 2,
496 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
499 c::IO_REPARSE_TAG_MOUNT_POINT => {
500 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
501 &buf.rest as *const _ as *const _;
503 &(*info).PathBuffer as *const _ as *const u16,
504 (*info).SubstituteNameOffset / 2,
505 (*info).SubstituteNameLength / 2,
510 return Err(io::Error::new_const(
511 io::ErrorKind::Uncategorized,
512 &"Unsupported reparse point type",
516 let subst_ptr = path_buffer.offset(subst_off as isize);
517 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
518 // Absolute paths start with an NT internal namespace prefix `\??\`
519 // We should not let it leak through.
520 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
523 Ok(PathBuf::from(OsString::from_wide(subst)))
527 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
528 let mut info = c::FILE_BASIC_INFO {
533 FileAttributes: perm.attrs,
535 let size = mem::size_of_val(&info);
537 c::SetFileInformationByHandle(
538 self.handle.as_raw_handle(),
540 &mut info as *mut _ as *mut _,
548 impl AsInner<Handle> for File {
549 fn as_inner(&self) -> &Handle {
554 impl IntoInner<Handle> for File {
555 fn into_inner(self) -> Handle {
560 impl FromInner<Handle> for File {
561 fn from_inner(handle: Handle) -> File {
566 impl AsHandle for File {
567 fn as_handle(&self) -> BorrowedHandle<'_> {
568 self.as_inner().as_handle()
572 impl AsRawHandle for File {
573 fn as_raw_handle(&self) -> RawHandle {
574 self.as_inner().as_raw_handle()
578 impl IntoRawHandle for File {
579 fn into_raw_handle(self) -> RawHandle {
580 self.into_inner().into_raw_handle()
584 impl FromRawHandle for File {
585 unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
586 Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
590 impl fmt::Debug for File {
591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592 // FIXME(#24570): add more info here (e.g., mode)
593 let mut b = f.debug_struct("File");
594 b.field("handle", &self.handle.as_raw_handle());
595 if let Ok(path) = get_path(&self) {
596 b.field("path", &path);
603 pub fn size(&self) -> u64 {
607 pub fn perm(&self) -> FilePermissions {
608 FilePermissions { attrs: self.attributes }
611 pub fn attrs(&self) -> u32 {
615 pub fn file_type(&self) -> FileType {
616 FileType::new(self.attributes, self.reparse_tag)
619 pub fn modified(&self) -> io::Result<SystemTime> {
620 Ok(SystemTime::from(self.last_write_time))
623 pub fn accessed(&self) -> io::Result<SystemTime> {
624 Ok(SystemTime::from(self.last_access_time))
627 pub fn created(&self) -> io::Result<SystemTime> {
628 Ok(SystemTime::from(self.creation_time))
631 pub fn modified_u64(&self) -> u64 {
632 to_u64(&self.last_write_time)
635 pub fn accessed_u64(&self) -> u64 {
636 to_u64(&self.last_access_time)
639 pub fn created_u64(&self) -> u64 {
640 to_u64(&self.creation_time)
643 pub fn volume_serial_number(&self) -> Option<u32> {
644 self.volume_serial_number
647 pub fn number_of_links(&self) -> Option<u32> {
651 pub fn file_index(&self) -> Option<u64> {
656 fn to_u64(ft: &c::FILETIME) -> u64 {
657 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
660 impl FilePermissions {
661 pub fn readonly(&self) -> bool {
662 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
665 pub fn set_readonly(&mut self, readonly: bool) {
667 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
669 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
675 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
676 FileType { attributes: attrs, reparse_tag }
678 pub fn is_dir(&self) -> bool {
679 !self.is_symlink() && self.is_directory()
681 pub fn is_file(&self) -> bool {
682 !self.is_symlink() && !self.is_directory()
684 pub fn is_symlink(&self) -> bool {
685 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
687 pub fn is_symlink_dir(&self) -> bool {
688 self.is_symlink() && self.is_directory()
690 pub fn is_symlink_file(&self) -> bool {
691 self.is_symlink() && !self.is_directory()
693 fn is_directory(&self) -> bool {
694 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
696 fn is_reparse_point(&self) -> bool {
697 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
699 fn is_reparse_tag_name_surrogate(&self) -> bool {
700 self.reparse_tag & 0x20000000 != 0
705 pub fn new() -> DirBuilder {
709 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
710 let p = maybe_verbatim(p)?;
711 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
716 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
717 let root = p.to_path_buf();
718 let star = p.join("*");
719 let path = maybe_verbatim(&star)?;
722 let mut wfd = mem::zeroed();
723 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
724 if find_handle != c::INVALID_HANDLE_VALUE {
726 handle: FindNextFileHandle(find_handle),
727 root: Arc::new(root),
731 Err(Error::last_os_error())
736 pub fn unlink(p: &Path) -> io::Result<()> {
737 let p_u16s = maybe_verbatim(p)?;
738 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
742 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
743 let old = maybe_verbatim(old)?;
744 let new = maybe_verbatim(new)?;
745 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
749 pub fn rmdir(p: &Path) -> io::Result<()> {
750 let p = maybe_verbatim(p)?;
751 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
755 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
756 let filetype = lstat(path)?.file_type();
757 if filetype.is_symlink() {
758 // On Windows symlinks to files and directories are removed differently.
759 // rmdir only deletes dir symlinks and junctions, not file symlinks.
762 remove_dir_all_recursive(path)
766 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
767 for child in readdir(path)? {
769 let child_type = child.file_type()?;
770 if child_type.is_dir() {
771 remove_dir_all_recursive(&child.path())?;
772 } else if child_type.is_symlink_dir() {
773 rmdir(&child.path())?;
775 unlink(&child.path())?;
781 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
782 // Open the link with no access mode, instead of generic read.
783 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
784 // this is needed for a common case.
785 let mut opts = OpenOptions::new();
787 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
788 let file = File::open(&path, &opts)?;
792 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
793 symlink_inner(original, link, false)
796 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
797 let original = to_u16s(original)?;
798 let link = maybe_verbatim(link)?;
799 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
800 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
801 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
802 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
803 // added to dwFlags to opt into this behaviour.
804 let result = cvt(unsafe {
805 c::CreateSymbolicLinkW(
808 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
811 if let Err(err) = result {
812 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
813 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
814 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
816 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
825 #[cfg(not(target_vendor = "uwp"))]
826 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
827 let original = maybe_verbatim(original)?;
828 let link = maybe_verbatim(link)?;
829 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
833 #[cfg(target_vendor = "uwp")]
834 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
835 return Err(io::Error::new_const(
836 io::ErrorKind::Unsupported,
837 &"hard link are not supported on UWP",
841 pub fn stat(path: &Path) -> io::Result<FileAttr> {
842 let mut opts = OpenOptions::new();
843 // No read or write permissions are necessary
845 // This flag is so we can open directories too
846 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
847 let file = File::open(path, &opts)?;
851 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
852 let mut opts = OpenOptions::new();
853 // No read or write permissions are necessary
855 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
856 let file = File::open(path, &opts)?;
860 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
861 let p = maybe_verbatim(p)?;
863 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
868 fn get_path(f: &File) -> io::Result<PathBuf> {
869 super::fill_utf16_buf(
871 c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
873 |buf| PathBuf::from(OsString::from_wide(buf)),
877 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
878 let mut opts = OpenOptions::new();
879 // No read or write permissions are necessary
881 // This flag is so we can open directories too
882 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
883 let f = File::open(p, &opts)?;
887 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
888 unsafe extern "system" fn callback(
889 _TotalFileSize: c::LARGE_INTEGER,
890 _TotalBytesTransferred: c::LARGE_INTEGER,
891 _StreamSize: c::LARGE_INTEGER,
892 StreamBytesTransferred: c::LARGE_INTEGER,
893 dwStreamNumber: c::DWORD,
894 _dwCallbackReason: c::DWORD,
895 _hSourceFile: c::HANDLE,
896 _hDestinationFile: c::HANDLE,
899 if dwStreamNumber == 1 {
900 *(lpData as *mut i64) = StreamBytesTransferred;
904 let pfrom = maybe_verbatim(from)?;
905 let pto = maybe_verbatim(to)?;
912 &mut size as *mut _ as *mut _,
921 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
924 ) -> io::Result<()> {
925 symlink_junction_inner(original.as_ref(), junction.as_ref())
928 // Creating a directory junction on windows involves dealing with reparse
929 // points and the DeviceIoControl function, and this code is a skeleton of
930 // what can be found here:
932 // http://www.flexhex.com/docs/articles/hard-links.phtml
934 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
935 let d = DirBuilder::new();
938 let mut opts = OpenOptions::new();
940 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
941 let f = File::open(junction, &opts)?;
942 let h = f.as_inner().as_raw_handle();
945 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
946 let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
947 let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
949 // FIXME: this conversion is very hacky
951 let v = v.iter().map(|x| *x as u16);
952 for c in v.chain(original.as_os_str().encode_wide()) {
958 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
959 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
960 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
961 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
964 cvt(c::DeviceIoControl(
966 c::FSCTL_SET_REPARSE_POINT,
967 data.as_ptr() as *mut _,
968 (*db).ReparseDataLength + 8,
978 // Try to see if a file exists but, unlike `exists`, report I/O errors.
979 pub fn try_exists(path: &Path) -> io::Result<bool> {
980 // Open the file to ensure any symlinks are followed to their target.
981 let mut opts = OpenOptions::new();
982 // No read, write, etc access rights are needed.
984 // Backup semantics enables opening directories as well as files.
985 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
986 match File::open(path, &opts) {
987 Err(e) => match e.kind() {
988 // The file definitely does not exist
989 io::ErrorKind::NotFound => Ok(false),
991 // `ERROR_SHARING_VIOLATION` means that the file has been locked by
992 // another process. This is often temporary so we simply report it
993 // as the file existing.
994 _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
996 // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
997 // file exists. However, these types of errors are usually more
998 // permanent so we report them here.
1001 // The file was opened successfully therefore it must exist,