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};
26 creation_time: c::FILETIME,
27 last_access_time: c::FILETIME,
28 last_write_time: c::FILETIME,
30 reparse_tag: c::DWORD,
31 volume_serial_number: Option<u32>,
32 number_of_links: Option<u32>,
33 file_index: Option<u64>,
36 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
39 reparse_tag: c::DWORD,
43 handle: FindNextFileHandle,
45 first: Option<c::WIN32_FIND_DATAW>,
48 struct FindNextFileHandle(c::HANDLE);
50 unsafe impl Send for FindNextFileHandle {}
51 unsafe impl Sync for FindNextFileHandle {}
55 data: c::WIN32_FIND_DATAW,
58 #[derive(Clone, Debug)]
59 pub struct OpenOptions {
69 access_mode: Option<c::DWORD>,
72 security_qos_flags: c::DWORD,
73 security_attributes: usize, // FIXME: should be a reference
76 #[derive(Clone, PartialEq, Eq, Debug)]
77 pub struct FilePermissions {
82 pub struct DirBuilder;
84 impl fmt::Debug for ReadDir {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
87 // Thus the result will be e g 'ReadDir("C:\")'
88 fmt::Debug::fmt(&*self.root, f)
92 impl Iterator for ReadDir {
93 type Item = io::Result<DirEntry>;
94 fn next(&mut self) -> Option<io::Result<DirEntry>> {
95 if let Some(first) = self.first.take() {
96 if let Some(e) = DirEntry::new(&self.root, &first) {
101 let mut wfd = mem::zeroed();
103 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
104 if c::GetLastError() == c::ERROR_NO_MORE_FILES {
107 return Some(Err(Error::last_os_error()));
110 if let Some(e) = DirEntry::new(&self.root, &wfd) {
118 impl Drop for FindNextFileHandle {
120 let r = unsafe { c::FindClose(self.0) };
121 debug_assert!(r != 0);
126 fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
127 match &wfd.cFileName[0..3] {
128 // check for '.' and '..'
129 &[46, 0, ..] | &[46, 46, 0, ..] => return None,
133 Some(DirEntry { root: root.clone(), data: *wfd })
136 pub fn path(&self) -> PathBuf {
137 self.root.join(&self.file_name())
140 pub fn file_name(&self) -> OsString {
141 let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
142 OsString::from_wide(filename)
145 pub fn file_type(&self) -> io::Result<FileType> {
147 self.data.dwFileAttributes,
148 /* reparse_tag = */ self.data.dwReserved0,
152 pub fn metadata(&self) -> io::Result<FileAttr> {
154 attributes: self.data.dwFileAttributes,
155 creation_time: self.data.ftCreationTime,
156 last_access_time: self.data.ftLastAccessTime,
157 last_write_time: self.data.ftLastWriteTime,
158 file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
159 reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
160 // reserved unless this is a reparse point
161 self.data.dwReserved0
165 volume_serial_number: None,
166 number_of_links: None,
173 pub fn new() -> OpenOptions {
185 share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
187 security_qos_flags: 0,
188 security_attributes: 0,
192 pub fn read(&mut self, read: bool) {
195 pub fn write(&mut self, write: bool) {
198 pub fn append(&mut self, append: bool) {
199 self.append = append;
201 pub fn truncate(&mut self, truncate: bool) {
202 self.truncate = truncate;
204 pub fn create(&mut self, create: bool) {
205 self.create = create;
207 pub fn create_new(&mut self, create_new: bool) {
208 self.create_new = create_new;
211 pub fn custom_flags(&mut self, flags: u32) {
212 self.custom_flags = flags;
214 pub fn access_mode(&mut self, access_mode: u32) {
215 self.access_mode = Some(access_mode);
217 pub fn share_mode(&mut self, share_mode: u32) {
218 self.share_mode = share_mode;
220 pub fn attributes(&mut self, attrs: u32) {
221 self.attributes = attrs;
223 pub fn security_qos_flags(&mut self, flags: u32) {
224 // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
225 // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
226 self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
228 pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
229 self.security_attributes = attrs as usize;
232 fn get_access_mode(&self) -> io::Result<c::DWORD> {
233 const ERROR_INVALID_PARAMETER: i32 = 87;
235 match (self.read, self.write, self.append, self.access_mode) {
236 (.., Some(mode)) => Ok(mode),
237 (true, false, false, None) => Ok(c::GENERIC_READ),
238 (false, true, false, None) => Ok(c::GENERIC_WRITE),
239 (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
240 (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
241 (true, _, true, None) => {
242 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
244 (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
248 fn get_creation_mode(&self) -> io::Result<c::DWORD> {
249 const ERROR_INVALID_PARAMETER: i32 = 87;
251 match (self.write, self.append) {
254 if self.truncate || self.create || self.create_new {
255 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
259 if self.truncate && !self.create_new {
260 return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
265 Ok(match (self.create, self.truncate, self.create_new) {
266 (false, false, false) => c::OPEN_EXISTING,
267 (true, false, false) => c::OPEN_ALWAYS,
268 (false, true, false) => c::TRUNCATE_EXISTING,
269 (true, true, false) => c::CREATE_ALWAYS,
270 (_, _, true) => c::CREATE_NEW,
274 fn get_flags_and_attributes(&self) -> c::DWORD {
277 | self.security_qos_flags
278 | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
283 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
284 let path = to_u16s(path)?;
285 let handle = unsafe {
288 opts.get_access_mode()?,
290 opts.security_attributes as *mut _,
291 opts.get_creation_mode()?,
292 opts.get_flags_and_attributes(),
296 if handle == c::INVALID_HANDLE_VALUE {
297 Err(Error::last_os_error())
299 unsafe { Ok(File { handle: Handle::from_raw_handle(handle) }) }
303 pub fn fsync(&self) -> io::Result<()> {
304 cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
308 pub fn datasync(&self) -> io::Result<()> {
312 pub fn truncate(&self, size: u64) -> io::Result<()> {
313 let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
314 let size = mem::size_of_val(&info);
316 c::SetFileInformationByHandle(
317 self.handle.as_raw_handle(),
318 c::FileEndOfFileInfo,
319 &mut info as *mut _ as *mut _,
326 #[cfg(not(target_vendor = "uwp"))]
327 pub fn file_attr(&self) -> io::Result<FileAttr> {
329 let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
330 cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
331 let mut reparse_tag = 0;
332 if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
333 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
334 if let Ok((_, buf)) = self.reparse_point(&mut b) {
335 reparse_tag = buf.ReparseTag;
339 attributes: info.dwFileAttributes,
340 creation_time: info.ftCreationTime,
341 last_access_time: info.ftLastAccessTime,
342 last_write_time: info.ftLastWriteTime,
343 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
345 volume_serial_number: Some(info.dwVolumeSerialNumber),
346 number_of_links: Some(info.nNumberOfLinks),
348 (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
354 #[cfg(target_vendor = "uwp")]
355 pub fn file_attr(&self) -> io::Result<FileAttr> {
357 let mut info: c::FILE_BASIC_INFO = mem::zeroed();
358 let size = mem::size_of_val(&info);
359 cvt(c::GetFileInformationByHandleEx(
360 self.handle.as_raw_handle(),
362 &mut info as *mut _ as *mut libc::c_void,
365 let mut attr = FileAttr {
366 attributes: info.FileAttributes,
367 creation_time: c::FILETIME {
368 dwLowDateTime: info.CreationTime as c::DWORD,
369 dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
371 last_access_time: c::FILETIME {
372 dwLowDateTime: info.LastAccessTime as c::DWORD,
373 dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
375 last_write_time: c::FILETIME {
376 dwLowDateTime: info.LastWriteTime as c::DWORD,
377 dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
381 volume_serial_number: None,
382 number_of_links: None,
385 let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
386 let size = mem::size_of_val(&info);
387 cvt(c::GetFileInformationByHandleEx(
388 self.handle.as_raw_handle(),
390 &mut info as *mut _ as *mut libc::c_void,
393 attr.file_size = info.AllocationSize as u64;
394 attr.number_of_links = Some(info.NumberOfLinks);
395 if attr.file_type().is_reparse_point() {
396 let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
397 if let Ok((_, buf)) = self.reparse_point(&mut b) {
398 attr.reparse_tag = buf.ReparseTag;
405 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
406 self.handle.read(buf)
409 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
410 self.handle.read_vectored(bufs)
414 pub fn is_read_vectored(&self) -> bool {
415 self.handle.is_read_vectored()
418 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
419 self.handle.read_at(buf, offset)
422 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
423 self.handle.write(buf)
426 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
427 self.handle.write_vectored(bufs)
431 pub fn is_write_vectored(&self) -> bool {
432 self.handle.is_write_vectored()
435 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
436 self.handle.write_at(buf, offset)
439 pub fn flush(&self) -> io::Result<()> {
443 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
444 let (whence, pos) = match pos {
445 // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
447 SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
448 SeekFrom::End(n) => (c::FILE_END, n),
449 SeekFrom::Current(n) => (c::FILE_CURRENT, n),
451 let pos = pos as c::LARGE_INTEGER;
453 cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
457 pub fn duplicate(&self) -> io::Result<File> {
458 Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
461 fn reparse_point<'a>(
463 space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
464 ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
469 self.handle.as_raw_handle(),
470 c::FSCTL_GET_REPARSE_POINT,
473 space.as_mut_ptr() as *mut _,
474 space.len() as c::DWORD,
479 Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
483 fn readlink(&self) -> io::Result<PathBuf> {
484 let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
485 let (_bytes, buf) = self.reparse_point(&mut space)?;
487 let (path_buffer, subst_off, subst_len, relative) = match buf.ReparseTag {
488 c::IO_REPARSE_TAG_SYMLINK => {
489 let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
490 &buf.rest as *const _ as *const _;
492 &(*info).PathBuffer as *const _ as *const u16,
493 (*info).SubstituteNameOffset / 2,
494 (*info).SubstituteNameLength / 2,
495 (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
498 c::IO_REPARSE_TAG_MOUNT_POINT => {
499 let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
500 &buf.rest as *const _ as *const _;
502 &(*info).PathBuffer as *const _ as *const u16,
503 (*info).SubstituteNameOffset / 2,
504 (*info).SubstituteNameLength / 2,
509 return Err(io::Error::new_const(
510 io::ErrorKind::Uncategorized,
511 &"Unsupported reparse point type",
515 let subst_ptr = path_buffer.offset(subst_off as isize);
516 let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
517 // Absolute paths start with an NT internal namespace prefix `\??\`
518 // We should not let it leak through.
519 if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
522 Ok(PathBuf::from(OsString::from_wide(subst)))
526 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
527 let mut info = c::FILE_BASIC_INFO {
532 FileAttributes: perm.attrs,
534 let size = mem::size_of_val(&info);
536 c::SetFileInformationByHandle(
537 self.handle.as_raw_handle(),
539 &mut info as *mut _ as *mut _,
547 impl AsInner<Handle> for File {
548 fn as_inner(&self) -> &Handle {
553 impl IntoInner<Handle> for File {
554 fn into_inner(self) -> Handle {
559 impl FromInner<Handle> for File {
560 fn from_inner(handle: Handle) -> File {
561 File { handle: handle }
565 impl AsHandle for File {
566 fn as_handle(&self) -> BorrowedHandle<'_> {
567 self.as_inner().as_handle()
571 impl AsRawHandle for File {
572 fn as_raw_handle(&self) -> RawHandle {
573 self.as_inner().as_raw_handle()
577 impl IntoRawHandle for File {
578 fn into_raw_handle(self) -> RawHandle {
579 self.into_inner().into_raw_handle()
583 impl FromRawHandle for File {
584 unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
585 Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
589 impl fmt::Debug for File {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 // FIXME(#24570): add more info here (e.g., mode)
592 let mut b = f.debug_struct("File");
593 b.field("handle", &self.handle.as_raw_handle());
594 if let Ok(path) = get_path(&self) {
595 b.field("path", &path);
602 pub fn size(&self) -> u64 {
606 pub fn perm(&self) -> FilePermissions {
607 FilePermissions { attrs: self.attributes }
610 pub fn attrs(&self) -> u32 {
614 pub fn file_type(&self) -> FileType {
615 FileType::new(self.attributes, self.reparse_tag)
618 pub fn modified(&self) -> io::Result<SystemTime> {
619 Ok(SystemTime::from(self.last_write_time))
622 pub fn accessed(&self) -> io::Result<SystemTime> {
623 Ok(SystemTime::from(self.last_access_time))
626 pub fn created(&self) -> io::Result<SystemTime> {
627 Ok(SystemTime::from(self.creation_time))
630 pub fn modified_u64(&self) -> u64 {
631 to_u64(&self.last_write_time)
634 pub fn accessed_u64(&self) -> u64 {
635 to_u64(&self.last_access_time)
638 pub fn created_u64(&self) -> u64 {
639 to_u64(&self.creation_time)
642 pub fn volume_serial_number(&self) -> Option<u32> {
643 self.volume_serial_number
646 pub fn number_of_links(&self) -> Option<u32> {
650 pub fn file_index(&self) -> Option<u64> {
655 fn to_u64(ft: &c::FILETIME) -> u64 {
656 (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
659 impl FilePermissions {
660 pub fn readonly(&self) -> bool {
661 self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
664 pub fn set_readonly(&mut self, readonly: bool) {
666 self.attrs |= c::FILE_ATTRIBUTE_READONLY;
668 self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
674 fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
675 FileType { attributes: attrs, reparse_tag: reparse_tag }
677 pub fn is_dir(&self) -> bool {
678 !self.is_symlink() && self.is_directory()
680 pub fn is_file(&self) -> bool {
681 !self.is_symlink() && !self.is_directory()
683 pub fn is_symlink(&self) -> bool {
684 self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
686 pub fn is_symlink_dir(&self) -> bool {
687 self.is_symlink() && self.is_directory()
689 pub fn is_symlink_file(&self) -> bool {
690 self.is_symlink() && !self.is_directory()
692 fn is_directory(&self) -> bool {
693 self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
695 fn is_reparse_point(&self) -> bool {
696 self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
698 fn is_reparse_tag_name_surrogate(&self) -> bool {
699 self.reparse_tag & 0x20000000 != 0
704 pub fn new() -> DirBuilder {
708 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
710 cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
715 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
716 let root = p.to_path_buf();
717 let star = p.join("*");
718 let path = to_u16s(&star)?;
721 let mut wfd = mem::zeroed();
722 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
723 if find_handle != c::INVALID_HANDLE_VALUE {
725 handle: FindNextFileHandle(find_handle),
726 root: Arc::new(root),
730 Err(Error::last_os_error())
735 pub fn unlink(p: &Path) -> io::Result<()> {
736 let p_u16s = to_u16s(p)?;
737 cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
741 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
742 let old = to_u16s(old)?;
743 let new = to_u16s(new)?;
744 cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
748 pub fn rmdir(p: &Path) -> io::Result<()> {
750 cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
754 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
755 let filetype = lstat(path)?.file_type();
756 if filetype.is_symlink() {
757 // On Windows symlinks to files and directories are removed differently.
758 // rmdir only deletes dir symlinks and junctions, not file symlinks.
761 remove_dir_all_recursive(path)
765 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
766 for child in readdir(path)? {
768 let child_type = child.file_type()?;
769 if child_type.is_dir() {
770 remove_dir_all_recursive(&child.path())?;
771 } else if child_type.is_symlink_dir() {
772 rmdir(&child.path())?;
774 unlink(&child.path())?;
780 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
781 // Open the link with no access mode, instead of generic read.
782 // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
783 // this is needed for a common case.
784 let mut opts = OpenOptions::new();
786 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
787 let file = File::open(&path, &opts)?;
791 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
792 symlink_inner(original, link, false)
795 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
796 let original = to_u16s(original)?;
797 let link = to_u16s(link)?;
798 let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
799 // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
800 // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
801 // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
802 // added to dwFlags to opt into this behaviour.
803 let result = cvt(unsafe {
804 c::CreateSymbolicLinkW(
807 flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
810 if let Err(err) = result {
811 if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
812 // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
813 // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
815 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
824 #[cfg(not(target_vendor = "uwp"))]
825 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
826 let original = to_u16s(original)?;
827 let link = to_u16s(link)?;
828 cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
832 #[cfg(target_vendor = "uwp")]
833 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
834 return Err(io::Error::new_const(
835 io::ErrorKind::Unsupported,
836 &"hard link are not supported on UWP",
840 pub fn stat(path: &Path) -> io::Result<FileAttr> {
841 let mut opts = OpenOptions::new();
842 // No read or write permissions are necessary
844 // This flag is so we can open directories too
845 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
846 let file = File::open(path, &opts)?;
850 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
851 let mut opts = OpenOptions::new();
852 // No read or write permissions are necessary
854 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
855 let file = File::open(path, &opts)?;
859 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
862 cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
867 fn get_path(f: &File) -> io::Result<PathBuf> {
868 super::fill_utf16_buf(
870 c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
872 |buf| PathBuf::from(OsString::from_wide(buf)),
876 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
877 let mut opts = OpenOptions::new();
878 // No read or write permissions are necessary
880 // This flag is so we can open directories too
881 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
882 let f = File::open(p, &opts)?;
886 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
887 unsafe extern "system" fn callback(
888 _TotalFileSize: c::LARGE_INTEGER,
889 _TotalBytesTransferred: c::LARGE_INTEGER,
890 _StreamSize: c::LARGE_INTEGER,
891 StreamBytesTransferred: c::LARGE_INTEGER,
892 dwStreamNumber: c::DWORD,
893 _dwCallbackReason: c::DWORD,
894 _hSourceFile: c::HANDLE,
895 _hDestinationFile: c::HANDLE,
898 if dwStreamNumber == 1 {
899 *(lpData as *mut i64) = StreamBytesTransferred;
903 let pfrom = to_u16s(from)?;
904 let pto = to_u16s(to)?;
911 &mut size as *mut _ as *mut _,
920 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
923 ) -> io::Result<()> {
924 symlink_junction_inner(original.as_ref(), junction.as_ref())
927 // Creating a directory junction on windows involves dealing with reparse
928 // points and the DeviceIoControl function, and this code is a skeleton of
929 // what can be found here:
931 // http://www.flexhex.com/docs/articles/hard-links.phtml
933 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
934 let d = DirBuilder::new();
937 let mut opts = OpenOptions::new();
939 opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
940 let f = File::open(junction, &opts)?;
941 let h = f.as_inner().as_raw_handle();
944 let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
945 let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
946 let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
948 // FIXME: this conversion is very hacky
950 let v = v.iter().map(|x| *x as u16);
951 for c in v.chain(original.as_os_str().encode_wide()) {
957 (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
958 (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
959 (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
960 (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
963 cvt(c::DeviceIoControl(
965 c::FSCTL_SET_REPARSE_POINT,
966 data.as_ptr() as *mut _,
967 (*db).ReparseDataLength + 8,
977 // Try to see if a file exists but, unlike `exists`, report I/O errors.
978 pub fn try_exists(path: &Path) -> io::Result<bool> {
979 // Open the file to ensure any symlinks are followed to their target.
980 let mut opts = OpenOptions::new();
981 // No read, write, etc access rights are needed.
983 // Backup semantics enables opening directories as well as files.
984 opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
985 match File::open(path, &opts) {
986 Err(e) => match e.kind() {
987 // The file definitely does not exist
988 io::ErrorKind::NotFound => Ok(false),
990 // `ERROR_SHARING_VIOLATION` means that the file has been locked by
991 // another process. This is often temporary so we simply report it
992 // as the file existing.
993 _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
995 // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
996 // file exists. However, these types of errors are usually more
997 // permanent so we report them here.
1000 // The file was opened successfully therefore it must exist,