Skip to main content

miri/shims/unix/
fs.rs

1//! File and file system access
2
3use std::borrow::Cow;
4use std::ffi::OsString;
5use std::fs::{self, DirBuilder, File, FileTimes, OpenOptions, TryLockError};
6use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write};
7use std::path::{self, Path};
8use std::time::SystemTime;
9
10use rand::RngExt;
11use rustc_abi::Size;
12use rustc_data_structures::either::Either;
13use rustc_data_structures::fx::FxHashMap;
14use rustc_target::spec::Os;
15
16use self::shims::time::system_time_to_duration;
17use crate::shims::files::{
18    BIG_ACCESS, DirHandle, DynFileDescriptionRef, EvalContextExt as _, FdNum, FileHandle,
19    open_file_or_dir,
20};
21use crate::shims::os_str::{PathConversion, bytes_to_os_str};
22use crate::shims::sig::Varargs;
23use crate::shims::unix::fd::{EvalContextExt as _, FlockOp, UnixFileDescription};
24use crate::shims::{FdId, FileDescription};
25use crate::*;
26
27/// An open directory stream (`DIR`), tracked by DirTable.
28#[derive(Debug)]
29struct DirStream {
30    /// The directory stream on the host.
31    read_dir: fs::ReadDir,
32    /// Unix directory streams have an "underlying FD" that can be exposed; this is that FD. This is
33    /// not a reference; it *can* be separately closed, leading to UB if the DIR is used again. We
34    /// also store the FD ID to catch cases where the FD was closed and a different one re-opened.
35    fd_num: FdNum,
36    fd_id: FdId,
37    /// The "special" entries that must still be yielded by the iterator.
38    /// Used for `.` and `..`.
39    special_entries: Vec<&'static str>,
40    /// The most recent entry returned by readdir(). Will be freed by the next call.
41    /// The string is the type used to allocate it.
42    entry: Option<(Pointer, &'static str)>,
43}
44
45impl DirStream {
46    fn new(read_dir: fs::ReadDir, fd_num: FdNum, fd_id: FdId) -> Self {
47        Self { read_dir, fd_num, fd_id, special_entries: vec!["..", "."], entry: None }
48    }
49
50    fn next_host_entry(&mut self) -> Option<io::Result<Either<fs::DirEntry, &'static str>>> {
51        if let Some(special) = self.special_entries.pop() {
52            return Some(Ok(Either::Right(special)));
53        }
54        let entry = self.read_dir.next()?;
55        Some(entry.map(Either::Left))
56    }
57}
58
59#[derive(Debug)]
60struct DirEntry {
61    name: OsString,
62    ino: u64,
63    d_type: i32,
64}
65
66/// What a `futimens` `timespec` asks for: leave the timestamp alone (`UTIME_OMIT`) or set it.
67#[derive(Copy, Clone)]
68enum TimeUpdate {
69    Omit,
70    Set(SystemTime),
71}
72
73impl UnixFileDescription for FileHandle {
74    fn pread<'tcx>(
75        &self,
76        communicate_allowed: bool,
77        ptr: Pointer,
78        len: u64,
79        offset: u64,
80        ecx: &mut MiriInterpCx<'tcx>,
81        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
82    ) -> InterpResult<'tcx> {
83        assert!(communicate_allowed, "isolation should have prevented even opening a file");
84        if !self.readable {
85            return finish.call(ecx, Err(LibcError("EBADF")));
86        }
87
88        let file = &mut &self.file;
89        // Emulates pread using seek + read + seek to restore cursor position.
90        // Correctness of this emulation relies on sequential nature of Miri execution.
91        let result = ecx.read_from_host(ptr, len, |buf| {
92            let cursor_pos = file.stream_position()?;
93            file.seek(SeekFrom::Start(offset))?;
94            let res = file.read(buf);
95            // Attempt to restore cursor position even if the read has failed
96            file.seek(SeekFrom::Start(cursor_pos))
97                .expect("failed to restore file position, this shouldn't be possible");
98            res
99        })?;
100        finish.call(ecx, result)
101    }
102
103    fn pwrite<'tcx>(
104        &self,
105        communicate_allowed: bool,
106        ptr: Pointer,
107        len: u64,
108        offset: u64,
109        ecx: &mut MiriInterpCx<'tcx>,
110        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
111    ) -> InterpResult<'tcx> {
112        assert!(communicate_allowed, "isolation should have prevented even opening a file");
113        if !self.writable {
114            return finish.call(ecx, Err(LibcError("EBADF")));
115        }
116        if self.append {
117            // On "append" files, pwrite cannot be emulated with seeking.
118            throw_unsup_format!("pwrite is not supported on files opened with O_APPEND");
119        }
120
121        let file = &mut &self.file;
122        // Emulates pwrite using seek + write + seek to restore cursor position.
123        // Correctness of this emulation relies on sequential nature of Miri execution.
124        let result = ecx.write_to_host(ptr, len, |buf| {
125            let cursor_pos = file.stream_position()?;
126            file.seek(SeekFrom::Start(offset))?;
127            let res = file.write(buf);
128            // Attempt to restore cursor position even if the write has failed
129            file.seek(SeekFrom::Start(cursor_pos))
130                .expect("failed to restore file position, this shouldn't be possible");
131            res
132        })?;
133        finish.call(ecx, result)
134    }
135
136    fn flock<'tcx>(
137        &self,
138        communicate_allowed: bool,
139        op: FlockOp,
140    ) -> InterpResult<'tcx, io::Result<()>> {
141        assert!(communicate_allowed, "isolation should have prevented even opening a file");
142
143        use FlockOp::*;
144        // We must not block the interpreter loop, so we always `try_lock`.
145        let (res, nonblocking) = match op {
146            SharedLock { nonblocking } => (self.file.try_lock_shared(), nonblocking),
147            ExclusiveLock { nonblocking } => (self.file.try_lock(), nonblocking),
148            Unlock => {
149                return interp_ok(self.file.unlock());
150            }
151        };
152
153        match res {
154            Ok(()) => interp_ok(Ok(())),
155            Err(TryLockError::Error(err)) => interp_ok(Err(err)),
156            Err(TryLockError::WouldBlock) =>
157                if nonblocking {
158                    interp_ok(Err(ErrorKind::WouldBlock.into()))
159                } else {
160                    throw_unsup_format!("blocking `flock` is not currently supported");
161                },
162        }
163    }
164
165    fn get_flags<'tcx>(&self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
166        interp_ok(match (self.readable, self.writable) {
167            (true, true) => ecx.eval_libc("O_RDWR"),
168            (true, false) => ecx.eval_libc("O_RDONLY"),
169            (false, true) => ecx.eval_libc("O_WRONLY"),
170            _ => unreachable!(),
171        })
172    }
173}
174
175impl UnixFileDescription for DirHandle {
176    fn get_flags<'tcx>(&self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
177        // Directories are always readonly on Unix.
178        interp_ok(ecx.eval_libc("O_RDONLY"))
179    }
180}
181
182/// The table of open directories.
183/// Curiously, Unix/POSIX does not unify this into the "file descriptor" concept... everything
184/// is a file, except a directory is not?
185#[derive(Debug)]
186pub struct DirTable {
187    /// Directory iterators used to emulate libc "directory streams", as used in opendir, readdir,
188    /// and closedir.
189    ///
190    /// When opendir is called, a directory iterator is created on the host for the target
191    /// directory, and an entry is stored in this hash map, indexed by an ID which represents
192    /// the directory stream. When readdir is called, the directory stream ID is used to look up
193    /// the corresponding ReadDir iterator from this map, and information from the next
194    /// directory entry is returned. When closedir is called, the ReadDir iterator is removed from
195    /// the map.
196    streams: FxHashMap<u64, DirStream>,
197    /// ID number to be used by the next call to opendir
198    next_id: u64,
199}
200
201impl DirTable {
202    #[expect(clippy::arithmetic_side_effects)]
203    fn insert_new(&mut self, stream: DirStream) -> u64 {
204        let id = self.next_id;
205        self.next_id += 1;
206        self.streams.try_insert(id, stream).unwrap();
207        id
208    }
209}
210
211impl Default for DirTable {
212    fn default() -> DirTable {
213        DirTable {
214            streams: FxHashMap::default(),
215            // Skip 0 as an ID, because it looks like a null pointer to libc
216            next_id: 1,
217        }
218    }
219}
220
221impl VisitProvenance for DirTable {
222    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
223        let DirTable { streams, next_id: _ } = self;
224
225        for dir in streams.values() {
226            dir.entry.visit_provenance(visit);
227        }
228    }
229}
230
231fn maybe_sync_file(
232    file: &FileHandle,
233    operation: fn(&File) -> std::io::Result<()>,
234) -> std::io::Result<i32> {
235    if !file.writable && cfg!(windows) {
236        // sync_all() and sync_data() will return an error on Windows hosts if the file is not opened
237        // for writing. (FlushFileBuffers requires that the file handle have the
238        // GENERIC_WRITE right)
239        Ok(0i32)
240    } else {
241        let result = operation(&file.file);
242        result.map(|_| 0i32)
243    }
244}
245
246/// Whether `path` is a symlink to a directory on the host.
247/// If `dir` is given, a relative `path` is resolved relative to that directory.
248#[cfg(windows)]
249fn host_is_symlink_dir(dir: Option<&DirHandle>, path: &Path) -> bool {
250    use std::os::windows::fs::FileTypeExt;
251    let metadata = match dir {
252        Some(dir) => dir.dir.symlink_metadata(path),
253        None => path.symlink_metadata(),
254    };
255    metadata.is_ok_and(|m| m.file_type().is_symlink_dir())
256}
257
258/// Removes the file at `path` on the host, with the semantics of `unlink`.
259/// If `dir` is given, a relative `path` is resolved relative to that directory.
260fn host_remove_file(dir: Option<&DirHandle>, path: &Path) -> io::Result<()> {
261    cfg_select! {
262        unix =>
263            match dir {
264                Some(dir) => dir.dir.remove_file(path),
265                None => fs::remove_file(path),
266            },
267        windows => {{
268            // This should be able to remove symlinks to dirs, but on Windows that requires
269            // `remove_dir`. Our work-around is racy but there's not a lot we can do about that.
270            // FIXME: maybe we can retry based on the error code?
271            let symlink_dir = host_is_symlink_dir(dir, path);
272            match (dir, symlink_dir) {
273                (Some(dir), true) => dir.dir.remove_dir(path),
274                (Some(dir), false) => dir.dir.remove_file(path),
275                (None, true) => fs::remove_dir(path),
276                (None, false) => fs::remove_file(path),
277            }
278        }}
279    }
280}
281
282/// Removes the directory at `path` on the host, with the semantics of `rmdir`.
283/// If `dir` is given, a relative `path` is resolved relative to that directory.
284fn host_remove_dir(dir: Option<&DirHandle>, path: &Path) -> io::Result<()> {
285    #[cfg(windows)]
286    {
287        // This should *not* be able to remove symlinks to dirs, but on Windows it is. Our
288        // work-around is racy (it might change to being a directory symlink after we
289        // checked it), but there's not a lot we can do about that.
290        if host_is_symlink_dir(dir, path) {
291            return Err(ErrorKind::NotADirectory.into());
292        }
293    }
294    match dir {
295        Some(dir) => dir.dir.remove_dir(path),
296        None => fs::remove_dir(path),
297    }
298}
299
300/// The host `FileTimes` that applies the given access and modification time updates.
301fn host_file_times_from_updates(access: TimeUpdate, modified: TimeUpdate) -> FileTimes {
302    let mut filetimes = FileTimes::new();
303    if let TimeUpdate::Set(access) = access {
304        filetimes = filetimes.set_accessed(access);
305    }
306    if let TimeUpdate::Set(modified) = modified {
307        filetimes = filetimes.set_modified(modified);
308    }
309    filetimes
310}
311
312fn same_host_file(file1: &fs::Metadata, file2: &fs::Metadata) -> bool {
313    cfg_select! {
314        unix => {
315            use std::os::unix::fs::MetadataExt;
316            file1.dev() == file2.dev() && file1.ino() == file2.ino()
317        }
318        windows => {
319            use std::os::windows::fs::MetadataExt;
320            file1.volume_serial_number().unwrap() == file2.volume_serial_number().unwrap()
321                && file1.file_index().unwrap() == file2.file_index().unwrap()
322        }
323    }
324}
325
326impl<'tcx> EvalContextExtPrivate<'tcx> for crate::MiriInterpCx<'tcx> {}
327trait EvalContextExtPrivate<'tcx>: crate::MiriInterpCxExt<'tcx> {
328    /// Decode one `futimens` `timespec`, handling the `UTIME_NOW`/`UTIME_OMIT` `tv_nsec` values.
329    /// `None` means the `timespec` is invalid and the caller should report `EINVAL`.
330    fn parse_utimens_timespec(
331        &self,
332        tp: &MPlaceTy<'tcx>,
333    ) -> InterpResult<'tcx, Option<TimeUpdate>> {
334        let this = self.eval_context_ref();
335        // `UTIME_NOW` reads the host clock, which we must not do under isolation.
336        assert!(this.machine.communicate(), "isolation should have prevented reaching this");
337
338        // `tv_nsec` and the `UTIME_*` constants are `c_long`, i.e. the target's `isize`.
339        let nsec_place = this.project_field_named(tp, "tv_nsec")?;
340        let nsec = this.read_scalar(&nsec_place)?.to_target_isize(this)?;
341
342        if nsec == this.eval_libc("UTIME_OMIT").to_target_isize(this)? {
343            return interp_ok(Some(TimeUpdate::Omit));
344        }
345        if nsec == this.eval_libc("UTIME_NOW").to_target_isize(this)? {
346            return interp_ok(Some(TimeUpdate::Set(SystemTime::now())));
347        }
348
349        let Some(duration) = this.read_timespec(tp)? else {
350            return interp_ok(None);
351        };
352        interp_ok(SystemTime::UNIX_EPOCH.checked_add(duration).map(TimeUpdate::Set))
353    }
354
355    /// Decode the `times` argument of `futimens`/`utimensat`: `[atime, mtime]`, or NULL to set both
356    /// to now, as `(access, modified)`.
357    /// `None` means a `timespec` is invalid and the caller should report `EINVAL`.
358    fn parse_utimens_times(
359        &self,
360        times: &MPlaceTy<'tcx>,
361    ) -> InterpResult<'tcx, Option<(TimeUpdate, TimeUpdate)>> {
362        let this = self.eval_context_ref();
363
364        if this.ptr_is_null(times.ptr())? {
365            let now = TimeUpdate::Set(SystemTime::now());
366            interp_ok(Some((now, now)))
367        } else {
368            let access_place = this.project_c_array_field(times, 0)?;
369            let modified_place = this.project_c_array_field(times, 1)?;
370            let Some(access) = this.parse_utimens_timespec(&access_place)? else {
371                return interp_ok(None);
372            };
373            let Some(modified) = this.parse_utimens_timespec(&modified_place)? else {
374                return interp_ok(None);
375            };
376            interp_ok(Some((access, modified)))
377        }
378    }
379
380    fn write_stat_buf(
381        &mut self,
382        metadata: FileMetadata,
383        buf_op: &OpTy<'tcx>,
384    ) -> InterpResult<'tcx, i32> {
385        let this = self.eval_context_mut();
386
387        let (access_sec, access_nsec) = metadata.accessed.unwrap_or((0, 0));
388        let (created_sec, created_nsec) = metadata.created.unwrap_or((0, 0));
389        let (modified_sec, modified_nsec) = metadata.modified.unwrap_or((0, 0));
390
391        let buf = this.deref_pointer(buf_op)?;
392
393        this.write_int_fields_named(
394            &[
395                ("st_dev", metadata.dev.unwrap_or(0).into()),
396                ("st_mode", metadata.mode.into()),
397                ("st_nlink", metadata.nlink.unwrap_or(0).into()),
398                ("st_ino", metadata.ino.unwrap_or(0).into()),
399                ("st_uid", metadata.uid.unwrap_or(0).into()),
400                ("st_gid", metadata.gid.unwrap_or(0).into()),
401                ("st_rdev", 0),
402                ("st_atime", access_sec.into()),
403                ("st_atime_nsec", access_nsec.into()),
404                ("st_mtime", modified_sec.into()),
405                ("st_mtime_nsec", modified_nsec.into()),
406                ("st_ctime", 0),
407                ("st_ctime_nsec", 0),
408                ("st_size", metadata.size.into()),
409                ("st_blocks", metadata.blocks.unwrap_or(0).into()),
410                ("st_blksize", metadata.blksize.unwrap_or(0).into()),
411            ],
412            &buf,
413        )?;
414
415        if matches!(&this.tcx.sess.target.os, Os::MacOs | Os::FreeBsd) {
416            this.write_int_fields_named(
417                &[
418                    ("st_birthtime", created_sec.into()),
419                    ("st_birthtime_nsec", created_nsec.into()),
420                    ("st_flags", 0),
421                    ("st_gen", 0),
422                ],
423                &buf,
424            )?;
425        }
426
427        if matches!(&this.tcx.sess.target.os, Os::Solaris | Os::Illumos) {
428            let st_fstype = this.project_field_named(&buf, "st_fstype")?;
429            // This is an array; write 0 into first element so that it encodes the empty string.
430            this.write_int(0, &this.project_index(&st_fstype, 0)?)?;
431        }
432
433        interp_ok(0)
434    }
435
436    #[cfg(windows)]
437    fn file_type_to_d_type(&self, file_type: fs::FileType) -> InterpResult<'tcx, i32> {
438        let this = self.eval_context_ref();
439        match () {
440            _ if file_type.is_dir() => interp_ok(this.eval_libc("DT_DIR").to_u8()?.into()),
441            _ if file_type.is_file() => interp_ok(this.eval_libc("DT_REG").to_u8()?.into()),
442            _ if file_type.is_symlink() => interp_ok(this.eval_libc("DT_LNK").to_u8()?.into()),
443            // Fallback
444            _ => interp_ok(this.eval_libc("DT_UNKNOWN").to_u8()?.into()),
445        }
446    }
447
448    fn dir_entry_fields(
449        &self,
450        entry: Either<fs::DirEntry, &'static str>,
451    ) -> InterpResult<'tcx, DirEntry> {
452        let this = self.eval_context_ref();
453        interp_ok(match entry {
454            Either::Left(dir_entry) => {
455                cfg_select! {
456                    unix => {
457                        use std::os::unix::fs::DirEntryExt;
458                        DirEntry {
459                            name: dir_entry.file_name(),
460                            d_type: {
461                                // We cannot rely on `dir_entry.file_type`, it might use a separate
462                                // syscall based on `file_name` which is racy.
463                                // It's always okay to return DT_UNKNOWN instead.
464                                this.eval_libc("DT_UNKNOWN").to_u8()?.into()
465                            },
466                            ino: dir_entry.ino(),
467                        }
468                    }
469                    windows => {
470                        DirEntry {
471                            name: dir_entry.file_name(),
472                            // `DirEntry::file_type` is always race-free and never fails on Windows.
473                            d_type: this.file_type_to_d_type(dir_entry.file_type().unwrap())?,
474                            ino: 0u64,
475                        }
476                    }
477                }
478            }
479            Either::Right(special) =>
480                DirEntry {
481                    name: special.into(),
482                    d_type: this.eval_libc("DT_DIR").to_u8()?.into(),
483                    ino: 0,
484                },
485        })
486    }
487
488    fn host_permissions_from_mode(
489        &self,
490        mode: u32,
491        old_permissions: impl FnOnce() -> io::Result<fs::Permissions>,
492    ) -> InterpResult<'tcx, io::Result<fs::Permissions>> {
493        cfg_select! {
494            unix => {
495                use std::os::unix::fs::PermissionsExt;
496
497                let _ = old_permissions;
498                interp_ok(Ok(fs::Permissions::from_mode(mode)))
499            }
500            _ => {
501                let ecx = self.eval_context_ref();
502
503                let mut permissions = match old_permissions() {
504                    Ok(p) => p,
505                    Err(err) => return interp_ok(Err(err)),
506                };
507                // Only support default mode for non-UNIX (i.e. Windows) host.
508                // Ignore the "regular file" bit which is a NOP.
509                let s_ifreg = ecx.eval_libc_int::<u32>("S_IFREG");
510                match mode & !s_ifreg {
511                    0o666 => {
512                        permissions.set_readonly(false);
513                    }
514                    0o444 => {
515                        permissions.set_readonly(true);
516                    }
517                    _ => {
518                        throw_unsup_format!(
519                            "changing permissions to mode 0o{:o} is not supported on non-Unix hosts",
520                            mode
521                        );
522                    }
523                }
524                interp_ok(Ok(permissions))
525            }
526        }
527    }
528}
529
530impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
531pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
532    fn open(
533        &mut self,
534        dirfd: Option<&OpTy<'tcx>>,
535        path_raw: &OpTy<'tcx>,
536        flag: &OpTy<'tcx>,
537        varargs: Varargs<'tcx, '_>,
538    ) -> InterpResult<'tcx, Scalar> {
539        #[cfg(unix)]
540        use std::os::unix::fs::OpenOptionsExt;
541        #[cfg(windows)]
542        use std::os::windows::fs::OpenOptionsExt;
543
544        let ecx = self.eval_context_mut();
545        let open_name = if dirfd.is_some() { "openat" } else { "open" };
546
547        let dirfd = match dirfd {
548            Some(dirfd) => Some(ecx.read_scalar(dirfd)?.to_i32()?),
549            None => None,
550        };
551        let path_raw = ecx.read_pointer(path_raw)?;
552        let flag = ecx.read_scalar(flag)?.to_i32()?;
553
554        let path = ecx.read_path_from_c_str(path_raw)?;
555        // Files in `/proc` won't work properly.
556        if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::Illumos | Os::Solaris)
557            && path::absolute(&path).is_ok_and(|path| path.starts_with("/proc"))
558        {
559            ecx.machine.emit_diagnostic(NonHaltingDiagnostic::FileInProcOpened);
560        }
561
562        // Helper for those flags that read the `mode` parameter.
563        let read_mode = |ecx: &MiriInterpCx<'tcx>,
564                         options: &mut OpenOptions,
565                         fn_name: &str|
566         -> InterpResult<'tcx> {
567            let ([mode], _) = ecx.check_varargs(
568                if ecx.libc_ty_layout("mode_t").size.bytes() >= 4 {
569                    // `mode_t` is big enough, no C integer promotion.
570                    shim_varargs![libc::mode_t]
571                } else {
572                    // Types smaller than int get promoted to int
573                    // (see https://github.com/rust-lang/rust/issues/71915).
574                    shim_varargs![i32]
575                },
576                varargs,
577                fn_name,
578            )?;
579            let mode = ecx.read_scalar(&mode)?.to_u32()?;
580
581            cfg_select! {
582                unix => {
583                    // Support all modes on UNIX host
584                    options.mode(mode);
585                }
586                _ => {
587                    let _unused = options;
588
589                    // Only support default mode for non-UNIX (i.e. Windows) host.
590                    // Ignore the "regular file" bit which is a NOP.
591                    let s_ifreg = ecx.eval_libc_int::<u32>("S_IFREG");
592                    if mode & !s_ifreg != 0o666 {
593                        throw_unsup_format!(
594                            "{open_name}: non-default mode 0o{:o} is not supported on non-Unix hosts",
595                            mode
596                        );
597                    }
598                }
599            }
600
601            interp_ok(())
602        };
603
604        // We will "subtract" supported flags from this and at the end check that no bits are left.
605        let mut flag = flag;
606
607        let mut options = OpenOptions::new();
608        let mut custom_flags = 0;
609
610        let o_rdonly = ecx.eval_libc_i32("O_RDONLY");
611        let o_wronly = ecx.eval_libc_i32("O_WRONLY");
612        let o_rdwr = ecx.eval_libc_i32("O_RDWR");
613        // The first two bits of the flag correspond to the access mode in linux, macOS and
614        // windows. We need to check that in fact the access mode flags for the current target
615        // only use these two bits, otherwise we are in an unsupported target and should error.
616        if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
617            throw_unsup_format!("{open_name}: access mode flags on this target are unsupported");
618        }
619        let mut writable = true;
620        let mut readable = true;
621
622        // Now we check the access mode
623        let access_mode = flag & ecx.eval_libc_i32("O_ACCMODE");
624        flag &= !access_mode;
625
626        if access_mode == o_rdonly {
627            writable = false;
628            options.read(true);
629        } else if access_mode == o_wronly {
630            readable = false;
631            options.write(true);
632        } else if access_mode == o_rdwr {
633            options.read(true).write(true);
634        } else {
635            throw_unsup_format!("{open_name}: unsupported access mode {:#x}", access_mode);
636        }
637
638        if ecx.tcx.sess.target.os == Os::Linux {
639            let o_largefile = ecx.eval_libc_i32("O_LARGEFILE");
640            if flag & o_largefile == o_largefile {
641                flag &= !o_largefile;
642                // `fs::File` always opens in largefile mode so this is a NOP.
643            }
644            let o_tmpfile = ecx.eval_libc_i32("O_TMPFILE");
645            // Note that this overaps with O_DIRECTORY! So we have to check O_TMPFILE first.
646            if flag & o_tmpfile == o_tmpfile {
647                // This flag requires a mode.
648                read_mode(
649                    ecx,
650                    &mut options,
651                    if dirfd.is_some() {
652                        "openat(dirfd, pathname, O_TMPFILE, ...)"
653                    } else {
654                        "open(pathname, O_TMPFILE, ...)"
655                    },
656                )?;
657
658                // We don't currently support this, error gracefully.
659                return ecx.set_errno_and_return_neg1_i32(LibcError("EOPNOTSUPP"));
660            }
661        }
662        let o_directory = ecx.eval_libc_i32("O_DIRECTORY");
663        let mut want_directory = false;
664        if flag & o_directory == o_directory {
665            flag &= !o_directory;
666            want_directory = true;
667            // On Unix we can ask the host to only open directories. That's helpful especially in
668            // combination with O_NOFOLLOW as it affects which error we get when the final component
669            // is a symlink. Fixing the error up ourselves is non-trivial so we make the host
670            // generate the right error.
671            #[cfg(unix)]
672            {
673                custom_flags |= libc::O_DIRECTORY;
674            }
675        }
676        let o_append = ecx.eval_libc_i32("O_APPEND");
677        let append = flag & o_append == o_append;
678        if append {
679            flag &= !o_append;
680            // The flag is a NOP if the file is not writable.
681            if writable {
682                options.append(true);
683            }
684        }
685        let o_trunc = ecx.eval_libc_i32("O_TRUNC");
686        if flag & o_trunc == o_trunc {
687            flag &= !o_trunc;
688            options.truncate(true);
689        }
690        let o_creat = ecx.eval_libc_i32("O_CREAT");
691        if flag & o_creat == o_creat {
692            flag &= !o_creat;
693            // Get the mode.
694            read_mode(
695                ecx,
696                &mut options,
697                if dirfd.is_some() {
698                    "openat(dirfd, pathname, O_CREAT, ...)"
699                } else {
700                    "open(pathname, O_CREAT, ...)"
701                },
702            )?;
703
704            if want_directory {
705                // O_CREAT + O_DIRECTORY is invalid.
706                return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
707            }
708
709            // O_EXCL is only allowed if O_CREAT is set.
710            let o_excl = ecx.eval_libc_i32("O_EXCL");
711            if flag & o_excl == o_excl {
712                flag &= !o_excl;
713                options.create_new(true);
714            } else {
715                options.create(true);
716            }
717            // Creating a file requires opening it for writing.
718            // Write accesses will still get rejected as `writable` is not set on the `FileHandle`.
719            options.write(true);
720        }
721        let o_cloexec = ecx.eval_libc_i32("O_CLOEXEC");
722        if flag & o_cloexec == o_cloexec {
723            flag &= !o_cloexec;
724            // We do not need to do anything for this flag because `std` already sets it.
725            // (Technically we do not support *not* setting this flag, but we ignore that.)
726        }
727        let o_nofollow = ecx.eval_libc_i32("O_NOFOLLOW");
728        let mut nofollow = false;
729        if flag & o_nofollow == o_nofollow {
730            flag &= !o_nofollow;
731            nofollow = true;
732            cfg_select! {
733                unix => {
734                    custom_flags |= libc::O_NOFOLLOW;
735                }
736                windows => {
737                    if dirfd.is_some() {
738                        throw_unsup_format!(
739                            "openat: `O_NOFOLLOW` is not supported on Windows hosts"
740                        );
741                    }
742                    custom_flags |=
743                        windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
744                }
745            }
746        }
747
748        // If `flag` has any bits left set, those are not supported.
749        if flag != 0 {
750            throw_unsup_format!("{open_name}: unsupported flags: {flag:#x}");
751        }
752
753        // Reject if isolation is enabled.
754        if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op {
755            ecx.reject_in_isolation(&format!("`{open_name}`"), reject_with)?;
756            return ecx.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied);
757        }
758
759        let dirfd = match dirfd {
760            Some(dirfd) => {
761                if path.is_absolute() || dirfd == ecx.eval_libc_i32("AT_FDCWD") {
762                    None
763                } else {
764                    // relative to dirfd, which must be a directory handle
765                    let Some(fd) = ecx.machine.fds.get(dirfd) else {
766                        return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
767                    };
768                    let Some(dir) = fd.downcast::<DirHandle>() else {
769                        return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTDIR"));
770                    };
771                    Some(dir)
772                }
773            }
774            None => None,
775        };
776
777        // Empty path should consistently error.
778        if path.is_empty() {
779            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOENT"));
780        }
781        // Windows does not support "." relative to a `Dir` handle, but the empty path works.
782        // (https://github.com/rust-lang/rust/issues/163032)
783        let path = if cfg!(windows) && dirfd.is_some() && path.to_str() == Some(".") {
784            Path::new("")
785        } else {
786            &path
787        };
788
789        // Let's see what we get when we open this!
790        let f_or_d = open_file_or_dir(
791            dirfd.as_ref().map(|d| &d.dir),
792            path,
793            options.custom_flags(custom_flags),
794        );
795        match f_or_d {
796            Err(err) => ecx.set_errno_and_return_neg1_i32(err),
797            Ok(Either::Right(dir)) => {
798                // This means it cannot be a symlink, so `nofollow` is fine.
799                if writable {
800                    // On Windows, opening a folder writable can succeed.
801                    // But here we want it to always fail.
802                    return ecx.set_errno_and_return_neg1_i32(LibcError("EISDIR"));
803                }
804
805                let Some(fd) = ecx.machine.fds.insert_new(DirHandle { dir }) else {
806                    return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE"));
807                };
808                interp_ok(Scalar::from_i32(fd))
809            }
810            Ok(Either::Left(file)) => {
811                if want_directory {
812                    return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTDIR"));
813                }
814                if file.metadata().unwrap().is_symlink() {
815                    if nofollow {
816                        // On Windows, FILE_FLAG_OPEN_REPARSE_POINT makes opening still succeed, it
817                        // just opens the symlink rather than the target. Turn that into an error.
818                        return ecx.set_errno_and_return_neg1_i32(LibcError("ELOOP"));
819                    }
820                    panic!("we should not get a symlink here");
821                }
822
823                let Some(fd) =
824                    ecx.machine.fds.insert_new(FileHandle { file, writable, readable, append })
825                else {
826                    return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE"));
827                };
828                interp_ok(Scalar::from_i32(fd))
829            }
830        }
831    }
832
833    fn lseek(
834        &mut self,
835        fd_num: i32,
836        offset: i64,
837        whence: i32,
838        dest: &MPlaceTy<'tcx>,
839    ) -> InterpResult<'tcx> {
840        let this = self.eval_context_mut();
841
842        // Isolation check is done via `FileDescription` trait.
843
844        let seek_from = if whence == this.eval_libc_i32("SEEK_SET") {
845            let Ok(offset) = u64::try_from(offset) else {
846                // Negative offsets return `EINVAL`.
847                return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest);
848            };
849            SeekFrom::Start(offset)
850        } else if whence == this.eval_libc_i32("SEEK_CUR") {
851            SeekFrom::Current(offset)
852        } else if whence == this.eval_libc_i32("SEEK_END") {
853            SeekFrom::End(offset)
854        } else {
855            return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest);
856        };
857
858        let communicate = this.machine.communicate();
859
860        let Some(fd) = this.machine.fds.get(fd_num) else {
861            return this.set_errno_and_return_neg1(LibcError("EBADF"), dest);
862        };
863        let result = fd.seek(communicate, seek_from)?.map(|offset| i64::try_from(offset).unwrap());
864        drop(fd);
865
866        let result = this.try_unwrap_io_result(result)?;
867        this.write_int(result, dest)?;
868        interp_ok(())
869    }
870
871    fn unlink(&mut self, path_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
872        let ecx = self.eval_context_mut();
873
874        let path = ecx.read_path_from_c_str(ecx.read_pointer(path_op)?)?;
875
876        // Reject if isolation is enabled.
877        if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op {
878            ecx.reject_in_isolation("`unlink`", reject_with)?;
879            return ecx.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied);
880        }
881
882        let result = host_remove_file(None, &path);
883        interp_ok(Scalar::from_i32(ecx.try_unwrap_io_result(result.map(|()| 0))?))
884    }
885
886    fn unlinkat(
887        &mut self,
888        dirfd_op: &OpTy<'tcx>,
889        path_op: &OpTy<'tcx>,
890        flags_op: &OpTy<'tcx>,
891    ) -> InterpResult<'tcx, Scalar> {
892        let ecx = self.eval_context_mut();
893
894        let dirfd = ecx.read_scalar(dirfd_op)?.to_i32()?;
895        let path = ecx.read_path_from_c_str(ecx.read_pointer(path_op)?)?.into_owned();
896        let flags = ecx.read_scalar(flags_op)?.to_i32()?;
897
898        // Reject if isolation is enabled.
899        if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op {
900            ecx.reject_in_isolation("`unlinkat`", reject_with)?;
901            return ecx.set_errno_and_return_neg1_i32(LibcError("EACCES"));
902        }
903
904        // We only support `AT_REMOVEDIR`, which makes this behave like `rmdir`.
905        let remove_dir = if flags == 0 {
906            false
907        } else if flags == ecx.eval_libc_i32("AT_REMOVEDIR") {
908            true
909        } else {
910            throw_unsup_format!("unsupported flags for `unlinkat`: {flags:#x}")
911        };
912
913        let dir = if path.is_absolute() || dirfd == ecx.eval_libc_i32("AT_FDCWD") {
914            None
915        } else {
916            // relative to dirfd, which must be a directory handle
917            let Some(fd) = ecx.machine.fds.get(dirfd) else {
918                return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
919            };
920            let Some(dir) = fd.downcast::<DirHandle>() else {
921                return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTDIR"));
922            };
923            Some(dir)
924        };
925        let result = if remove_dir {
926            host_remove_dir(dir.as_deref(), &path)
927        } else {
928            host_remove_file(dir.as_deref(), &path)
929        };
930        interp_ok(Scalar::from_i32(ecx.try_unwrap_io_result(result.map(|()| 0))?))
931    }
932
933    fn symlink(
934        &mut self,
935        target_op: &OpTy<'tcx>,
936        linkpath_op: &OpTy<'tcx>,
937    ) -> InterpResult<'tcx, Scalar> {
938        fn create_link(target: &Path, link: &Path) -> std::io::Result<()> {
939            cfg_select! {
940                unix => std::os::unix::fs::symlink(target, link),
941                windows => {
942                    use std::os::windows::fs;
943
944                    // The target filename is interpreted relative to where `link` is located,
945                    // but we need it relative to where we are.
946                    let target_is_dir = link.parent().is_some_and(|dir| dir.join(target).is_dir());
947                    // This is racy, but not much we can do about that.
948                    // FIXME: maybe we can retry based on the error code?
949                    if target_is_dir {
950                        fs::symlink_dir(target, link)
951                    } else {
952                        fs::symlink_file(target, link)
953                    }
954                }
955            }
956        }
957
958        let this = self.eval_context_mut();
959        let target = this.read_path_from_c_str(this.read_pointer(target_op)?)?;
960        let linkpath = this.read_path_from_c_str(this.read_pointer(linkpath_op)?)?;
961
962        // Reject if isolation is enabled.
963        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
964            this.reject_in_isolation("`symlink`", reject_with)?;
965            return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied);
966        }
967
968        let result = create_link(&target, &linkpath).map(|_| 0);
969        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
970    }
971
972    fn linkat(
973        &mut self,
974        oldfd_op: &OpTy<'tcx>,
975        oldpath_op: &OpTy<'tcx>,
976        newfd_op: &OpTy<'tcx>,
977        newpath_op: &OpTy<'tcx>,
978        flags_op: &OpTy<'tcx>,
979    ) -> InterpResult<'tcx, Scalar> {
980        let this = self.eval_context_mut();
981
982        // Load all arguments
983        let flags = this.read_scalar(flags_op)?.to_i32()?;
984        let oldfd = this.read_scalar(oldfd_op)?.to_i32()?;
985        let newfd = this.read_scalar(newfd_op)?.to_i32()?;
986        let oldpath_ptr = this.read_pointer(oldpath_op)?;
987        let newpath_ptr = this.read_pointer(newpath_op)?;
988
989        // Relevant libc constants
990        let at_fdcwd = this.eval_libc_i32("AT_FDCWD");
991
992        // Reject if isolation is enabled.
993        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
994            this.reject_in_isolation("`linkat`", reject_with)?;
995            return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied);
996        }
997
998        // Read flags - only support 0.
999        if flags != 0 {
1000            throw_unsup_format!("unsupported linkat flags {:#x}", flags);
1001        }
1002
1003        // Resolve oldpath
1004        if oldfd != at_fdcwd {
1005            throw_unsup_format!("linkat with `olddirfd` not equal to `AT_FDCWD` is not supported");
1006        }
1007        if this.ptr_is_null(oldpath_ptr)? {
1008            return this.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
1009        }
1010        let oldpath = this.read_path_from_c_str(oldpath_ptr)?.into_owned();
1011
1012        // Resolve newpath
1013        if newfd != at_fdcwd {
1014            throw_unsup_format!("linkat with `newdirfd` not equal to `AT_FDCWD` is not supported");
1015        }
1016        if this.ptr_is_null(newpath_ptr)? {
1017            return this.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
1018        }
1019        let newpath = this.read_path_from_c_str(newpath_ptr)?.into_owned();
1020
1021        let result = fs::hard_link(&oldpath, &newpath).map(|()| 0);
1022        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
1023    }
1024
1025    fn stat(&mut self, path_op: &OpTy<'tcx>, buf_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1026        let this = self.eval_context_mut();
1027
1028        if !matches!(
1029            &this.tcx.sess.target.os,
1030            Os::MacOs | Os::FreeBsd | Os::Solaris | Os::Illumos | Os::Android | Os::Linux
1031        ) {
1032            panic!("`stat` should not be called on {}", this.tcx.sess.target.os);
1033        }
1034
1035        let path_scalar = this.read_pointer(path_op)?;
1036        let path = this.read_path_from_c_str(path_scalar)?.into_owned();
1037
1038        // Reject if isolation is enabled.
1039        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1040            this.reject_in_isolation("`stat`", reject_with)?;
1041            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
1042        }
1043
1044        let metadata = match FileMetadata::from_host(this, fs::metadata(path))? {
1045            Ok(metadata) => metadata,
1046            Err(err) => return this.set_errno_and_return_neg1_i32(err),
1047        };
1048
1049        interp_ok(Scalar::from_i32(this.write_stat_buf(metadata, buf_op)?))
1050    }
1051
1052    // `lstat` is used to get symlink metadata.
1053    fn lstat(&mut self, path_op: &OpTy<'tcx>, buf_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1054        let this = self.eval_context_mut();
1055
1056        if !matches!(
1057            &this.tcx.sess.target.os,
1058            Os::MacOs | Os::FreeBsd | Os::Solaris | Os::Illumos | Os::Android | Os::Linux
1059        ) {
1060            panic!("`lstat` should not be called on {}", this.tcx.sess.target.os);
1061        }
1062
1063        let path_scalar = this.read_pointer(path_op)?;
1064        let path = this.read_path_from_c_str(path_scalar)?.into_owned();
1065
1066        // Reject if isolation is enabled.
1067        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1068            this.reject_in_isolation("`lstat`", reject_with)?;
1069            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
1070        }
1071
1072        let metadata = match FileMetadata::from_host(this, fs::symlink_metadata(path))? {
1073            Ok(metadata) => metadata,
1074            Err(err) => return this.set_errno_and_return_neg1_i32(err),
1075        };
1076
1077        interp_ok(Scalar::from_i32(this.write_stat_buf(metadata, buf_op)?))
1078    }
1079
1080    fn fstat(&mut self, fd_op: &OpTy<'tcx>, buf_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1081        let this = self.eval_context_mut();
1082
1083        if !matches!(
1084            &this.tcx.sess.target.os,
1085            Os::MacOs | Os::FreeBsd | Os::Solaris | Os::Illumos | Os::Linux | Os::Android
1086        ) {
1087            panic!("`fstat` should not be called on {}", this.tcx.sess.target.os);
1088        }
1089
1090        let fd = this.read_scalar(fd_op)?.to_i32()?;
1091
1092        // Reject if isolation is enabled.
1093        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1094            this.reject_in_isolation("`fstat`", reject_with)?;
1095            // Set error code as "EBADF" (bad fd); "EACCESS" does not make much sense here.
1096            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1097        }
1098
1099        let metadata = match FileMetadata::from_fd_num(this, fd)? {
1100            Ok(metadata) => metadata,
1101            Err(err) => return this.set_errno_and_return_neg1_i32(err),
1102        };
1103        interp_ok(Scalar::from_i32(this.write_stat_buf(metadata, buf_op)?))
1104    }
1105
1106    fn fstatat(
1107        &mut self,
1108        dirfd_op: &OpTy<'tcx>,
1109        path_op: &OpTy<'tcx>,
1110        buf_op: &OpTy<'tcx>,
1111        flags_op: &OpTy<'tcx>,
1112    ) -> InterpResult<'tcx, Scalar> {
1113        let this = self.eval_context_mut();
1114
1115        if !matches!(
1116            &this.tcx.sess.target.os,
1117            Os::MacOs | Os::FreeBsd | Os::Solaris | Os::Illumos | Os::Linux | Os::Android
1118        ) {
1119            panic!("`fstatat` should not be called on {}", this.tcx.sess.target.os);
1120        }
1121
1122        let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
1123        let path = this.read_pointer(path_op)?;
1124        let flags = this.read_scalar(flags_op)?.to_i32()?;
1125
1126        // Reject if isolation is enabled.
1127        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1128            this.reject_in_isolation("`fstatat`", reject_with)?;
1129            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
1130        }
1131
1132        // Parse flags.
1133        let mut flags = flags;
1134        // AT_SYMLINK_NOFOLLOW
1135        let at_symlink_nofollow = this.eval_libc_i32("AT_SYMLINK_NOFOLLOW");
1136        let symlink_nofollow_flag = flags & at_symlink_nofollow == at_symlink_nofollow;
1137        flags &= !at_symlink_nofollow;
1138        // Complain about unknown flags.
1139        if flags != 0 {
1140            throw_unsup_format!("unsupported flags for `fstatat`: {flags:#x}")
1141        }
1142
1143        let path = this.read_path_from_c_str(path)?.into_owned();
1144        // Resolve dirfd + path to metadata.
1145        let metadata = FileMetadata::at(
1146            this,
1147            dirfd,
1148            &path,
1149            symlink_nofollow_flag,
1150            /* empty_path_flag */ false,
1151        )?;
1152
1153        let metadata = match metadata {
1154            Ok(metadata) => metadata,
1155            Err(err) => return this.set_errno_and_return_neg1_i32(err),
1156        };
1157        interp_ok(Scalar::from_i32(this.write_stat_buf(metadata, buf_op)?))
1158    }
1159
1160    fn linux_statx(
1161        &mut self,
1162        dirfd_op: &OpTy<'tcx>,    // Should be an `int`
1163        pathname_op: &OpTy<'tcx>, // Should be a `const char *`
1164        flags_op: &OpTy<'tcx>,    // Should be an `int`
1165        mask_op: &OpTy<'tcx>,     // Should be an `unsigned int`
1166        statxbuf_op: &OpTy<'tcx>, // Should be a `struct statx *`
1167    ) -> InterpResult<'tcx, Scalar> {
1168        let this = self.eval_context_mut();
1169        this.assert_target_os_is_linux_like("statx");
1170
1171        let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
1172        let pathname_ptr = this.read_pointer(pathname_op)?;
1173        let flags = this.read_scalar(flags_op)?.to_i32()?;
1174        let _mask = this.read_scalar(mask_op)?.to_u32()?;
1175        let statxbuf_ptr = this.read_pointer(statxbuf_op)?;
1176
1177        // If the statxbuf or pathname pointers are null, the function fails with `EFAULT`.
1178        if this.ptr_is_null(statxbuf_ptr)? || this.ptr_is_null(pathname_ptr)? {
1179            return this.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
1180        }
1181
1182        let statxbuf = this.deref_pointer(statxbuf_op)?;
1183        let path = this.read_path_from_c_str(pathname_ptr)?.into_owned();
1184
1185        // Parse flags.
1186        let mut flags = flags;
1187        // AT_EMPTY_PATH
1188        let at_empty_path = this.eval_libc_i32("AT_EMPTY_PATH");
1189        let empty_path_flag = flags & at_empty_path == at_empty_path;
1190        flags &= !at_empty_path;
1191        // AT_SYMLINK_NOFOLLOW
1192        let at_symlink_nofollow = this.eval_libc_i32("AT_SYMLINK_NOFOLLOW");
1193        let symlink_nofollow_flag = flags & at_symlink_nofollow == at_symlink_nofollow;
1194        flags &= !at_symlink_nofollow;
1195        // Complain about unknown flags.
1196        if flags != 0 {
1197            throw_unsup_format!("unsupported flags for `statx`: {flags:#x}")
1198        }
1199
1200        // Reject if isolation is enabled.
1201        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1202            this.reject_in_isolation("`statx`", reject_with)?;
1203            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
1204        }
1205
1206        // Resolve dirfd + path to metadata.
1207        let metadata =
1208            FileMetadata::at(this, dirfd, &path, symlink_nofollow_flag, empty_path_flag)?;
1209
1210        let metadata = match metadata {
1211            Ok(metadata) => metadata,
1212            Err(err) => return this.set_errno_and_return_neg1_i32(err),
1213        };
1214
1215        // The `_mask_op` parameter specifies the file information that the caller requested.
1216        // However, `statx` is allowed to return information that was not requested or to not
1217        // return information that was requested. This `mask` represents the information we can
1218        // actually provide for any target.
1219        let mut mask = this.eval_libc_u32("STATX_TYPE")
1220            | this.eval_libc_u32("STATX_MODE")
1221            | this.eval_libc_u32("STATX_SIZE");
1222
1223        // Check which pieces of metadata we acquired, and set the appropriate flags in the mask.
1224        if metadata.ino.is_some() {
1225            mask |= this.eval_libc_u32("STATX_INO");
1226        }
1227        if metadata.nlink.is_some() {
1228            mask |= this.eval_libc_u32("STATX_NLINK");
1229        }
1230        if metadata.uid.is_some() {
1231            mask |= this.eval_libc_u32("STATX_UID");
1232        }
1233        if metadata.gid.is_some() {
1234            mask |= this.eval_libc_u32("STATX_GID");
1235        }
1236        if metadata.blocks.is_some() {
1237            mask |= this.eval_libc_u32("STATX_BLOCKS");
1238        }
1239
1240        // We need to set the corresponding bits of `mask` if the access, creation and modification
1241        // times were available. Otherwise we let them be zero.
1242        let (access_sec, access_nsec) = metadata
1243            .accessed
1244            .map(|tup| {
1245                mask |= this.eval_libc_u32("STATX_ATIME");
1246                interp_ok(tup)
1247            })
1248            .unwrap_or_else(|| interp_ok((0, 0)))?;
1249
1250        let (created_sec, created_nsec) = metadata
1251            .created
1252            .map(|tup| {
1253                mask |= this.eval_libc_u32("STATX_BTIME");
1254                interp_ok(tup)
1255            })
1256            .unwrap_or_else(|| interp_ok((0, 0)))?;
1257
1258        let (modified_sec, modified_nsec) = metadata
1259            .modified
1260            .map(|tup| {
1261                mask |= this.eval_libc_u32("STATX_MTIME");
1262                interp_ok(tup)
1263            })
1264            .unwrap_or_else(|| interp_ok((0, 0)))?;
1265
1266        // Now we write everything to `statxbuf`. We write a zero for the unavailable fields.
1267        this.write_int_fields_named(
1268            &[
1269                ("stx_mask", mask.into()),
1270                ("stx_mode", metadata.mode.into()),
1271                ("stx_blksize", metadata.blksize.unwrap_or(0).into()),
1272                ("stx_nlink", metadata.nlink.unwrap_or(0).into()),
1273                ("stx_uid", metadata.uid.unwrap_or(0).into()),
1274                ("stx_gid", metadata.gid.unwrap_or(0).into()),
1275                ("stx_ino", metadata.ino.unwrap_or(0).into()),
1276                ("stx_size", metadata.size.into()),
1277                ("stx_blocks", metadata.blocks.unwrap_or(0).into()),
1278                // These fields do not seem to have a bit in `mask`, they are "always present",
1279                // so we make sure they get initialized.
1280                ("stx_attributes_mask", 0),
1281                ("stx_attributes", 0),
1282                ("stx_rdev_major", 0),
1283                ("stx_rdev_minor", 0),
1284                ("stx_dev_major", 0),
1285                ("stx_dev_minor", 0),
1286            ],
1287            &statxbuf,
1288        )?;
1289        #[rustfmt::skip]
1290        this.write_int_fields_named(
1291            &[
1292                ("tv_sec", access_sec.into()),
1293                ("tv_nsec", access_nsec.into()),
1294            ],
1295            &this.project_field_named(&statxbuf, "stx_atime")?,
1296        )?;
1297        #[rustfmt::skip]
1298        this.write_int_fields_named(
1299            &[
1300                ("tv_sec", created_sec.into()),
1301                ("tv_nsec", created_nsec.into()),
1302            ],
1303            &this.project_field_named(&statxbuf, "stx_btime")?,
1304        )?;
1305        #[rustfmt::skip]
1306        this.write_int_fields_named(
1307            &[
1308                ("tv_sec", 0.into()),
1309                ("tv_nsec", 0.into()),
1310            ],
1311            &this.project_field_named(&statxbuf, "stx_ctime")?,
1312        )?;
1313        #[rustfmt::skip]
1314        this.write_int_fields_named(
1315            &[
1316                ("tv_sec", modified_sec.into()),
1317                ("tv_nsec", modified_nsec.into()),
1318            ],
1319            &this.project_field_named(&statxbuf, "stx_mtime")?,
1320        )?;
1321
1322        // The remaining fields have a mask bit associated with them, a bit that we do not
1323        // set. Therefore we also do not initialize them.
1324
1325        interp_ok(Scalar::from_i32(0))
1326    }
1327
1328    fn chmod(&mut self, path_op: &OpTy<'tcx>, mode_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1329        let this = self.eval_context_mut();
1330
1331        let path_ptr = this.read_pointer(path_op)?;
1332        let mode = this.read_int::<u32>(mode_op)?;
1333
1334        if this.ptr_is_null(path_ptr)? {
1335            return this.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
1336        }
1337        let path = this.read_path_from_c_str(path_ptr)?;
1338
1339        // Reject if isolation is enabled.
1340        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1341            this.reject_in_isolation("`chmod`", reject_with)?;
1342            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
1343        }
1344
1345        let permissions = this.host_permissions_from_mode(mode, || {
1346            // We get here if we need to read the old permissions before we can set new ones.
1347            // This is fundamentally racy. We cannot even use a file handle to make it less racy:
1348            // setting permissions requires opening for writing, but opening for writing fails
1349            // if the file is not already writable... so how do we make a read-only file writable?
1350            fs::metadata(&path).map(|m| m.permissions())
1351        })?;
1352        let res = permissions.and_then(|permissions| fs::set_permissions(path, permissions));
1353        if let Err(err) = res {
1354            return this.set_errno_and_return_neg1_i32(err);
1355        }
1356
1357        interp_ok(Scalar::from_i32(0))
1358    }
1359
1360    fn fchmod(&mut self, fd_op: &OpTy<'tcx>, mode_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1361        let this = self.eval_context_mut();
1362
1363        let fd_num = this.read_scalar(fd_op)?.to_i32()?;
1364        let mode = this.read_int::<u32>(mode_op)?;
1365
1366        let Some(fd) = this.machine.fds.get(fd_num) else {
1367            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1368        };
1369        let Some(file) = fd.downcast::<FileHandle>() else {
1370            // The docs don't talk about what happens for non-regular files...
1371            throw_unsup_format!("`fchmod` is only supported on regular files")
1372        };
1373        if !file.writable && !file.readable {
1374            // Apparently, `fchmod` on a read-only file is fine. But let's not allow it on a
1375            // path-only file.
1376            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1377        }
1378        assert!(this.machine.communicate(), "isolation should have prevented even opening a file");
1379
1380        let permissions = this.host_permissions_from_mode(mode, || {
1381            // We get here if we need to read the old permissions before we can set new ones.
1382            // This is fundamentally racy.
1383            file.file.metadata().map(|m| m.permissions())
1384        })?;
1385        let res = permissions.and_then(|permissions| file.file.set_permissions(permissions));
1386        if let Err(err) = res {
1387            return this.set_errno_and_return_neg1_i32(err);
1388        }
1389
1390        interp_ok(Scalar::from_i32(0))
1391    }
1392
1393    fn rename(
1394        &mut self,
1395        oldpath_op: &OpTy<'tcx>,
1396        newpath_op: &OpTy<'tcx>,
1397    ) -> InterpResult<'tcx, Scalar> {
1398        let this = self.eval_context_mut();
1399
1400        let oldpath_ptr = this.read_pointer(oldpath_op)?;
1401        let newpath_ptr = this.read_pointer(newpath_op)?;
1402
1403        if this.ptr_is_null(oldpath_ptr)? || this.ptr_is_null(newpath_ptr)? {
1404            return this.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
1405        }
1406
1407        let oldpath = this.read_path_from_c_str(oldpath_ptr)?;
1408        let newpath = this.read_path_from_c_str(newpath_ptr)?;
1409
1410        // Reject if isolation is enabled.
1411        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1412            this.reject_in_isolation("`rename`", reject_with)?;
1413            return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied);
1414        }
1415
1416        let result = fs::rename(oldpath, newpath).map(|_| 0);
1417
1418        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
1419    }
1420
1421    fn mkdir(
1422        &mut self,
1423        dirfd_op: Option<&OpTy<'tcx>>,
1424        path_op: &OpTy<'tcx>,
1425        mode_op: &OpTy<'tcx>,
1426        dest: &MPlaceTy<'tcx>,
1427    ) -> InterpResult<'tcx> {
1428        let ecx = self.eval_context_mut();
1429        let mkdir_name = if dirfd_op.is_some() { "mkdirat" } else { "mkdir" };
1430
1431        let dirfd = match dirfd_op {
1432            Some(dirfd_op) => Some(ecx.read_scalar(dirfd_op)?.to_i32()?),
1433            None => None,
1434        };
1435        let path = ecx.read_path_from_c_str(ecx.read_pointer(path_op)?)?;
1436        let mode = ecx.read_int::<u32>(mode_op)?;
1437
1438        // Reject if isolation is enabled.
1439        if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op {
1440            ecx.reject_in_isolation(&format!("`{mkdir_name}`"), reject_with)?;
1441            return ecx.set_errno_and_return_neg1(LibcError("EACCES"), dest);
1442        }
1443
1444        let dir = match dirfd {
1445            Some(dirfd) => {
1446                if path.is_absolute() || dirfd == ecx.eval_libc_i32("AT_FDCWD") {
1447                    None
1448                } else {
1449                    // relative to dirfd, which must be a directory handle
1450                    let Some(fd) = ecx.machine.fds.get(dirfd) else {
1451                        return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
1452                    };
1453                    let Some(dir) = fd.downcast::<DirHandle>() else {
1454                        return ecx.set_errno_and_return_neg1(LibcError("ENOTDIR"), dest);
1455                    };
1456                    Some(dir)
1457                }
1458            }
1459            None => None,
1460        };
1461
1462        let result = match dir {
1463            Some(dir) => {
1464                // `Dir::create_dir` does not take a mode; std always uses 0o777 internally.
1465                // So we can only support that mode here.
1466                if mode != 0o777 {
1467                    throw_unsup_format!(
1468                        "`mkdirat` relative to a directory file descriptor with mode {mode:#o} is not supported \
1469                        (only 0o777 is supported)"
1470                    );
1471                }
1472                dir.dir.create_dir(&path)
1473            }
1474            None => {
1475                #[cfg_attr(not(unix), allow(unused_mut))]
1476                let mut builder = DirBuilder::new();
1477
1478                // On Unix hosts, forward the mode of the directory
1479                // (i.e. permission bits and the sticky bit).
1480                // Other hosts can't represent it, so we only support the default mode there.
1481                cfg_select! {
1482                    unix => {
1483                        use std::os::unix::fs::DirBuilderExt;
1484                        builder.mode(mode);
1485                    }
1486                    _ =>
1487                        if mode != 0o777 {
1488                            throw_unsup_format!(
1489                                "`{mkdir_name}` with mode {mode:#o} is not supported on non-Unix hosts \
1490                                (only 0o777 is supported)"
1491                            );
1492                        },
1493                }
1494
1495                builder.create(path)
1496            }
1497        };
1498
1499        ecx.return_io_result_via_errno(result.map(|()| 0), dest)?;
1500        interp_ok(())
1501    }
1502
1503    fn rmdir(&mut self, path_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1504        let this = self.eval_context_mut();
1505
1506        let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
1507
1508        // Reject if isolation is enabled.
1509        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1510            this.reject_in_isolation("`rmdir`", reject_with)?;
1511            return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied);
1512        }
1513
1514        let result = host_remove_dir(None, &path);
1515        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|_| 0i32))?))
1516    }
1517
1518    fn opendir(&mut self, name_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1519        let this = self.eval_context_mut();
1520
1521        let name = this.read_path_from_c_str(this.read_pointer(name_op)?)?;
1522
1523        // Reject if isolation is enabled.
1524        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1525            this.reject_in_isolation("`opendir`", reject_with)?;
1526            this.set_last_error(LibcError("EACCES"))?;
1527            return interp_ok(Scalar::null_ptr(this));
1528        }
1529
1530        let result = fs::read_dir(&name);
1531
1532        match result {
1533            Ok(read_dir) => {
1534                // Create an underlying FD as well, in case someone calls `dirfd` later.
1535                // (We could do this lazily but that does not seem worth it.)
1536                let Ok(dir) = read_dir.dir() else {
1537                    throw_unsup_format!(
1538                        "cannot `opendir` this directory: failed to create directory handle"
1539                    );
1540                };
1541                let dir = this.machine.fds.new_ref(DirHandle { dir });
1542                let dir_fd_id = dir.id();
1543                let Some(dir_fd_num) = this.machine.fds.insert(dir) else {
1544                    return this.set_errno_and_return_neg1_i32(LibcError("EMFILE"));
1545                };
1546
1547                let stream = DirStream::new(read_dir, dir_fd_num, dir_fd_id);
1548                let id = this.machine.dirs.insert_new(stream);
1549
1550                // The libc API for opendir says that this method returns a pointer to an opaque
1551                // structure, but we are returning an ID number. Thus, pass it as a scalar of
1552                // pointer width. This also conveniently means that any attempt to access
1553                // memory via this pointer raises UB.
1554                interp_ok(Scalar::from_target_usize(id, this))
1555            }
1556            Err(e) => {
1557                this.set_last_error(e)?;
1558                interp_ok(Scalar::null_ptr(this))
1559            }
1560        }
1561    }
1562
1563    fn readdir(
1564        &mut self,
1565        dirp_op: &OpTy<'tcx>,
1566        dest: &MPlaceTy<'tcx>,
1567        buf_type: &'static str,
1568    ) -> InterpResult<'tcx> {
1569        let this = self.eval_context_mut();
1570
1571        if !matches!(
1572            &this.tcx.sess.target.os,
1573            Os::Linux | Os::Android | Os::Solaris | Os::Illumos | Os::FreeBsd | Os::MacOs
1574        ) {
1575            throw_unsup_format!("`readdir` is not yet supported on {}", this.tcx.sess.target.os);
1576        }
1577
1578        let dirp = this.read_target_usize(dirp_op)?;
1579
1580        // Reject if isolation is enabled.
1581        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1582            this.reject_in_isolation("`readdir`", reject_with)?;
1583            this.set_last_error(LibcError("EBADF"))?;
1584            this.write_int(0, dest)?;
1585            return interp_ok(());
1586        }
1587
1588        let open_dir = this.machine.dirs.streams.get_mut(&dirp).ok_or_else(|| {
1589            err_ub_format!("the DIR pointer passed to `readdir` did not come from opendir")
1590        })?;
1591
1592        // Check that the backing FD is still valid.
1593        if this.machine.fds.get(open_dir.fd_num).is_none_or(|fd| fd.id() != open_dir.fd_id) {
1594            throw_ub_format!("the backing FD for this DIR stream has been tampered with");
1595        }
1596
1597        let entry = match open_dir.next_host_entry() {
1598            Some(Ok(dir_entry)) => {
1599                let dir_entry = this.dir_entry_fields(dir_entry)?;
1600
1601                // Write the directory entry into a newly allocated buffer.
1602                // The name is written with write_bytes, while the rest of the
1603                // dirent64 (or dirent) struct is written using write_int_fields.
1604
1605                // For reference:
1606                // On Linux:
1607                // pub struct dirent64 {
1608                //     pub d_ino: ino64_t,
1609                //     pub d_off: off64_t,
1610                //     pub d_reclen: c_ushort,
1611                //     pub d_type: c_uchar,
1612                //     pub d_name: [c_char; 256],
1613                // }
1614                //
1615                // On Solaris:
1616                // pub struct dirent {
1617                //     pub d_ino: ino64_t,
1618                //     pub d_off: off64_t,
1619                //     pub d_reclen: c_ushort,
1620                //     pub d_name: [c_char; 3],
1621                // }
1622                //
1623                // On FreeBSD:
1624                // pub struct dirent {
1625                //     pub d_fileno: uint32_t,
1626                //     pub d_reclen: uint16_t,
1627                //     pub d_type: uint8_t,
1628                //     pub d_namlen: uint8_t,
1629                //     pub d_name: [c_char; 256],
1630                // }
1631                //
1632                // On macOS:
1633                // pub struct dirent {
1634                //     pub d_ino: u64,
1635                //     pub d_seekoff: u64,
1636                //     pub d_reclen: u16,
1637                //     pub d_namlen: u16,
1638                //     pub d_type: u8,
1639                //     pub d_name: [c_char; 1024],
1640                // }
1641
1642                let dirent_layout = this.libc_ty_layout(buf_type);
1643                let fields = &dirent_layout.fields;
1644                let d_name_offset = fields.offset(fields.count().strict_sub(1)).bytes();
1645
1646                // Determine the size of the buffer we have to allocate.
1647                let mut name = dir_entry.name; // not a Path as there are no separators!
1648                name.push("\0"); // Add a NUL terminator
1649                let name_bytes = name.as_encoded_bytes();
1650                let name_len = u64::try_from(name_bytes.len()).unwrap();
1651                let size = d_name_offset.strict_add(name_len);
1652
1653                let entry = this.allocate_ptr(
1654                    Size::from_bytes(size),
1655                    dirent_layout.align,
1656                    MiriMemoryKind::Runtime.into(),
1657                    AllocInit::Uninit,
1658                )?;
1659                let entry = this.ptr_to_mplace(entry.into(), dirent_layout);
1660
1661                // Write the name.
1662                // The name is not a normal field, we already computed the offset above.
1663                let name_ptr = entry.ptr().wrapping_offset(Size::from_bytes(d_name_offset), this);
1664                this.write_bytes_ptr(name_ptr, name_bytes.iter().copied())?;
1665
1666                // Write common fields.
1667                let ino_name =
1668                    if this.tcx.sess.target.os == Os::FreeBsd { "d_fileno" } else { "d_ino" };
1669                this.write_int_fields_named(
1670                    &[(ino_name, dir_entry.ino.into()), ("d_reclen", size.into())],
1671                    &entry,
1672                )?;
1673
1674                // Write "optional" fields.
1675                if let Some(d_off) = this.try_project_field_named(&entry, "d_off")? {
1676                    this.write_int(0, &d_off)?;
1677                }
1678                if let Some(d_seekoff) = this.try_project_field_named(&entry, "d_seekoff")? {
1679                    this.write_int(0, &d_seekoff)?;
1680                }
1681                if let Some(d_namlen) = this.try_project_field_named(&entry, "d_namlen")? {
1682                    this.write_int(name_len.strict_sub(1), &d_namlen)?;
1683                }
1684                if let Some(d_type) = this.try_project_field_named(&entry, "d_type")? {
1685                    this.write_int(dir_entry.d_type, &d_type)?;
1686                }
1687
1688                Some(entry.ptr())
1689            }
1690            None => {
1691                // end of stream: return NULL
1692                None
1693            }
1694            Some(Err(e)) => {
1695                this.set_last_error(e)?;
1696                None
1697            }
1698        };
1699
1700        let open_dir = this.machine.dirs.streams.get_mut(&dirp).unwrap();
1701        if let Some((old_entry, old_type)) =
1702            std::mem::replace(&mut open_dir.entry, entry.map(|e| (e, buf_type)))
1703        {
1704            if old_type != buf_type {
1705                throw_ub_format!("mixing different `readdir` variants on the same `DIR` instance");
1706            }
1707            this.deallocate_ptr(old_entry, None, MiriMemoryKind::Runtime.into())?;
1708        }
1709
1710        this.write_pointer(entry.unwrap_or_else(Pointer::null), dest)?;
1711        interp_ok(())
1712    }
1713
1714    fn dirfd(&mut self, dirp_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
1715        let this = self.eval_context_mut();
1716
1717        let dirp = this.read_target_usize(dirp_op)?;
1718
1719        let open_dir = this.machine.dirs.streams.get_mut(&dirp).ok_or_else(|| {
1720            err_ub_format!("the DIR pointer passed to `readdir` did not come from opendir")
1721        })?;
1722
1723        // Check that the backing FD is still valid.
1724        if this.machine.fds.get(open_dir.fd_num).is_none_or(|fd| fd.id() != open_dir.fd_id) {
1725            throw_ub_format!("the backing FD for this DIR stream has been tampered with");
1726        }
1727
1728        let fd_num = open_dir.fd_num;
1729        this.write_int(fd_num, dest)?;
1730        interp_ok(())
1731    }
1732
1733    fn closedir(&mut self, dirp_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1734        let this = self.eval_context_mut();
1735
1736        let dirp = this.read_target_usize(dirp_op)?;
1737
1738        // Reject if isolation is enabled.
1739        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1740            this.reject_in_isolation("`closedir`", reject_with)?;
1741            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1742        }
1743
1744        let mut open_dir = this.machine.dirs.streams.remove(&dirp).ok_or_else(|| {
1745            err_ub_format!("the DIR pointer passed to `closedir` did not come from opendir")
1746        })?;
1747
1748        // Check that the backing FD is still valid.
1749        if this.machine.fds.get(open_dir.fd_num).is_none_or(|fd| fd.id() != open_dir.fd_id) {
1750            throw_ub_format!("the backing FD for this DIR stream has been tampered with");
1751        }
1752        // And close it.
1753        this.close(open_dir.fd_num)?;
1754
1755        if let Some((entry, _type)) = open_dir.entry.take() {
1756            this.deallocate_ptr(entry, None, MiriMemoryKind::Runtime.into())?;
1757        }
1758        // We drop the `open_dir`, which will close the host dir handle.
1759        drop(open_dir);
1760
1761        interp_ok(Scalar::from_i32(0))
1762    }
1763
1764    fn ftruncate64(&mut self, fd_num: i32, length: i64) -> InterpResult<'tcx, Scalar> {
1765        let this = self.eval_context_mut();
1766
1767        let Some(fd) = this.machine.fds.get(fd_num) else {
1768            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1769        };
1770        let Some(file) = fd.downcast::<FileHandle>() else {
1771            // The docs say that EINVAL is returned when the FD "does not reference a regular file
1772            // or a POSIX shared memory object" (and we don't support shmem objects).
1773            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
1774        };
1775        if !file.writable {
1776            // man page says "EBADF or EINVAL", Linux seems to use EINVAL.
1777            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
1778        }
1779        assert!(this.machine.communicate(), "isolation should have prevented even opening a file");
1780
1781        if let Ok(length) = length.try_into() {
1782            let result = file.file.set_len(length);
1783            let result = this.try_unwrap_io_result(result.map(|_| 0i32))?;
1784            interp_ok(Scalar::from_i32(result))
1785        } else {
1786            this.set_errno_and_return_neg1_i32(LibcError("EINVAL"))
1787        }
1788    }
1789
1790    /// NOTE: According to the man page of `possix_fallocate`, it returns the error code instead
1791    /// of setting `errno`.
1792    fn posix_fallocate(
1793        &mut self,
1794        fd_num: i32,
1795        offset: i64,
1796        len: i64,
1797    ) -> InterpResult<'tcx, Scalar> {
1798        let this = self.eval_context_mut();
1799
1800        // Reject if isolation is enabled.
1801        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1802            this.reject_in_isolation("`posix_fallocate`", reject_with)?;
1803            // Return error code "EBADF" (bad fd).
1804            return interp_ok(this.eval_libc("EBADF"));
1805        }
1806
1807        match this.fallocate_impl(fd_num, offset, len)? {
1808            Ok(()) => interp_ok(Scalar::from_i32(0)),
1809            Err(e) => this.io_error_to_errnum(e),
1810        }
1811    }
1812
1813    fn linux_fallocate(
1814        &mut self,
1815        fd: i32,
1816        mode: i32,
1817        offset: i64,
1818        size: i64,
1819    ) -> InterpResult<'tcx, Scalar> {
1820        // This is mostly a copy of `posix_fallocate` except that errors are returned via errno.
1821        let this = self.eval_context_mut();
1822        this.assert_target_os_is_linux_like("fallocate");
1823
1824        // Reject if isolation is enabled.
1825        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1826            this.reject_in_isolation("`fallocate`", reject_with)?;
1827            // Set error code "EBADF" (bad fd).
1828            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1829        }
1830
1831        // We only support `fallocate` as a replacement for `posix_fallocate` on linux,
1832        // so a non-default `mode` is not supported.
1833        if mode != 0 {
1834            throw_unsup_format!("unsupported flags for `fallocate` in `mode` argument: {mode:#x}")
1835        }
1836
1837        match this.fallocate_impl(fd, offset, size)? {
1838            Ok(()) => interp_ok(Scalar::from_i32(0)),
1839            Err(e) => this.set_errno_and_return_neg1_i32(e),
1840        }
1841    }
1842
1843    /// Shared logic between `posix_fallocate` and `linux_fallocate`.
1844    fn fallocate_impl(
1845        &self,
1846        fd_num: i32,
1847        offset: i64,
1848        len: i64,
1849    ) -> InterpResult<'tcx, Result<(), IoError>> {
1850        let this = self.eval_context_ref();
1851
1852        // EINVAL is returned/set when: "offset was less than 0, or len was less than or equal to 0".
1853        if offset < 0 || len <= 0 {
1854            return interp_ok(Err(LibcError("EINVAL")));
1855        }
1856
1857        let Some(fd) = this.machine.fds.get(fd_num) else {
1858            return interp_ok(Err(LibcError("EBADF")));
1859        };
1860        let Some(file) = fd.downcast::<FileHandle>() else {
1861            // Man page specifies to return ENODEV if `fd` is not a regular file.
1862            return interp_ok(Err(LibcError("ENODEV")));
1863        };
1864
1865        if !file.writable {
1866            return interp_ok(Err(LibcError("EBADF")));
1867        }
1868
1869        let current_size = match file.file.metadata() {
1870            Ok(metadata) => metadata.len(),
1871            Err(err) => return interp_ok(Err(err.into())),
1872        };
1873
1874        // Checked i64 addition, to ensure the result does not exceed the max file size.
1875        let new_size = match offset.checked_add(len) {
1876            // `new_size` is definitely non-negative, so we can cast to `u64`.
1877            Some(new_size) => u64::try_from(new_size).unwrap(),
1878            None => return interp_ok(Err(LibcError("EFBIG"))), // new size too big
1879        };
1880
1881        // If the size of the file is less than offset+size, then the file is increased to this
1882        // size; otherwise the file size is left unchanged.
1883        if current_size < new_size {
1884            match file.file.set_len(new_size) {
1885                Ok(()) => interp_ok(Ok(())),
1886                Err(err) => interp_ok(Err(err.into())),
1887            }
1888        } else {
1889            interp_ok(Ok(()))
1890        }
1891    }
1892
1893    fn fsync(&mut self, fd_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1894        // On macOS, `fsync` (unlike `fcntl(F_FULLFSYNC)`) does not wait for the
1895        // underlying disk to finish writing. In the interest of host compatibility,
1896        // we conservatively implement this with `sync_all`, which
1897        // *does* wait for the disk.
1898
1899        let this = self.eval_context_mut();
1900
1901        let fd = this.read_scalar(fd_op)?.to_i32()?;
1902
1903        this.ffullsync_fd(fd)
1904    }
1905
1906    fn ffullsync_fd(&mut self, fd_num: i32) -> InterpResult<'tcx, Scalar> {
1907        let this = self.eval_context_mut();
1908        let Some(fd) = this.machine.fds.get(fd_num) else {
1909            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1910        };
1911        // Only regular files support synchronization.
1912        let file = fd.downcast::<FileHandle>().ok_or_else(|| {
1913            err_unsup_format!("`fsync` is only supported on file-backed file descriptors")
1914        })?;
1915        assert!(this.machine.communicate(), "isolation should have prevented even opening a file");
1916
1917        let io_result = maybe_sync_file(&file, File::sync_all);
1918        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(io_result)?))
1919    }
1920
1921    fn fdatasync(&mut self, fd_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
1922        let this = self.eval_context_mut();
1923
1924        let fd = this.read_scalar(fd_op)?.to_i32()?;
1925
1926        let Some(fd) = this.machine.fds.get(fd) else {
1927            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1928        };
1929        // Only regular files support synchronization.
1930        let file = fd.downcast::<FileHandle>().ok_or_else(|| {
1931            err_unsup_format!("`fdatasync` is only supported on file-backed file descriptors")
1932        })?;
1933        assert!(this.machine.communicate(), "isolation should have prevented even opening a file");
1934
1935        let io_result = maybe_sync_file(&file, File::sync_data);
1936        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(io_result)?))
1937    }
1938
1939    /// `futimens(fd, times)`: set `fd`'s access/modification times. `times` is `[atime, mtime]`, or
1940    /// NULL to set both to now.
1941    fn futimens(
1942        &mut self,
1943        fd_op: &OpTy<'tcx>,
1944        times_op: &OpTy<'tcx>,
1945    ) -> InterpResult<'tcx, Scalar> {
1946        let this = self.eval_context_mut();
1947
1948        let fd_num = this.read_scalar(fd_op)?.to_i32()?;
1949        let times = this.deref_pointer(times_op)?;
1950
1951        let Some(fd) = this.machine.fds.get(fd_num) else {
1952            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
1953        };
1954        let file = fd.downcast::<FileHandle>().ok_or_else(|| {
1955            err_unsup_format!("`futimens` is only supported on file-backed file descriptors")
1956        })?;
1957        assert!(this.machine.communicate(), "isolation should have prevented even opening a file");
1958
1959        let Some((access, modified)) = this.parse_utimens_times(&times)? else {
1960            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
1961        };
1962        let result = file.file.set_times(host_file_times_from_updates(access, modified));
1963        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|()| 0i32))?))
1964    }
1965
1966    /// `utimensat(dirfd, path, times, flags)`: like `futimens`, but for the file at `path`. With
1967    /// `AT_SYMLINK_NOFOLLOW`, a symlink at `path` is updated itself rather than its target.
1968    fn utimensat(
1969        &mut self,
1970        dirfd_op: &OpTy<'tcx>,
1971        path_op: &OpTy<'tcx>,
1972        times_op: &OpTy<'tcx>,
1973        flags_op: &OpTy<'tcx>,
1974    ) -> InterpResult<'tcx, Scalar> {
1975        let this = self.eval_context_mut();
1976
1977        let dirfd = this.read_scalar(dirfd_op)?.to_i32()?;
1978        let path_ptr = this.read_pointer(path_op)?;
1979        let times = this.deref_pointer(times_op)?;
1980        let flags = this.read_scalar(flags_op)?.to_i32()?;
1981
1982        if this.ptr_is_null(path_ptr)? {
1983            // With `AT_FDCWD` this is a bad address on all systems. With any other `dirfd`, Linux
1984            // operates on `dirfd` itself (like `futimens`) while macOS still fails.
1985            if dirfd != this.eval_libc_i32("AT_FDCWD") {
1986                throw_unsup_format!(
1987                    "`utimensat` with a NULL path is only supported for `AT_FDCWD`"
1988                );
1989            }
1990            return this.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
1991        }
1992        let path = this.read_path_from_c_str(path_ptr)?.into_owned();
1993
1994        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
1995            this.reject_in_isolation("`utimensat`", reject_with)?;
1996            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
1997        }
1998
1999        let mut flags = flags;
2000        // Parse known flags and subtract them from `flags`.
2001        let at_symlink_nofollow = this.eval_libc_i32("AT_SYMLINK_NOFOLLOW");
2002        let symlink_nofollow_flag = flags & at_symlink_nofollow == at_symlink_nofollow;
2003        flags &= !at_symlink_nofollow;
2004
2005        if flags != 0 {
2006            throw_unsup_format!("unsupported flags for `utimensat`: {flags:#x}")
2007        }
2008
2009        if !(path.is_absolute() || dirfd == this.eval_libc_i32("AT_FDCWD")) {
2010            throw_unsup_format!("`utimensat` with a path relative to a `dirfd` is not supported");
2011        }
2012
2013        let Some((access, modified)) = this.parse_utimens_times(&times)? else {
2014            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
2015        };
2016        if matches!((access, modified), (TimeUpdate::Omit, TimeUpdate::Omit)) {
2017            // Nothing to do. Behavior in this case differs between platforms: Linux always
2018            // succeeds, macOS/FreeBSD check whether the file exists. POSIX arguably allows both.
2019            // We decide to follow Linux.
2020            return interp_ok(Scalar::from_i32(0));
2021        }
2022        let filetimes = host_file_times_from_updates(access, modified);
2023        let result = if symlink_nofollow_flag {
2024            fs::set_times_nofollow(path, filetimes)
2025        } else {
2026            fs::set_times(path, filetimes)
2027        };
2028        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|()| 0i32))?))
2029    }
2030
2031    fn linux_sync_file_range(
2032        &mut self,
2033        fd_op: &OpTy<'tcx>,
2034        offset_op: &OpTy<'tcx>,
2035        nbytes_op: &OpTy<'tcx>,
2036        flags_op: &OpTy<'tcx>,
2037    ) -> InterpResult<'tcx, Scalar> {
2038        let this = self.eval_context_mut();
2039        this.assert_target_os_is_linux_like("sync_file_range");
2040
2041        let fd = this.read_scalar(fd_op)?.to_i32()?;
2042        let offset = this.read_scalar(offset_op)?.to_i64()?;
2043        let nbytes = this.read_scalar(nbytes_op)?.to_i64()?;
2044        let flags = this.read_scalar(flags_op)?.to_i32()?;
2045
2046        if offset < 0 || nbytes < 0 {
2047            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
2048        }
2049        let allowed_flags = this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_BEFORE")
2050            | this.eval_libc_i32("SYNC_FILE_RANGE_WRITE")
2051            | this.eval_libc_i32("SYNC_FILE_RANGE_WAIT_AFTER");
2052        if flags & allowed_flags != flags {
2053            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
2054        }
2055
2056        let Some(fd) = this.machine.fds.get(fd) else {
2057            return this.set_errno_and_return_neg1_i32(LibcError("EBADF"));
2058        };
2059        // Only regular files support synchronization.
2060        let file = fd.downcast::<FileHandle>().ok_or_else(|| {
2061            err_unsup_format!("`sync_data_range` is only supported on file-backed file descriptors")
2062        })?;
2063        assert!(this.machine.communicate(), "isolation should have prevented even opening a file");
2064
2065        let io_result = maybe_sync_file(&file, File::sync_data);
2066        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(io_result)?))
2067    }
2068
2069    fn readlink(
2070        &mut self,
2071        pathname_op: &OpTy<'tcx>,
2072        buf_op: &OpTy<'tcx>,
2073        bufsize_op: &OpTy<'tcx>,
2074    ) -> InterpResult<'tcx, i64> {
2075        let this = self.eval_context_mut();
2076
2077        let pathname = this.read_os_str_from_c_str(this.read_pointer(pathname_op)?)?;
2078        let buf = this.read_pointer(buf_op)?;
2079        let bufsize = this.read_target_usize(bufsize_op)?;
2080
2081        // Reject if isolation is enabled.
2082        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
2083            this.reject_in_isolation("`readlink`", reject_with)?;
2084            this.set_last_error(LibcError("EACCES"))?;
2085            return interp_ok(-1);
2086        }
2087
2088        // Special case the procfs link to the current executable so that
2089        // `std::env::current_exe` works in cross-execution.
2090        let self_exe = match this.tcx.sess.target.os {
2091            Os::Linux | Os::Android => Some("/proc/self/exe"),
2092            Os::Solaris | Os::Illumos => Some("/proc/self/path/a.out"),
2093            _ => None,
2094        };
2095        let result = if self_exe.is_some() && pathname.to_str() == self_exe {
2096            this.machine.current_exe.clone().ok_or(ErrorKind::NotFound.into())
2097        } else if matches!(
2098            this.tcx.sess.target.os,
2099            Os::Linux | Os::Android | Os::Illumos | Os::Solaris
2100        ) && path::absolute(pathname).is_ok_and(|path| path.starts_with("/proc"))
2101        {
2102            // Trying to read a symlink inside `/proc` is likely going to be nonsense, e.g.
2103            // `/proc/self/fd/N` doesn't use the same FD numbering. So we pretend nothing exists.
2104            this.set_last_error(ErrorKind::NotFound)?;
2105            return interp_ok(-1);
2106        } else {
2107            // We read `pathname` as `OsStr` above so we could do the /proc/self/exe check.
2108            // But now we need a (host) path.
2109            let pathname = this.convert_path(Cow::Borrowed(pathname), PathConversion::TargetToHost);
2110            std::fs::read_link(pathname)
2111        };
2112
2113        match result {
2114            Ok(resolved) => {
2115                // 'readlink' truncates the resolved path if the provided buffer is not large
2116                // enough, and does *not* add a null terminator. That means we cannot use the usual
2117                // `write_path_to_c_str` and have to re-implement parts of it ourselves.
2118                let resolved = this
2119                    .convert_path(Cow::Borrowed(resolved.as_ref()), PathConversion::HostToTarget);
2120                let mut path_bytes = resolved.as_encoded_bytes();
2121                let bufsize: usize = bufsize.try_into().unwrap();
2122                if path_bytes.len() > bufsize {
2123                    path_bytes = &path_bytes[..bufsize]
2124                }
2125                this.write_bytes_ptr(buf, path_bytes.iter().copied())?;
2126                interp_ok(path_bytes.len().try_into().unwrap())
2127            }
2128            Err(e) => {
2129                this.set_last_error(e)?;
2130                interp_ok(-1)
2131            }
2132        }
2133    }
2134
2135    fn isatty(&mut self, miri_fd: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
2136        let this = self.eval_context_mut();
2137        // "returns 1 if fd is an open file descriptor referring to a terminal;
2138        // otherwise 0 is returned, and errno is set to indicate the error"
2139        let fd = this.read_scalar(miri_fd)?.to_i32()?;
2140        let error = if let Some(fd) = this.machine.fds.get(fd) {
2141            if fd.is_tty(this.machine.communicate()) {
2142                return interp_ok(Scalar::from_i32(1));
2143            } else {
2144                LibcError("ENOTTY")
2145            }
2146        } else {
2147            // FD does not exist
2148            LibcError("EBADF")
2149        };
2150        this.set_last_error(error)?;
2151        interp_ok(Scalar::from_i32(0))
2152    }
2153
2154    fn realpath(
2155        &mut self,
2156        path_op: &OpTy<'tcx>,
2157        processed_path_op: &OpTy<'tcx>,
2158    ) -> InterpResult<'tcx, Scalar> {
2159        let this = self.eval_context_mut();
2160        this.assert_target_os_is_unix("realpath");
2161
2162        let pathname = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
2163        let processed_ptr = this.read_pointer(processed_path_op)?;
2164
2165        // Reject if isolation is enabled.
2166        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
2167            this.reject_in_isolation("`realpath`", reject_with)?;
2168            this.set_last_error(LibcError("EACCES"))?;
2169            return interp_ok(Scalar::from_target_usize(0, this));
2170        }
2171
2172        let result = std::fs::canonicalize(pathname);
2173        match result {
2174            Ok(resolved) => {
2175                let path_max = this
2176                    .eval_libc_i32("PATH_MAX")
2177                    .try_into()
2178                    .expect("PATH_MAX does not fit in u64");
2179                let dest = if this.ptr_is_null(processed_ptr)? {
2180                    // POSIX says behavior when passing a null pointer is implementation-defined,
2181                    // but GNU/linux, freebsd, netbsd, bionic/android, and macos all treat a null pointer
2182                    // similarly to:
2183                    //
2184                    // "If resolved_path is specified as NULL, then realpath() uses
2185                    // malloc(3) to allocate a buffer of up to PATH_MAX bytes to hold
2186                    // the resolved pathname, and returns a pointer to this buffer.  The
2187                    // caller should deallocate this buffer using free(3)."
2188                    // <https://man7.org/linux/man-pages/man3/realpath.3.html>
2189                    this.alloc_path_as_c_str(&resolved, MiriMemoryKind::C.into())?
2190                } else {
2191                    let (wrote_path, _) =
2192                        this.write_path_to_c_str(&resolved, processed_ptr, path_max)?;
2193
2194                    if !wrote_path {
2195                        // Note that we do not explicitly handle `FILENAME_MAX`
2196                        // (different from `PATH_MAX` above) as it is Linux-specific and
2197                        // seems like a bit of a mess anyway: <https://eklitzke.org/path-max-is-tricky>.
2198                        this.set_last_error(LibcError("ENAMETOOLONG"))?;
2199                        return interp_ok(Scalar::from_target_usize(0, this));
2200                    }
2201                    processed_ptr
2202                };
2203
2204                interp_ok(Scalar::from_maybe_pointer(dest, this))
2205            }
2206            Err(e) => {
2207                this.set_last_error(e)?;
2208                interp_ok(Scalar::from_target_usize(0, this))
2209            }
2210        }
2211    }
2212    fn mkstemp(&mut self, template_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
2213        use rand::seq::IndexedRandom;
2214
2215        // POSIX defines the template string.
2216        const TEMPFILE_TEMPLATE_STR: &str = "XXXXXX";
2217
2218        let this = self.eval_context_mut();
2219        this.assert_target_os_is_unix("mkstemp");
2220
2221        // POSIX defines the maximum number of attempts before failure.
2222        //
2223        // `mkstemp()` relies on `tmpnam()` which in turn relies on `TMP_MAX`.
2224        // POSIX says this about `TMP_MAX`:
2225        // * Minimum number of unique filenames generated by `tmpnam()`.
2226        // * Maximum number of times an application can call `tmpnam()` reliably.
2227        //   * The value of `TMP_MAX` is at least 25.
2228        //   * On XSI-conformant systems, the value of `TMP_MAX` is at least 10000.
2229        // See <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdio.h.html>.
2230        let max_attempts = this.eval_libc_u32("TMP_MAX");
2231
2232        // Get the raw bytes from the template -- as a byte slice, this is a string in the target
2233        // (and the target is unix, so a byte slice is the right representation).
2234        let template_ptr = this.read_pointer(template_op)?;
2235        let mut template = this.eval_context_ref().read_c_str(template_ptr)?.to_owned();
2236        let template_bytes = template.as_mut_slice();
2237
2238        // Reject if isolation is enabled.
2239        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
2240            this.reject_in_isolation("`mkstemp`", reject_with)?;
2241            return this.set_errno_and_return_neg1_i32(LibcError("EACCES"));
2242        }
2243
2244        // Get the bytes of the suffix we expect in _target_ encoding.
2245        let suffix_bytes = TEMPFILE_TEMPLATE_STR.as_bytes();
2246
2247        // At this point we have one `&[u8]` that represents the template and one `&[u8]`
2248        // that represents the expected suffix.
2249
2250        // Now we figure out the index of the slice we expect to contain the suffix.
2251        let start_pos = template_bytes.len().saturating_sub(suffix_bytes.len());
2252        let end_pos = template_bytes.len();
2253        let last_six_char_bytes = &template_bytes[start_pos..end_pos];
2254
2255        // If we don't find the suffix, it is an error.
2256        if last_six_char_bytes != suffix_bytes {
2257            return this.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
2258        }
2259
2260        // At this point we know we have 6 ASCII 'X' characters as a suffix.
2261
2262        // From <https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/sysdeps/posix/tempname.c#L175>
2263        const SUBSTITUTIONS: &[char; 62] = &[
2264            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
2265            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
2266            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
2267            'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2268        ];
2269
2270        // The file is opened with specific options, which Rust does not expose in a portable way.
2271        // So we use specific APIs depending on the host OS.
2272        let mut fopts = OpenOptions::new();
2273        fopts.read(true).write(true).create_new(true);
2274
2275        cfg_select! {
2276            unix => {
2277                use std::os::unix::fs::OpenOptionsExt;
2278                // Do not allow others to read or modify this file.
2279                fopts.mode(0o600);
2280                fopts.custom_flags(libc::O_EXCL);
2281            }
2282            windows => {
2283                use std::os::windows::fs::OpenOptionsExt;
2284                // Do not allow others to read or modify this file.
2285                fopts.share_mode(0);
2286            }
2287            _ => {
2288                throw_unsup_format!("`mkstemp` is not supported on this host OS");
2289            }
2290        }
2291
2292        // If the generated file already exists, we will try again `max_attempts` many times.
2293        for _ in 0..max_attempts {
2294            let rng = this.machine.rng.get_mut();
2295
2296            // Generate a random unique suffix.
2297            let unique_suffix =
2298                (0..6).map(|_| SUBSTITUTIONS.choose(rng).unwrap()).collect::<String>();
2299
2300            // Replace the template string with the random string.
2301            template_bytes[start_pos..end_pos].copy_from_slice(unique_suffix.as_bytes());
2302
2303            // Write the modified template back to the passed in pointer to maintain POSIX semantics.
2304            this.write_bytes_ptr(template_ptr, template_bytes.iter().copied())?;
2305
2306            // See if we can create and open this file.
2307            let file = fopts.open(bytes_to_os_str(template_bytes)?);
2308            match file {
2309                Ok(f) => {
2310                    let Some(fd) = this.machine.fds.insert_new(FileHandle {
2311                        file: f,
2312                        writable: true,
2313                        readable: true,
2314                        append: false,
2315                    }) else {
2316                        return this.set_errno_and_return_neg1_i32(LibcError("EMFILE"));
2317                    };
2318                    return interp_ok(Scalar::from_i32(fd));
2319                }
2320                Err(e) =>
2321                    match e.kind() {
2322                        // If the random file already exists, keep trying.
2323                        ErrorKind::AlreadyExists => continue,
2324                        // Any other errors are returned to the caller.
2325                        _ => {
2326                            // "On error, -1 is returned, and errno is set to
2327                            // indicate the error"
2328                            return this.set_errno_and_return_neg1_i32(e);
2329                        }
2330                    },
2331            }
2332        }
2333
2334        // We ran out of attempts to create the file, return an error.
2335        this.set_errno_and_return_neg1_i32(LibcError("EEXIST"))
2336    }
2337
2338    /// Only supports null offset pointers, i.e. copying from and advancing the file positions.
2339    fn linux_copy_file_range(
2340        &mut self,
2341        fd_in_op: &OpTy<'tcx>,
2342        off_in_op: &OpTy<'tcx>,
2343        fd_out_op: &OpTy<'tcx>,
2344        off_out_op: &OpTy<'tcx>,
2345        len_op: &OpTy<'tcx>,
2346        flags_op: &OpTy<'tcx>,
2347        dest: &MPlaceTy<'tcx>,
2348    ) -> InterpResult<'tcx> {
2349        let ecx = self.eval_context_mut();
2350        ecx.assert_target_os_is_linux_like("copy_file_range");
2351
2352        let fd_in = ecx.read_scalar(fd_in_op)?.to_i32()?;
2353        let off_in = ecx.read_pointer(off_in_op)?;
2354        let fd_out = ecx.read_scalar(fd_out_op)?.to_i32()?;
2355        let off_out = ecx.read_pointer(off_out_op)?;
2356        let len = ecx.read_target_usize(len_op)?;
2357        let flags = ecx.read_scalar(flags_op)?.to_u32()?;
2358
2359        let (Some(fd_in), Some(fd_out)) = (ecx.machine.fds.get(fd_in), ecx.machine.fds.get(fd_out))
2360        else {
2361            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
2362        };
2363        if flags != 0 {
2364            throw_unsup_format!("`copy_file_range` with non-zero flags is not supported");
2365        }
2366        if !ecx.ptr_is_null(off_in)? || !ecx.ptr_is_null(off_out)? {
2367            throw_unsup_format!("`copy_file_range` with non-null offset pointers is not supported");
2368        }
2369        // Like Linux, check for directories (EISDIR), then other non-regular files (EINVAL),
2370        // then the access modes (EBADF).
2371        let is_dir = |fd: &DynFileDescriptionRef| fd.clone().downcast::<DirHandle>().is_some();
2372        let as_regular_file = |fd: DynFileDescriptionRef| {
2373            let file = fd.downcast::<FileHandle>()?;
2374            // Ensure we catch on-disk FIFOs and unix domain sockets.
2375            file.file.metadata().is_ok_and(|metadata| metadata.is_file()).then_some(file)
2376        };
2377        if is_dir(&fd_in) || is_dir(&fd_out) {
2378            return ecx.set_errno_and_return_neg1(LibcError("EISDIR"), dest);
2379        }
2380        let (Some(file_in), Some(file_out)) = (as_regular_file(fd_in), as_regular_file(fd_out))
2381        else {
2382            return ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest);
2383        };
2384        if !file_in.readable || !file_out.writable || file_out.append {
2385            // The docs explicitly say that O_APPEND on the output file is forbidden.
2386            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
2387        }
2388        assert!(ecx.machine.communicate(), "isolation should have prevented even opening a file");
2389
2390        // Non-deterministically decide to further reduce the length, simulating a partial copy (but
2391        // never to 0, that would indicate EOF).
2392        let len = if ecx.machine.short_fd_operations
2393            && (file_in.short_fd_operations() || file_out.short_fd_operations())
2394            && len >= 2
2395            && let rng = ecx.machine.rng.get_mut()
2396            // Big accesses are shortened with a chance of 75%.
2397            && (rng.random() || (len >= BIG_ACCESS && rng.random()))
2398        {
2399            // Also cap length to remaining input length as otherwise halving it does nothing.
2400            let mut input = &file_in.file;
2401            let remaining_bytes =
2402                try { input.stream_len()?.saturating_sub(input.stream_position()?).clamp_to(2..) };
2403            let len = len.clamp_to(..=remaining_bytes.unwrap_or(u64::MAX));
2404            len / 2 // since `len` is at least 2, the result is still at least 1
2405        } else {
2406            len
2407        };
2408
2409        let copy = || -> io::Result<u64> {
2410            let (mut input, mut output) = (&file_in.file, &file_out.file);
2411            let (pos_in, pos_out) = (input.stream_position()?, output.stream_position()?);
2412
2413            // Error if both FDs refer to the same file and the ranges overlap.
2414            let (meta_in, meta_out) = (input.metadata()?, output.metadata()?);
2415            if same_host_file(&meta_in, &meta_out)
2416                && (pos_in.checked_add(len).is_none_or(|end_in| end_in > pos_out)
2417                    && pos_out.checked_add(len).is_none_or(|end_out| end_out > pos_in))
2418            {
2419                return Err(io::ErrorKind::InvalidInput.into());
2420            }
2421
2422            io::copy(&mut input.take(len), &mut output).inspect_err(|_| {
2423                // Like Linux, leave the file positions unchanged on error. See
2424                // <https://github.com/torvalds/linux/blob/81dfa035891f0502674332ee97db348a16486de0/fs/read_write.c#L1686-L1703>.
2425                let _ = input.seek(SeekFrom::Start(pos_in));
2426                let _ = output.seek(SeekFrom::Start(pos_out));
2427            })
2428        };
2429        ecx.return_io_result_via_errno(copy(), dest)
2430    }
2431}
2432
2433/// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when
2434/// `time` is Ok. Returns `None` if `time` is an error. Fails if `time` happens before the unix
2435/// epoch.
2436fn extract_sec_and_nsec<'tcx>(
2437    time: std::io::Result<SystemTime>,
2438) -> InterpResult<'tcx, Option<(u64, u32)>> {
2439    match time.ok() {
2440        Some(time) => {
2441            let duration = system_time_to_duration(&time)?;
2442            interp_ok(Some((duration.as_secs(), duration.subsec_nanos())))
2443        }
2444        None => interp_ok(None),
2445    }
2446}
2447
2448fn file_type_to_mode_name(file_type: std::fs::FileType) -> &'static str {
2449    if file_type.is_file() {
2450        "S_IFREG"
2451    } else if file_type.is_dir() {
2452        "S_IFDIR"
2453    } else if file_type.is_symlink() {
2454        "S_IFLNK"
2455    } else {
2456        // Certain file types are only available when the host is a Unix system.
2457        #[cfg(unix)]
2458        {
2459            use std::os::unix::fs::FileTypeExt;
2460            if file_type.is_socket() {
2461                return "S_IFSOCK";
2462            } else if file_type.is_fifo() {
2463                return "S_IFIFO";
2464            } else if file_type.is_char_device() {
2465                return "S_IFCHR";
2466            } else if file_type.is_block_device() {
2467                return "S_IFBLK";
2468            }
2469        }
2470        "S_IFREG"
2471    }
2472}
2473
2474/// Stores a file's metadata in order to avoid code duplication in the different metadata related
2475/// shims.
2476///
2477/// Some fields are host/platform-specific. `None` means that Miri does not have a real value for
2478/// this field, for example because the metadata is synthetic or because the host platform does not
2479/// expose it. `statx` must only advertise the corresponding `STATX_*` bit when the field is `Some`;
2480/// legacy `stat` writes zero for `None` to preserve the old fallback behavior.
2481struct FileMetadata {
2482    /// This holds both the file type (dir, regular, symlink, ...) and permissions.
2483    mode: u32,
2484    size: u64,
2485    created: Option<(u64, u32)>,
2486    accessed: Option<(u64, u32)>,
2487    modified: Option<(u64, u32)>,
2488    dev: Option<u64>,
2489    ino: Option<u64>,
2490    nlink: Option<u64>,
2491    uid: Option<u32>,
2492    gid: Option<u32>,
2493    blksize: Option<u64>,
2494    blocks: Option<u64>,
2495}
2496
2497impl FileMetadata {
2498    /// Implements the shared "metadata at" semantics of `fstatat` and `statx`.
2499    fn at<'tcx>(
2500        ecx: &mut MiriInterpCx<'tcx>,
2501        dirfd: FdNum,
2502        path: &Path,
2503        symlink_nofollow_flag: bool,
2504        empty_path_flag: bool,
2505    ) -> InterpResult<'tcx, Result<FileMetadata, IoError>> {
2506        // If the path is empty, and the AT_EMPTY_PATH flag is set, we query the open file
2507        // represented by dirfd, whether it's a directory or otherwise.
2508        if path.is_empty() {
2509            // no path: invalid by default, load metadata about dirfd with flag
2510            if !empty_path_flag {
2511                return interp_ok(Err(LibcError("ENOENT")));
2512            }
2513            FileMetadata::from_fd_num(ecx, dirfd)
2514        } else if path.is_absolute() || dirfd == ecx.eval_libc_i32("AT_FDCWD") {
2515            // Either absolute path (dirfd is ignored) or relative to working directory.
2516            FileMetadata::from_host(
2517                ecx,
2518                if symlink_nofollow_flag { path.symlink_metadata() } else { path.metadata() },
2519            )
2520        } else {
2521            // relative to dirfd, which must be a directory handle
2522            let Some(fd) = ecx.machine.fds.get(dirfd) else {
2523                return interp_ok(Err(LibcError("EBADF")));
2524            };
2525            let Some(dir) = fd.downcast::<DirHandle>() else {
2526                return interp_ok(Err(LibcError("ENOTDIR")));
2527            };
2528
2529            // Windows does not support "." relative to a `Dir` handle, but the empty path works.
2530            // (https://github.com/rust-lang/rust/issues/163032)
2531            let path =
2532                if cfg!(windows) && path.to_str() == Some(".") { Path::new("") } else { path };
2533            let metadata = if symlink_nofollow_flag {
2534                dir.dir.symlink_metadata(path)
2535            } else {
2536                dir.dir.metadata(path)
2537            };
2538            FileMetadata::from_host(ecx, metadata)
2539        }
2540    }
2541
2542    fn from_fd_num<'tcx>(
2543        ecx: &mut MiriInterpCx<'tcx>,
2544        fd_num: FdNum,
2545    ) -> InterpResult<'tcx, Result<FileMetadata, IoError>> {
2546        let Some(fd) = ecx.machine.fds.get(fd_num) else {
2547            return interp_ok(Err(LibcError("EBADF")));
2548        };
2549        match fd.metadata(ecx.machine.communicate())? {
2550            Either::Left(host) => Self::from_host(ecx, host),
2551            Either::Right(mode_name) => Self::synthetic(ecx, mode_name),
2552        }
2553    }
2554
2555    fn synthetic<'tcx>(
2556        ecx: &mut MiriInterpCx<'tcx>,
2557        mode_name: &str,
2558    ) -> InterpResult<'tcx, Result<FileMetadata, IoError>> {
2559        let mode = ecx.eval_libc_int::<u32>(mode_name);
2560        // We observed 0x777 on sockets and 0x600 on pipes...
2561        let mode = mode | 0o666;
2562        interp_ok(Ok(FileMetadata {
2563            mode,
2564            size: 0,
2565            created: None,
2566            accessed: None,
2567            modified: None,
2568            dev: None,
2569            uid: None,
2570            gid: None,
2571            blksize: None,
2572            blocks: None,
2573            ino: None,
2574            nlink: None,
2575        }))
2576    }
2577
2578    fn from_host<'tcx>(
2579        ecx: &mut MiriInterpCx<'tcx>,
2580        metadata: Result<std::fs::Metadata, std::io::Error>,
2581    ) -> InterpResult<'tcx, Result<FileMetadata, IoError>> {
2582        let metadata = match metadata {
2583            Ok(metadata) => metadata,
2584            Err(e) => {
2585                return interp_ok(Err(e.into()));
2586            }
2587        };
2588
2589        let file_type = metadata.file_type();
2590        let mut mode = ecx.eval_libc_int::<u32>(file_type_to_mode_name(file_type));
2591
2592        let size = metadata.len();
2593
2594        let created = extract_sec_and_nsec(metadata.created())?;
2595        let accessed = extract_sec_and_nsec(metadata.accessed())?;
2596        let modified = extract_sec_and_nsec(metadata.modified())?;
2597
2598        // FIXME: Provide more fields using platform specific methods.
2599
2600        cfg_select! {
2601            unix => {
2602                use std::os::unix::fs::{MetadataExt, PermissionsExt};
2603
2604                let dev = metadata.dev();
2605                let ino = metadata.ino();
2606                let nlink = metadata.nlink();
2607                let uid = metadata.uid();
2608                let gid = metadata.gid();
2609                let blksize = metadata.blksize();
2610                let blocks = metadata.blocks();
2611
2612                mode |= metadata.permissions().mode();
2613
2614                interp_ok(Ok(FileMetadata {
2615                    mode,
2616                    size,
2617                    created,
2618                    accessed,
2619                    modified,
2620                    dev: Some(dev),
2621                    ino: Some(ino),
2622                    nlink: Some(nlink),
2623                    uid: Some(uid),
2624                    gid: Some(gid),
2625                    blksize: Some(blksize),
2626                    blocks: Some(blocks),
2627                }))
2628            }
2629            _ => {
2630                // Emulate "everyone can read" or "everyone can read and write".
2631                mode |= if metadata.permissions().readonly() { 0o444 } else { 0o666 };
2632
2633                interp_ok(Ok(FileMetadata {
2634                    mode,
2635                    size,
2636                    created,
2637                    accessed,
2638                    modified,
2639                    dev: None,
2640                    ino: None,
2641                    nlink: None,
2642                    uid: None,
2643                    gid: None,
2644                    blksize: None,
2645                    blocks: None,
2646                }))
2647            }
2648        }
2649    }
2650}