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