Skip to main content

miri/shims/windows/
fs.rs

1use std::io::{Seek, SeekFrom};
2use std::time::SystemTime;
3use std::{fs, io};
4
5use bitflags::bitflags;
6use rustc_abi::Size;
7use rustc_target::spec::Os;
8
9use crate::shims::files::{DirHandle, FileHandle, open_file_or_dir};
10use crate::shims::windows::handle::{EvalContextExt as _, Handle};
11use crate::*;
12
13#[derive(Copy, Clone, Debug, PartialEq)]
14enum CreationDisposition {
15    /// Truncates the file if it exists; create it if it is missing.
16    CreateAlways,
17    /// Fails if the file already exists; create it if it is missing.
18    CreateNew,
19    /// Create the file if it is missing.
20    OpenAlways,
21    /// Fail if the file is missing.
22    OpenExisting,
23    /// Truncates the file if it exists; fails if it is missing.
24    TruncateExisting,
25}
26
27impl CreationDisposition {
28    fn new<'tcx>(
29        value: u32,
30        ecx: &mut MiriInterpCx<'tcx>,
31    ) -> InterpResult<'tcx, CreationDisposition> {
32        let create_always = ecx.eval_windows_u32("c", "CREATE_ALWAYS");
33        let create_new = ecx.eval_windows_u32("c", "CREATE_NEW");
34        let open_always = ecx.eval_windows_u32("c", "OPEN_ALWAYS");
35        let open_existing = ecx.eval_windows_u32("c", "OPEN_EXISTING");
36        let truncate_existing = ecx.eval_windows_u32("c", "TRUNCATE_EXISTING");
37
38        let out = if value == create_always {
39            CreationDisposition::CreateAlways
40        } else if value == create_new {
41            CreationDisposition::CreateNew
42        } else if value == open_always {
43            CreationDisposition::OpenAlways
44        } else if value == open_existing {
45            CreationDisposition::OpenExisting
46        } else if value == truncate_existing {
47            CreationDisposition::TruncateExisting
48        } else {
49            throw_unsup_format!("CreateFileW: Unsupported creation disposition: {value}");
50        };
51        interp_ok(out)
52    }
53}
54
55bitflags! {
56    #[derive(PartialEq)]
57    struct FileAttributes: u32 {
58        const ZERO = 0;
59        const NORMAL = 1 << 0;
60        /// This must be passed to allow getting directory handles. If not passed, we error on trying
61        /// to open directories
62        const BACKUP_SEMANTICS = 1 << 1;
63        /// Open a reparse point as a regular file - this is basically similar to 'readlink' in Unix
64        /// terminology. A reparse point is a file with custom logic when navigated to, of which
65        /// a symlink is one specific example.
66        const OPEN_REPARSE = 1 << 2;
67    }
68}
69
70impl FileAttributes {
71    fn new<'tcx>(
72        mut value: u32,
73        ecx: &mut MiriInterpCx<'tcx>,
74    ) -> InterpResult<'tcx, FileAttributes> {
75        let file_attribute_normal = ecx.eval_windows_u32("c", "FILE_ATTRIBUTE_NORMAL");
76        let file_flag_backup_semantics = ecx.eval_windows_u32("c", "FILE_FLAG_BACKUP_SEMANTICS");
77        let file_flag_open_reparse_point =
78            ecx.eval_windows_u32("c", "FILE_FLAG_OPEN_REPARSE_POINT");
79
80        let mut out = FileAttributes::ZERO;
81        if value & file_flag_backup_semantics != 0 {
82            value &= !file_flag_backup_semantics;
83            out |= FileAttributes::BACKUP_SEMANTICS;
84        }
85        if value & file_flag_open_reparse_point != 0 {
86            value &= !file_flag_open_reparse_point;
87            out |= FileAttributes::OPEN_REPARSE;
88        }
89        if value & file_attribute_normal != 0 {
90            value &= !file_attribute_normal;
91            out |= FileAttributes::NORMAL;
92        }
93
94        if value != 0 {
95            throw_unsup_format!("CreateFileW: Unsupported flags_and_attributes: {value}");
96        }
97
98        if out == FileAttributes::ZERO {
99            // NORMAL is equivalent to 0. Avoid needing to check both cases by unifying the two.
100            out = FileAttributes::NORMAL;
101        }
102        interp_ok(out)
103    }
104}
105
106impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
107#[allow(non_snake_case)]
108pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
109    fn CreateFileW(
110        &mut self,
111        file_name: &OpTy<'tcx>,            // LPCWSTR
112        desired_access: &OpTy<'tcx>,       // DWORD
113        share_mode: &OpTy<'tcx>,           // DWORD
114        security_attributes: &OpTy<'tcx>,  // LPSECURITY_ATTRIBUTES
115        creation_disposition: &OpTy<'tcx>, // DWORD
116        flags_and_attributes: &OpTy<'tcx>, // DWORD
117        template_file: &OpTy<'tcx>,        // HANDLE
118    ) -> InterpResult<'tcx, Handle> {
119        // ^ Returns HANDLE
120        use CreationDisposition::*;
121
122        let ecx = self.eval_context_mut();
123        ecx.assert_target_os(Os::Windows, "CreateFileW");
124        ecx.check_no_isolation("`CreateFileW`")?;
125
126        // This function appears to always set the error to 0. This is important for some flag
127        // combinations, which may set error code on success.
128        ecx.set_last_error(IoError::Raw(Scalar::from_i32(0)))?;
129
130        let file_name = ecx.read_path_from_wide_str(ecx.read_pointer(file_name)?)?;
131        let mut desired_access = ecx.read_scalar(desired_access)?.to_u32()?;
132        let share_mode = ecx.read_scalar(share_mode)?.to_u32()?;
133        let security_attributes = ecx.read_pointer(security_attributes)?;
134        let creation_disposition = ecx.read_scalar(creation_disposition)?.to_u32()?;
135        let flags_and_attributes = ecx.read_scalar(flags_and_attributes)?.to_u32()?;
136        let template_file = ecx.read_target_usize(template_file)?;
137
138        let generic_read = ecx.eval_windows_u32("c", "GENERIC_READ");
139        let generic_write = ecx.eval_windows_u32("c", "GENERIC_WRITE");
140
141        let file_share_delete = ecx.eval_windows_u32("c", "FILE_SHARE_DELETE");
142        let file_share_read = ecx.eval_windows_u32("c", "FILE_SHARE_READ");
143        let file_share_write = ecx.eval_windows_u32("c", "FILE_SHARE_WRITE");
144
145        let creation_disposition = CreationDisposition::new(creation_disposition, ecx)?;
146        let attributes = FileAttributes::new(flags_and_attributes, ecx)?;
147
148        if share_mode != (file_share_delete | file_share_read | file_share_write) {
149            throw_unsup_format!("CreateFileW: Unsupported share mode: {share_mode}");
150        }
151        if !ecx.ptr_is_null(security_attributes)? {
152            throw_unsup_format!("CreateFileW: Security attributes are not supported");
153        }
154        if template_file != 0 {
155            throw_unsup_format!("CreateFileW: Template files are not supported");
156        }
157
158        // Parse desired_access
159        let mut desired_read = false;
160        if desired_access & generic_read != 0 {
161            desired_read = true;
162            desired_access &= !generic_read;
163        }
164        let mut desired_write = false;
165        if desired_access & generic_write != 0 {
166            desired_write = true;
167            desired_access &= !generic_write;
168        }
169
170        if desired_access != 0 {
171            throw_unsup_format!(
172                "CreateFileW: Unsupported bits set for access mode: {desired_access:#x}"
173            );
174        }
175
176        // Attribute validation.
177        if attributes.contains(FileAttributes::OPEN_REPARSE) != (creation_disposition == CreateNew)
178        {
179            // For CreateNew, the effect of OPEN_REPARSE is to avoid creating a file wherever
180            // a dangling symlink points to. That's always how `OpenOptions::create_new` behaves
181            // so we cannot even support anything else.
182            // But for all other creation dispositions we'd have to do actual work, so reject those.
183            throw_unsup_format!(
184                "CreateFileW: FILE_FLAG_OPEN_REPARSE_POINT must be set if and only if CREATE_NEW is set"
185            );
186        }
187        if attributes.contains(FileAttributes::BACKUP_SEMANTICS)
188            && creation_disposition != OpenExisting
189        {
190            throw_unsup_format!(
191                "CreateFileW: FILE_FLAG_BACKUP_SEMANTICS is only supported with OPEN_EXISTING"
192            );
193        }
194        if attributes.contains(FileAttributes::BACKUP_SEMANTICS) && desired_write {
195            throw_unsup_format!(
196                "CreateFileW: FILE_FLAG_BACKUP_SEMANTICS is not supported with GENERIC_WRITE"
197            );
198        }
199
200        // We start a retry loop to deal with the `exists_already` race, see below.
201        // We add a retry counter to avoid infinite loops when things go wrong.
202        let mut counter = 0u32;
203        loop {
204            if counter >= 100 {
205                panic!(
206                    "CreateFileW seems stuck in an infinite retry loop. \
207                    If you can reproduce this, please file a bug."
208                );
209            }
210            counter = counter.strict_add(1);
211
212            // Per the documentation:
213            // If the specified file exists and is writable, the function truncates the file,
214            // the function succeeds, and last-error code is set to ERROR_ALREADY_EXISTS.
215            // If the specified file does not exist and is a valid path, a new file is created,
216            // the function succeeds, and the last-error code is set to zero.
217            // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
218            //
219            // We check whether it exists before trying to open it. This is racy, but there
220            // doesn't appear to be an std API that both succeeds whether or not a file already
221            // exists and tells us whether it is new. So instead we will open the file in a way
222            // that we can verify whether our guess is correct, and retry if it is not.
223            let exists_already = file_name.exists();
224
225            // Compute the OpenOptions.
226            let mut options = fs::OpenOptions::new();
227            options.read(desired_read);
228            options.write(desired_write);
229            match creation_disposition {
230                CreateAlways | OpenAlways => {
231                    // These two create the file if it is missing, but also succeed if it
232                    // already exists. As explained above we cannot just always set `create_new`
233                    // here, so we only do that if we think it is needed.
234                    // We later verify our `exists_already` guess: if we expect it to already
235                    // exist, we set no flag, thus failing if it doesn't exist. If we expect the
236                    // file to not exist, we use `create_new` to fail if it does exist.
237                    if !exists_already {
238                        options.create_new(true);
239                        // Per `create_new` documentation:
240                        // The file must be opened with write or append access in order to create a new file.
241                        // https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new
242                        // So we open it for writing anyway, to make creating the file work. Write
243                        // accesses will still be rejected because `writable` is not set on the
244                        // `FileHandle`.
245                        options.write(true);
246                    }
247                    if creation_disposition == CreateAlways {
248                        options.truncate(true);
249                    }
250                }
251                CreateNew => {
252                    options.create_new(true);
253                    // See above for why we need to also request write access.
254                    options.write(true);
255                }
256                OpenExisting => {
257                    if !desired_read && !desired_write {
258                        // Windows supports handles with no permissions. These allow things such as
259                        // reading metadata, but not file content. This is used by `Path::metadata`.
260                        // `std` does not support this. To ensure we behave correctly as often as
261                        // possible, we open the file for reading and live with the fact that this
262                        // might incorrectly return `PermissionDenied`.
263                        // FIXME: We could probably use `OpenOptionsExt`? On a Unix host,
264                        // `O_PATH` apparently can open files for metadata use only.
265                        options.read(true);
266                    }
267                }
268                TruncateExisting => {
269                    options.truncate(true);
270                }
271            }
272
273            // Let's see what we get when we open this!
274            return match open_file_or_dir(None, &file_name, &options) {
275                Err(err) => {
276                    let kind = err.kind();
277                    if exists_already && kind == io::ErrorKind::NotFound {
278                        // The file disappeared. Retry.
279                        continue;
280                    }
281                    if !exists_already && kind == io::ErrorKind::AlreadyExists {
282                        // The file got created by something else. Retry.
283                        continue;
284                    }
285
286                    if kind == io::ErrorKind::IsADirectory && desired_write {
287                        // This can happen on Unix hosts when write permissions are requested.
288                        // Windows uses a different error code in that case.
289                        ecx.set_last_error(IoError::WindowsError("ERROR_ACCESS_DENIED"))?;
290                    } else {
291                        ecx.set_last_error(err)?;
292                    }
293                    return interp_ok(Handle::Invalid);
294                }
295                Ok((Either::Right(dir), _file_type)) => {
296                    // BACKUP_SEMANTICS is how Windows calls the act of opening a directory handle.
297                    if !attributes.contains(FileAttributes::BACKUP_SEMANTICS) {
298                        ecx.set_last_error(IoError::WindowsError("ERROR_ACCESS_DENIED"))?;
299                        return interp_ok(Handle::Invalid);
300                    }
301                    // We excluded this above.
302                    if matches!(creation_disposition, CreateAlways | OpenAlways) {
303                        unreachable!()
304                    }
305
306                    let Some(fd_num) = ecx.machine.fds.insert_new(DirHandle { dir }) else {
307                        throw_unsup_format!("we ran out of FD numbers")
308                    };
309                    interp_ok(Handle::File(fd_num))
310                }
311                Ok((Either::Left(file), file_type)) => {
312                    // CreateAlways | OpenAlways update the status code even on success.
313                    if matches!(creation_disposition, CreateAlways | OpenAlways) && exists_already {
314                        ecx.set_last_error(IoError::WindowsError("ERROR_ALREADY_EXISTS"))?;
315                    }
316
317                    let Some(fd_num) = ecx.machine.fds.insert_new(FileHandle {
318                        file,
319                        file_type,
320                        writable: desired_write,
321                        readable: desired_read,
322                        append: false,
323                    }) else {
324                        throw_unsup_format!("we ran out of FD numbers")
325                    };
326                    interp_ok(Handle::File(fd_num))
327                }
328            };
329        }
330    }
331
332    fn GetFileInformationByHandle(
333        &mut self,
334        file: &OpTy<'tcx>,             // HANDLE
335        file_information: &OpTy<'tcx>, // LPBY_HANDLE_FILE_INFORMATION
336    ) -> InterpResult<'tcx, Scalar> {
337        // ^ Returns BOOL (i32 on Windows)
338        let ecx = self.eval_context_mut();
339        ecx.assert_target_os(Os::Windows, "GetFileInformationByHandle");
340        ecx.check_no_isolation("`GetFileInformationByHandle`")?;
341
342        let file = ecx.read_handle(file, "GetFileInformationByHandle")?;
343        let file_information = ecx.deref_pointer(file_information)?;
344
345        let Handle::File(fd_num) = file else { ecx.invalid_handle("GetFileInformationByHandle")? };
346
347        let Some(desc) = ecx.machine.fds.get(fd_num) else {
348            ecx.invalid_handle("GetFileInformationByHandle")?
349        };
350
351        let metadata = match desc.metadata(ecx.machine.communicate())? {
352            Either::Left(Ok(meta)) => meta,
353            Either::Left(Err(e)) => {
354                ecx.set_last_error(e)?;
355                return interp_ok(ecx.eval_windows("c", "FALSE"));
356            }
357            Either::Right(_mode) =>
358                throw_unsup_format!(
359                    "`GetFileInformationByHandle` is not supported on non-file-backed handles"
360                ),
361        };
362
363        let size = metadata.len();
364
365        let file_type = metadata.file_type();
366        let attributes = if file_type.is_dir() {
367            ecx.eval_windows_u32("c", "FILE_ATTRIBUTE_DIRECTORY")
368        } else if file_type.is_file() {
369            // Normal files seem to have the "archive" attribute. There's also
370            // `FILE_ATTRIBUTE_NORMAL` but that's for files without any other attribute which,
371            // apparently, is not normal.
372            ecx.eval_windows_u32("c", "FILE_ATTRIBUTE_ARCHIVE")
373        } else {
374            ecx.eval_windows_u32("c", "FILE_ATTRIBUTE_DEVICE")
375        };
376
377        // Per the Windows documentation:
378        // "If the underlying file system does not support the [...] time, this member is zero (0)."
379        // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/ns-fileapi-by_handle_file_information
380        let created = extract_windows_epoch(ecx, metadata.created())?.unwrap_or((0, 0));
381        let accessed = extract_windows_epoch(ecx, metadata.accessed())?.unwrap_or((0, 0));
382        let written = extract_windows_epoch(ecx, metadata.modified())?.unwrap_or((0, 0));
383
384        ecx.write_int_fields_named(&[("dwFileAttributes", attributes.into())], &file_information)?;
385        write_filetime_field(ecx, &file_information, "ftCreationTime", created)?;
386        write_filetime_field(ecx, &file_information, "ftLastAccessTime", accessed)?;
387        write_filetime_field(ecx, &file_information, "ftLastWriteTime", written)?;
388        ecx.write_int_fields_named(
389            &[
390                ("dwVolumeSerialNumber", 0),
391                ("nFileSizeHigh", (size >> 32).into()),
392                ("nFileSizeLow", (size & 0xFFFFFFFF).into()),
393                ("nNumberOfLinks", 1),
394                ("nFileIndexHigh", 0),
395                ("nFileIndexLow", 0),
396            ],
397            &file_information,
398        )?;
399
400        interp_ok(ecx.eval_windows("c", "TRUE"))
401    }
402
403    fn SetFileInformationByHandle(
404        &mut self,
405        file: &OpTy<'tcx>,             // HANDLE
406        class: &OpTy<'tcx>,            // FILE_INFO_BY_HANDLE_CLASS
407        file_information: &OpTy<'tcx>, // LPVOID
408        buffer_size: &OpTy<'tcx>,      // DWORD
409    ) -> InterpResult<'tcx, Scalar> {
410        // ^ Returns BOOL (i32 on Windows)
411        let ecx = self.eval_context_mut();
412        ecx.assert_target_os(Os::Windows, "SetFileInformationByHandle");
413        ecx.check_no_isolation("`SetFileInformationByHandle`")?;
414
415        let class = ecx.read_scalar(class)?.to_u32()?;
416        let buffer_size = ecx.read_scalar(buffer_size)?.to_u32()?;
417        let file_information = ecx.read_pointer(file_information)?;
418        ecx.check_ptr_access(
419            file_information,
420            Size::from_bytes(buffer_size),
421            CheckInAllocMsg::MemoryAccess,
422        )?;
423
424        let file = ecx.read_handle(file, "SetFileInformationByHandle")?;
425        let Handle::File(fd_num) = file else { ecx.invalid_handle("SetFileInformationByHandle")? };
426        let Some(desc) = ecx.machine.fds.get(fd_num) else {
427            ecx.invalid_handle("SetFileInformationByHandle")?
428        };
429        let file = desc.downcast::<FileHandle>().ok_or_else(|| {
430            err_unsup_format!(
431                "`SetFileInformationByHandle` is only supported on file-backed file descriptors"
432            )
433        })?;
434
435        if class == ecx.eval_windows_u32("c", "FileEndOfFileInfo") {
436            let place =
437                ecx.ptr_to_mplace(file_information, ecx.windows_ty_layout("FILE_END_OF_FILE_INFO"));
438            let new_len =
439                ecx.read_scalar(&ecx.project_field_named(&place, "EndOfFile")?)?.to_i64()?;
440            match file.file.set_len(new_len.try_into().unwrap()) {
441                Ok(_) => interp_ok(ecx.eval_windows("c", "TRUE")),
442                Err(e) => {
443                    ecx.set_last_error(e)?;
444                    interp_ok(ecx.eval_windows("c", "FALSE"))
445                }
446            }
447        } else if class == ecx.eval_windows_u32("c", "FileAllocationInfo") {
448            // On Windows, files are somewhat similar to a `Vec` in that they have a separate
449            // "length" (called "EOF position") and "capacity" (called "allocation size").
450            // Growing the allocation size is largely a performance hint which we can
451            // ignore -- it can also be directly queried, but we currently do not support that.
452            // (Linux has something equivalent, `fallocate` with `FALLOC_FL_KEEP_SIZE`, but std does
453            // not expose it so we cannot easily use it.)
454            // So we only need to do something if this operation shrinks the allocation size
455            // so far that it affects the EOF position.
456            let place =
457                ecx.ptr_to_mplace(file_information, ecx.windows_ty_layout("FILE_ALLOCATION_INFO"));
458            let new_alloc_size: u64 = ecx
459                .read_scalar(&ecx.project_field_named(&place, "AllocationSize")?)?
460                .to_i64()?
461                .try_into()
462                .unwrap();
463            let old_len = match (&file.file).stream_len() {
464                Ok(l) => l,
465                Err(e) => {
466                    ecx.set_last_error(e)?;
467                    return interp_ok(ecx.eval_windows("c", "FALSE"));
468                }
469            };
470            if new_alloc_size < old_len {
471                match file.file.set_len(new_alloc_size) {
472                    Ok(_) => interp_ok(ecx.eval_windows("c", "TRUE")),
473                    Err(e) => {
474                        ecx.set_last_error(e)?;
475                        interp_ok(ecx.eval_windows("c", "FALSE"))
476                    }
477                }
478            } else {
479                interp_ok(ecx.eval_windows("c", "TRUE"))
480            }
481        } else {
482            throw_unsup_format!(
483                "SetFileInformationByHandle: Unsupported `FileInformationClass` value {}",
484                class
485            )
486        }
487    }
488
489    fn FlushFileBuffers(
490        &mut self,
491        file: &OpTy<'tcx>, // HANDLE
492    ) -> InterpResult<'tcx, Scalar> {
493        // ^ returns BOOL (i32 on Windows)
494        let ecx = self.eval_context_mut();
495        ecx.assert_target_os(Os::Windows, "FlushFileBuffers");
496
497        let file = ecx.read_handle(file, "FlushFileBuffers")?;
498        let Handle::File(fd_num) = file else { ecx.invalid_handle("FlushFileBuffers")? };
499        let Some(desc) = ecx.machine.fds.get(fd_num) else {
500            ecx.invalid_handle("FlushFileBuffers")?
501        };
502        let file = desc.downcast::<FileHandle>().ok_or_else(|| {
503            err_unsup_format!(
504                "`FlushFileBuffers` is only supported on file-backed file descriptors"
505            )
506        })?;
507
508        if !file.writable {
509            ecx.set_last_error(IoError::WindowsError("ERROR_ACCESS_DENIED"))?;
510            return interp_ok(ecx.eval_windows("c", "FALSE"));
511        }
512
513        match file.file.sync_all() {
514            Ok(_) => interp_ok(ecx.eval_windows("c", "TRUE")),
515            Err(e) => {
516                ecx.set_last_error(e)?;
517                interp_ok(ecx.eval_windows("c", "FALSE"))
518            }
519        }
520    }
521
522    fn MoveFileExW(
523        &mut self,
524        existing_name: &OpTy<'tcx>,
525        new_name: &OpTy<'tcx>,
526        flags: &OpTy<'tcx>,
527    ) -> InterpResult<'tcx, Scalar> {
528        let ecx = self.eval_context_mut();
529
530        let existing_name = ecx.read_path_from_wide_str(ecx.read_pointer(existing_name)?)?;
531        let new_name = ecx.read_path_from_wide_str(ecx.read_pointer(new_name)?)?;
532
533        let flags = ecx.read_scalar(flags)?.to_u32()?;
534
535        // Flag to indicate whether we should replace an existing file.
536        // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw
537        let movefile_replace_existing = ecx.eval_windows_u32("c", "MOVEFILE_REPLACE_EXISTING");
538
539        if flags != movefile_replace_existing {
540            throw_unsup_format!("MoveFileExW: Unsupported `dwFlags` value {}", flags);
541        }
542
543        match std::fs::rename(existing_name, new_name) {
544            Ok(_) => interp_ok(ecx.eval_windows("c", "TRUE")),
545            Err(e) => {
546                ecx.set_last_error(e)?;
547                interp_ok(ecx.eval_windows("c", "FALSE"))
548            }
549        }
550    }
551
552    fn DeleteFileW(
553        &mut self,
554        file_name: &OpTy<'tcx>, // LPCWSTR
555    ) -> InterpResult<'tcx, Scalar> {
556        // ^ Returns BOOL (i32 on Windows)
557        let ecx = self.eval_context_mut();
558        ecx.assert_target_os(Os::Windows, "DeleteFileW");
559        ecx.check_no_isolation("`DeleteFileW`")?;
560
561        let file_name = ecx.read_path_from_wide_str(ecx.read_pointer(file_name)?)?;
562        match std::fs::remove_file(file_name) {
563            Ok(_) => interp_ok(ecx.eval_windows("c", "TRUE")),
564            Err(e) => {
565                ecx.set_last_error(e)?;
566                interp_ok(ecx.eval_windows("c", "FALSE"))
567            }
568        }
569    }
570
571    fn NtWriteFile(
572        &mut self,
573        handle: &OpTy<'tcx>,          // HANDLE
574        event: &OpTy<'tcx>,           // HANDLE
575        apc_routine: &OpTy<'tcx>,     // PIO_APC_ROUTINE
576        apc_ctx: &OpTy<'tcx>,         // PVOID
577        io_status_block: &OpTy<'tcx>, // PIO_STATUS_BLOCK
578        buf: &OpTy<'tcx>,             // PVOID
579        n: &OpTy<'tcx>,               // ULONG
580        byte_offset: &OpTy<'tcx>,     // PLARGE_INTEGER
581        key: &OpTy<'tcx>,             // PULONG
582        dest: &MPlaceTy<'tcx>,        // return type: NTSTATUS
583    ) -> InterpResult<'tcx, ()> {
584        let ecx = self.eval_context_mut();
585
586        let handle = ecx.read_handle(handle, "NtWriteFile")?;
587        let event = ecx.read_handle(event, "NtWriteFile")?;
588        let apc_routine = ecx.read_pointer(apc_routine)?;
589        let apc_ctx = ecx.read_pointer(apc_ctx)?;
590        let buf = ecx.read_pointer(buf)?;
591        let count = ecx.read_scalar(n)?.to_u32()?;
592        let byte_offset = ecx.read_target_usize(byte_offset)?; // is actually a pointer, but we only support null
593        let key = ecx.read_pointer(key)?;
594        let io_status_block = ecx.deref_pointer(io_status_block)?;
595
596        if event != Handle::Null {
597            throw_unsup_format!(
598                "`NtWriteFile` `Event` parameter is non-null, which is unsupported"
599            );
600        }
601
602        if !ecx.ptr_is_null(apc_routine)? {
603            throw_unsup_format!(
604                "`NtWriteFile` `ApcRoutine` parameter is non-null, which is unsupported"
605            );
606        }
607
608        if !ecx.ptr_is_null(apc_ctx)? {
609            throw_unsup_format!(
610                "`NtWriteFile` `ApcContext` parameter is non-null, which is unsupported"
611            );
612        }
613
614        if byte_offset != 0 {
615            throw_unsup_format!(
616                "`NtWriteFile` `ByteOffset` parameter is non-null, which is unsupported"
617            );
618        }
619
620        if !ecx.ptr_is_null(key)? {
621            throw_unsup_format!("`NtWriteFile` `Key` parameter is non-null, which is unsupported");
622        }
623
624        let Handle::File(fd) = handle else { ecx.invalid_handle("NtWriteFile")? };
625
626        let Some(desc) = ecx.machine.fds.get(fd) else { ecx.invalid_handle("NtWriteFile")? };
627
628        // Windows writes the output code to IO_STATUS_BLOCK.Status, and number of bytes written
629        // to IO_STATUS_BLOCK.Information.
630        // The status block value and the returned value don't need to match - but
631        // for the cases implemented by miri so far, we can choose to decide that they do.
632        let io_status = {
633            let anon = ecx.project_field_named(&io_status_block, "Anonymous")?;
634            ecx.project_field_named(&anon, "Status")?
635        };
636        let io_status_info = ecx.project_field_named(&io_status_block, "Information")?;
637
638        // It seems like short writes are not a thing on Windows, so we don't truncate `count` here.
639        // FIXME: if we are on a Unix host, short host writes are still visible to the program!
640
641        let finish = {
642            let io_status = io_status.clone();
643            let io_status_info = io_status_info.clone();
644            let dest = dest.clone();
645            callback!(
646                @capture<'tcx> {
647                    count: u32,
648                    io_status: MPlaceTy<'tcx>,
649                    io_status_info: MPlaceTy<'tcx>,
650                    dest: MPlaceTy<'tcx>,
651                }
652                |ecx, result: Result<u64, IoError>| {
653                    match result {
654                        Ok(read_size) => {
655                            assert!(read_size <= count.into());
656                            // This must fit since `count` fits.
657                            ecx.write_int(read_size, &io_status_info)?;
658                            ecx.write_int(0, &io_status)?;
659                            ecx.write_int(0, &dest)
660                        }
661                        Err(e) => {
662                            // Native testing indicates that `io_status_block` is not written here.
663                            let status = e.into_ntstatus();
664                            ecx.write_int(status, &dest)
665                        }
666                }}
667            )
668        };
669        desc.write(ecx.machine.communicate(), buf, count.into(), ecx, finish)?;
670
671        // Return status is written to `dest` and `io_status_block` on callback completion.
672        interp_ok(())
673    }
674
675    fn NtReadFile(
676        &mut self,
677        handle: &OpTy<'tcx>,          // HANDLE
678        event: &OpTy<'tcx>,           // HANDLE
679        apc_routine: &OpTy<'tcx>,     // PIO_APC_ROUTINE
680        apc_ctx: &OpTy<'tcx>,         // PVOID
681        io_status_block: &OpTy<'tcx>, // PIO_STATUS_BLOCK
682        buf: &OpTy<'tcx>,             // PVOID
683        n: &OpTy<'tcx>,               // ULONG
684        byte_offset: &OpTy<'tcx>,     // PLARGE_INTEGER
685        key: &OpTy<'tcx>,             // PULONG
686        dest: &MPlaceTy<'tcx>,        // return type: NTSTATUS
687    ) -> InterpResult<'tcx, ()> {
688        let ecx = self.eval_context_mut();
689
690        let handle = ecx.read_handle(handle, "NtReadFile")?;
691        let event = ecx.read_handle(event, "NtReadFile")?;
692        let apc_routine = ecx.read_pointer(apc_routine)?;
693        let apc_ctx = ecx.read_pointer(apc_ctx)?;
694        let buf = ecx.read_pointer(buf)?;
695        let count = ecx.read_scalar(n)?.to_u32()?;
696        let byte_offset = ecx.read_target_usize(byte_offset)?; // is actually a pointer, but we only support null
697        let key = ecx.read_pointer(key)?;
698        let io_status_block = ecx.deref_pointer(io_status_block)?;
699
700        if event != Handle::Null {
701            throw_unsup_format!("`NtReadFile` `Event` parameter is non-null, which is unsupported");
702        }
703
704        if !ecx.ptr_is_null(apc_routine)? {
705            throw_unsup_format!(
706                "`NtReadFile` `ApcRoutine` parameter is non-null, which is unsupported"
707            );
708        }
709
710        if !ecx.ptr_is_null(apc_ctx)? {
711            throw_unsup_format!(
712                "`NtReadFile` `ApcContext` parameter is non-null, which is unsupported"
713            );
714        }
715
716        if byte_offset != 0 {
717            throw_unsup_format!(
718                "`NtReadFile` `ByteOffset` parameter is non-null, which is unsupported"
719            );
720        }
721
722        if !ecx.ptr_is_null(key)? {
723            throw_unsup_format!("`NtReadFile` `Key` parameter is non-null, which is unsupported");
724        }
725
726        // See NtWriteFile above for commentary on this
727        let io_status = {
728            let anon = ecx.project_field_named(&io_status_block, "Anonymous")?;
729            ecx.project_field_named(&anon, "Status")?
730        };
731        let io_status_info = ecx.project_field_named(&io_status_block, "Information")?;
732
733        let Handle::File(fd) = handle else { ecx.invalid_handle("NtWriteFile")? };
734
735        let Some(desc) = ecx.machine.fds.get(fd) else { ecx.invalid_handle("NtReadFile")? };
736
737        // It seems like short reads are not a thing on Windows, so we don't truncate `count` here.
738        // FIXME: if we are on a Unix host, short host reads are still visible to the program!
739
740        let finish = {
741            let io_status = io_status.clone();
742            let io_status_info = io_status_info.clone();
743            let dest = dest.clone();
744            callback!(
745                @capture<'tcx> {
746                    count: u32,
747                    io_status: MPlaceTy<'tcx>,
748                    io_status_info: MPlaceTy<'tcx>,
749                    dest: MPlaceTy<'tcx>,
750                }
751                |ecx, result: Result<u64, IoError>| {
752                    match result {
753                        Ok(read_size) => {
754                            assert!(read_size <= count.into());
755                            // This must fit since `count` fits.
756                            ecx.write_int(read_size, &io_status_info)?;
757                            ecx.write_int(0, &io_status)?;
758                            ecx.write_int(0, &dest)
759                        }
760                        Err(e) => {
761                            // Native testing indicates that `io_status_block` is not written here.
762                            let status = e.into_ntstatus();
763                            ecx.write_int(status, &dest)
764                        }
765                }}
766            )
767        };
768        desc.read(ecx.machine.communicate(), buf, count.into(), ecx, finish)?;
769
770        // See NtWriteFile for commentary on this
771        interp_ok(())
772    }
773
774    fn SetFilePointerEx(
775        &mut self,
776        file: &OpTy<'tcx>,         // HANDLE
777        dist_to_move: &OpTy<'tcx>, // LARGE_INTEGER
778        new_fp: &OpTy<'tcx>,       // PLARGE_INTEGER
779        move_method: &OpTy<'tcx>,  // DWORD
780    ) -> InterpResult<'tcx, Scalar> {
781        // ^ Returns BOOL (i32 on Windows)
782        let ecx = self.eval_context_mut();
783
784        let file = ecx.read_handle(file, "SetFilePointerEx")?;
785        let dist_to_move = ecx.read_scalar(dist_to_move)?.to_i64()?;
786        let new_fp_ptr = ecx.read_pointer(new_fp)?;
787        let move_method = ecx.read_scalar(move_method)?.to_u32()?;
788
789        let Handle::File(fd) = file else { ecx.invalid_handle("SetFilePointerEx")? };
790
791        let Some(desc) = ecx.machine.fds.get(fd) else {
792            throw_unsup_format!("`SetFilePointerEx` is only supported on file backed handles");
793        };
794
795        let file_begin = ecx.eval_windows_u32("c", "FILE_BEGIN");
796        let file_current = ecx.eval_windows_u32("c", "FILE_CURRENT");
797        let file_end = ecx.eval_windows_u32("c", "FILE_END");
798
799        let seek = if move_method == file_begin {
800            SeekFrom::Start(dist_to_move.try_into().unwrap())
801        } else if move_method == file_current {
802            SeekFrom::Current(dist_to_move)
803        } else if move_method == file_end {
804            SeekFrom::End(dist_to_move)
805        } else {
806            throw_unsup_format!("Invalid move method: {move_method}")
807        };
808
809        match desc.seek(ecx.machine.communicate(), seek)? {
810            Ok(n) => {
811                if !ecx.ptr_is_null(new_fp_ptr)? {
812                    ecx.write_scalar(
813                        Scalar::from_i64(n.try_into().unwrap()),
814                        &ecx.deref_pointer(new_fp)?,
815                    )?;
816                }
817                interp_ok(ecx.eval_windows("c", "TRUE"))
818            }
819            Err(e) => {
820                ecx.set_last_error(e)?;
821                interp_ok(ecx.eval_windows("c", "FALSE"))
822            }
823        }
824    }
825}
826
827/// Windows FILETIME is measured in 100-nanosecs since 1601
828fn extract_windows_epoch<'tcx>(
829    ecx: &MiriInterpCx<'tcx>,
830    time: io::Result<SystemTime>,
831) -> InterpResult<'tcx, Option<(u32, u32)>> {
832    match time.ok() {
833        Some(time) => {
834            let duration = ecx.system_time_since_windows_epoch(&time)?;
835            let duration_ticks = ecx.windows_ticks_for(duration)?;
836            #[expect(clippy::as_conversions)]
837            interp_ok(Some((duration_ticks as u32, (duration_ticks >> 32) as u32)))
838        }
839        None => interp_ok(None),
840    }
841}
842
843fn write_filetime_field<'tcx>(
844    cx: &mut MiriInterpCx<'tcx>,
845    val: &MPlaceTy<'tcx>,
846    name: &str,
847    (low, high): (u32, u32),
848) -> InterpResult<'tcx> {
849    cx.write_int_fields_named(
850        &[("dwLowDateTime", low.into()), ("dwHighDateTime", high.into())],
851        &cx.project_field_named(val, name)?,
852    )
853}