]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/fs.rs
`SetFileTime` doesn't allow setting the file time to `0xFFFF_FFFF_FFFF_FFFF`
[rust.git] / library / std / src / sys / windows / fs.rs
1 use crate::os::windows::prelude::*;
2
3 use crate::ffi::OsString;
4 use crate::fmt;
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};
9 use crate::ptr;
10 use crate::slice;
11 use crate::sync::Arc;
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};
16 use crate::thread;
17
18 use super::path::maybe_verbatim;
19 use super::to_u16s;
20
21 pub struct File {
22     handle: Handle,
23 }
24
25 #[derive(Clone)]
26 pub struct FileAttr {
27     attributes: c::DWORD,
28     creation_time: c::FILETIME,
29     last_access_time: c::FILETIME,
30     last_write_time: c::FILETIME,
31     file_size: u64,
32     reparse_tag: c::DWORD,
33     volume_serial_number: Option<u32>,
34     number_of_links: Option<u32>,
35     file_index: Option<u64>,
36 }
37
38 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
39 pub struct FileType {
40     attributes: c::DWORD,
41     reparse_tag: c::DWORD,
42 }
43
44 pub struct ReadDir {
45     handle: FindNextFileHandle,
46     root: Arc<PathBuf>,
47     first: Option<c::WIN32_FIND_DATAW>,
48 }
49
50 struct FindNextFileHandle(c::HANDLE);
51
52 unsafe impl Send for FindNextFileHandle {}
53 unsafe impl Sync for FindNextFileHandle {}
54
55 pub struct DirEntry {
56     root: Arc<PathBuf>,
57     data: c::WIN32_FIND_DATAW,
58 }
59
60 unsafe impl Send for OpenOptions {}
61 unsafe impl Sync for OpenOptions {}
62
63 #[derive(Clone, Debug)]
64 pub struct OpenOptions {
65     // generic
66     read: bool,
67     write: bool,
68     append: bool,
69     truncate: bool,
70     create: bool,
71     create_new: bool,
72     // system-specific
73     custom_flags: u32,
74     access_mode: Option<c::DWORD>,
75     attributes: c::DWORD,
76     share_mode: c::DWORD,
77     security_qos_flags: c::DWORD,
78     security_attributes: c::LPSECURITY_ATTRIBUTES,
79 }
80
81 #[derive(Clone, PartialEq, Eq, Debug)]
82 pub struct FilePermissions {
83     attrs: c::DWORD,
84 }
85
86 #[derive(Copy, Clone, Debug, Default)]
87 pub struct FileTimes {
88     accessed: Option<c::FILETIME>,
89     modified: Option<c::FILETIME>,
90 }
91
92 #[derive(Debug)]
93 pub struct DirBuilder;
94
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)
100     }
101 }
102
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) {
108                 return Some(Ok(e));
109             }
110         }
111         unsafe {
112             let mut wfd = mem::zeroed();
113             loop {
114                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
115                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
116                         return None;
117                     } else {
118                         return Some(Err(Error::last_os_error()));
119                     }
120                 }
121                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
122                     return Some(Ok(e));
123                 }
124             }
125         }
126     }
127 }
128
129 impl Drop for FindNextFileHandle {
130     fn drop(&mut self) {
131         let r = unsafe { c::FindClose(self.0) };
132         debug_assert!(r != 0);
133     }
134 }
135
136 impl DirEntry {
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,
141             _ => {}
142         }
143
144         Some(DirEntry { root: root.clone(), data: *wfd })
145     }
146
147     pub fn path(&self) -> PathBuf {
148         self.root.join(&self.file_name())
149     }
150
151     pub fn file_name(&self) -> OsString {
152         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
153         OsString::from_wide(filename)
154     }
155
156     pub fn file_type(&self) -> io::Result<FileType> {
157         Ok(FileType::new(
158             self.data.dwFileAttributes,
159             /* reparse_tag = */ self.data.dwReserved0,
160         ))
161     }
162
163     pub fn metadata(&self) -> io::Result<FileAttr> {
164         Ok(self.data.into())
165     }
166 }
167
168 impl OpenOptions {
169     pub fn new() -> OpenOptions {
170         OpenOptions {
171             // generic
172             read: false,
173             write: false,
174             append: false,
175             truncate: false,
176             create: false,
177             create_new: false,
178             // system-specific
179             custom_flags: 0,
180             access_mode: None,
181             share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
182             attributes: 0,
183             security_qos_flags: 0,
184             security_attributes: ptr::null_mut(),
185         }
186     }
187
188     pub fn read(&mut self, read: bool) {
189         self.read = read;
190     }
191     pub fn write(&mut self, write: bool) {
192         self.write = write;
193     }
194     pub fn append(&mut self, append: bool) {
195         self.append = append;
196     }
197     pub fn truncate(&mut self, truncate: bool) {
198         self.truncate = truncate;
199     }
200     pub fn create(&mut self, create: bool) {
201         self.create = create;
202     }
203     pub fn create_new(&mut self, create_new: bool) {
204         self.create_new = create_new;
205     }
206
207     pub fn custom_flags(&mut self, flags: u32) {
208         self.custom_flags = flags;
209     }
210     pub fn access_mode(&mut self, access_mode: u32) {
211         self.access_mode = Some(access_mode);
212     }
213     pub fn share_mode(&mut self, share_mode: u32) {
214         self.share_mode = share_mode;
215     }
216     pub fn attributes(&mut self, attrs: u32) {
217         self.attributes = attrs;
218     }
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;
223     }
224     pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
225         self.security_attributes = attrs;
226     }
227
228     fn get_access_mode(&self) -> io::Result<c::DWORD> {
229         const ERROR_INVALID_PARAMETER: i32 = 87;
230
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))
239             }
240             (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
241         }
242     }
243
244     fn get_creation_mode(&self) -> io::Result<c::DWORD> {
245         const ERROR_INVALID_PARAMETER: i32 = 87;
246
247         match (self.write, self.append) {
248             (true, false) => {}
249             (false, false) => {
250                 if self.truncate || self.create || self.create_new {
251                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
252                 }
253             }
254             (_, true) => {
255                 if self.truncate && !self.create_new {
256                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
257                 }
258             }
259         }
260
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,
267         })
268     }
269
270     fn get_flags_and_attributes(&self) -> c::DWORD {
271         self.custom_flags
272             | self.attributes
273             | self.security_qos_flags
274             | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
275     }
276 }
277
278 impl File {
279     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
280         let path = maybe_verbatim(path)?;
281         let handle = unsafe {
282             c::CreateFileW(
283                 path.as_ptr(),
284                 opts.get_access_mode()?,
285                 opts.share_mode,
286                 opts.security_attributes,
287                 opts.get_creation_mode()?,
288                 opts.get_flags_and_attributes(),
289                 ptr::null_mut(),
290             )
291         };
292         if let Ok(handle) = handle.try_into() {
293             Ok(File { handle: Handle::from_inner(handle) })
294         } else {
295             Err(Error::last_os_error())
296         }
297     }
298
299     pub fn fsync(&self) -> io::Result<()> {
300         cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
301         Ok(())
302     }
303
304     pub fn datasync(&self) -> io::Result<()> {
305         self.fsync()
306     }
307
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);
311         cvt(unsafe {
312             c::SetFileInformationByHandle(
313                 self.handle.as_raw_handle(),
314                 c::FileEndOfFileInfo,
315                 &mut info as *mut _ as *mut _,
316                 size as c::DWORD,
317             )
318         })?;
319         Ok(())
320     }
321
322     #[cfg(not(target_vendor = "uwp"))]
323     pub fn file_attr(&self) -> io::Result<FileAttr> {
324         unsafe {
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(),
335                 ))?;
336                 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
337                     reparse_tag = attr_tag.ReparseTag;
338                 }
339             }
340             Ok(FileAttr {
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),
346                 reparse_tag,
347                 volume_serial_number: Some(info.dwVolumeSerialNumber),
348                 number_of_links: Some(info.nNumberOfLinks),
349                 file_index: Some(
350                     (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
351                 ),
352             })
353         }
354     }
355
356     #[cfg(target_vendor = "uwp")]
357     pub fn file_attr(&self) -> io::Result<FileAttr> {
358         unsafe {
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(),
363                 c::FileBasicInfo,
364                 &mut info as *mut _ as *mut libc::c_void,
365                 size as c::DWORD,
366             ))?;
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,
372                 },
373                 last_access_time: c::FILETIME {
374                     dwLowDateTime: info.LastAccessTime as c::DWORD,
375                     dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
376                 },
377                 last_write_time: c::FILETIME {
378                     dwLowDateTime: info.LastWriteTime as c::DWORD,
379                     dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
380                 },
381                 file_size: 0,
382                 reparse_tag: 0,
383                 volume_serial_number: None,
384                 number_of_links: None,
385                 file_index: None,
386             };
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(),
391                 c::FileStandardInfo,
392                 &mut info as *mut _ as *mut libc::c_void,
393                 size as c::DWORD,
394             ))?;
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(),
404                 ))?;
405                 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
406                     attr.reparse_tag = attr_tag.ReparseTag;
407                 }
408             }
409             Ok(attr)
410         }
411     }
412
413     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
414         self.handle.read(buf)
415     }
416
417     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
418         self.handle.read_vectored(bufs)
419     }
420
421     #[inline]
422     pub fn is_read_vectored(&self) -> bool {
423         self.handle.is_read_vectored()
424     }
425
426     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
427         self.handle.read_at(buf, offset)
428     }
429
430     pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
431         self.handle.read_buf(cursor)
432     }
433
434     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
435         self.handle.write(buf)
436     }
437
438     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
439         self.handle.write_vectored(bufs)
440     }
441
442     #[inline]
443     pub fn is_write_vectored(&self) -> bool {
444         self.handle.is_write_vectored()
445     }
446
447     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
448         self.handle.write_at(buf, offset)
449     }
450
451     pub fn flush(&self) -> io::Result<()> {
452         Ok(())
453     }
454
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
458             // integer as `u64`.
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),
462         };
463         let pos = pos as c::LARGE_INTEGER;
464         let mut newpos = 0;
465         cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
466         Ok(newpos as u64)
467     }
468
469     pub fn duplicate(&self) -> io::Result<File> {
470         Ok(Self { handle: self.handle.try_clone()? })
471     }
472
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`.
476     fn reparse_point(
477         &self,
478         space: &mut Align8<[MaybeUninit<u8>]>,
479     ) -> io::Result<(c::DWORD, *const c::REPARSE_DATA_BUFFER)> {
480         unsafe {
481             let mut bytes = 0;
482             cvt({
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();
486                 c::DeviceIoControl(
487                     self.handle.as_raw_handle(),
488                     c::FSCTL_GET_REPARSE_POINT,
489                     ptr::null_mut(),
490                     0,
491                     space.0.as_mut_ptr().cast(),
492                     len as c::DWORD,
493                     &mut bytes,
494                     ptr::null_mut(),
495                 )
496             })?;
497             const _: () = assert!(core::mem::align_of::<c::REPARSE_DATA_BUFFER>() <= 8);
498             Ok((bytes, space.0.as_ptr().cast::<c::REPARSE_DATA_BUFFER>()))
499         }
500     }
501
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)?;
505         unsafe {
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());
511                     (
512                         ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
513                         (*info).SubstituteNameOffset / 2,
514                         (*info).SubstituteNameLength / 2,
515                         (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
516                     )
517                 }
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());
522                     (
523                         ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
524                         (*info).SubstituteNameOffset / 2,
525                         (*info).SubstituteNameLength / 2,
526                         false,
527                     )
528                 }
529                 _ => {
530                     return Err(io::const_io_error!(
531                         io::ErrorKind::Uncategorized,
532                         "Unsupported reparse point type",
533                     ));
534                 }
535             };
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]) {
541                 subst = &subst[4..];
542             }
543             Ok(PathBuf::from(OsString::from_wide(subst)))
544         }
545     }
546
547     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
548         let mut info = c::FILE_BASIC_INFO {
549             CreationTime: 0,
550             LastAccessTime: 0,
551             LastWriteTime: 0,
552             ChangeTime: 0,
553             FileAttributes: perm.attrs,
554         };
555         let size = mem::size_of_val(&info);
556         cvt(unsafe {
557             c::SetFileInformationByHandle(
558                 self.handle.as_raw_handle(),
559                 c::FileBasicInfo,
560                 &mut info as *mut _ as *mut _,
561                 size as c::DWORD,
562             )
563         })?;
564         Ok(())
565     }
566
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",
573             ));
574         }
575         let is_max =
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",
581             ));
582         }
583         cvt(unsafe {
584             c::SetFileTime(self.as_handle(), None, times.accessed.as_ref(), times.modified.as_ref())
585         })?;
586         Ok(())
587     }
588
589     /// Get only basic file information such as attributes and file times.
590     fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
591         unsafe {
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(),
596                 c::FileBasicInfo,
597                 &mut info as *mut _ as *mut libc::c_void,
598                 size as c::DWORD,
599             ))?;
600             Ok(info)
601         }
602     }
603     /// Delete using POSIX semantics.
604     ///
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.
608     ///
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,
616         };
617         let size = mem::size_of_val(&info);
618         cvt(unsafe {
619             c::SetFileInformationByHandle(
620                 self.handle.as_raw_handle(),
621                 c::FileDispositionInfoEx,
622                 &mut info as *mut _ as *mut _,
623                 size as c::DWORD,
624             )
625         })?;
626         Ok(())
627     }
628
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);
635         cvt(unsafe {
636             c::SetFileInformationByHandle(
637                 self.handle.as_raw_handle(),
638                 c::FileDispositionInfo,
639                 &mut info as *mut _ as *mut _,
640                 size as c::DWORD,
641             )
642         })?;
643         Ok(())
644     }
645
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`.
649     ///
650     /// The returned bool indicates if there are more entries or not.
651     /// It is an error if `self` is not a directory.
652     ///
653     /// # Symlinks and other reparse points
654     ///
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> {
660         let class =
661             if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
662
663         unsafe {
664             let result = cvt(c::GetFileInformationByHandleEx(
665                 self.handle.as_raw_handle(),
666                 class,
667                 buffer.as_mut_ptr().cast(),
668                 buffer.capacity() as _,
669             ));
670             match result {
671                 Ok(_) => Ok(true),
672                 Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
673                 Err(e) => Err(e),
674             }
675         }
676     }
677 }
678
679 /// A buffer for holding directory entries.
680 struct DirBuff {
681     buffer: Box<Align8<[MaybeUninit<u8>; Self::BUFFER_SIZE]>>,
682 }
683 impl DirBuff {
684     const BUFFER_SIZE: usize = 1024;
685     fn new() -> Self {
686         Self {
687             // Safety: `Align8<[MaybeUninit<u8>; N]>` does not need
688             // initialization.
689             buffer: unsafe { Box::new_uninit().assume_init() },
690         }
691     }
692     fn capacity(&self) -> usize {
693         self.buffer.0.len()
694     }
695     fn as_mut_ptr(&mut self) -> *mut u8 {
696         self.buffer.0.as_mut_ptr().cast()
697     }
698     /// Returns a `DirBuffIter`.
699     fn iter(&self) -> DirBuffIter<'_> {
700         DirBuffIter::new(self)
701     }
702 }
703 impl AsRef<[MaybeUninit<u8>]> for DirBuff {
704     fn as_ref(&self) -> &[MaybeUninit<u8>] {
705         &self.buffer.0
706     }
707 }
708
709 /// An iterator over entries stored in a `DirBuff`.
710 ///
711 /// Currently only returns file names (UTF-16 encoded).
712 struct DirBuffIter<'a> {
713     buffer: Option<&'a [MaybeUninit<u8>]>,
714     cursor: usize,
715 }
716 impl<'a> DirBuffIter<'a> {
717     fn new(buffer: &'a DirBuff) -> Self {
718         Self { buffer: Some(buffer.as_ref()), cursor: 0 }
719     }
720 }
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..];
726
727         // Get the name and next entry from the buffer.
728         // SAFETY:
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>(),
744             );
745             let is_directory = ((*info).FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
746
747             (name, is_directory, next_entry)
748         };
749
750         if next_entry == 0 {
751             self.buffer = None
752         } else {
753             self.cursor += next_entry
754         }
755
756         // Skip `.` and `..` pseudo entries.
757         const DOT: u16 = b'.' as u16;
758         match name {
759             [DOT] | [DOT, DOT] => self.next(),
760             _ => Some((name, is_directory)),
761         }
762     }
763 }
764
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.
770     //
771     // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
772     unsafe {
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()
786         };
787         let status = c::NtCreateFile(
788             &mut handle,
789             access,
790             &object,
791             &mut io_status,
792             crate::ptr::null_mut(),
793             0,
794             c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
795             c::FILE_OPEN,
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(),
799             0,
800         );
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
807             // very unhelpful.
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
811         {
812             // Try without `OBJ_DONT_REPARSE`. See above.
813             ATTRIBUTES.store(0, Ordering::Relaxed);
814             open_link_no_reparse(parent, name, access)
815         } else {
816             Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
817         }
818     }
819 }
820
821 impl AsInner<Handle> for File {
822     fn as_inner(&self) -> &Handle {
823         &self.handle
824     }
825 }
826
827 impl IntoInner<Handle> for File {
828     fn into_inner(self) -> Handle {
829         self.handle
830     }
831 }
832
833 impl FromInner<Handle> for File {
834     fn from_inner(handle: Handle) -> File {
835         File { handle }
836     }
837 }
838
839 impl AsHandle for File {
840     fn as_handle(&self) -> BorrowedHandle<'_> {
841         self.as_inner().as_handle()
842     }
843 }
844
845 impl AsRawHandle for File {
846     fn as_raw_handle(&self) -> RawHandle {
847         self.as_inner().as_raw_handle()
848     }
849 }
850
851 impl IntoRawHandle for File {
852     fn into_raw_handle(self) -> RawHandle {
853         self.into_inner().into_raw_handle()
854     }
855 }
856
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)) }
860     }
861 }
862
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);
870         }
871         b.finish()
872     }
873 }
874
875 impl FileAttr {
876     pub fn size(&self) -> u64 {
877         self.file_size
878     }
879
880     pub fn perm(&self) -> FilePermissions {
881         FilePermissions { attrs: self.attributes }
882     }
883
884     pub fn attrs(&self) -> u32 {
885         self.attributes
886     }
887
888     pub fn file_type(&self) -> FileType {
889         FileType::new(self.attributes, self.reparse_tag)
890     }
891
892     pub fn modified(&self) -> io::Result<SystemTime> {
893         Ok(SystemTime::from(self.last_write_time))
894     }
895
896     pub fn accessed(&self) -> io::Result<SystemTime> {
897         Ok(SystemTime::from(self.last_access_time))
898     }
899
900     pub fn created(&self) -> io::Result<SystemTime> {
901         Ok(SystemTime::from(self.creation_time))
902     }
903
904     pub fn modified_u64(&self) -> u64 {
905         to_u64(&self.last_write_time)
906     }
907
908     pub fn accessed_u64(&self) -> u64 {
909         to_u64(&self.last_access_time)
910     }
911
912     pub fn created_u64(&self) -> u64 {
913         to_u64(&self.creation_time)
914     }
915
916     pub fn volume_serial_number(&self) -> Option<u32> {
917         self.volume_serial_number
918     }
919
920     pub fn number_of_links(&self) -> Option<u32> {
921         self.number_of_links
922     }
923
924     pub fn file_index(&self) -> Option<u64> {
925         self.file_index
926     }
927 }
928 impl From<c::WIN32_FIND_DATAW> for FileAttr {
929     fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
930         FileAttr {
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
938                 wfd.dwReserved0
939             } else {
940                 0
941             },
942             volume_serial_number: None,
943             number_of_links: None,
944             file_index: None,
945         }
946     }
947 }
948
949 fn to_u64(ft: &c::FILETIME) -> u64 {
950     (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
951 }
952
953 impl FilePermissions {
954     pub fn readonly(&self) -> bool {
955         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
956     }
957
958     pub fn set_readonly(&mut self, readonly: bool) {
959         if readonly {
960             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
961         } else {
962             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
963         }
964     }
965 }
966
967 impl FileTimes {
968     pub fn set_accessed(&mut self, t: SystemTime) {
969         self.accessed = Some(t.into_inner());
970     }
971
972     pub fn set_modified(&mut self, t: SystemTime) {
973         self.modified = Some(t.into_inner());
974     }
975 }
976
977 impl FileType {
978     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
979         FileType { attributes: attrs, reparse_tag }
980     }
981     pub fn is_dir(&self) -> bool {
982         !self.is_symlink() && self.is_directory()
983     }
984     pub fn is_file(&self) -> bool {
985         !self.is_symlink() && !self.is_directory()
986     }
987     pub fn is_symlink(&self) -> bool {
988         self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
989     }
990     pub fn is_symlink_dir(&self) -> bool {
991         self.is_symlink() && self.is_directory()
992     }
993     pub fn is_symlink_file(&self) -> bool {
994         self.is_symlink() && !self.is_directory()
995     }
996     fn is_directory(&self) -> bool {
997         self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
998     }
999     fn is_reparse_point(&self) -> bool {
1000         self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
1001     }
1002     fn is_reparse_tag_name_surrogate(&self) -> bool {
1003         self.reparse_tag & 0x20000000 != 0
1004     }
1005 }
1006
1007 impl DirBuilder {
1008     pub fn new() -> DirBuilder {
1009         DirBuilder
1010     }
1011
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()) })?;
1015         Ok(())
1016     }
1017 }
1018
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)?;
1023
1024     unsafe {
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 {
1028             Ok(ReadDir {
1029                 handle: FindNextFileHandle(find_handle),
1030                 root: Arc::new(root),
1031                 first: Some(wfd),
1032             })
1033         } else {
1034             Err(Error::last_os_error())
1035         }
1036     }
1037 }
1038
1039 pub fn unlink(p: &Path) -> io::Result<()> {
1040     let p_u16s = maybe_verbatim(p)?;
1041     cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
1042     Ok(())
1043 }
1044
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) })?;
1049     Ok(())
1050 }
1051
1052 pub fn rmdir(p: &Path) -> io::Result<()> {
1053     let p = maybe_verbatim(p)?;
1054     cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
1055     Ok(())
1056 }
1057
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)
1066 }
1067
1068 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
1069     let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
1070
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 _));
1074     }
1075
1076     match remove_dir_all_iterative(&file, File::posix_delete) {
1077         Err(e) => {
1078             if let Some(code) = e.raw_os_error() {
1079                 match code as u32 {
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)
1085                     }
1086                     _ => Err(e),
1087                 }
1088             } else {
1089                 Err(e)
1090             }
1091         }
1092         ok => ok,
1093     }
1094 }
1095
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;
1100
1101     let mut buffer = DirBuff::new();
1102     let mut dirlist = vec![f.duplicate()?];
1103
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())) }
1107     }
1108
1109     let mut restart = true;
1110     while let Some(dir) = dirlist.last() {
1111         let dir = copy_handle(dir);
1112
1113         // Fill the buffer and iterate the entries.
1114         let more_data = dir.fill_dir_buff(&mut buffer, restart)?;
1115         restart = false;
1116         for (name, is_directory) in buffer.iter() {
1117             if is_directory {
1118                 let child_dir = open_link_no_reparse(
1119                     &dir,
1120                     name,
1121                     c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY,
1122                 )?;
1123                 dirlist.push(child_dir);
1124             } else {
1125                 for i in 1..=MAX_RETRIES {
1126                     let result = open_link_no_reparse(&dir, name, c::SYNCHRONIZE | c::DELETE);
1127                     match result {
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.
1132                         Err(e)
1133                             if i < MAX_RETRIES
1134                                 && (e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
1135                                     || e.raw_os_error()
1136                                         == Some(c::ERROR_SHARING_VIOLATION as _)) => {}
1137                         // Otherwise return the error.
1138                         Err(e) => return Err(e),
1139                     }
1140                     thread::yield_now();
1141                 }
1142             }
1143         }
1144         // If there were no more files then delete the directory.
1145         if !more_data {
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 {
1152                             return Err(e);
1153                         }
1154                         thread::yield_now();
1155                     } else {
1156                         break;
1157                     }
1158                 }
1159             }
1160         }
1161     }
1162     Ok(())
1163 }
1164
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)?;
1173     file.readlink()
1174 }
1175
1176 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1177     symlink_inner(original, link, false)
1178 }
1179
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(
1190             link.as_ptr(),
1191             original.as_ptr(),
1192             flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1193         ) as c::BOOL
1194     });
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.
1199             cvt(unsafe {
1200                 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1201             })?;
1202         } else {
1203             return Err(err);
1204         }
1205     }
1206     Ok(())
1207 }
1208
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()) })?;
1214     Ok(())
1215 }
1216
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",
1222     ));
1223 }
1224
1225 pub fn stat(path: &Path) -> io::Result<FileAttr> {
1226     metadata(path, ReparsePoint::Follow)
1227 }
1228
1229 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
1230     metadata(path, ReparsePoint::Open)
1231 }
1232
1233 #[repr(u32)]
1234 #[derive(Clone, Copy, PartialEq, Eq)]
1235 enum ReparsePoint {
1236     Follow = 0,
1237     Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
1238 }
1239 impl ReparsePoint {
1240     fn as_flag(self) -> u32 {
1241         self as u32
1242     }
1243 }
1244
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());
1250
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.
1261             unsafe {
1262                 let path = maybe_verbatim(path)?;
1263
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);
1271
1272                 if handle == c::INVALID_HANDLE_VALUE {
1273                     // This can fail if the user does not have read access to the
1274                     // directory.
1275                     Err(e)
1276                 } else {
1277                     // We no longer need the find handle.
1278                     c::FindClose(handle);
1279
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() {
1284                         Err(e)
1285                     } else {
1286                         Ok(attrs)
1287                     }
1288                 }
1289             }
1290         }
1291         Err(e) => Err(e),
1292     }
1293 }
1294
1295 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1296     let p = maybe_verbatim(p)?;
1297     unsafe {
1298         cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1299         Ok(())
1300     }
1301 }
1302
1303 fn get_path(f: &File) -> io::Result<PathBuf> {
1304     super::fill_utf16_buf(
1305         |buf, sz| unsafe {
1306             c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1307         },
1308         |buf| PathBuf::from(OsString::from_wide(buf)),
1309     )
1310 }
1311
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)?;
1319     get_path(&f)
1320 }
1321
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,
1332         lpData: c::LPVOID,
1333     ) -> c::DWORD {
1334         if dwStreamNumber == 1 {
1335             *(lpData as *mut i64) = StreamBytesTransferred;
1336         }
1337         c::PROGRESS_CONTINUE
1338     }
1339     let pfrom = maybe_verbatim(from)?;
1340     let pto = maybe_verbatim(to)?;
1341     let mut size = 0i64;
1342     cvt(unsafe {
1343         c::CopyFileExW(
1344             pfrom.as_ptr(),
1345             pto.as_ptr(),
1346             Some(callback),
1347             &mut size as *mut _ as *mut _,
1348             ptr::null_mut(),
1349             0,
1350         )
1351     })?;
1352     Ok(size as u64)
1353 }
1354
1355 #[allow(dead_code)]
1356 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
1357     original: P,
1358     junction: Q,
1359 ) -> io::Result<()> {
1360     symlink_junction_inner(original.as_ref(), junction.as_ref())
1361 }
1362
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:
1366 //
1367 // http://www.flexhex.com/docs/articles/hard-links.phtml
1368 #[allow(dead_code)]
1369 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
1370     let d = DirBuilder::new();
1371     d.mkdir(&junction)?;
1372
1373     let mut opts = OpenOptions::new();
1374     opts.write(true);
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();
1378
1379     unsafe {
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>();
1384         let mut i = 0;
1385         // FIXME: this conversion is very hacky
1386         let v = br"\??\";
1387         let v = v.iter().map(|x| *x as u16);
1388         for c in v.chain(original.as_os_str().encode_wide()) {
1389             *buf.add(i) = c;
1390             i += 1;
1391         }
1392         *buf.add(i) = 0;
1393         i += 1;
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;
1398
1399         let mut ret = 0;
1400         cvt(c::DeviceIoControl(
1401             h as *mut _,
1402             c::FSCTL_SET_REPARSE_POINT,
1403             data_ptr.cast(),
1404             (*db).ReparseDataLength + 8,
1405             ptr::null_mut(),
1406             0,
1407             &mut ret,
1408             ptr::null_mut(),
1409         ))
1410         .map(drop)
1411     }
1412 }
1413
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),
1426
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),
1431
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.
1435             _ => Err(e),
1436         },
1437         // The file was opened successfully therefore it must exist,
1438         Ok(_) => Ok(true),
1439     }
1440 }