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