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