]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/fs.rs
Rollup merge of #106273 - notriddle:notriddle/source-content-overflow, r=GuillaumeGomez
[rust.git] / library / std / src / sys / windows / fs.rs
1 use crate::os::windows::prelude::*;
2
3 use crate::borrow::Cow;
4 use crate::ffi::OsString;
5 use crate::fmt;
6 use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
7 use crate::mem::{self, MaybeUninit};
8 use crate::os::windows::io::{AsHandle, BorrowedHandle};
9 use crate::path::{Path, PathBuf};
10 use crate::ptr;
11 use crate::slice;
12 use crate::sync::Arc;
13 use crate::sys::handle::Handle;
14 use crate::sys::time::SystemTime;
15 use crate::sys::{c, cvt, Align8};
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
17 use crate::thread;
18
19 use super::path::maybe_verbatim;
20 use super::to_u16s;
21
22 pub struct File {
23     handle: Handle,
24 }
25
26 #[derive(Clone)]
27 pub struct FileAttr {
28     attributes: c::DWORD,
29     creation_time: c::FILETIME,
30     last_access_time: c::FILETIME,
31     last_write_time: c::FILETIME,
32     file_size: u64,
33     reparse_tag: c::DWORD,
34     volume_serial_number: Option<u32>,
35     number_of_links: Option<u32>,
36     file_index: Option<u64>,
37 }
38
39 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
40 pub struct FileType {
41     attributes: c::DWORD,
42     reparse_tag: c::DWORD,
43 }
44
45 pub struct ReadDir {
46     handle: FindNextFileHandle,
47     root: Arc<PathBuf>,
48     first: Option<c::WIN32_FIND_DATAW>,
49 }
50
51 struct FindNextFileHandle(c::HANDLE);
52
53 unsafe impl Send for FindNextFileHandle {}
54 unsafe impl Sync for FindNextFileHandle {}
55
56 pub struct DirEntry {
57     root: Arc<PathBuf>,
58     data: c::WIN32_FIND_DATAW,
59 }
60
61 unsafe impl Send for OpenOptions {}
62 unsafe impl Sync for OpenOptions {}
63
64 #[derive(Clone, Debug)]
65 pub struct OpenOptions {
66     // generic
67     read: bool,
68     write: bool,
69     append: bool,
70     truncate: bool,
71     create: bool,
72     create_new: bool,
73     // system-specific
74     custom_flags: u32,
75     access_mode: Option<c::DWORD>,
76     attributes: c::DWORD,
77     share_mode: c::DWORD,
78     security_qos_flags: c::DWORD,
79     security_attributes: c::LPSECURITY_ATTRIBUTES,
80 }
81
82 #[derive(Clone, PartialEq, Eq, Debug)]
83 pub struct FilePermissions {
84     attrs: c::DWORD,
85 }
86
87 #[derive(Copy, Clone, Debug, Default)]
88 pub struct FileTimes {
89     accessed: Option<c::FILETIME>,
90     modified: Option<c::FILETIME>,
91 }
92
93 #[derive(Debug)]
94 pub struct DirBuilder;
95
96 impl fmt::Debug for ReadDir {
97     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98         // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
99         // Thus the result will be e g 'ReadDir("C:\")'
100         fmt::Debug::fmt(&*self.root, f)
101     }
102 }
103
104 impl Iterator for ReadDir {
105     type Item = io::Result<DirEntry>;
106     fn next(&mut self) -> Option<io::Result<DirEntry>> {
107         if let Some(first) = self.first.take() {
108             if let Some(e) = DirEntry::new(&self.root, &first) {
109                 return Some(Ok(e));
110             }
111         }
112         unsafe {
113             let mut wfd = mem::zeroed();
114             loop {
115                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
116                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
117                         return None;
118                     } else {
119                         return Some(Err(Error::last_os_error()));
120                     }
121                 }
122                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
123                     return Some(Ok(e));
124                 }
125             }
126         }
127     }
128 }
129
130 impl Drop for FindNextFileHandle {
131     fn drop(&mut self) {
132         let r = unsafe { c::FindClose(self.0) };
133         debug_assert!(r != 0);
134     }
135 }
136
137 impl DirEntry {
138     fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
139         match &wfd.cFileName[0..3] {
140             // check for '.' and '..'
141             &[46, 0, ..] | &[46, 46, 0, ..] => return None,
142             _ => {}
143         }
144
145         Some(DirEntry { root: root.clone(), data: *wfd })
146     }
147
148     pub fn path(&self) -> PathBuf {
149         self.root.join(&self.file_name())
150     }
151
152     pub fn file_name(&self) -> OsString {
153         let filename = super::truncate_utf16_at_nul(&self.data.cFileName);
154         OsString::from_wide(filename)
155     }
156
157     pub fn file_type(&self) -> io::Result<FileType> {
158         Ok(FileType::new(
159             self.data.dwFileAttributes,
160             /* reparse_tag = */ self.data.dwReserved0,
161         ))
162     }
163
164     pub fn metadata(&self) -> io::Result<FileAttr> {
165         Ok(self.data.into())
166     }
167 }
168
169 impl OpenOptions {
170     pub fn new() -> OpenOptions {
171         OpenOptions {
172             // generic
173             read: false,
174             write: false,
175             append: false,
176             truncate: false,
177             create: false,
178             create_new: false,
179             // system-specific
180             custom_flags: 0,
181             access_mode: None,
182             share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
183             attributes: 0,
184             security_qos_flags: 0,
185             security_attributes: ptr::null_mut(),
186         }
187     }
188
189     pub fn read(&mut self, read: bool) {
190         self.read = read;
191     }
192     pub fn write(&mut self, write: bool) {
193         self.write = write;
194     }
195     pub fn append(&mut self, append: bool) {
196         self.append = append;
197     }
198     pub fn truncate(&mut self, truncate: bool) {
199         self.truncate = truncate;
200     }
201     pub fn create(&mut self, create: bool) {
202         self.create = create;
203     }
204     pub fn create_new(&mut self, create_new: bool) {
205         self.create_new = create_new;
206     }
207
208     pub fn custom_flags(&mut self, flags: u32) {
209         self.custom_flags = flags;
210     }
211     pub fn access_mode(&mut self, access_mode: u32) {
212         self.access_mode = Some(access_mode);
213     }
214     pub fn share_mode(&mut self, share_mode: u32) {
215         self.share_mode = share_mode;
216     }
217     pub fn attributes(&mut self, attrs: u32) {
218         self.attributes = attrs;
219     }
220     pub fn security_qos_flags(&mut self, flags: u32) {
221         // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
222         // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
223         self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
224     }
225     pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) {
226         self.security_attributes = attrs;
227     }
228
229     fn get_access_mode(&self) -> io::Result<c::DWORD> {
230         const ERROR_INVALID_PARAMETER: i32 = 87;
231
232         match (self.read, self.write, self.append, self.access_mode) {
233             (.., Some(mode)) => Ok(mode),
234             (true, false, false, None) => Ok(c::GENERIC_READ),
235             (false, true, false, None) => Ok(c::GENERIC_WRITE),
236             (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
237             (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
238             (true, _, true, None) => {
239                 Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
240             }
241             (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
242         }
243     }
244
245     fn get_creation_mode(&self) -> io::Result<c::DWORD> {
246         const ERROR_INVALID_PARAMETER: i32 = 87;
247
248         match (self.write, self.append) {
249             (true, false) => {}
250             (false, false) => {
251                 if self.truncate || self.create || self.create_new {
252                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
253                 }
254             }
255             (_, true) => {
256                 if self.truncate && !self.create_new {
257                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
258                 }
259             }
260         }
261
262         Ok(match (self.create, self.truncate, self.create_new) {
263             (false, false, false) => c::OPEN_EXISTING,
264             (true, false, false) => c::OPEN_ALWAYS,
265             (false, true, false) => c::TRUNCATE_EXISTING,
266             (true, true, false) => c::CREATE_ALWAYS,
267             (_, _, true) => c::CREATE_NEW,
268         })
269     }
270
271     fn get_flags_and_attributes(&self) -> c::DWORD {
272         self.custom_flags
273             | self.attributes
274             | self.security_qos_flags
275             | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
276     }
277 }
278
279 impl File {
280     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
281         let path = maybe_verbatim(path)?;
282         let handle = unsafe {
283             c::CreateFileW(
284                 path.as_ptr(),
285                 opts.get_access_mode()?,
286                 opts.share_mode,
287                 opts.security_attributes,
288                 opts.get_creation_mode()?,
289                 opts.get_flags_and_attributes(),
290                 ptr::null_mut(),
291             )
292         };
293         if let Ok(handle) = handle.try_into() {
294             Ok(File { handle: Handle::from_inner(handle) })
295         } else {
296             Err(Error::last_os_error())
297         }
298     }
299
300     pub fn fsync(&self) -> io::Result<()> {
301         cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
302         Ok(())
303     }
304
305     pub fn datasync(&self) -> io::Result<()> {
306         self.fsync()
307     }
308
309     pub fn truncate(&self, size: u64) -> io::Result<()> {
310         let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
311         let size = mem::size_of_val(&info);
312         cvt(unsafe {
313             c::SetFileInformationByHandle(
314                 self.handle.as_raw_handle(),
315                 c::FileEndOfFileInfo,
316                 &mut info as *mut _ as *mut _,
317                 size as c::DWORD,
318             )
319         })?;
320         Ok(())
321     }
322
323     #[cfg(not(target_vendor = "uwp"))]
324     pub fn file_attr(&self) -> io::Result<FileAttr> {
325         unsafe {
326             let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
327             cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
328             let mut reparse_tag = 0;
329             if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
330                 let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
331                 cvt(c::GetFileInformationByHandleEx(
332                     self.handle.as_raw_handle(),
333                     c::FileAttributeTagInfo,
334                     ptr::addr_of_mut!(attr_tag).cast(),
335                     mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
336                 ))?;
337                 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
338                     reparse_tag = attr_tag.ReparseTag;
339                 }
340             }
341             Ok(FileAttr {
342                 attributes: info.dwFileAttributes,
343                 creation_time: info.ftCreationTime,
344                 last_access_time: info.ftLastAccessTime,
345                 last_write_time: info.ftLastWriteTime,
346                 file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
347                 reparse_tag,
348                 volume_serial_number: Some(info.dwVolumeSerialNumber),
349                 number_of_links: Some(info.nNumberOfLinks),
350                 file_index: Some(
351                     (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
352                 ),
353             })
354         }
355     }
356
357     #[cfg(target_vendor = "uwp")]
358     pub fn file_attr(&self) -> io::Result<FileAttr> {
359         unsafe {
360             let mut info: c::FILE_BASIC_INFO = mem::zeroed();
361             let size = mem::size_of_val(&info);
362             cvt(c::GetFileInformationByHandleEx(
363                 self.handle.as_raw_handle(),
364                 c::FileBasicInfo,
365                 &mut info as *mut _ as *mut libc::c_void,
366                 size as c::DWORD,
367             ))?;
368             let mut attr = FileAttr {
369                 attributes: info.FileAttributes,
370                 creation_time: c::FILETIME {
371                     dwLowDateTime: info.CreationTime as c::DWORD,
372                     dwHighDateTime: (info.CreationTime >> 32) as c::DWORD,
373                 },
374                 last_access_time: c::FILETIME {
375                     dwLowDateTime: info.LastAccessTime as c::DWORD,
376                     dwHighDateTime: (info.LastAccessTime >> 32) as c::DWORD,
377                 },
378                 last_write_time: c::FILETIME {
379                     dwLowDateTime: info.LastWriteTime as c::DWORD,
380                     dwHighDateTime: (info.LastWriteTime >> 32) as c::DWORD,
381                 },
382                 file_size: 0,
383                 reparse_tag: 0,
384                 volume_serial_number: None,
385                 number_of_links: None,
386                 file_index: None,
387             };
388             let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
389             let size = mem::size_of_val(&info);
390             cvt(c::GetFileInformationByHandleEx(
391                 self.handle.as_raw_handle(),
392                 c::FileStandardInfo,
393                 &mut info as *mut _ as *mut libc::c_void,
394                 size as c::DWORD,
395             ))?;
396             attr.file_size = info.AllocationSize as u64;
397             attr.number_of_links = Some(info.NumberOfLinks);
398             if attr.file_type().is_reparse_point() {
399                 let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
400                 cvt(c::GetFileInformationByHandleEx(
401                     self.handle.as_raw_handle(),
402                     c::FileAttributeTagInfo,
403                     ptr::addr_of_mut!(attr_tag).cast(),
404                     mem::size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
405                 ))?;
406                 if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
407                     attr.reparse_tag = attr_tag.ReparseTag;
408                 }
409             }
410             Ok(attr)
411         }
412     }
413
414     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
415         self.handle.read(buf)
416     }
417
418     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
419         self.handle.read_vectored(bufs)
420     }
421
422     #[inline]
423     pub fn is_read_vectored(&self) -> bool {
424         self.handle.is_read_vectored()
425     }
426
427     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
428         self.handle.read_at(buf, offset)
429     }
430
431     pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
432         self.handle.read_buf(cursor)
433     }
434
435     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
436         self.handle.write(buf)
437     }
438
439     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
440         self.handle.write_vectored(bufs)
441     }
442
443     #[inline]
444     pub fn is_write_vectored(&self) -> bool {
445         self.handle.is_write_vectored()
446     }
447
448     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
449         self.handle.write_at(buf, offset)
450     }
451
452     pub fn flush(&self) -> io::Result<()> {
453         Ok(())
454     }
455
456     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
457         let (whence, pos) = match pos {
458             // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
459             // integer as `u64`.
460             SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
461             SeekFrom::End(n) => (c::FILE_END, n),
462             SeekFrom::Current(n) => (c::FILE_CURRENT, n),
463         };
464         let pos = pos as c::LARGE_INTEGER;
465         let mut newpos = 0;
466         cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
467         Ok(newpos as u64)
468     }
469
470     pub fn duplicate(&self) -> io::Result<File> {
471         Ok(Self { handle: self.handle.try_clone()? })
472     }
473
474     // NB: returned pointer is derived from `space`, and has provenance to
475     // match. A raw pointer is returned rather than a reference in order to
476     // avoid narrowing provenance to the actual `REPARSE_DATA_BUFFER`.
477     fn reparse_point(
478         &self,
479         space: &mut Align8<[MaybeUninit<u8>]>,
480     ) -> io::Result<(c::DWORD, *const c::REPARSE_DATA_BUFFER)> {
481         unsafe {
482             let mut bytes = 0;
483             cvt({
484                 // Grab this in advance to avoid it invalidating the pointer
485                 // we get from `space.0.as_mut_ptr()`.
486                 let len = space.0.len();
487                 c::DeviceIoControl(
488                     self.handle.as_raw_handle(),
489                     c::FSCTL_GET_REPARSE_POINT,
490                     ptr::null_mut(),
491                     0,
492                     space.0.as_mut_ptr().cast(),
493                     len as c::DWORD,
494                     &mut bytes,
495                     ptr::null_mut(),
496                 )
497             })?;
498             const _: () = assert!(core::mem::align_of::<c::REPARSE_DATA_BUFFER>() <= 8);
499             Ok((bytes, space.0.as_ptr().cast::<c::REPARSE_DATA_BUFFER>()))
500         }
501     }
502
503     fn readlink(&self) -> io::Result<PathBuf> {
504         let mut space = Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
505         let (_bytes, buf) = self.reparse_point(&mut space)?;
506         unsafe {
507             let (path_buffer, subst_off, subst_len, relative) = match (*buf).ReparseTag {
508                 c::IO_REPARSE_TAG_SYMLINK => {
509                     let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
510                         ptr::addr_of!((*buf).rest).cast();
511                     assert!(info.is_aligned());
512                     (
513                         ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
514                         (*info).SubstituteNameOffset / 2,
515                         (*info).SubstituteNameLength / 2,
516                         (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
517                     )
518                 }
519                 c::IO_REPARSE_TAG_MOUNT_POINT => {
520                     let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
521                         ptr::addr_of!((*buf).rest).cast();
522                     assert!(info.is_aligned());
523                     (
524                         ptr::addr_of!((*info).PathBuffer).cast::<u16>(),
525                         (*info).SubstituteNameOffset / 2,
526                         (*info).SubstituteNameLength / 2,
527                         false,
528                     )
529                 }
530                 _ => {
531                     return Err(io::const_io_error!(
532                         io::ErrorKind::Uncategorized,
533                         "Unsupported reparse point type",
534                     ));
535                 }
536             };
537             let subst_ptr = path_buffer.add(subst_off.into());
538             let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
539             // Absolute paths start with an NT internal namespace prefix `\??\`
540             // We should not let it leak through.
541             if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
542                 subst = &subst[4..];
543             }
544             Ok(PathBuf::from(OsString::from_wide(subst)))
545         }
546     }
547
548     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
549         let mut info = c::FILE_BASIC_INFO {
550             CreationTime: 0,
551             LastAccessTime: 0,
552             LastWriteTime: 0,
553             ChangeTime: 0,
554             FileAttributes: perm.attrs,
555         };
556         let size = mem::size_of_val(&info);
557         cvt(unsafe {
558             c::SetFileInformationByHandle(
559                 self.handle.as_raw_handle(),
560                 c::FileBasicInfo,
561                 &mut info as *mut _ as *mut _,
562                 size as c::DWORD,
563             )
564         })?;
565         Ok(())
566     }
567
568     pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
569         let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0;
570         if times.accessed.map_or(false, is_zero) || times.modified.map_or(false, is_zero) {
571             return Err(io::const_io_error!(
572                 io::ErrorKind::InvalidInput,
573                 "Cannot set file timestamp to 0",
574             ));
575         }
576         let is_max =
577             |t: c::FILETIME| t.dwLowDateTime == c::DWORD::MAX && t.dwHighDateTime == c::DWORD::MAX;
578         if times.accessed.map_or(false, is_max) || times.modified.map_or(false, is_max) {
579             return Err(io::const_io_error!(
580                 io::ErrorKind::InvalidInput,
581                 "Cannot set file timestamp to 0xFFFF_FFFF_FFFF_FFFF",
582             ));
583         }
584         cvt(unsafe {
585             c::SetFileTime(self.as_handle(), None, times.accessed.as_ref(), times.modified.as_ref())
586         })?;
587         Ok(())
588     }
589
590     /// Get only basic file information such as attributes and file times.
591     fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
592         unsafe {
593             let mut info: c::FILE_BASIC_INFO = mem::zeroed();
594             let size = mem::size_of_val(&info);
595             cvt(c::GetFileInformationByHandleEx(
596                 self.handle.as_raw_handle(),
597                 c::FileBasicInfo,
598                 &mut info as *mut _ as *mut libc::c_void,
599                 size as c::DWORD,
600             ))?;
601             Ok(info)
602         }
603     }
604     /// Delete using POSIX semantics.
605     ///
606     /// Files will be deleted as soon as the handle is closed. This is supported
607     /// for Windows 10 1607 (aka RS1) and later. However some filesystem
608     /// drivers will not support it even then, e.g. FAT32.
609     ///
610     /// If the operation is not supported for this filesystem or OS version
611     /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
612     fn posix_delete(&self) -> io::Result<()> {
613         let mut info = c::FILE_DISPOSITION_INFO_EX {
614             Flags: c::FILE_DISPOSITION_DELETE
615                 | c::FILE_DISPOSITION_POSIX_SEMANTICS
616                 | c::FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE,
617         };
618         let size = mem::size_of_val(&info);
619         cvt(unsafe {
620             c::SetFileInformationByHandle(
621                 self.handle.as_raw_handle(),
622                 c::FileDispositionInfoEx,
623                 &mut info as *mut _ as *mut _,
624                 size as c::DWORD,
625             )
626         })?;
627         Ok(())
628     }
629
630     /// Delete a file using win32 semantics. The file won't actually be deleted
631     /// until all file handles are closed. However, marking a file for deletion
632     /// will prevent anyone from opening a new handle to the file.
633     fn win32_delete(&self) -> io::Result<()> {
634         let mut info = c::FILE_DISPOSITION_INFO { DeleteFile: c::TRUE as _ };
635         let size = mem::size_of_val(&info);
636         cvt(unsafe {
637             c::SetFileInformationByHandle(
638                 self.handle.as_raw_handle(),
639                 c::FileDispositionInfo,
640                 &mut info as *mut _ as *mut _,
641                 size as c::DWORD,
642             )
643         })?;
644         Ok(())
645     }
646
647     /// Fill the given buffer with as many directory entries as will fit.
648     /// This will remember its position and continue from the last call unless
649     /// `restart` is set to `true`.
650     ///
651     /// The returned bool indicates if there are more entries or not.
652     /// It is an error if `self` is not a directory.
653     ///
654     /// # Symlinks and other reparse points
655     ///
656     /// On Windows a file is either a directory or a non-directory.
657     /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
658     /// So if you open a link (not its target) and iterate the directory,
659     /// you will always iterate an empty directory regardless of the target.
660     fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> io::Result<bool> {
661         let class =
662             if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
663
664         unsafe {
665             let result = cvt(c::GetFileInformationByHandleEx(
666                 self.handle.as_raw_handle(),
667                 class,
668                 buffer.as_mut_ptr().cast(),
669                 buffer.capacity() as _,
670             ));
671             match result {
672                 Ok(_) => Ok(true),
673                 Err(e) if e.raw_os_error() == Some(c::ERROR_NO_MORE_FILES as _) => Ok(false),
674                 Err(e) => Err(e),
675             }
676         }
677     }
678 }
679
680 /// A buffer for holding directory entries.
681 struct DirBuff {
682     buffer: Box<Align8<[MaybeUninit<u8>; Self::BUFFER_SIZE]>>,
683 }
684 impl DirBuff {
685     const BUFFER_SIZE: usize = 1024;
686     fn new() -> Self {
687         Self {
688             // Safety: `Align8<[MaybeUninit<u8>; N]>` does not need
689             // initialization.
690             buffer: unsafe { Box::new_uninit().assume_init() },
691         }
692     }
693     fn capacity(&self) -> usize {
694         self.buffer.0.len()
695     }
696     fn as_mut_ptr(&mut self) -> *mut u8 {
697         self.buffer.0.as_mut_ptr().cast()
698     }
699     /// Returns a `DirBuffIter`.
700     fn iter(&self) -> DirBuffIter<'_> {
701         DirBuffIter::new(self)
702     }
703 }
704 impl AsRef<[MaybeUninit<u8>]> for DirBuff {
705     fn as_ref(&self) -> &[MaybeUninit<u8>] {
706         &self.buffer.0
707     }
708 }
709
710 /// An iterator over entries stored in a `DirBuff`.
711 ///
712 /// Currently only returns file names (UTF-16 encoded).
713 struct DirBuffIter<'a> {
714     buffer: Option<&'a [MaybeUninit<u8>]>,
715     cursor: usize,
716 }
717 impl<'a> DirBuffIter<'a> {
718     fn new(buffer: &'a DirBuff) -> Self {
719         Self { buffer: Some(buffer.as_ref()), cursor: 0 }
720     }
721 }
722 impl<'a> Iterator for DirBuffIter<'a> {
723     type Item = (Cow<'a, [u16]>, bool);
724     fn next(&mut self) -> Option<Self::Item> {
725         use crate::mem::size_of;
726         let buffer = &self.buffer?[self.cursor..];
727
728         // Get the name and next entry from the buffer.
729         // SAFETY:
730         // - The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the last
731         //   field (the file name) is unsized. So an offset has to be used to
732         //   get the file name slice.
733         // - The OS has guaranteed initialization of the fields of
734         //   `FILE_ID_BOTH_DIR_INFO` and the trailing filename (for at least
735         //   `FileNameLength` bytes)
736         let (name, is_directory, next_entry) = unsafe {
737             let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
738             // While this is guaranteed to be aligned in documentation for
739             // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_both_dir_info
740             // it does not seem that reality is so kind, and assuming this
741             // caused crashes in some cases (https://github.com/rust-lang/rust/issues/104530)
742             // presumably, this can be blamed on buggy filesystem drivers, but who knows.
743             let next_entry = ptr::addr_of!((*info).NextEntryOffset).read_unaligned() as usize;
744             let length = ptr::addr_of!((*info).FileNameLength).read_unaligned() as usize;
745             let attrs = ptr::addr_of!((*info).FileAttributes).read_unaligned();
746             let name = from_maybe_unaligned(
747                 ptr::addr_of!((*info).FileName).cast::<u16>(),
748                 length / size_of::<u16>(),
749             );
750             let is_directory = (attrs & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
751
752             (name, is_directory, next_entry)
753         };
754
755         if next_entry == 0 {
756             self.buffer = None
757         } else {
758             self.cursor += next_entry
759         }
760
761         // Skip `.` and `..` pseudo entries.
762         const DOT: u16 = b'.' as u16;
763         match &name[..] {
764             [DOT] | [DOT, DOT] => self.next(),
765             _ => Some((name, is_directory)),
766         }
767     }
768 }
769
770 unsafe fn from_maybe_unaligned<'a>(p: *const u16, len: usize) -> Cow<'a, [u16]> {
771     if p.is_aligned() {
772         Cow::Borrowed(crate::slice::from_raw_parts(p, len))
773     } else {
774         Cow::Owned((0..len).map(|i| p.add(i).read_unaligned()).collect())
775     }
776 }
777
778 /// Open a link relative to the parent directory, ensure no symlinks are followed.
779 fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<File> {
780     // This is implemented using the lower level `NtCreateFile` function as
781     // unfortunately opening a file relative to a parent is not supported by
782     // win32 functions. It is however a fundamental feature of the NT kernel.
783     //
784     // See https://docs.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
785     unsafe {
786         let mut handle = ptr::null_mut();
787         let mut io_status = c::IO_STATUS_BLOCK::default();
788         let name_str = c::UNICODE_STRING::from_ref(name);
789         use crate::sync::atomic::{AtomicU32, Ordering};
790         // The `OBJ_DONT_REPARSE` attribute ensures that we haven't been
791         // tricked into following a symlink. However, it may not be available in
792         // earlier versions of Windows.
793         static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
794         let object = c::OBJECT_ATTRIBUTES {
795             ObjectName: &name_str,
796             RootDirectory: parent.as_raw_handle(),
797             Attributes: ATTRIBUTES.load(Ordering::Relaxed),
798             ..c::OBJECT_ATTRIBUTES::default()
799         };
800         let status = c::NtCreateFile(
801             &mut handle,
802             access,
803             &object,
804             &mut io_status,
805             crate::ptr::null_mut(),
806             0,
807             c::FILE_SHARE_DELETE | c::FILE_SHARE_READ | c::FILE_SHARE_WRITE,
808             c::FILE_OPEN,
809             // If `name` is a symlink then open the link rather than the target.
810             c::FILE_OPEN_REPARSE_POINT,
811             crate::ptr::null_mut(),
812             0,
813         );
814         // Convert an NTSTATUS to the more familiar Win32 error codes (aka "DosError")
815         if c::nt_success(status) {
816             Ok(File::from_raw_handle(handle))
817         } else if status == c::STATUS_DELETE_PENDING {
818             // We make a special exception for `STATUS_DELETE_PENDING` because
819             // otherwise this will be mapped to `ERROR_ACCESS_DENIED` which is
820             // very unhelpful.
821             Err(io::Error::from_raw_os_error(c::ERROR_DELETE_PENDING as _))
822         } else if status == c::STATUS_INVALID_PARAMETER
823             && ATTRIBUTES.load(Ordering::Relaxed) == c::OBJ_DONT_REPARSE
824         {
825             // Try without `OBJ_DONT_REPARSE`. See above.
826             ATTRIBUTES.store(0, Ordering::Relaxed);
827             open_link_no_reparse(parent, name, access)
828         } else {
829             Err(io::Error::from_raw_os_error(c::RtlNtStatusToDosError(status) as _))
830         }
831     }
832 }
833
834 impl AsInner<Handle> for File {
835     fn as_inner(&self) -> &Handle {
836         &self.handle
837     }
838 }
839
840 impl IntoInner<Handle> for File {
841     fn into_inner(self) -> Handle {
842         self.handle
843     }
844 }
845
846 impl FromInner<Handle> for File {
847     fn from_inner(handle: Handle) -> File {
848         File { handle }
849     }
850 }
851
852 impl AsHandle for File {
853     fn as_handle(&self) -> BorrowedHandle<'_> {
854         self.as_inner().as_handle()
855     }
856 }
857
858 impl AsRawHandle for File {
859     fn as_raw_handle(&self) -> RawHandle {
860         self.as_inner().as_raw_handle()
861     }
862 }
863
864 impl IntoRawHandle for File {
865     fn into_raw_handle(self) -> RawHandle {
866         self.into_inner().into_raw_handle()
867     }
868 }
869
870 impl FromRawHandle for File {
871     unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
872         Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
873     }
874 }
875
876 impl fmt::Debug for File {
877     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
878         // FIXME(#24570): add more info here (e.g., mode)
879         let mut b = f.debug_struct("File");
880         b.field("handle", &self.handle.as_raw_handle());
881         if let Ok(path) = get_path(&self) {
882             b.field("path", &path);
883         }
884         b.finish()
885     }
886 }
887
888 impl FileAttr {
889     pub fn size(&self) -> u64 {
890         self.file_size
891     }
892
893     pub fn perm(&self) -> FilePermissions {
894         FilePermissions { attrs: self.attributes }
895     }
896
897     pub fn attrs(&self) -> u32 {
898         self.attributes
899     }
900
901     pub fn file_type(&self) -> FileType {
902         FileType::new(self.attributes, self.reparse_tag)
903     }
904
905     pub fn modified(&self) -> io::Result<SystemTime> {
906         Ok(SystemTime::from(self.last_write_time))
907     }
908
909     pub fn accessed(&self) -> io::Result<SystemTime> {
910         Ok(SystemTime::from(self.last_access_time))
911     }
912
913     pub fn created(&self) -> io::Result<SystemTime> {
914         Ok(SystemTime::from(self.creation_time))
915     }
916
917     pub fn modified_u64(&self) -> u64 {
918         to_u64(&self.last_write_time)
919     }
920
921     pub fn accessed_u64(&self) -> u64 {
922         to_u64(&self.last_access_time)
923     }
924
925     pub fn created_u64(&self) -> u64 {
926         to_u64(&self.creation_time)
927     }
928
929     pub fn volume_serial_number(&self) -> Option<u32> {
930         self.volume_serial_number
931     }
932
933     pub fn number_of_links(&self) -> Option<u32> {
934         self.number_of_links
935     }
936
937     pub fn file_index(&self) -> Option<u64> {
938         self.file_index
939     }
940 }
941 impl From<c::WIN32_FIND_DATAW> for FileAttr {
942     fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
943         FileAttr {
944             attributes: wfd.dwFileAttributes,
945             creation_time: wfd.ftCreationTime,
946             last_access_time: wfd.ftLastAccessTime,
947             last_write_time: wfd.ftLastWriteTime,
948             file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
949             reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
950                 // reserved unless this is a reparse point
951                 wfd.dwReserved0
952             } else {
953                 0
954             },
955             volume_serial_number: None,
956             number_of_links: None,
957             file_index: None,
958         }
959     }
960 }
961
962 fn to_u64(ft: &c::FILETIME) -> u64 {
963     (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
964 }
965
966 impl FilePermissions {
967     pub fn readonly(&self) -> bool {
968         self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
969     }
970
971     pub fn set_readonly(&mut self, readonly: bool) {
972         if readonly {
973             self.attrs |= c::FILE_ATTRIBUTE_READONLY;
974         } else {
975             self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
976         }
977     }
978 }
979
980 impl FileTimes {
981     pub fn set_accessed(&mut self, t: SystemTime) {
982         self.accessed = Some(t.into_inner());
983     }
984
985     pub fn set_modified(&mut self, t: SystemTime) {
986         self.modified = Some(t.into_inner());
987     }
988 }
989
990 impl FileType {
991     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
992         FileType { attributes: attrs, reparse_tag }
993     }
994     pub fn is_dir(&self) -> bool {
995         !self.is_symlink() && self.is_directory()
996     }
997     pub fn is_file(&self) -> bool {
998         !self.is_symlink() && !self.is_directory()
999     }
1000     pub fn is_symlink(&self) -> bool {
1001         self.is_reparse_point() && self.is_reparse_tag_name_surrogate()
1002     }
1003     pub fn is_symlink_dir(&self) -> bool {
1004         self.is_symlink() && self.is_directory()
1005     }
1006     pub fn is_symlink_file(&self) -> bool {
1007         self.is_symlink() && !self.is_directory()
1008     }
1009     fn is_directory(&self) -> bool {
1010         self.attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
1011     }
1012     fn is_reparse_point(&self) -> bool {
1013         self.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0
1014     }
1015     fn is_reparse_tag_name_surrogate(&self) -> bool {
1016         self.reparse_tag & 0x20000000 != 0
1017     }
1018 }
1019
1020 impl DirBuilder {
1021     pub fn new() -> DirBuilder {
1022         DirBuilder
1023     }
1024
1025     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1026         let p = maybe_verbatim(p)?;
1027         cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
1028         Ok(())
1029     }
1030 }
1031
1032 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1033     let root = p.to_path_buf();
1034     let star = p.join("*");
1035     let path = maybe_verbatim(&star)?;
1036
1037     unsafe {
1038         let mut wfd = mem::zeroed();
1039         let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
1040         if find_handle != c::INVALID_HANDLE_VALUE {
1041             Ok(ReadDir {
1042                 handle: FindNextFileHandle(find_handle),
1043                 root: Arc::new(root),
1044                 first: Some(wfd),
1045             })
1046         } else {
1047             Err(Error::last_os_error())
1048         }
1049     }
1050 }
1051
1052 pub fn unlink(p: &Path) -> io::Result<()> {
1053     let p_u16s = maybe_verbatim(p)?;
1054     cvt(unsafe { c::DeleteFileW(p_u16s.as_ptr()) })?;
1055     Ok(())
1056 }
1057
1058 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1059     let old = maybe_verbatim(old)?;
1060     let new = maybe_verbatim(new)?;
1061     cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
1062     Ok(())
1063 }
1064
1065 pub fn rmdir(p: &Path) -> io::Result<()> {
1066     let p = maybe_verbatim(p)?;
1067     cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
1068     Ok(())
1069 }
1070
1071 /// Open a file or directory without following symlinks.
1072 fn open_link(path: &Path, access_mode: u32) -> io::Result<File> {
1073     let mut opts = OpenOptions::new();
1074     opts.access_mode(access_mode);
1075     // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
1076     // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
1077     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1078     File::open(path, &opts)
1079 }
1080
1081 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
1082     let file = open_link(path, c::DELETE | c::FILE_LIST_DIRECTORY)?;
1083
1084     // Test if the file is not a directory or a symlink to a directory.
1085     if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
1086         return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
1087     }
1088
1089     match remove_dir_all_iterative(&file, File::posix_delete) {
1090         Err(e) => {
1091             if let Some(code) = e.raw_os_error() {
1092                 match code as u32 {
1093                     // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
1094                     c::ERROR_NOT_SUPPORTED
1095                     | c::ERROR_INVALID_FUNCTION
1096                     | c::ERROR_INVALID_PARAMETER => {
1097                         remove_dir_all_iterative(&file, File::win32_delete)
1098                     }
1099                     _ => Err(e),
1100                 }
1101             } else {
1102                 Err(e)
1103             }
1104         }
1105         ok => ok,
1106     }
1107 }
1108
1109 fn remove_dir_all_iterative(f: &File, delete: fn(&File) -> io::Result<()>) -> io::Result<()> {
1110     // When deleting files we may loop this many times when certain error conditions occur.
1111     // This allows remove_dir_all to succeed when the error is temporary.
1112     const MAX_RETRIES: u32 = 10;
1113
1114     let mut buffer = DirBuff::new();
1115     let mut dirlist = vec![f.duplicate()?];
1116
1117     // FIXME: This is a hack so we can push to the dirlist vec after borrowing from it.
1118     fn copy_handle(f: &File) -> mem::ManuallyDrop<File> {
1119         unsafe { mem::ManuallyDrop::new(File::from_raw_handle(f.as_raw_handle())) }
1120     }
1121
1122     let mut restart = true;
1123     while let Some(dir) = dirlist.last() {
1124         let dir = copy_handle(dir);
1125
1126         // Fill the buffer and iterate the entries.
1127         let more_data = dir.fill_dir_buff(&mut buffer, restart)?;
1128         restart = false;
1129         for (name, is_directory) in buffer.iter() {
1130             if is_directory {
1131                 let child_dir = open_link_no_reparse(
1132                     &dir,
1133                     &name,
1134                     c::SYNCHRONIZE | c::DELETE | c::FILE_LIST_DIRECTORY,
1135                 )?;
1136                 dirlist.push(child_dir);
1137             } else {
1138                 for i in 1..=MAX_RETRIES {
1139                     let result = open_link_no_reparse(&dir, &name, c::SYNCHRONIZE | c::DELETE);
1140                     match result {
1141                         Ok(f) => delete(&f)?,
1142                         // Already deleted, so skip.
1143                         Err(e) if e.kind() == io::ErrorKind::NotFound => break,
1144                         // Retry a few times if the file is locked or a delete is already in progress.
1145                         Err(e)
1146                             if i < MAX_RETRIES
1147                                 && (e.raw_os_error() == Some(c::ERROR_DELETE_PENDING as _)
1148                                     || e.raw_os_error()
1149                                         == Some(c::ERROR_SHARING_VIOLATION as _)) => {}
1150                         // Otherwise return the error.
1151                         Err(e) => return Err(e),
1152                     }
1153                     thread::yield_now();
1154                 }
1155             }
1156         }
1157         // If there were no more files then delete the directory.
1158         if !more_data {
1159             if let Some(dir) = dirlist.pop() {
1160                 // Retry deleting a few times in case we need to wait for a file to be deleted.
1161                 for i in 1..=MAX_RETRIES {
1162                     let result = delete(&dir);
1163                     if let Err(e) = result {
1164                         if i == MAX_RETRIES || e.kind() != io::ErrorKind::DirectoryNotEmpty {
1165                             return Err(e);
1166                         }
1167                         thread::yield_now();
1168                     } else {
1169                         break;
1170                     }
1171                 }
1172             }
1173         }
1174     }
1175     Ok(())
1176 }
1177
1178 pub fn readlink(path: &Path) -> io::Result<PathBuf> {
1179     // Open the link with no access mode, instead of generic read.
1180     // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1181     // this is needed for a common case.
1182     let mut opts = OpenOptions::new();
1183     opts.access_mode(0);
1184     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1185     let file = File::open(&path, &opts)?;
1186     file.readlink()
1187 }
1188
1189 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1190     symlink_inner(original, link, false)
1191 }
1192
1193 pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1194     let original = to_u16s(original)?;
1195     let link = maybe_verbatim(link)?;
1196     let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1197     // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1198     // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1199     // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1200     // added to dwFlags to opt into this behaviour.
1201     let result = cvt(unsafe {
1202         c::CreateSymbolicLinkW(
1203             link.as_ptr(),
1204             original.as_ptr(),
1205             flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1206         ) as c::BOOL
1207     });
1208     if let Err(err) = result {
1209         if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1210             // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1211             // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1212             cvt(unsafe {
1213                 c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1214             })?;
1215         } else {
1216             return Err(err);
1217         }
1218     }
1219     Ok(())
1220 }
1221
1222 #[cfg(not(target_vendor = "uwp"))]
1223 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1224     let original = maybe_verbatim(original)?;
1225     let link = maybe_verbatim(link)?;
1226     cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1227     Ok(())
1228 }
1229
1230 #[cfg(target_vendor = "uwp")]
1231 pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
1232     return Err(io::const_io_error!(
1233         io::ErrorKind::Unsupported,
1234         "hard link are not supported on UWP",
1235     ));
1236 }
1237
1238 pub fn stat(path: &Path) -> io::Result<FileAttr> {
1239     metadata(path, ReparsePoint::Follow)
1240 }
1241
1242 pub fn lstat(path: &Path) -> io::Result<FileAttr> {
1243     metadata(path, ReparsePoint::Open)
1244 }
1245
1246 #[repr(u32)]
1247 #[derive(Clone, Copy, PartialEq, Eq)]
1248 enum ReparsePoint {
1249     Follow = 0,
1250     Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
1251 }
1252 impl ReparsePoint {
1253     fn as_flag(self) -> u32 {
1254         self as u32
1255     }
1256 }
1257
1258 fn metadata(path: &Path, reparse: ReparsePoint) -> io::Result<FileAttr> {
1259     let mut opts = OpenOptions::new();
1260     // No read or write permissions are necessary
1261     opts.access_mode(0);
1262     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());
1263
1264     // Attempt to open the file normally.
1265     // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileW`.
1266     // If the fallback fails for any reason we return the original error.
1267     match File::open(path, &opts) {
1268         Ok(file) => file.file_attr(),
1269         Err(e) if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {
1270             // `ERROR_SHARING_VIOLATION` will almost never be returned.
1271             // Usually if a file is locked you can still read some metadata.
1272             // However, there are special system files, such as
1273             // `C:\hiberfil.sys`, that are locked in a way that denies even that.
1274             unsafe {
1275                 let path = maybe_verbatim(path)?;
1276
1277                 // `FindFirstFileW` accepts wildcard file names.
1278                 // Fortunately wildcards are not valid file names and
1279                 // `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
1280                 // therefore it's safe to assume the file name given does not
1281                 // include wildcards.
1282                 let mut wfd = mem::zeroed();
1283                 let handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
1284
1285                 if handle == c::INVALID_HANDLE_VALUE {
1286                     // This can fail if the user does not have read access to the
1287                     // directory.
1288                     Err(e)
1289                 } else {
1290                     // We no longer need the find handle.
1291                     c::FindClose(handle);
1292
1293                     // `FindFirstFileW` reads the cached file information from the
1294                     // directory. The downside is that this metadata may be outdated.
1295                     let attrs = FileAttr::from(wfd);
1296                     if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
1297                         Err(e)
1298                     } else {
1299                         Ok(attrs)
1300                     }
1301                 }
1302             }
1303         }
1304         Err(e) => Err(e),
1305     }
1306 }
1307
1308 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1309     let p = maybe_verbatim(p)?;
1310     unsafe {
1311         cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1312         Ok(())
1313     }
1314 }
1315
1316 fn get_path(f: &File) -> io::Result<PathBuf> {
1317     super::fill_utf16_buf(
1318         |buf, sz| unsafe {
1319             c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1320         },
1321         |buf| PathBuf::from(OsString::from_wide(buf)),
1322     )
1323 }
1324
1325 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1326     let mut opts = OpenOptions::new();
1327     // No read or write permissions are necessary
1328     opts.access_mode(0);
1329     // This flag is so we can open directories too
1330     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1331     let f = File::open(p, &opts)?;
1332     get_path(&f)
1333 }
1334
1335 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1336     unsafe extern "system" fn callback(
1337         _TotalFileSize: c::LARGE_INTEGER,
1338         _TotalBytesTransferred: c::LARGE_INTEGER,
1339         _StreamSize: c::LARGE_INTEGER,
1340         StreamBytesTransferred: c::LARGE_INTEGER,
1341         dwStreamNumber: c::DWORD,
1342         _dwCallbackReason: c::DWORD,
1343         _hSourceFile: c::HANDLE,
1344         _hDestinationFile: c::HANDLE,
1345         lpData: c::LPVOID,
1346     ) -> c::DWORD {
1347         if dwStreamNumber == 1 {
1348             *(lpData as *mut i64) = StreamBytesTransferred;
1349         }
1350         c::PROGRESS_CONTINUE
1351     }
1352     let pfrom = maybe_verbatim(from)?;
1353     let pto = maybe_verbatim(to)?;
1354     let mut size = 0i64;
1355     cvt(unsafe {
1356         c::CopyFileExW(
1357             pfrom.as_ptr(),
1358             pto.as_ptr(),
1359             Some(callback),
1360             &mut size as *mut _ as *mut _,
1361             ptr::null_mut(),
1362             0,
1363         )
1364     })?;
1365     Ok(size as u64)
1366 }
1367
1368 #[allow(dead_code)]
1369 pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
1370     original: P,
1371     junction: Q,
1372 ) -> io::Result<()> {
1373     symlink_junction_inner(original.as_ref(), junction.as_ref())
1374 }
1375
1376 // Creating a directory junction on windows involves dealing with reparse
1377 // points and the DeviceIoControl function, and this code is a skeleton of
1378 // what can be found here:
1379 //
1380 // http://www.flexhex.com/docs/articles/hard-links.phtml
1381 #[allow(dead_code)]
1382 fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
1383     let d = DirBuilder::new();
1384     d.mkdir(&junction)?;
1385
1386     let mut opts = OpenOptions::new();
1387     opts.write(true);
1388     opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1389     let f = File::open(junction, &opts)?;
1390     let h = f.as_inner().as_raw_handle();
1391
1392     unsafe {
1393         let mut data = Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
1394         let data_ptr = data.0.as_mut_ptr();
1395         let db = data_ptr.cast::<c::REPARSE_MOUNTPOINT_DATA_BUFFER>();
1396         let buf = ptr::addr_of_mut!((*db).ReparseTarget).cast::<c::WCHAR>();
1397         let mut i = 0;
1398         // FIXME: this conversion is very hacky
1399         let v = br"\??\";
1400         let v = v.iter().map(|x| *x as u16);
1401         for c in v.chain(original.as_os_str().encode_wide()) {
1402             *buf.add(i) = c;
1403             i += 1;
1404         }
1405         *buf.add(i) = 0;
1406         i += 1;
1407         (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
1408         (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
1409         (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
1410         (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
1411
1412         let mut ret = 0;
1413         cvt(c::DeviceIoControl(
1414             h as *mut _,
1415             c::FSCTL_SET_REPARSE_POINT,
1416             data_ptr.cast(),
1417             (*db).ReparseDataLength + 8,
1418             ptr::null_mut(),
1419             0,
1420             &mut ret,
1421             ptr::null_mut(),
1422         ))
1423         .map(drop)
1424     }
1425 }
1426
1427 // Try to see if a file exists but, unlike `exists`, report I/O errors.
1428 pub fn try_exists(path: &Path) -> io::Result<bool> {
1429     // Open the file to ensure any symlinks are followed to their target.
1430     let mut opts = OpenOptions::new();
1431     // No read, write, etc access rights are needed.
1432     opts.access_mode(0);
1433     // Backup semantics enables opening directories as well as files.
1434     opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1435     match File::open(path, &opts) {
1436         Err(e) => match e.kind() {
1437             // The file definitely does not exist
1438             io::ErrorKind::NotFound => Ok(false),
1439
1440             // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1441             // another process. This is often temporary so we simply report it
1442             // as the file existing.
1443             _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1444
1445             // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1446             // file exists. However, these types of errors are usually more
1447             // permanent so we report them here.
1448             _ => Err(e),
1449         },
1450         // The file was opened successfully therefore it must exist,
1451         Ok(_) => Ok(true),
1452     }
1453 }