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