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 tell(&self) -> io::Result<u64> {
620        self.seek(SeekFrom::Current(0))
621    }
622
623    pub fn duplicate(&self) -> io::Result<File> {
624        Ok(Self { handle: self.handle.try_clone()? })
625    }
626
627    // NB: returned pointer is derived from `space`, and has provenance to
628    // match. A raw pointer is returned rather than a reference in order to
629    // avoid narrowing provenance to the actual `REPARSE_DATA_BUFFER`.
630    fn reparse_point(
631        &self,
632        space: &mut Align8<[MaybeUninit<u8>]>,
633    ) -> io::Result<(u32, *mut c::REPARSE_DATA_BUFFER)> {
634        unsafe {
635            let mut bytes = 0;
636            cvt({
637                // Grab this in advance to avoid it invalidating the pointer
638                // we get from `space.0.as_mut_ptr()`.
639                let len = space.0.len();
640                c::DeviceIoControl(
641                    self.handle.as_raw_handle(),
642                    c::FSCTL_GET_REPARSE_POINT,
643                    ptr::null_mut(),
644                    0,
645                    space.0.as_mut_ptr().cast(),
646                    len as u32,
647                    &mut bytes,
648                    ptr::null_mut(),
649                )
650            })?;
651            const _: () = assert!(align_of::<c::REPARSE_DATA_BUFFER>() <= 8);
652            Ok((bytes, space.0.as_mut_ptr().cast::<c::REPARSE_DATA_BUFFER>()))
653        }
654    }
655
656    fn readlink(&self) -> io::Result<PathBuf> {
657        let mut space =
658            Align8([MaybeUninit::<u8>::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize]);
659        let (_bytes, buf) = self.reparse_point(&mut space)?;
660        unsafe {
661            let (path_buffer, subst_off, subst_len, relative) = match (*buf).ReparseTag {
662                c::IO_REPARSE_TAG_SYMLINK => {
663                    let info: *mut c::SYMBOLIC_LINK_REPARSE_BUFFER = (&raw mut (*buf).rest).cast();
664                    assert!(info.is_aligned());
665                    (
666                        (&raw mut (*info).PathBuffer).cast::<u16>(),
667                        (*info).SubstituteNameOffset / 2,
668                        (*info).SubstituteNameLength / 2,
669                        (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
670                    )
671                }
672                c::IO_REPARSE_TAG_MOUNT_POINT => {
673                    let info: *mut c::MOUNT_POINT_REPARSE_BUFFER = (&raw mut (*buf).rest).cast();
674                    assert!(info.is_aligned());
675                    (
676                        (&raw mut (*info).PathBuffer).cast::<u16>(),
677                        (*info).SubstituteNameOffset / 2,
678                        (*info).SubstituteNameLength / 2,
679                        false,
680                    )
681                }
682                _ => {
683                    return Err(io::const_error!(
684                        io::ErrorKind::Uncategorized,
685                        "Unsupported reparse point type",
686                    ));
687                }
688            };
689            let subst_ptr = path_buffer.add(subst_off.into());
690            let subst = slice::from_raw_parts_mut(subst_ptr, subst_len as usize);
691            // Absolute paths start with an NT internal namespace prefix `\??\`
692            // We should not let it leak through.
693            if !relative && subst.starts_with(&[92u16, 63u16, 63u16, 92u16]) {
694                // Turn `\??\` into `\\?\` (a verbatim path).
695                subst[1] = b'\\' as u16;
696                // Attempt to convert to a more user-friendly path.
697                let user = crate::sys::args::from_wide_to_user_path(
698                    subst.iter().copied().chain([0]).collect(),
699                )?;
700                Ok(PathBuf::from(OsString::from_wide(user.strip_suffix(&[0]).unwrap_or(&user))))
701            } else {
702                Ok(PathBuf::from(OsString::from_wide(subst)))
703            }
704        }
705    }
706
707    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
708        let info = c::FILE_BASIC_INFO {
709            CreationTime: 0,
710            LastAccessTime: 0,
711            LastWriteTime: 0,
712            ChangeTime: 0,
713            FileAttributes: perm.attrs,
714        };
715        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info).io_result()
716    }
717
718    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
719        let is_zero = |t: c::FILETIME| t.dwLowDateTime == 0 && t.dwHighDateTime == 0;
720        if times.accessed.map_or(false, is_zero)
721            || times.modified.map_or(false, is_zero)
722            || times.created.map_or(false, is_zero)
723        {
724            return Err(io::const_error!(
725                io::ErrorKind::InvalidInput,
726                "cannot set file timestamp to 0",
727            ));
728        }
729        let is_max = |t: c::FILETIME| t.dwLowDateTime == u32::MAX && t.dwHighDateTime == u32::MAX;
730        if times.accessed.map_or(false, is_max)
731            || times.modified.map_or(false, is_max)
732            || times.created.map_or(false, is_max)
733        {
734            return Err(io::const_error!(
735                io::ErrorKind::InvalidInput,
736                "cannot set file timestamp to 0xFFFF_FFFF_FFFF_FFFF",
737            ));
738        }
739        cvt(unsafe {
740            let created =
741                times.created.as_ref().map(|a| a as *const c::FILETIME).unwrap_or(ptr::null());
742            let accessed =
743                times.accessed.as_ref().map(|a| a as *const c::FILETIME).unwrap_or(ptr::null());
744            let modified =
745                times.modified.as_ref().map(|a| a as *const c::FILETIME).unwrap_or(ptr::null());
746            c::SetFileTime(self.as_raw_handle(), created, accessed, modified)
747        })?;
748        Ok(())
749    }
750
751    /// Gets only basic file information such as attributes and file times.
752    fn basic_info(&self) -> io::Result<c::FILE_BASIC_INFO> {
753        unsafe {
754            let mut info: c::FILE_BASIC_INFO = mem::zeroed();
755            let size = size_of_val(&info);
756            cvt(c::GetFileInformationByHandleEx(
757                self.handle.as_raw_handle(),
758                c::FileBasicInfo,
759                (&raw mut info) as *mut c_void,
760                size as u32,
761            ))?;
762            Ok(info)
763        }
764    }
765
766    /// Deletes the file, consuming the file handle to ensure the delete occurs
767    /// as immediately as possible.
768    /// This attempts to use `posix_delete` but falls back to `win32_delete`
769    /// if that is not supported by the filesystem.
770    #[allow(unused)]
771    fn delete(self) -> Result<(), WinError> {
772        // If POSIX delete is not supported for this filesystem then fallback to win32 delete.
773        match self.posix_delete() {
774            Err(WinError::INVALID_PARAMETER)
775            | Err(WinError::NOT_SUPPORTED)
776            | Err(WinError::INVALID_FUNCTION) => self.win32_delete(),
777            result => result,
778        }
779    }
780
781    /// Delete using POSIX semantics.
782    ///
783    /// Files will be deleted as soon as the handle is closed. This is supported
784    /// for Windows 10 1607 (aka RS1) and later. However some filesystem
785    /// drivers will not support it even then, e.g. FAT32.
786    ///
787    /// If the operation is not supported for this filesystem or OS version
788    /// then errors will be `ERROR_NOT_SUPPORTED` or `ERROR_INVALID_PARAMETER`.
789    #[allow(unused)]
790    fn posix_delete(&self) -> Result<(), WinError> {
791        let info = c::FILE_DISPOSITION_INFO_EX {
792            Flags: c::FILE_DISPOSITION_FLAG_DELETE
793                | c::FILE_DISPOSITION_FLAG_POSIX_SEMANTICS
794                | c::FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE,
795        };
796        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info)
797    }
798
799    /// Delete a file using win32 semantics. The file won't actually be deleted
800    /// until all file handles are closed. However, marking a file for deletion
801    /// will prevent anyone from opening a new handle to the file.
802    #[allow(unused)]
803    fn win32_delete(&self) -> Result<(), WinError> {
804        let info = c::FILE_DISPOSITION_INFO { DeleteFile: true };
805        api::set_file_information_by_handle(self.handle.as_raw_handle(), &info)
806    }
807
808    /// Fill the given buffer with as many directory entries as will fit.
809    /// This will remember its position and continue from the last call unless
810    /// `restart` is set to `true`.
811    ///
812    /// The returned bool indicates if there are more entries or not.
813    /// It is an error if `self` is not a directory.
814    ///
815    /// # Symlinks and other reparse points
816    ///
817    /// On Windows a file is either a directory or a non-directory.
818    /// A symlink directory is simply an empty directory with some "reparse" metadata attached.
819    /// So if you open a link (not its target) and iterate the directory,
820    /// you will always iterate an empty directory regardless of the target.
821    #[allow(unused)]
822    fn fill_dir_buff(&self, buffer: &mut DirBuff, restart: bool) -> Result<bool, WinError> {
823        let class =
824            if restart { c::FileIdBothDirectoryRestartInfo } else { c::FileIdBothDirectoryInfo };
825
826        unsafe {
827            let result = c::GetFileInformationByHandleEx(
828                self.as_raw_handle(),
829                class,
830                buffer.as_mut_ptr().cast(),
831                buffer.capacity() as _,
832            );
833            if result == 0 {
834                let err = api::get_last_error();
835                if err.code == c::ERROR_NO_MORE_FILES { Ok(false) } else { Err(err) }
836            } else {
837                Ok(true)
838            }
839        }
840    }
841}
842
843/// A buffer for holding directory entries.
844struct DirBuff {
845    buffer: Box<Align8<[MaybeUninit<u8>; Self::BUFFER_SIZE]>>,
846}
847impl DirBuff {
848    const BUFFER_SIZE: usize = 1024;
849    fn new() -> Self {
850        Self {
851            // Safety: `Align8<[MaybeUninit<u8>; N]>` does not need
852            // initialization.
853            buffer: unsafe { Box::new_uninit().assume_init() },
854        }
855    }
856    fn capacity(&self) -> usize {
857        self.buffer.0.len()
858    }
859    fn as_mut_ptr(&mut self) -> *mut u8 {
860        self.buffer.0.as_mut_ptr().cast()
861    }
862    /// Returns a `DirBuffIter`.
863    fn iter(&self) -> DirBuffIter<'_> {
864        DirBuffIter::new(self)
865    }
866}
867impl AsRef<[MaybeUninit<u8>]> for DirBuff {
868    fn as_ref(&self) -> &[MaybeUninit<u8>] {
869        &self.buffer.0
870    }
871}
872
873/// An iterator over entries stored in a `DirBuff`.
874///
875/// Currently only returns file names (UTF-16 encoded).
876struct DirBuffIter<'a> {
877    buffer: Option<&'a [MaybeUninit<u8>]>,
878    cursor: usize,
879}
880impl<'a> DirBuffIter<'a> {
881    fn new(buffer: &'a DirBuff) -> Self {
882        Self { buffer: Some(buffer.as_ref()), cursor: 0 }
883    }
884}
885impl<'a> Iterator for DirBuffIter<'a> {
886    type Item = (Cow<'a, [u16]>, bool);
887    fn next(&mut self) -> Option<Self::Item> {
888        let buffer = &self.buffer?[self.cursor..];
889
890        // Get the name and next entry from the buffer.
891        // SAFETY:
892        // - The buffer contains a `FILE_ID_BOTH_DIR_INFO` struct but the last
893        //   field (the file name) is unsized. So an offset has to be used to
894        //   get the file name slice.
895        // - The OS has guaranteed initialization of the fields of
896        //   `FILE_ID_BOTH_DIR_INFO` and the trailing filename (for at least
897        //   `FileNameLength` bytes)
898        let (name, is_directory, next_entry) = unsafe {
899            let info = buffer.as_ptr().cast::<c::FILE_ID_BOTH_DIR_INFO>();
900            // While this is guaranteed to be aligned in documentation for
901            // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_both_dir_info
902            // it does not seem that reality is so kind, and assuming this
903            // caused crashes in some cases (https://github.com/rust-lang/rust/issues/104530)
904            // presumably, this can be blamed on buggy filesystem drivers, but who knows.
905            let next_entry = (&raw const (*info).NextEntryOffset).read_unaligned() as usize;
906            let length = (&raw const (*info).FileNameLength).read_unaligned() as usize;
907            let attrs = (&raw const (*info).FileAttributes).read_unaligned();
908            let name = from_maybe_unaligned(
909                (&raw const (*info).FileName).cast::<u16>(),
910                length / size_of::<u16>(),
911            );
912            let is_directory = (attrs & c::FILE_ATTRIBUTE_DIRECTORY) != 0;
913
914            (name, is_directory, next_entry)
915        };
916
917        if next_entry == 0 {
918            self.buffer = None
919        } else {
920            self.cursor += next_entry
921        }
922
923        // Skip `.` and `..` pseudo entries.
924        const DOT: u16 = b'.' as u16;
925        match &name[..] {
926            [DOT] | [DOT, DOT] => self.next(),
927            _ => Some((name, is_directory)),
928        }
929    }
930}
931
932unsafe fn from_maybe_unaligned<'a>(p: *const u16, len: usize) -> Cow<'a, [u16]> {
933    unsafe {
934        if p.is_aligned() {
935            Cow::Borrowed(crate::slice::from_raw_parts(p, len))
936        } else {
937            Cow::Owned((0..len).map(|i| p.add(i).read_unaligned()).collect())
938        }
939    }
940}
941
942impl AsInner<Handle> for File {
943    #[inline]
944    fn as_inner(&self) -> &Handle {
945        &self.handle
946    }
947}
948
949impl IntoInner<Handle> for File {
950    fn into_inner(self) -> Handle {
951        self.handle
952    }
953}
954
955impl FromInner<Handle> for File {
956    fn from_inner(handle: Handle) -> File {
957        File { handle }
958    }
959}
960
961impl AsHandle for File {
962    fn as_handle(&self) -> BorrowedHandle<'_> {
963        self.as_inner().as_handle()
964    }
965}
966
967impl AsRawHandle for File {
968    fn as_raw_handle(&self) -> RawHandle {
969        self.as_inner().as_raw_handle()
970    }
971}
972
973impl IntoRawHandle for File {
974    fn into_raw_handle(self) -> RawHandle {
975        self.into_inner().into_raw_handle()
976    }
977}
978
979impl FromRawHandle for File {
980    unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self {
981        unsafe {
982            Self { handle: FromInner::from_inner(FromRawHandle::from_raw_handle(raw_handle)) }
983        }
984    }
985}
986
987impl fmt::Debug for File {
988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989        // FIXME(#24570): add more info here (e.g., mode)
990        let mut b = f.debug_struct("File");
991        b.field("handle", &self.handle.as_raw_handle());
992        if let Ok(path) = get_path(self) {
993            b.field("path", &path);
994        }
995        b.finish()
996    }
997}
998
999impl FileAttr {
1000    pub fn size(&self) -> u64 {
1001        self.file_size
1002    }
1003
1004    pub fn perm(&self) -> FilePermissions {
1005        FilePermissions { attrs: self.attributes }
1006    }
1007
1008    pub fn attrs(&self) -> u32 {
1009        self.attributes
1010    }
1011
1012    pub fn file_type(&self) -> FileType {
1013        FileType::new(self.attributes, self.reparse_tag)
1014    }
1015
1016    pub fn modified(&self) -> io::Result<SystemTime> {
1017        Ok(SystemTime::from(self.last_write_time))
1018    }
1019
1020    pub fn accessed(&self) -> io::Result<SystemTime> {
1021        Ok(SystemTime::from(self.last_access_time))
1022    }
1023
1024    pub fn created(&self) -> io::Result<SystemTime> {
1025        Ok(SystemTime::from(self.creation_time))
1026    }
1027
1028    pub fn modified_u64(&self) -> u64 {
1029        to_u64(&self.last_write_time)
1030    }
1031
1032    pub fn accessed_u64(&self) -> u64 {
1033        to_u64(&self.last_access_time)
1034    }
1035
1036    pub fn created_u64(&self) -> u64 {
1037        to_u64(&self.creation_time)
1038    }
1039
1040    pub fn changed_u64(&self) -> Option<u64> {
1041        self.change_time.as_ref().map(|c| to_u64(c))
1042    }
1043
1044    pub fn volume_serial_number(&self) -> Option<u32> {
1045        self.volume_serial_number
1046    }
1047
1048    pub fn number_of_links(&self) -> Option<u32> {
1049        self.number_of_links
1050    }
1051
1052    pub fn file_index(&self) -> Option<u64> {
1053        self.file_index
1054    }
1055}
1056impl From<c::WIN32_FIND_DATAW> for FileAttr {
1057    fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
1058        FileAttr {
1059            attributes: wfd.dwFileAttributes,
1060            creation_time: wfd.ftCreationTime,
1061            last_access_time: wfd.ftLastAccessTime,
1062            last_write_time: wfd.ftLastWriteTime,
1063            change_time: None,
1064            file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
1065            reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1066                // reserved unless this is a reparse point
1067                wfd.dwReserved0
1068            } else {
1069                0
1070            },
1071            volume_serial_number: None,
1072            number_of_links: None,
1073            file_index: None,
1074        }
1075    }
1076}
1077
1078fn to_u64(ft: &c::FILETIME) -> u64 {
1079    (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
1080}
1081
1082impl FilePermissions {
1083    pub fn readonly(&self) -> bool {
1084        self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
1085    }
1086
1087    pub fn set_readonly(&mut self, readonly: bool) {
1088        if readonly {
1089            self.attrs |= c::FILE_ATTRIBUTE_READONLY;
1090        } else {
1091            self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
1092        }
1093    }
1094}
1095
1096impl FileTimes {
1097    pub fn set_accessed(&mut self, t: SystemTime) {
1098        self.accessed = Some(t.into_inner());
1099    }
1100
1101    pub fn set_modified(&mut self, t: SystemTime) {
1102        self.modified = Some(t.into_inner());
1103    }
1104
1105    pub fn set_created(&mut self, t: SystemTime) {
1106        self.created = Some(t.into_inner());
1107    }
1108}
1109
1110impl FileType {
1111    fn new(attributes: u32, reparse_tag: u32) -> FileType {
1112        let is_directory = attributes & c::FILE_ATTRIBUTE_DIRECTORY != 0;
1113        let is_symlink = {
1114            let is_reparse_point = attributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0;
1115            let is_reparse_tag_name_surrogate = reparse_tag & 0x20000000 != 0;
1116            is_reparse_point && is_reparse_tag_name_surrogate
1117        };
1118        FileType { is_directory, is_symlink }
1119    }
1120    pub fn is_dir(&self) -> bool {
1121        !self.is_symlink && self.is_directory
1122    }
1123    pub fn is_file(&self) -> bool {
1124        !self.is_symlink && !self.is_directory
1125    }
1126    pub fn is_symlink(&self) -> bool {
1127        self.is_symlink
1128    }
1129    pub fn is_symlink_dir(&self) -> bool {
1130        self.is_symlink && self.is_directory
1131    }
1132    pub fn is_symlink_file(&self) -> bool {
1133        self.is_symlink && !self.is_directory
1134    }
1135}
1136
1137impl DirBuilder {
1138    pub fn new() -> DirBuilder {
1139        DirBuilder
1140    }
1141
1142    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1143        let p = maybe_verbatim(p)?;
1144        cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
1145        Ok(())
1146    }
1147}
1148
1149pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1150    // We push a `*` to the end of the path which cause the empty path to be
1151    // treated as the current directory. So, for consistency with other platforms,
1152    // we explicitly error on the empty path.
1153    if p.as_os_str().is_empty() {
1154        // Return an error code consistent with other ways of opening files.
1155        // E.g. fs::metadata or File::open.
1156        return Err(io::Error::from_raw_os_error(c::ERROR_PATH_NOT_FOUND as i32));
1157    }
1158    let root = p.to_path_buf();
1159    let star = p.join("*");
1160    let path = maybe_verbatim(&star)?;
1161
1162    unsafe {
1163        let mut wfd: c::WIN32_FIND_DATAW = mem::zeroed();
1164        // this is like FindFirstFileW (see https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirstfileexw),
1165        // but with FindExInfoBasic it should skip filling WIN32_FIND_DATAW.cAlternateFileName
1166        // (see https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-win32_find_dataw)
1167        // (which will be always null string value and currently unused) and should be faster.
1168        //
1169        // We can pass FIND_FIRST_EX_LARGE_FETCH to dwAdditionalFlags to speed up things more,
1170        // but as we don't know user's use profile of this function, lets be conservative.
1171        let find_handle = c::FindFirstFileExW(
1172            path.as_ptr(),
1173            c::FindExInfoBasic,
1174            &mut wfd as *mut _ as _,
1175            c::FindExSearchNameMatch,
1176            ptr::null(),
1177            0,
1178        );
1179
1180        if find_handle != c::INVALID_HANDLE_VALUE {
1181            Ok(ReadDir {
1182                handle: Some(FindNextFileHandle(find_handle)),
1183                root: Arc::new(root),
1184                first: Some(wfd),
1185            })
1186        } else {
1187            // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileExW` function
1188            // if no matching files can be found, but not necessarily that the path to find the
1189            // files in does not exist.
1190            //
1191            // Hence, a check for whether the path to search in exists is added when the last
1192            // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario.
1193            // If that is the case, an empty `ReadDir` iterator is returned as it returns `None`
1194            // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been
1195            // returned by the `FindNextFileW` function.
1196            //
1197            // See issue #120040: https://github.com/rust-lang/rust/issues/120040.
1198            let last_error = api::get_last_error();
1199            if last_error == WinError::FILE_NOT_FOUND {
1200                return Ok(ReadDir { handle: None, root: Arc::new(root), first: None });
1201            }
1202
1203            // Just return the error constructed from the raw OS error if the above is not the case.
1204            //
1205            // Note: `ERROR_PATH_NOT_FOUND` would have been returned by the `FindFirstFileExW` function
1206            // when the path to search in does not exist in the first place.
1207            Err(Error::from_raw_os_error(last_error.code as i32))
1208        }
1209    }
1210}
1211
1212pub fn unlink(path: &WCStr) -> io::Result<()> {
1213    if unsafe { c::DeleteFileW(path.as_ptr()) } == 0 {
1214        let err = api::get_last_error();
1215        // if `DeleteFileW` fails with ERROR_ACCESS_DENIED then try to remove
1216        // the file while ignoring the readonly attribute.
1217        // This is accomplished by calling the `posix_delete` function on an open file handle.
1218        if err == WinError::ACCESS_DENIED {
1219            let mut opts = OpenOptions::new();
1220            opts.access_mode(c::DELETE);
1221            opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT);
1222            if let Ok(f) = File::open_native(&path, &opts) {
1223                if f.posix_delete().is_ok() {
1224                    return Ok(());
1225                }
1226            }
1227        }
1228        // return the original error if any of the above fails.
1229        Err(io::Error::from_raw_os_error(err.code as i32))
1230    } else {
1231        Ok(())
1232    }
1233}
1234
1235pub fn rename(old: &WCStr, new: &WCStr) -> io::Result<()> {
1236    if unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) } == 0 {
1237        let err = api::get_last_error();
1238        // if `MoveFileExW` fails with ERROR_ACCESS_DENIED then try to move
1239        // the file while ignoring the readonly attribute.
1240        // This is accomplished by calling `SetFileInformationByHandle` with `FileRenameInfoEx`.
1241        if err == WinError::ACCESS_DENIED {
1242            let mut opts = OpenOptions::new();
1243            opts.access_mode(c::DELETE);
1244            opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1245            let Ok(f) = File::open_native(&old, &opts) else { return Err(err).io_result() };
1246
1247            // Calculate the layout of the `FILE_RENAME_INFO` we pass to `SetFileInformation`
1248            // This is a dynamically sized struct so we need to get the position of the last field to calculate the actual size.
1249            let Ok(new_len_without_nul_in_bytes): Result<u32, _> =
1250                ((new.count_bytes() - 1) * 2).try_into()
1251            else {
1252                return Err(err).io_result();
1253            };
1254            let offset: u32 = offset_of!(c::FILE_RENAME_INFO, FileName).try_into().unwrap();
1255            let struct_size = offset + new_len_without_nul_in_bytes + 2;
1256            let layout =
1257                Layout::from_size_align(struct_size as usize, align_of::<c::FILE_RENAME_INFO>())
1258                    .unwrap();
1259
1260            // SAFETY: We allocate enough memory for a full FILE_RENAME_INFO struct and a filename.
1261            let file_rename_info;
1262            unsafe {
1263                file_rename_info = alloc(layout).cast::<c::FILE_RENAME_INFO>();
1264                if file_rename_info.is_null() {
1265                    return Err(io::ErrorKind::OutOfMemory.into());
1266                }
1267
1268                (&raw mut (*file_rename_info).Anonymous).write(c::FILE_RENAME_INFO_0 {
1269                    Flags: c::FILE_RENAME_FLAG_REPLACE_IF_EXISTS
1270                        | c::FILE_RENAME_FLAG_POSIX_SEMANTICS,
1271                });
1272
1273                (&raw mut (*file_rename_info).RootDirectory).write(ptr::null_mut());
1274                // Don't include the NULL in the size
1275                (&raw mut (*file_rename_info).FileNameLength).write(new_len_without_nul_in_bytes);
1276
1277                new.as_ptr().copy_to_nonoverlapping(
1278                    (&raw mut (*file_rename_info).FileName).cast::<u16>(),
1279                    new.count_bytes(),
1280                );
1281            }
1282
1283            let result = unsafe {
1284                c::SetFileInformationByHandle(
1285                    f.as_raw_handle(),
1286                    c::FileRenameInfoEx,
1287                    file_rename_info.cast::<c_void>(),
1288                    struct_size,
1289                )
1290            };
1291            unsafe { dealloc(file_rename_info.cast::<u8>(), layout) };
1292            if result == 0 {
1293                if api::get_last_error() == WinError::DIR_NOT_EMPTY {
1294                    return Err(WinError::DIR_NOT_EMPTY).io_result();
1295                } else {
1296                    return Err(err).io_result();
1297                }
1298            }
1299        } else {
1300            return Err(err).io_result();
1301        }
1302    }
1303    Ok(())
1304}
1305
1306pub fn rmdir(p: &WCStr) -> io::Result<()> {
1307    cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) })?;
1308    Ok(())
1309}
1310
1311pub fn remove_dir_all(path: &WCStr) -> io::Result<()> {
1312    // Open a file or directory without following symlinks.
1313    let mut opts = OpenOptions::new();
1314    opts.access_mode(c::FILE_LIST_DIRECTORY);
1315    // `FILE_FLAG_BACKUP_SEMANTICS` allows opening directories.
1316    // `FILE_FLAG_OPEN_REPARSE_POINT` opens a link instead of its target.
1317    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
1318    let file = File::open_native(path, &opts)?;
1319
1320    // Test if the file is not a directory or a symlink to a directory.
1321    if (file.basic_info()?.FileAttributes & c::FILE_ATTRIBUTE_DIRECTORY) == 0 {
1322        return Err(io::Error::from_raw_os_error(c::ERROR_DIRECTORY as _));
1323    }
1324
1325    // Remove the directory and all its contents.
1326    remove_dir_all_iterative(file).io_result()
1327}
1328
1329pub fn readlink(path: &WCStr) -> io::Result<PathBuf> {
1330    // Open the link with no access mode, instead of generic read.
1331    // By default FILE_LIST_DIRECTORY is denied for the junction "C:\Documents and Settings", so
1332    // this is needed for a common case.
1333    let mut opts = OpenOptions::new();
1334    opts.access_mode(0);
1335    opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1336    let file = File::open_native(&path, &opts)?;
1337    file.readlink()
1338}
1339
1340pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1341    symlink_inner(original, link, false)
1342}
1343
1344pub fn symlink_inner(original: &Path, link: &Path, dir: bool) -> io::Result<()> {
1345    let original = to_u16s(original)?;
1346    let link = maybe_verbatim(link)?;
1347    let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 };
1348    // Formerly, symlink creation required the SeCreateSymbolicLink privilege. For the Windows 10
1349    // Creators Update, Microsoft loosened this to allow unprivileged symlink creation if the
1350    // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
1351    // added to dwFlags to opt into this behavior.
1352    let result = cvt(unsafe {
1353        c::CreateSymbolicLinkW(
1354            link.as_ptr(),
1355            original.as_ptr(),
1356            flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1357        ) as c::BOOL
1358    });
1359    if let Err(err) = result {
1360        if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
1361            // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
1362            // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
1363            cvt(unsafe {
1364                c::CreateSymbolicLinkW(link.as_ptr(), original.as_ptr(), flags) as c::BOOL
1365            })?;
1366        } else {
1367            return Err(err);
1368        }
1369    }
1370    Ok(())
1371}
1372
1373#[cfg(not(target_vendor = "uwp"))]
1374pub fn link(original: &WCStr, link: &WCStr) -> io::Result<()> {
1375    cvt(unsafe { c::CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null_mut()) })?;
1376    Ok(())
1377}
1378
1379#[cfg(target_vendor = "uwp")]
1380pub fn link(_original: &WCStr, _link: &WCStr) -> io::Result<()> {
1381    return Err(io::const_error!(io::ErrorKind::Unsupported, "hard link are not supported on UWP"));
1382}
1383
1384pub fn stat(path: &WCStr) -> io::Result<FileAttr> {
1385    match metadata(path, ReparsePoint::Follow) {
1386        Err(err) if err.raw_os_error() == Some(c::ERROR_CANT_ACCESS_FILE as i32) => {
1387            if let Ok(attrs) = lstat(path) {
1388                if !attrs.file_type().is_symlink() {
1389                    return Ok(attrs);
1390                }
1391            }
1392            Err(err)
1393        }
1394        result => result,
1395    }
1396}
1397
1398pub fn lstat(path: &WCStr) -> io::Result<FileAttr> {
1399    metadata(path, ReparsePoint::Open)
1400}
1401
1402#[repr(u32)]
1403#[derive(Clone, Copy, PartialEq, Eq)]
1404enum ReparsePoint {
1405    Follow = 0,
1406    Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
1407}
1408impl ReparsePoint {
1409    fn as_flag(self) -> u32 {
1410        self as u32
1411    }
1412}
1413
1414fn metadata(path: &WCStr, reparse: ReparsePoint) -> io::Result<FileAttr> {
1415    let mut opts = OpenOptions::new();
1416    // No read or write permissions are necessary
1417    opts.access_mode(0);
1418    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());
1419
1420    // Attempt to open the file normally.
1421    // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileExW`.
1422    // If the fallback fails for any reason we return the original error.
1423    match File::open_native(&path, &opts) {
1424        Ok(file) => file.file_attr(),
1425        Err(e)
1426            if [Some(c::ERROR_SHARING_VIOLATION as _), Some(c::ERROR_ACCESS_DENIED as _)]
1427                .contains(&e.raw_os_error()) =>
1428        {
1429            // `ERROR_ACCESS_DENIED` is returned when the user doesn't have permission for the resource.
1430            // One such example is `System Volume Information` as default but can be created as well
1431            // `ERROR_SHARING_VIOLATION` will almost never be returned.
1432            // Usually if a file is locked you can still read some metadata.
1433            // However, there are special system files, such as
1434            // `C:\hiberfil.sys`, that are locked in a way that denies even that.
1435            unsafe {
1436                // `FindFirstFileExW` accepts wildcard file names.
1437                // Fortunately wildcards are not valid file names and
1438                // `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
1439                // therefore it's safe to assume the file name given does not
1440                // include wildcards.
1441                let mut wfd: c::WIN32_FIND_DATAW = mem::zeroed();
1442                let handle = c::FindFirstFileExW(
1443                    path.as_ptr(),
1444                    c::FindExInfoBasic,
1445                    &mut wfd as *mut _ as _,
1446                    c::FindExSearchNameMatch,
1447                    ptr::null(),
1448                    0,
1449                );
1450
1451                if handle == c::INVALID_HANDLE_VALUE {
1452                    // This can fail if the user does not have read access to the
1453                    // directory.
1454                    Err(e)
1455                } else {
1456                    // We no longer need the find handle.
1457                    c::FindClose(handle);
1458
1459                    // `FindFirstFileExW` reads the cached file information from the
1460                    // directory. The downside is that this metadata may be outdated.
1461                    let attrs = FileAttr::from(wfd);
1462                    if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
1463                        Err(e)
1464                    } else {
1465                        Ok(attrs)
1466                    }
1467                }
1468            }
1469        }
1470        Err(e) => Err(e),
1471    }
1472}
1473
1474pub fn set_perm(p: &WCStr, perm: FilePermissions) -> io::Result<()> {
1475    unsafe {
1476        cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs))?;
1477        Ok(())
1478    }
1479}
1480
1481fn get_path(f: &File) -> io::Result<PathBuf> {
1482    fill_utf16_buf(
1483        |buf, sz| unsafe {
1484            c::GetFinalPathNameByHandleW(f.handle.as_raw_handle(), buf, sz, c::VOLUME_NAME_DOS)
1485        },
1486        |buf| PathBuf::from(OsString::from_wide(buf)),
1487    )
1488}
1489
1490pub fn canonicalize(p: &WCStr) -> io::Result<PathBuf> {
1491    let mut opts = OpenOptions::new();
1492    // No read or write permissions are necessary
1493    opts.access_mode(0);
1494    // This flag is so we can open directories too
1495    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1496    let f = File::open_native(p, &opts)?;
1497    get_path(&f)
1498}
1499
1500pub fn copy(from: &WCStr, to: &WCStr) -> io::Result<u64> {
1501    unsafe extern "system" fn callback(
1502        _TotalFileSize: i64,
1503        _TotalBytesTransferred: i64,
1504        _StreamSize: i64,
1505        StreamBytesTransferred: i64,
1506        dwStreamNumber: u32,
1507        _dwCallbackReason: u32,
1508        _hSourceFile: c::HANDLE,
1509        _hDestinationFile: c::HANDLE,
1510        lpData: *const c_void,
1511    ) -> u32 {
1512        unsafe {
1513            if dwStreamNumber == 1 {
1514                *(lpData as *mut i64) = StreamBytesTransferred;
1515            }
1516            c::PROGRESS_CONTINUE
1517        }
1518    }
1519    let mut size = 0i64;
1520    cvt(unsafe {
1521        c::CopyFileExW(
1522            from.as_ptr(),
1523            to.as_ptr(),
1524            Some(callback),
1525            (&raw mut size) as *mut _,
1526            ptr::null_mut(),
1527            0,
1528        )
1529    })?;
1530    Ok(size as u64)
1531}
1532
1533pub fn junction_point(original: &Path, link: &Path) -> io::Result<()> {
1534    // Create and open a new directory in one go.
1535    let mut opts = OpenOptions::new();
1536    opts.create_new(true);
1537    opts.write(true);
1538    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_POSIX_SEMANTICS);
1539    opts.attributes(c::FILE_ATTRIBUTE_DIRECTORY);
1540
1541    let d = File::open(link, &opts)?;
1542
1543    // We need to get an absolute, NT-style path.
1544    let path_bytes = original.as_os_str().as_encoded_bytes();
1545    let abs_path: Vec<u16> = if path_bytes.starts_with(br"\\?\") || path_bytes.starts_with(br"\??\")
1546    {
1547        // It's already an absolute path, we just need to convert the prefix to `\??\`
1548        let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&path_bytes[4..]) };
1549        r"\??\".encode_utf16().chain(bytes.encode_wide()).collect()
1550    } else {
1551        // Get an absolute path and then convert the prefix to `\??\`
1552        let abs_path = crate::path::absolute(original)?.into_os_string().into_encoded_bytes();
1553        if abs_path.len() > 0 && abs_path[1..].starts_with(br":\") {
1554            let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&abs_path) };
1555            r"\??\".encode_utf16().chain(bytes.encode_wide()).collect()
1556        } else if abs_path.starts_with(br"\\.\") {
1557            let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&abs_path[4..]) };
1558            r"\??\".encode_utf16().chain(bytes.encode_wide()).collect()
1559        } else if abs_path.starts_with(br"\\") {
1560            let bytes = unsafe { OsStr::from_encoded_bytes_unchecked(&abs_path[2..]) };
1561            r"\??\UNC\".encode_utf16().chain(bytes.encode_wide()).collect()
1562        } else {
1563            return Err(io::const_error!(io::ErrorKind::InvalidInput, "path is not valid"));
1564        }
1565    };
1566    // Defined inline so we don't have to mess about with variable length buffer.
1567    #[repr(C)]
1568    pub struct MountPointBuffer {
1569        ReparseTag: u32,
1570        ReparseDataLength: u16,
1571        Reserved: u16,
1572        SubstituteNameOffset: u16,
1573        SubstituteNameLength: u16,
1574        PrintNameOffset: u16,
1575        PrintNameLength: u16,
1576        PathBuffer: [MaybeUninit<u16>; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize],
1577    }
1578    let data_len = 12 + (abs_path.len() * 2);
1579    if data_len > u16::MAX as usize {
1580        return Err(io::const_error!(io::ErrorKind::InvalidInput, "`original` path is too long"));
1581    }
1582    let data_len = data_len as u16;
1583    let mut header = MountPointBuffer {
1584        ReparseTag: c::IO_REPARSE_TAG_MOUNT_POINT,
1585        ReparseDataLength: data_len,
1586        Reserved: 0,
1587        SubstituteNameOffset: 0,
1588        SubstituteNameLength: (abs_path.len() * 2) as u16,
1589        PrintNameOffset: ((abs_path.len() + 1) * 2) as u16,
1590        PrintNameLength: 0,
1591        PathBuffer: [MaybeUninit::uninit(); c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize],
1592    };
1593    unsafe {
1594        let ptr = header.PathBuffer.as_mut_ptr();
1595        ptr.copy_from(abs_path.as_ptr().cast::<MaybeUninit<u16>>(), abs_path.len());
1596
1597        let mut ret = 0;
1598        cvt(c::DeviceIoControl(
1599            d.as_raw_handle(),
1600            c::FSCTL_SET_REPARSE_POINT,
1601            (&raw const header).cast::<c_void>(),
1602            data_len as u32 + 8,
1603            ptr::null_mut(),
1604            0,
1605            &mut ret,
1606            ptr::null_mut(),
1607        ))
1608        .map(drop)
1609    }
1610}
1611
1612// Try to see if a file exists but, unlike `exists`, report I/O errors.
1613pub fn exists(path: &WCStr) -> io::Result<bool> {
1614    // Open the file to ensure any symlinks are followed to their target.
1615    let mut opts = OpenOptions::new();
1616    // No read, write, etc access rights are needed.
1617    opts.access_mode(0);
1618    // Backup semantics enables opening directories as well as files.
1619    opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
1620    match File::open_native(path, &opts) {
1621        Err(e) => match e.kind() {
1622            // The file definitely does not exist
1623            io::ErrorKind::NotFound => Ok(false),
1624
1625            // `ERROR_SHARING_VIOLATION` means that the file has been locked by
1626            // another process. This is often temporary so we simply report it
1627            // as the file existing.
1628            _ if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => Ok(true),
1629
1630            // `ERROR_CANT_ACCESS_FILE` means that a file exists but that the
1631            // reparse point could not be handled by `CreateFile`.
1632            // This can happen for special files such as:
1633            // * Unix domain sockets which you need to `connect` to
1634            // * App exec links which require using `CreateProcess`
1635            _ if e.raw_os_error() == Some(c::ERROR_CANT_ACCESS_FILE as i32) => Ok(true),
1636
1637            // Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
1638            // file exists. However, these types of errors are usually more
1639            // permanent so we report them here.
1640            _ => Err(e),
1641        },
1642        // The file was opened successfully therefore it must exist,
1643        Ok(_) => Ok(true),
1644    }
1645}