std\sys\fs/
windows.rs

1#![allow(nonstandard_style)]
2
3use crate::alloc::{Layout, alloc, dealloc};
4use crate::borrow::Cow;
5use crate::ffi::{OsStr, OsString, c_void};
6use crate::fs::TryLockError;
7use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
8use crate::mem::{self, MaybeUninit, offset_of};
9use crate::os::windows::io::{AsHandle, BorrowedHandle};
10use crate::os::windows::prelude::*;
11use crate::path::{Path, PathBuf};
12use crate::sync::Arc;
13use crate::sys::handle::Handle;
14use crate::sys::pal::api::{self, WinError, set_file_information_by_handle};
15use crate::sys::pal::{IoResult, fill_utf16_buf, to_u16s, truncate_utf16_at_nul};
16use crate::sys::path::{WCStr, maybe_verbatim};
17use crate::sys::time::SystemTime;
18use crate::sys::{Align8, c, cvt};
19use crate::sys_common::{AsInner, FromInner, IntoInner};
20use crate::{fmt, ptr, slice};
21
22mod remove_dir_all;
23use remove_dir_all::remove_dir_all_iterative;
24
25pub struct File {
26    handle: Handle,
27}
28
29#[derive(Clone)]
30pub struct FileAttr {
31    attributes: u32,
32    creation_time: c::FILETIME,
33    last_access_time: c::FILETIME,
34    last_write_time: c::FILETIME,
35    change_time: Option<c::FILETIME>,
36    file_size: u64,
37    reparse_tag: u32,
38    volume_serial_number: Option<u32>,
39    number_of_links: Option<u32>,
40    file_index: Option<u64>,
41}
42
43#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
44pub struct FileType {
45    is_directory: bool,
46    is_symlink: bool,
47}
48
49pub struct ReadDir {
50    handle: Option<FindNextFileHandle>,
51    root: Arc<PathBuf>,
52    first: Option<c::WIN32_FIND_DATAW>,
53}
54
55struct FindNextFileHandle(c::HANDLE);
56
57unsafe impl Send for FindNextFileHandle {}
58unsafe impl Sync for FindNextFileHandle {}
59
60pub struct DirEntry {
61    root: Arc<PathBuf>,
62    data: c::WIN32_FIND_DATAW,
63}
64
65unsafe impl Send for OpenOptions {}
66unsafe impl Sync for OpenOptions {}
67
68#[derive(Clone, Debug)]
69pub struct OpenOptions {
70    // generic
71    read: bool,
72    write: bool,
73    append: bool,
74    truncate: bool,
75    create: bool,
76    create_new: bool,
77    // system-specific
78    custom_flags: u32,
79    access_mode: Option<u32>,
80    attributes: u32,
81    share_mode: u32,
82    security_qos_flags: u32,
83    security_attributes: *mut c::SECURITY_ATTRIBUTES,
84}
85
86#[derive(Clone, PartialEq, Eq, Debug)]
87pub struct FilePermissions {
88    attrs: u32,
89}
90
91#[derive(Copy, Clone, Debug, Default)]
92pub struct FileTimes {
93    accessed: Option<c::FILETIME>,
94    modified: Option<c::FILETIME>,
95    created: Option<c::FILETIME>,
96}
97
98impl fmt::Debug for c::FILETIME {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        let time = ((self.dwHighDateTime as u64) << 32) | self.dwLowDateTime as u64;
101        f.debug_tuple("FILETIME").field(&time).finish()
102    }
103}
104
105#[derive(Debug)]
106pub struct DirBuilder;
107
108impl fmt::Debug for ReadDir {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
111        // Thus the result will be e g 'ReadDir("C:\")'
112        fmt::Debug::fmt(&*self.root, f)
113    }
114}
115
116impl Iterator for ReadDir {
117    type Item = io::Result<DirEntry>;
118    fn next(&mut self) -> Option<io::Result<DirEntry>> {
119        let Some(handle) = self.handle.as_ref() else {
120            // This iterator was initialized with an `INVALID_HANDLE_VALUE` as its handle.
121            // Simply return `None` because this is only the case when `FindFirstFileExW` in
122            // the construction of this iterator returns `ERROR_FILE_NOT_FOUND` which means
123            // no matchhing files can be found.
124            return None;
125        };
126        if let Some(first) = self.first.take() {
127            if let Some(e) = DirEntry::new(&self.root, &first) {
128                return Some(Ok(e));
129            }
130        }
131        unsafe {
132            let mut wfd = mem::zeroed();
133            loop {
134                if c::FindNextFileW(handle.0, &mut wfd) == 0 {
135                    match api::get_last_error() {
136                        WinError::NO_MORE_FILES => return None,
137                        WinError { code } => {
138                            return Some(Err(Error::from_raw_os_error(code as i32)));
139                        }
140                    }
141                }
142                if let Some(e) = DirEntry::new(&self.root, &wfd) {
143                    return Some(Ok(e));
144                }
145            }
146        }
147    }
148}
149
150impl Drop for FindNextFileHandle {
151    fn drop(&mut self) {
152        let r = unsafe { c::FindClose(self.0) };
153        debug_assert!(r != 0);
154    }
155}
156
157impl DirEntry {
158    fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
159        match &wfd.cFileName[0..3] {
160            // check for '.' and '..'
161            &[46, 0, ..] | &[46, 46, 0, ..] => return None,
162            _ => {}
163        }
164
165        Some(DirEntry { root: root.clone(), data: *wfd })
166    }
167
168    pub fn path(&self) -> PathBuf {
169        self.root.join(self.file_name())
170    }
171
172    pub fn file_name(&self) -> OsString {
173        let filename = truncate_utf16_at_nul(&self.data.cFileName);
174        OsString::from_wide(filename)
175    }
176
177    pub fn file_type(&self) -> io::Result<FileType> {
178        Ok(FileType::new(
179            self.data.dwFileAttributes,
180            /* reparse_tag = */ self.data.dwReserved0,
181        ))
182    }
183
184    pub fn metadata(&self) -> io::Result<FileAttr> {
185        Ok(self.data.into())
186    }
187}
188
189impl OpenOptions {
190    pub fn new() -> OpenOptions {
191        OpenOptions {
192            // generic
193            read: false,
194            write: false,
195            append: false,
196            truncate: false,
197            create: false,
198            create_new: false,
199            // system-specific
200            custom_flags: 0,
201            access_mode: None,
202            share_mode: c::FILE_SHARE_READ | c::FILE_SHARE_WRITE | c::FILE_SHARE_DELETE,
203            attributes: 0,
204            security_qos_flags: 0,
205            security_attributes: ptr::null_mut(),
206        }
207    }
208
209    pub fn read(&mut self, read: bool) {
210        self.read = read;
211    }
212    pub fn write(&mut self, write: bool) {
213        self.write = write;
214    }
215    pub fn append(&mut self, append: bool) {
216        self.append = append;
217    }
218    pub fn truncate(&mut self, truncate: bool) {
219        self.truncate = truncate;
220    }
221    pub fn create(&mut self, create: bool) {
222        self.create = create;
223    }
224    pub fn create_new(&mut self, create_new: bool) {
225        self.create_new = create_new;
226    }
227
228    pub fn custom_flags(&mut self, flags: u32) {
229        self.custom_flags = flags;
230    }
231    pub fn access_mode(&mut self, access_mode: u32) {
232        self.access_mode = Some(access_mode);
233    }
234    pub fn share_mode(&mut self, share_mode: u32) {
235        self.share_mode = share_mode;
236    }
237    pub fn attributes(&mut self, attrs: u32) {
238        self.attributes = attrs;
239    }
240    pub fn security_qos_flags(&mut self, flags: u32) {
241        // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
242        // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
243        self.security_qos_flags = flags | c::SECURITY_SQOS_PRESENT;
244    }
245    pub fn security_attributes(&mut self, attrs: *mut c::SECURITY_ATTRIBUTES) {
246        self.security_attributes = attrs;
247    }
248
249    fn get_access_mode(&self) -> io::Result<u32> {
250        match (self.read, self.write, self.append, self.access_mode) {
251            (.., Some(mode)) => Ok(mode),
252            (true, false, false, None) => Ok(c::GENERIC_READ),
253            (false, true, false, None) => Ok(c::GENERIC_WRITE),
254            (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
255            (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
256            (true, _, true, None) => {
257                Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
258            }
259            (false, false, false, None) => {
260                Err(Error::from_raw_os_error(c::ERROR_INVALID_PARAMETER as i32))
261            }
262        }
263    }
264
265    fn get_creation_mode(&self) -> io::Result<u32> {
266        match (self.write, self.append) {
267            (true, false) => {}
268            (false, false) => {
269                if self.truncate || self.create || self.create_new {
270                    return Err(Error::from_raw_os_error(c::ERROR_INVALID_PARAMETER as i32));
271                }
272            }
273            (_, true) => {
274                if self.truncate && !self.create_new {
275                    return Err(Error::from_raw_os_error(c::ERROR_INVALID_PARAMETER as i32));
276                }
277            }
278        }
279
280        Ok(match (self.create, self.truncate, self.create_new) {
281            (false, false, false) => c::OPEN_EXISTING,
282            (true, false, false) => c::OPEN_ALWAYS,
283            (false, true, false) => c::TRUNCATE_EXISTING,
284            // `CREATE_ALWAYS` has weird semantics so we emulate it using
285            // `OPEN_ALWAYS` and a manual truncation step. See #115745.
286            (true, true, false) => c::OPEN_ALWAYS,
287            (_, _, true) => c::CREATE_NEW,
288        })
289    }
290
291    fn get_flags_and_attributes(&self) -> u32 {
292        self.custom_flags
293            | self.attributes
294            | self.security_qos_flags
295            | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
296    }
297}
298
299impl File {
300    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
301        let path = maybe_verbatim(path)?;
302        // SAFETY: maybe_verbatim returns null-terminated strings
303        let path = unsafe { WCStr::from_wchars_with_null_unchecked(&path) };
304        Self::open_native(&path, opts)
305    }
306
307    fn open_native(path: &WCStr, opts: &OpenOptions) -> io::Result<File> {
308        let creation = opts.get_creation_mode()?;
309        let handle = unsafe {
310            c::CreateFileW(
311                path.as_ptr(),
312                opts.get_access_mode()?,
313                opts.share_mode,
314                opts.security_attributes,
315                creation,
316                opts.get_flags_and_attributes(),
317                ptr::null_mut(),
318            )
319        };
320        let handle = unsafe { HandleOrInvalid::from_raw_handle(handle) };
321        if let Ok(handle) = OwnedHandle::try_from(handle) {
322            // Manual truncation. See #115745.
323            if opts.truncate
324                && creation == c::OPEN_ALWAYS
325                && api::get_last_error() == WinError::ALREADY_EXISTS
326            {
327                // This first tries `FileAllocationInfo` but falls back to
328                // `FileEndOfFileInfo` in order to support WINE.
329                // If WINE gains support for FileAllocationInfo, we should
330                // remove the fallback.
331                let alloc = c::FILE_ALLOCATION_INFO { AllocationSize: 0 };
332                set_file_information_by_handle(handle.as_raw_handle(), &alloc)
333                    .or_else(|_| {
334                        let eof = c::FILE_END_OF_FILE_INFO { EndOfFile: 0 };
335                        set_file_information_by_handle(handle.as_raw_handle(), &eof)
336                    })
337                    .io_result()?;
338            }
339            Ok(File { handle: Handle::from_inner(handle) })
340        } else {
341            Err(Error::last_os_error())
342        }
343    }
344
345    pub fn fsync(&self) -> io::Result<()> {
346        cvt(unsafe { c::FlushFileBuffers(self.handle.as_raw_handle()) })?;
347        Ok(())
348    }
349
350    pub fn datasync(&self) -> io::Result<()> {
351        self.fsync()
352    }
353
354    fn acquire_lock(&self, flags: c::LOCK_FILE_FLAGS) -> io::Result<()> {
355        unsafe {
356            let mut overlapped: c::OVERLAPPED = mem::zeroed();
357            let event = c::CreateEventW(ptr::null_mut(), c::FALSE, c::FALSE, ptr::null());
358            if event.is_null() {
359                return Err(io::Error::last_os_error());
360            }
361            overlapped.hEvent = event;
362            let lock_result = cvt(c::LockFileEx(
363                self.handle.as_raw_handle(),
364                flags,
365                0,
366                u32::MAX,
367                u32::MAX,
368                &mut overlapped,
369            ));
370
371            let final_result = match lock_result {
372                Ok(_) => Ok(()),
373                Err(err) => {
374                    if err.raw_os_error() == Some(c::ERROR_IO_PENDING as i32) {
375                        // Wait for the lock to be acquired, and get the lock operation status.
376                        // This can happen asynchronously, if the file handle was opened for async IO
377                        let mut bytes_transferred = 0;
378                        cvt(c::GetOverlappedResult(
379                            self.handle.as_raw_handle(),
380                            &mut overlapped,
381                            &mut bytes_transferred,
382                            c::TRUE,
383                        ))
384                        .map(|_| ())
385                    } else {
386                        Err(err)
387                    }
388                }
389            };
390            c::CloseHandle(overlapped.hEvent);
391            final_result
392        }
393    }
394
395    pub fn lock(&self) -> io::Result<()> {
396        self.acquire_lock(c::LOCKFILE_EXCLUSIVE_LOCK)
397    }
398
399    pub fn lock_shared(&self) -> io::Result<()> {
400        self.acquire_lock(0)
401    }
402
403    pub fn try_lock(&self) -> Result<(), TryLockError> {
404        let result = cvt(unsafe {
405            let mut overlapped = mem::zeroed();
406            c::LockFileEx(
407                self.handle.as_raw_handle(),
408                c::LOCKFILE_EXCLUSIVE_LOCK | c::LOCKFILE_FAIL_IMMEDIATELY,
409                0,
410                u32::MAX,
411                u32::MAX,
412                &mut overlapped,
413            )
414        });
415
416        match result {
417            Ok(_) => Ok(()),
418            Err(err) if err.raw_os_error() == Some(c::ERROR_LOCK_VIOLATION as i32) => {
419                Err(TryLockError::WouldBlock)
420            }
421            Err(err) => Err(TryLockError::Error(err)),
422        }
423    }
424
425    pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
426        let result = cvt(unsafe {
427            let mut overlapped = mem::zeroed();
428            c::LockFileEx(
429                self.handle.as_raw_handle(),
430                c::LOCKFILE_FAIL_IMMEDIATELY,
431                0,
432                u32::MAX,
433                u32::MAX,
434                &mut overlapped,
435            )
436        });
437
438        match result {
439            Ok(_) => Ok(()),
440            Err(err) if err.raw_os_error() == Some(c::ERROR_LOCK_VIOLATION as i32) => {
441                Err(TryLockError::WouldBlock)
442            }
443            Err(err) => Err(TryLockError::Error(err)),
444        }
445    }
446
447    pub fn unlock(&self) -> io::Result<()> {
448        // Unlock the handle twice because LockFileEx() allows a file handle to acquire
449        // both an exclusive and shared lock, in which case the documentation states that:
450        // "...two unlock operations are necessary to unlock the region; the first unlock operation
451        // unlocks the exclusive lock, the second unlock operation unlocks the shared lock"
452        cvt(unsafe { c::UnlockFile(self.handle.as_raw_handle(), 0, 0, u32::MAX, u32::MAX) })?;
453        let result =
454            cvt(unsafe { c::UnlockFile(self.handle.as_raw_handle(), 0, 0, u32::MAX, u32::MAX) });
455        match result {
456            Ok(_) => Ok(()),
457            Err(err) if err.raw_os_error() == Some(c::ERROR_NOT_LOCKED as i32) => Ok(()),
458            Err(err) => Err(err),
459        }
460    }
461
462    pub fn truncate(&self, size: u64) -> io::Result<()> {
463        let info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as i64 };
464        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info).io_result()
465    }
466
467    #[cfg(not(target_vendor = "uwp"))]
468    pub fn file_attr(&self) -> io::Result<FileAttr> {
469        unsafe {
470            let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
471            cvt(c::GetFileInformationByHandle(self.handle.as_raw_handle(), &mut info))?;
472            let mut reparse_tag = 0;
473            if info.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
474                let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
475                cvt(c::GetFileInformationByHandleEx(
476                    self.handle.as_raw_handle(),
477                    c::FileAttributeTagInfo,
478                    (&raw mut attr_tag).cast(),
479                    size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
480                ))?;
481                if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
482                    reparse_tag = attr_tag.ReparseTag;
483                }
484            }
485            Ok(FileAttr {
486                attributes: info.dwFileAttributes,
487                creation_time: info.ftCreationTime,
488                last_access_time: info.ftLastAccessTime,
489                last_write_time: info.ftLastWriteTime,
490                change_time: None, // Only available in FILE_BASIC_INFO
491                file_size: (info.nFileSizeLow as u64) | ((info.nFileSizeHigh as u64) << 32),
492                reparse_tag,
493                volume_serial_number: Some(info.dwVolumeSerialNumber),
494                number_of_links: Some(info.nNumberOfLinks),
495                file_index: Some(
496                    (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
497                ),
498            })
499        }
500    }
501
502    #[cfg(target_vendor = "uwp")]
503    pub fn file_attr(&self) -> io::Result<FileAttr> {
504        unsafe {
505            let mut info: c::FILE_BASIC_INFO = mem::zeroed();
506            let size = size_of_val(&info);
507            cvt(c::GetFileInformationByHandleEx(
508                self.handle.as_raw_handle(),
509                c::FileBasicInfo,
510                (&raw mut info) as *mut c_void,
511                size as u32,
512            ))?;
513            let mut attr = FileAttr {
514                attributes: info.FileAttributes,
515                creation_time: c::FILETIME {
516                    dwLowDateTime: info.CreationTime as u32,
517                    dwHighDateTime: (info.CreationTime >> 32) as u32,
518                },
519                last_access_time: c::FILETIME {
520                    dwLowDateTime: info.LastAccessTime as u32,
521                    dwHighDateTime: (info.LastAccessTime >> 32) as u32,
522                },
523                last_write_time: c::FILETIME {
524                    dwLowDateTime: info.LastWriteTime as u32,
525                    dwHighDateTime: (info.LastWriteTime >> 32) as u32,
526                },
527                change_time: Some(c::FILETIME {
528                    dwLowDateTime: info.ChangeTime as u32,
529                    dwHighDateTime: (info.ChangeTime >> 32) as u32,
530                }),
531                file_size: 0,
532                reparse_tag: 0,
533                volume_serial_number: None,
534                number_of_links: None,
535                file_index: None,
536            };
537            let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
538            let size = size_of_val(&info);
539            cvt(c::GetFileInformationByHandleEx(
540                self.handle.as_raw_handle(),
541                c::FileStandardInfo,
542                (&raw mut info) as *mut c_void,
543                size as u32,
544            ))?;
545            attr.file_size = info.AllocationSize as u64;
546            attr.number_of_links = Some(info.NumberOfLinks);
547            if attr.attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
548                let mut attr_tag: c::FILE_ATTRIBUTE_TAG_INFO = mem::zeroed();
549                cvt(c::GetFileInformationByHandleEx(
550                    self.handle.as_raw_handle(),
551                    c::FileAttributeTagInfo,
552                    (&raw mut attr_tag).cast(),
553                    size_of::<c::FILE_ATTRIBUTE_TAG_INFO>().try_into().unwrap(),
554                ))?;
555                if attr_tag.FileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
556                    attr.reparse_tag = attr_tag.ReparseTag;
557                }
558            }
559            Ok(attr)
560        }
561    }
562
563    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
564        self.handle.read(buf)
565    }
566
567    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
568        self.handle.read_vectored(bufs)
569    }
570
571    #[inline]
572    pub fn is_read_vectored(&self) -> bool {
573        self.handle.is_read_vectored()
574    }
575
576    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
577        self.handle.read_at(buf, offset)
578    }
579
580    pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
581        self.handle.read_buf(cursor)
582    }
583
584    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
585        self.handle.write(buf)
586    }
587
588    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
589        self.handle.write_vectored(bufs)
590    }
591
592    #[inline]
593    pub fn is_write_vectored(&self) -> bool {
594        self.handle.is_write_vectored()
595    }
596
597    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
598        self.handle.write_at(buf, offset)
599    }
600
601    pub fn flush(&self) -> io::Result<()> {
602        Ok(())
603    }
604
605    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
606        let (whence, pos) = match pos {
607            // Casting to `i64` is fine, `SetFilePointerEx` reinterprets this
608            // integer as `u64`.
609            SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64),
610            SeekFrom::End(n) => (c::FILE_END, n),
611            SeekFrom::Current(n) => (c::FILE_CURRENT, n),
612        };
613        let pos = pos as i64;
614        let mut newpos = 0;
615        cvt(unsafe { c::SetFilePointerEx(self.handle.as_raw_handle(), pos, &mut newpos, whence) })?;
616        Ok(newpos as u64)
617    }
618
619    pub fn size(&self) -> Option<io::Result<u64>> {
620        let mut result = 0;
621        Some(
622            cvt(unsafe { c::GetFileSizeEx(self.handle.as_raw_handle(), &mut result) })
623                .map(|_| result as u64),
624        )
625    }
626
627    pub fn tell(&self) -> io::Result<u64> {
628        self.seek(SeekFrom::Current(0))
629    }
630
631    pub fn duplicate(&self) -> io::Result<File> {
632        Ok(Self { handle: self.handle.try_clone()? })
633    }
634
635    // NB: returned pointer is derived from `space`, and has provenance to
636    // match. A raw pointer is returned rather than a reference in order to
637    // avoid narrowing provenance to the actual `REPARSE_DATA_BUFFER`.
638    fn reparse_point(
639        &self,
640        space: &mut Align8<[MaybeUninit<u8>]>,
641    ) -> io::Result<(u32, *mut c::REPARSE_DATA_BUFFER)> {
642        unsafe {
643            let mut bytes = 0;
644            cvt({
645                // Grab this in advance to avoid it invalidating the pointer
646                // we get from `space.0.as_mut_ptr()`.
647                let len = space.0.len();
648                c::DeviceIoControl(
649                    self.handle.as_raw_handle(),
650                    c::FSCTL_GET_REPARSE_POINT,
651                    ptr::null_mut(),
652                    0,
653                    space.0.as_mut_ptr().cast(),
654                    len as u32,
655                    &mut bytes,
656                    ptr::null_mut(),
657                )
658            })?;
659            const _: () = assert!(align_of::<c::REPARSE_DATA_BUFFER>() <= 8);
660            Ok((bytes, space.0.as_mut_ptr().cast::<c::REPARSE_DATA_BUFFER>()))
661        }
662    }
663
664    fn readlink(&self) -> io::Result<PathBuf> {
665        let mut space =
666            Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize]);
667        let (_bytes, buf) = self.reparse_point(&mut space)?;
668        unsafe {
669            let (path_buffer, subst_off, subst_len, relative) = match (*buf).ReparseTag {
670                c::IO_REPARSE_TAG_SYMLINK => {
671                    let info: *mut c::SYMBOLIC_LINK_REPARSE_BUFFER = (&raw mut (*buf).rest).cast();
672                    assert!(info.is_aligned());
673                    (
674                        (&raw mut (*info).PathBuffer).cast::<u16>(),
675                        (*info).SubstituteNameOffset / 2,
676                        (*info).SubstituteNameLength / 2,
677                        (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
678                    )
679                }
680                c::IO_REPARSE_TAG_MOUNT_POINT => {
681                    let info: *mut c::MOUNT_POINT_REPARSE_BUFFER = (&raw mut (*buf).rest).cast();
682                    assert!(info.is_aligned());
683                    (
684                        (&raw mut (*info).PathBuffer).cast::<u16>(),
685                        (*info).SubstituteNameOffset / 2,
686                        (*info).SubstituteNameLength / 2,
687                        false,
688                    )
689                }
690                _ => {
691                    return Err(io::const_error!(
692                        io::ErrorKind::Uncategorized,
693                        "Unsupported reparse point type",
694                    ));
695                }
696            };
697            let subst_ptr = path_buffer.add(subst_off.into());
698            let subst = slice::from_raw_parts_mut(subst_ptr, subst_len as usize);
699            // Absolute paths start with an NT internal namespace prefix `\??\`
700            // We should not let it leak through.
701            if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
702                // Turn `\??\` into `\\?\` (a verbatim path).
703                subst[1] = b'\\' as u16;
704                // Attempt to convert to a more user-friendly path.
705                let user = crate::sys::args::from_wide_to_user_path(
706                    subst.iter().copied().chain([0]).collect(),
707                )?;
708                Ok(PathBuf::from(OsString::from_wide(user.strip_suffix(&[0]).unwrap_or(&user))))
709            } else {
710                Ok(PathBuf::from(OsString::from_wide(subst)))
711            }
712        }
713    }
714
715    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
716        let info = c::FILE_BASIC_INFO {
717            CreationTime: 0,
718            LastAccessTime: 0,
719            LastWriteTime: 0,
720            ChangeTime: 0,
721            FileAttributes: perm.attrs,
722        };
723        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info).io_result()
724    }
725
726    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
727        let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0;
728        if times.accessed.map_or(false, is_zero)
729            || times.modified.map_or(false, is_zero)
730            || times.created.map_or(false, is_zero)
731        {
732            return Err(io::const_error!(
733                io::ErrorKind::InvalidInput,
734                "cannot set file timestamp to 0",
735            ));
736        }
737        let is_max = |t: c::FILETIME| t.dwLowDateTime == u32::MAX && t.dwHighDateTime == u32::MAX;
738        if times.accessed.map_or(false, is_max)
739            || times.modified.map_or(false, is_max)
740            || times.created.map_or(false, is_max)
741        {
742            return Err(io::const_error!(
743                io::ErrorKind::InvalidInput,
744                "cannot set file timestamp to 0xFFFF_FFFF_FFFF_FFFF",
745            ));
746        }
747        cvt(unsafe {
748            let created =
749                times.created.as_ref().map(|a| a as *const c::FILETIME).unwrap_or(ptr::null());
750            let accessed =
751                times.accessed.as_ref().map(|a| a as *const c::FILETIME).unwrap_or(ptr::null());
752            let modified =
753                times.modified.as_ref().map(|a| a as *const c::FILETIME).unwrap_or(ptr::null());
754            c::SetFileTime(self.as_raw_handle(), created, accessed, modified)
755        })?;
756        Ok(())
757    }
758
759    /// Gets only basic file information such as attributes and file times.
760    fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
761        unsafe {
762            let mut info: c::FILE_BASIC_INFO = mem::zeroed();
763            let size = size_of_val(&info);
764            cvt(c::GetFileInformationByHandleEx(
765                self.handle.as_raw_handle(),
766                c::FileBasicInfo,
767                (&raw mut info) as *mut c_void,
768                size as u32,
769            ))?;
770            Ok(info)
771        }
772    }
773
774    /// Deletes the file, consuming the file handle to ensure the delete occurs
775    /// as immediately as possible.
776    /// This attempts to use `posix_delete` but falls back to `win32_delete`
777    /// if that is not supported by the filesystem.
778    #[allow(unused)]
779    fn delete(self) -> Result<(), WinError> {
780        // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
781        match self.posix_delete() {
782            Err(WinError::INVALID_PARAMETER)
783            | Err(WinError::NOT_SUPPORTED)
784            | Err(WinError::INVALID_FUNCTION) => self.win32_delete(),
785            result => result,
786        }
787    }
788
789    /// Delete using POSIX semantics.
790    ///
791    /// Files will be deleted as soon as the handle is closed. This is supported
792    /// for Windows 10 1607 (aka RS1) and later. However some filesystem
793    /// drivers will not support it even then, e.g. FAT32.
794    ///
795    /// If the operation is not supported for this filesystem or OS version
796    /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
797    #[allow(unused)]
798    fn posix_delete(&self) -> Result<(), WinError> {
799        let info = c::FILE_DISPOSITION_INFO_EX {
800            Flags: c::FILE_DISPOSITION_FLAG_DELETE
801                | c::FILE_DISPOSITION_FLAG_POSIX_SEMANTICS
802                | c::FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE,
803        };
804        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info)
805    }
806
807    /// Delete a file using win32 semantics. The file won't actually be deleted
808    /// until all file handles are closed. However, marking a file for deletion
809    /// will prevent anyone from opening a new handle to the file.
810    #[allow(unused)]
811    fn win32_delete(&self) -> Result<(), WinError> {
812        let info = c::FILE_DISPOSITION_INFO { DeleteFile: true };
813        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info)
814    }
815
816    /// Fill the given buffer with as many directory entries as will fit.
817    /// This will remember its position and continue from the last call unless
818    /// `restart` is set to `true`.
819    ///
820    /// The returned bool indicates if there are more entries or not.
821    /// It is an error if `self` is not a directory.
822    ///
823    /// # Symlinks and other reparse points
824    ///
825    /// On Windows a file is either a directory or a non-directory.
826    /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
827    /// So if you open a link (not its target) and iterate the directory,
828    /// you will always iterate an empty directory regardless of the target.
829    #[allow(unused)]
830    fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> Result<bool, WinError> {
831        let class =
832            if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
833
834        unsafe {
835            let result = c::GetFileInformationByHandleEx(
836                self.as_raw_handle(),
837                class,
838                buffer.as_mut_ptr().cast(),
839                buffer.capacity() as _,
840            );
841            if result == 0 {
842                let err = api::get_last_error();
843                if err.code == c::ERROR_NO_MORE_FILES { Ok(false) } else { Err(err) }
844            } else {
845                Ok(true)
846            }
847        }
848    }
849}
850
851/// A buffer for holding directory entries.
852struct DirBuff {
853    buffer: Box<Align8<[MaybeUninit<u8>; Self::BUFFER_SIZE]>>,
854}
855impl DirBuff {
856    const BUFFER_SIZE: usize = 1024;
857    fn new() -> Self {
858        Self {
859            // Safety: `Align8<[MaybeUninit<u8>; N]>` does not need
860            // initialization.
861            buffer: unsafe { Box::new_uninit().assume_init() },
862        }
863    }
864    fn capacity(&self) -> usize {
865        self.buffer.0.len()
866    }
867    fn as_mut_ptr(&mut self) -> *mut u8 {
868        self.buffer.0.as_mut_ptr().cast()
869    }
870    /// Returns a `DirBuffIter`.
871    fn iter(&self) -> DirBuffIter<'_> {
872        DirBuffIter::new(self)
873    }
874}
875impl AsRef<[MaybeUninit<u8>]> for DirBuff {
876    fn as_ref(&self) -> &[MaybeUninit<u8>] {
877        &self.buffer.0
878    }
879}
880
881/// An iterator over entries stored in a `DirBuff`.
882///
883/// Currently only returns file names (UTF-16 encoded).
884struct DirBuffIter<'a> {
885    buffer: Option<&'a [MaybeUninit<u8>]>,
886    cursor: usize,
887}
888impl<'a> DirBuffIter<'a> {
889    fn new(buffer: &'a DirBuff) -> Self {
890        Self { buffer: Some(buffer.as_ref()), cursor: 0 }
891    }
892}
893impl<'a> Iterator for DirBuffIter<'a> {
894    type Item = (Cow<'a, [u16]>, bool);
895    fn next(&mut self) -> Option<Self::Item> {
896        let buffer = &self.buffer?[self.cursor..];
897
898        // Get the name and next entry from the buffer.
899        // SAFETY:
900        // - The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the last
901        //   field (the file name) is unsized. So an offset has to be used to
902        //   get the file name slice.
903        // - The OS has guaranteed initialization of the fields of
904        //   `FILE_ID_BOTH_DIR_INFO` and the trailing filename (for at least
905        //   `FileNameLength` bytes)
906        let (name, is_directory, next_entry) = unsafe {
907            let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
908            // While this is guaranteed to be aligned in documentation for
909            // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_both_dir_info
910            // it does not seem that reality is so kind, and assuming this
911            // caused crashes in some cases (https://github.com/rust-lang/rust/issues/104530)
912            // presumably, this can be blamed on buggy filesystem drivers, but who knows.
913            let next_entry = (&raw const (*info).NextEntryOffset).read_unaligned() as usize;
914            let length = (&raw const (*info).FileNameLength).read_unaligned() as usize;
915            let attrs = (&raw const (*info).FileAttributes).read_unaligned();
916            let name = from_maybe_unaligned(
917                (&raw const (*info).FileName).cast::<u16>(),
918                length / size_of::<u16>(),
919            );
920            let is_directory = (attrs & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
921
922            (name, is_directory, next_entry)
923        };
924
925        if next_entry == 0 {
926            self.buffer = None
927        } else {
928            self.cursor += next_entry
929        }
930
931        // Skip `.` and `..` pseudo entries.
932        const DOT: u16 = b'.' as u16;
933        match &name[..] {
934            [DOT] | [DOT, DOT] => self.next(),
935            _ => Some((name, is_directory)),
936        }
937    }
938}
939
940unsafe fn from_maybe_unaligned<'a>(p: *const u16, len: usize) -> Cow<'a, [u16]> {
941    unsafe {
942        if p.is_aligned() {
943            Cow::Borrowed(crate::slice::from_raw_parts(p, len))
944        } else {
945            Cow::Owned((0..len).map(|i| p.add(i).read_unaligned()).collect())
946        }
947    }
948}
949
950impl AsInner<Handle> for File {
951    #[inline]
952    fn as_inner(&self) -> &Handle {
953        &self.handle
954    }
955}
956
957impl IntoInner<Handle> for File {
958    fn into_inner(self) -> Handle {
959        self.handle
960    }
961}
962
963impl FromInner<Handle> for File {
964    fn from_inner(handle: Handle) -> File {
965        File { handle }
966    }
967}
968
969impl AsHandle for File {
970    fn as_handle(&self) -> BorrowedHandle<'_> {
971        self.as_inner().as_handle()
972    }
973}
974
975impl AsRawHandle for File {
976    fn as_raw_handle(&self) -> RawHandle {
977        self.as_inner().as_raw_handle()
978    }
979}
980
981impl IntoRawHandle for File {
982    fn into_raw_handle(self) -> RawHandle {
983        self.into_inner().into_raw_handle()
984    }
985}
986
987impl FromRawHandle for File {
988    unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
989        unsafe {
990            Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
991        }
992    }
993}
994
995impl fmt::Debug for File {
996    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997        // FIXME(#24570): add more info here (e.g., mode)
998        let mut b = f.debug_struct("File");
999        b.field("handle", &self.handle.as_raw_handle());
1000        if let Ok(path) = get_path(self) {
1001            b.field("path", &path);
1002        }
1003        b.finish()
1004    }
1005}
1006
1007impl FileAttr {
1008    pub fn size(&self) -> u64 {
1009        self.file_size
1010    }
1011
1012    pub fn perm(&self) -> FilePermissions {
1013        FilePermissions { attrs: self.attributes }
1014    }
1015
1016    pub fn attrs(&self) -> u32 {
1017        self.attributes
1018    }
1019
1020    pub fn file_type(&self) -> FileType {
1021        FileType::new(self.attributes, self.reparse_tag)
1022    }
1023
1024    pub fn modified(&self) -> io::Result<SystemTime> {
1025        Ok(SystemTime::from(self.last_write_time))
1026    }
1027
1028    pub fn accessed(&self) -> io::Result<SystemTime> {
1029        Ok(SystemTime::from(self.last_access_time))
1030    }
1031
1032    pub fn created(&self) -> io::Result<SystemTime> {
1033        Ok(SystemTime::from(self.creation_time))
1034    }
1035
1036    pub fn modified_u64(&self) -> u64 {
1037        to_u64(&self.last_write_time)
1038    }
1039
1040    pub fn accessed_u64(&self) -> u64 {
1041        to_u64(&self.last_access_time)
1042    }
1043
1044    pub fn created_u64(&self) -> u64 {
1045        to_u64(&self.creation_time)
1046    }
1047
1048    pub fn changed_u64(&self) -> Option<u64> {
1049        self.change_time.as_ref().map(|c| to_u64(c))
1050    }
1051
1052    pub fn volume_serial_number(&self) -> Option<u32> {
1053        self.volume_serial_number
1054    }
1055
1056    pub fn number_of_links(&self) -> Option<u32> {
1057        self.number_of_links
1058    }
1059
1060    pub fn file_index(&self) -> Option<u64> {
1061        self.file_index
1062    }
1063}
1064impl From<c::WIN32_FIND_DATAW> for FileAttr {
1065    fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
1066        FileAttr {
1067            attributes: wfd.dwFileAttributes,
1068            creation_time: wfd.ftCreationTime,
1069            last_access_time: wfd.ftLastAccessTime,
1070            last_write_time: wfd.ftLastWriteTime,
1071            change_time: None,
1072            file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
1073            reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1074                // reserved unless this is a reparse point
1075                wfd.dwReserved0
1076            } else {
1077                0
1078            },
1079            volume_serial_number: None,
1080            number_of_links: None,
1081            file_index: None,
1082        }
1083    }
1084}
1085
1086fn to_u64(ft: &c::FILETIME) -> u64 {
1087    (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
1088}
1089
1090impl FilePermissions {
1091    pub fn readonly(&self) -> bool {
1092        self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
1093    }
1094
1095    pub fn set_readonly(&mut self, readonly: bool) {
1096        if readonly {
1097            self.attrs |= c::FILE_ATTRIBUTE_READONLY;
1098        } else {
1099            self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
1100        }
1101    }
1102}
1103
1104impl FileTimes {
1105    pub fn set_accessed(&mut self, t: SystemTime) {
1106        self.accessed = Some(t.into_inner());
1107    }
1108
1109    pub fn set_modified(&mut self, t: SystemTime) {
1110        self.modified = Some(t.into_inner());
1111    }
1112
1113    pub fn set_created(&mut self, t: SystemTime) {
1114        self.created = Some(t.into_inner());
1115    }
1116}
1117
1118impl FileType {
1119    fn new(attributes: u32, reparse_tag: u32) -> FileType {
1120        let is_directory = attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0;
1121        let is_symlink = {
1122            let is_reparse_point = attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0;
1123            let is_reparse_tag_name_surrogate = reparse_tag & 0x20000000 != 0;
1124            is_reparse_point && is_reparse_tag_name_surrogate
1125        };
1126        FileType { is_directory, is_symlink }
1127    }
1128    pub fn is_dir(&self) -> bool {
1129        !self.is_symlink && self.is_directory
1130    }
1131    pub fn is_file(&self) -> bool {
1132        !self.is_symlink && !self.is_directory
1133    }
1134    pub fn is_symlink(&self) -> bool {
1135        self.is_symlink
1136    }
1137    pub fn is_symlink_dir(&self) -> bool {
1138        self.is_symlink && self.is_directory
1139    }
1140    pub fn is_symlink_file(&self) -> bool {
1141        self.is_symlink && !self.is_directory
1142    }
1143}
1144
1145impl DirBuilder {
1146    pub fn new() -> DirBuilder {
1147        DirBuilder
1148    }
1149
1150    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1151        let p = maybe_verbatim(p)?;
1152        cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
1153        Ok(())
1154    }
1155}
1156
1157pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1158    // We push a `*` to the end of the path which cause the empty path to be
1159    // treated as the current directory. So, for consistency with other platforms,
1160    // we explicitly error on the empty path.
1161    if p.as_os_str().is_empty() {
1162        // Return an error code consistent with other ways of opening files.
1163        // E.g. fs::metadata or File::open.
1164        return Err(io::Error::from_raw_os_error(c::ERROR_PATH_NOT_FOUND as i32));
1165    }
1166    let root = p.to_path_buf();
1167    let star = p.join("*");
1168    let path = maybe_verbatim(&star)?;
1169
1170    unsafe {
1171        let mut wfd: c::WIN32_FIND_DATAW = mem::zeroed();
1172        // this is like FindFirstFileW (see https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirstfileexw),
1173        // but with FindExInfoBasic it should skip filling WIN32_FIND_DATAW.cAlternateFileName
1174        // (see https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-win32_find_dataw)
1175        // (which will be always null string value and currently unused) and should be faster.
1176        //
1177        // We can pass FIND_FIRST_EX_LARGE_FETCH to dwAdditionalFlags to speed up things more,
1178        // but as we don't know user's use profile of this function, lets be conservative.
1179        let find_handle = c::FindFirstFileExW(
1180            path.as_ptr(),
1181            c::FindExInfoBasic,
1182            &mut wfd as *mut _ as _,
1183            c::FindExSearchNameMatch,
1184            ptr::null(),
1185            0,
1186        );
1187
1188        if find_handle != c::INVALID_HANDLE_VALUE {
1189            Ok(ReadDir {
1190                handle: Some(FindNextFileHandle(find_handle)),
1191                root: Arc::new(root),
1192                first: Some(wfd),
1193            })
1194        } else {
1195            // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileExW` function
1196            // if no matching files can be found, but not necessarily that the path to find the
1197            // files in does not exist.
1198            //
1199            // Hence, a check for whether the path to search in exists is added when the last
1200            // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario.
1201            // If that is the case, an empty `ReadDir` iterator is returned as it returns `None`
1202            // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been
1203            // returned by the `FindNextFileW` function.
1204            //
1205            // See issue #120040: https://github.com/rust-lang/rust/issues/120040.
1206            let last_error = api::get_last_error();
1207            if last_error == WinError::FILE_NOT_FOUND {
1208                return Ok(ReadDir { handle: None, root: Arc::new(root), first: None });
1209            }
1210
1211            // Just return the error constructed from the raw OS error if the above is not the case.
1212            //
1213            // Note: `ERROR_PATH_NOT_FOUND` would have been returned by the `FindFirstFileExW` function
1214            // when the path to search in does not exist in the first place.
1215            Err(Error::from_raw_os_error(last_error.code as i32))
1216        }
1217    }
1218}
1219
1220pub fn unlink(path: &WCStr) -> io::Result<()> {
1221    if unsafe { c::DeleteFileW(path.as_ptr()) } == 0 {
1222        let err = api::get_last_error();
1223        // if `DeleteFileW` fails with ERROR_ACCESS_DENIED then try to remove
1224        // the file while ignoring the readonly attribute.
1225        // This is accomplished by calling the `posix_delete` function on an open file handle.
1226        if err == WinError::ACCESS_DENIED {
1227            let mut opts = OpenOptions::new();
1228            opts.access_mode(c::DELETE);
1229            opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT);
1230            if let Ok(f) = File::open_native(&path, &opts) {
1231                if f.posix_delete().is_ok() {
1232                    return Ok(());
1233                }
1234            }
1235        }
1236        // return the original error if any of the above fails.
1237        Err(io::Error::from_raw_os_error(err.code as i32))
1238    } else {
1239        Ok(())
1240    }
1241}
1242
1243pub fn rename(old: &WCStr, new: &WCStr) -> io::Result<()> {
1244    if unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) } == 0 {
1245        let err = api::get_last_error();
1246        // if `MoveFileExW` fails with ERROR_ACCESS_DENIED then try to move
1247        // the file while ignoring the readonly attribute.
1248        // This is accomplished by calling `SetFileInformationByHandle` with `FileRenameInfoEx`.
1249        if err == WinError::ACCESS_DENIED {
1250            let mut opts = OpenOptions::new();
1251            opts.access_mode(c::DELETE);
1252            opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1253            let Ok(f) = File::open_native(&old, &opts) else { return Err(err).io_result() };
1254
1255            // Calculate the layout of the `FILE_RENAME_INFO` we pass to `SetFileInformation`
1256            // This is a dynamically sized struct so we need to get the position of the last field to calculate the actual size.
1257            let Ok(new_len_without_nul_in_bytes): Result<u32, _> =
1258                ((new.count_bytes() - 1) * 2).try_into()
1259            else {
1260                return Err(err).io_result();
1261            };
1262            let offset: u32 = offset_of!(c::FILE_RENAME_INFO, FileName).try_into().unwrap();
1263            let struct_size = offset + new_len_without_nul_in_bytes + 2;
1264            let layout =
1265                Layout::from_size_align(struct_size as usize, align_of::<c::FILE_RENAME_INFO>())
1266                    .unwrap();
1267
1268            // SAFETY: We allocate enough memory for a full FILE_RENAME_INFO struct and a filename.
1269            let file_rename_info;
1270            unsafe {
1271                file_rename_info = alloc(layout).cast::<c::FILE_RENAME_INFO>();
1272                if file_rename_info.is_null() {
1273                    return Err(io::ErrorKind::OutOfMemory.into());
1274                }
1275
1276                (&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1277                    Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS
1278                        | c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1279                });
1280
1281                (&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1282                // Don't include the NULL in the size
1283                (&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
1284
1285                new.as_ptr().copy_to_nonoverlapping(
1286                    (&raw mut (*file_rename_info).FileName).cast::<u16>(),
1287                    new.count_bytes(),
1288                );
1289            }
1290
1291            let result = unsafe {
1292                c::SetFileInformationByHandle(
1293                    f.as_raw_handle(),
1294                    c::FileRenameInfoEx,
1295                    file_rename_info.cast::<c_void>(),
1296                    struct_size,
1297                )
1298            };
1299            unsafe { dealloc(file_rename_info.cast::<u8>(), layout) };
1300            if result == 0 {
1301                if api::get_last_error() == WinError::DIR_NOT_EMPTY {
1302                    return Err(WinError::DIR_NOT_EMPTY).io_result();
1303                } else {
1304                    return Err(err).io_result();
1305                }
1306            }
1307        } else {
1308            return Err(err).io_result();
1309        }
1310    }
1311    Ok(())
1312}
1313
1314pub fn rmdir(p: &WCStr) -> io::Result<()> {
1315    cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
1316    Ok(())
1317}
1318
1319pub fn remove_dir_all(path: &WCStr) -> io::Result<()> {
1320    // Open a file or directory without following symlinks.
1321    let mut opts = OpenOptions::new();
1322    opts.access_mode(c::FILE_LIST_DIRECTORY);
1323    // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
1324    // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
1325    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1326    let file = File::open_native(path, &opts)?;
1327
1328    // Test if the file is not a directory or a symlink to a directory.
1329    if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
1330        return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
1331    }
1332
1333    // Remove the directory and all its contents.
1334    remove_dir_all_iterative(file).io_result()
1335}
1336
1337pub fn readlink(path: &WCStr) -> io::Result<PathBuf> {
1338    // Open the link with no access mode, instead of generic read.
1339    // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1340    // this is needed for a common case.
1341    let mut opts = OpenOptions::new();
1342    opts.access_mode(0);
1343    opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1344    let file = File::open_native(&path, &opts)?;
1345    file.readlink()
1346}
1347
1348pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1349    symlink_inner(original, link, false)
1350}
1351
1352pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1353    let original = to_u16s(original)?;
1354    let link = maybe_verbatim(link)?;
1355    let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1356    // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1357    // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1358    // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1359    // added to dwFlags to opt into this behavior.
1360    let result = cvt(unsafe {
1361        c::CreateSymbolicLinkW(
1362            link.as_ptr(),
1363            original.as_ptr(),
1364            flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1365        ) as c::BOOL
1366    });
1367    if let Err(err) = result {
1368        if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1369            // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1370            // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1371            cvt(unsafe {
1372                c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1373            })?;
1374        } else {
1375            return Err(err);
1376        }
1377    }
1378    Ok(())
1379}
1380
1381#[cfg(not(target_vendor = "uwp"))]
1382pub fn link(original: &WCStr, link: &WCStr) -> io::Result<()> {
1383    cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1384    Ok(())
1385}
1386
1387#[cfg(target_vendor = "uwp")]
1388pub fn link(_original: &WCStr, _link: &WCStr) -> io::Result<()> {
1389    return Err(io::const_error!(io::ErrorKind::Unsupported, "hard link are not supported on UWP"));
1390}
1391
1392pub fn stat(path: &WCStr) -> io::Result<FileAttr> {
1393    match metadata(path, ReparsePoint::Follow) {
1394        Err(err) if err.raw_os_error() == Some(c::ERROR_CANT_ACCESS_FILE as i32) => {
1395            if let Ok(attrs) = lstat(path) {
1396                if !attrs.file_type().is_symlink() {
1397                    return Ok(attrs);
1398                }
1399            }
1400            Err(err)
1401        }
1402        result => result,
1403    }
1404}
1405
1406pub fn lstat(path: &WCStr) -> io::Result<FileAttr> {
1407    metadata(path, ReparsePoint::Open)
1408}
1409
1410#[repr(u32)]
1411#[derive(Clone, Copy, PartialEq, Eq)]
1412enum ReparsePoint {
1413    Follow = 0,
1414    Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
1415}
1416impl ReparsePoint {
1417    fn as_flag(self) -> u32 {
1418        self as u32
1419    }
1420}
1421
1422fn metadata(path: &WCStr, reparse: ReparsePoint) -> io::Result<FileAttr> {
1423    let mut opts = OpenOptions::new();
1424    // No read or write permissions are necessary
1425    opts.access_mode(0);
1426    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());
1427
1428    // Attempt to open the file normally.
1429    // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileExW`.
1430    // If the fallback fails for any reason we return the original error.
1431    match File::open_native(&path, &opts) {
1432        Ok(file) => file.file_attr(),
1433        Err(e)
1434            if [Some(c::ERROR_SHARING_VIOLATION as _), Some(c::ERROR_ACCESS_DENIED as _)]
1435                .contains(&e.raw_os_error()) =>
1436        {
1437            // `ERROR_ACCESS_DENIED` is returned when the user doesn't have permission for the resource.
1438            // One such example is `System Volume Information` as default but can be created as well
1439            // `ERROR_SHARING_VIOLATION` will almost never be returned.
1440            // Usually if a file is locked you can still read some metadata.
1441            // However, there are special system files, such as
1442            // `C:\hiberfil.sys`, that are locked in a way that denies even that.
1443            unsafe {
1444                // `FindFirstFileExW` accepts wildcard file names.
1445                // Fortunately wildcards are not valid file names and
1446                // `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
1447                // therefore it's safe to assume the file name given does not
1448                // include wildcards.
1449                let mut wfd: c::WIN32_FIND_DATAW = mem::zeroed();
1450                let handle = c::FindFirstFileExW(
1451                    path.as_ptr(),
1452                    c::FindExInfoBasic,
1453                    &mut wfd as *mut _ as _,
1454                    c::FindExSearchNameMatch,
1455                    ptr::null(),
1456                    0,
1457                );
1458
1459                if handle == c::INVALID_HANDLE_VALUE {
1460                    // This can fail if the user does not have read access to the
1461                    // directory.
1462                    Err(e)
1463                } else {
1464                    // We no longer need the find handle.
1465                    c::FindClose(handle);
1466
1467                    // `FindFirstFileExW` reads the cached file information from the
1468                    // directory. The downside is that this metadata may be outdated.
1469                    let attrs = FileAttr::from(wfd);
1470                    if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
1471                        Err(e)
1472                    } else {
1473                        Ok(attrs)
1474                    }
1475                }
1476            }
1477        }
1478        Err(e) => Err(e),
1479    }
1480}
1481
1482pub fn set_perm(p: &WCStr, perm: FilePermissions) -> io::Result<()> {
1483    unsafe {
1484        cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1485        Ok(())
1486    }
1487}
1488
1489fn get_path(f: &File) -> io::Result<PathBuf> {
1490    fill_utf16_buf(
1491        |buf, sz| unsafe {
1492            c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1493        },
1494        |buf| PathBuf::from(OsString::from_wide(buf)),
1495    )
1496}
1497
1498pub fn canonicalize(p: &WCStr) -> io::Result<PathBuf> {
1499    let mut opts = OpenOptions::new();
1500    // No read or write permissions are necessary
1501    opts.access_mode(0);
1502    // This flag is so we can open directories too
1503    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1504    let f = File::open_native(p, &opts)?;
1505    get_path(&f)
1506}
1507
1508pub fn copy(from: &WCStr, to: &WCStr) -> io::Result<u64> {
1509    unsafe extern "system" fn callback(
1510        _TotalFileSize: i64,
1511        _TotalBytesTransferred: i64,
1512        _StreamSize: i64,
1513        StreamBytesTransferred: i64,
1514        dwStreamNumber: u32,
1515        _dwCallbackReason: u32,
1516        _hSourceFile: c::HANDLE,
1517        _hDestinationFile: c::HANDLE,
1518        lpData: *const c_void,
1519    ) -> u32 {
1520        unsafe {
1521            if dwStreamNumber == 1 {
1522                *(lpData as *mut i64) = StreamBytesTransferred;
1523            }
1524            c::PROGRESS_CONTINUE
1525        }
1526    }
1527    let mut size = 0i64;
1528    cvt(unsafe {
1529        c::CopyFileExW(
1530            from.as_ptr(),
1531            to.as_ptr(),
1532            Some(callback),
1533            (&raw mut size) as *mut _,
1534            ptr::null_mut(),
1535            0,
1536        )
1537    })?;
1538    Ok(size as u64)
1539}
1540
1541pub fn junction_point(original: &Path, link: &Path) -> io::Result<()> {
1542    // Create and open a new directory in one go.
1543    let mut opts = OpenOptions::new();
1544    opts.create_new(true);
1545    opts.write(true);
1546    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_POSIX_SEMANTICS);
1547    opts.attributes(c::FILE_ATTRIBUTE_DIRECTORY);
1548
1549    let d = File::open(link, &opts)?;
1550
1551    // We need to get an absolute, NT-style path.
1552    let path_bytes = original.as_os_str().as_encoded_bytes();
1553    let abs_path: Vec<u16> = if path_bytes.starts_with(br"\\?\") || path_bytes.starts_with(br"\??\")
1554    {
1555        // It's already an absolute path, we just need to convert the prefix to `\??\`
1556        let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&path_bytes[4..]) };
1557        r"\??\".encode_utf16().chain(bytes.encode_wide()).collect()
1558    } else {
1559        // Get an absolute path and then convert the prefix to `\??\`
1560        let abs_path = crate::path::absolute(original)?.into_os_string().into_encoded_bytes();
1561        if abs_path.len() > 0 && abs_path[1..].starts_with(br":\") {
1562            let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&abs_path) };
1563            r"\??\".encode_utf16().chain(bytes.encode_wide()).collect()
1564        } else if abs_path.starts_with(br"\\.\") {
1565            let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&abs_path[4..]) };
1566            r"\??\".encode_utf16().chain(bytes.encode_wide()).collect()
1567        } else if abs_path.starts_with(br"\\") {
1568            let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&abs_path[2..]) };
1569            r"\??\UNC\".encode_utf16().chain(bytes.encode_wide()).collect()
1570        } else {
1571            return Err(io::const_error!(io::ErrorKind::InvalidInput, "path is not valid"));
1572        }
1573    };
1574    // Defined inline so we don't have to mess about with variable length buffer.
1575    #[repr(C)]
1576    pub struct MountPointBuffer {
1577        ReparseTag: u32,
1578        ReparseDataLength: u16,
1579        Reserved: u16,
1580        SubstituteNameOffset: u16,
1581        SubstituteNameLength: u16,
1582        PrintNameOffset: u16,
1583        PrintNameLength: u16,
1584        PathBuffer: [MaybeUninit<u16>; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize],
1585    }
1586    let data_len = 12 + (abs_path.len() * 2);
1587    if data_len > u16::MAX as usize {
1588        return Err(io::const_error!(io::ErrorKind::InvalidInput, "`original` path is too long"));
1589    }
1590    let data_len = data_len as u16;
1591    let mut header = MountPointBuffer {
1592        ReparseTag: c::IO_REPARSE_TAG_MOUNT_POINT,
1593        ReparseDataLength: data_len,
1594        Reserved: 0,
1595        SubstituteNameOffset: 0,
1596        SubstituteNameLength: (abs_path.len() * 2) as u16,
1597        PrintNameOffset: ((abs_path.len() + 1) * 2) as u16,
1598        PrintNameLength: 0,
1599        PathBuffer: [MaybeUninit::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize],
1600    };
1601    unsafe {
1602        let ptr = header.PathBuffer.as_mut_ptr();
1603        ptr.copy_from(abs_path.as_ptr().cast::<MaybeUninit<u16>>(), abs_path.len());
1604
1605        let mut ret = 0;
1606        cvt(c::DeviceIoControl(
1607            d.as_raw_handle(),
1608            c::FSCTL_SET_REPARSE_POINT,
1609            (&raw const header).cast::<c_void>(),
1610            data_len as u32 + 8,
1611            ptr::null_mut(),
1612            0,
1613            &mut ret,
1614            ptr::null_mut(),
1615        ))
1616        .map(drop)
1617    }
1618}
1619
1620// Try to see if a file exists but, unlike `exists`, report I/O errors.
1621pub fn exists(path: &WCStr) -> io::Result<bool> {
1622    // Open the file to ensure any symlinks are followed to their target.
1623    let mut opts = OpenOptions::new();
1624    // No read, write, etc access rights are needed.
1625    opts.access_mode(0);
1626    // Backup semantics enables opening directories as well as files.
1627    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1628    match File::open_native(path, &opts) {
1629        Err(e) => match e.kind() {
1630            // The file definitely does not exist
1631            io::ErrorKind::NotFound => Ok(false),
1632
1633            // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1634            // another process. This is often temporary so we simply report it
1635            // as the file existing.
1636            _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1637
1638            // `ERROR_CANT_ACCESS_FILE` means that a file exists but that the
1639            // reparse point could not be handled by `CreateFile`.
1640            // This can happen for special files such as:
1641            // * Unix domain sockets which you need to `connect` to
1642            // * App exec links which require using `CreateProcess`
1643            _ if e.raw_os_error() == Some(c::ERROR_CANT_ACCESS_FILE as i32) => Ok(true),
1644
1645            // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1646            // file exists. However, these types of errors are usually more
1647            // permanent so we report them here.
1648            _ => Err(e),
1649        },
1650        // The file was opened successfully therefore it must exist,
1651        Ok(_) => Ok(true),
1652    }
1653}