Skip to main content

miri/shims/
files.rs

1use std::any::Any;
2use std::collections::BTreeMap;
3use std::convert::BoundedCastFromInt;
4use std::io::{ErrorKind, IsTerminal, Read, Seek, SeekFrom, Write};
5use std::marker::CoercePointee;
6use std::ops::Deref;
7use std::rc::{Rc, Weak};
8use std::{fs, io};
9
10use rustc_abi::Size;
11
12use crate::shims::unix::UnixFileDescription;
13use crate::*;
14
15/// Internal type of a file-descriptor - this is what [`FdTable`] expects
16pub type FdNum = i32;
17
18/// The maximum number of open FDs.
19pub const FD_LIMIT: FdNum = 524288; // default hard limit on Debian
20
21/// Accesses this large have a higher chance of being shortened.
22/// We use twice the usual page size, which means the shortened access is at least a page.
23pub const BIG_ACCESS: u64 = 8 * 1024;
24
25/// A unique id for file descriptions. While we could use the address, considering that
26/// is definitely unique, the address would expose interpreter internal state when used
27/// for sorting things. So instead we generate a unique id per file description which is the same
28/// for all `dup`licates and is never reused.
29#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
30pub struct FdId(usize);
31
32impl FdId {
33    pub fn to_usize(self) -> usize {
34        self.0
35    }
36
37    /// Create a new fd id from a `usize` without checking if this fd exists.
38    pub fn new_unchecked(id: usize) -> Self {
39        Self(id)
40    }
41}
42
43#[derive(Debug, Clone)]
44struct FdIdWith<T: ?Sized> {
45    id: FdId,
46    inner: T,
47}
48
49/// A refcounted pointer to a file description, also tracking the
50/// globally unique ID of this file description.
51#[repr(transparent)]
52#[derive(CoercePointee, Debug)]
53// Sadly `CoercePointee` does not let us keep the `FdId` *outside* the `Rc`.
54pub struct FileDescriptionRef<T: ?Sized>(Rc<FdIdWith<T>>);
55
56impl<T: ?Sized> Clone for FileDescriptionRef<T> {
57    fn clone(&self) -> Self {
58        FileDescriptionRef(self.0.clone())
59    }
60}
61
62impl<T: ?Sized> Deref for FileDescriptionRef<T> {
63    type Target = T;
64    fn deref(&self) -> &T {
65        &self.0.inner
66    }
67}
68
69impl<T: ?Sized> FileDescriptionRef<T> {
70    pub fn id(&self) -> FdId {
71        self.0.id
72    }
73}
74
75impl<T: ?Sized> PartialEq for FileDescriptionRef<T> {
76    fn eq(&self, other: &Self) -> bool {
77        self.0.id == other.0.id
78    }
79}
80
81impl<T: ?Sized> Eq for FileDescriptionRef<T> {}
82
83/// Holds a weak reference to the actual file description.
84#[derive(Debug)]
85pub struct WeakFileDescriptionRef<T: ?Sized>(Weak<FdIdWith<T>>);
86
87impl<T: ?Sized> Clone for WeakFileDescriptionRef<T> {
88    fn clone(&self) -> Self {
89        WeakFileDescriptionRef(self.0.clone())
90    }
91}
92
93impl<T: ?Sized> FileDescriptionRef<T> {
94    pub fn downgrade(this: &Self) -> WeakFileDescriptionRef<T> {
95        WeakFileDescriptionRef(Rc::downgrade(&this.0))
96    }
97}
98
99impl<T: ?Sized> WeakFileDescriptionRef<T> {
100    pub fn upgrade(&self) -> Option<FileDescriptionRef<T>> {
101        self.0.upgrade().map(FileDescriptionRef)
102    }
103
104    /// Returns whether the file description that this weak reference points to
105    /// has been closed, i.e., there are no more strong references.
106    pub fn is_closed(&self) -> bool {
107        self.0.strong_count() == 0
108    }
109}
110
111impl<T> VisitProvenance for FileDescriptionRef<T> {
112    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
113        // All our FileDescription instances do not have any provenance.
114    }
115}
116
117/// A helper trait to indirectly allow downcasting on `Rc<FdIdWith<dyn _>>`.
118/// Ideally we'd just add a `FdIdWith<Self>: Any` bound to the `FileDescription` trait,
119/// but that does not allow upcasting.
120pub trait FileDescriptionExt: 'static {
121    fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any>;
122}
123
124impl<T: FileDescription + 'static> FileDescriptionExt for T {
125    fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any> {
126        self.0
127    }
128}
129
130pub type DynFileDescriptionRef = FileDescriptionRef<dyn FileDescription>;
131pub type WeakDynFileDescriptionRef = WeakFileDescriptionRef<dyn FileDescription>;
132
133impl FileDescriptionRef<dyn FileDescription> {
134    pub fn downcast<T: FileDescription + 'static>(self) -> Option<FileDescriptionRef<T>> {
135        let inner = self.into_rc_any().downcast::<FdIdWith<T>>().ok()?;
136        Some(FileDescriptionRef(inner))
137    }
138}
139
140/// Represents an open file description.
141pub trait FileDescription: std::fmt::Debug + FileDescriptionExt {
142    fn name(&self) -> &'static str;
143
144    /// Reads as much as possible into the given buffer `ptr`.
145    /// `len` indicates how many bytes we should try to read.
146    ///
147    /// When the read is done, `finish` will be called. Note that `read` itself may return before
148    /// that happens! Everything that should happen "after" the `read` needs to happen inside
149    /// `finish`.
150    fn read<'tcx>(
151        self: FileDescriptionRef<Self>,
152        _communicate_allowed: bool,
153        _ptr: Pointer,
154        _len: u64,
155        _ecx: &mut MiriInterpCx<'tcx>,
156        _finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
157    ) -> InterpResult<'tcx> {
158        throw_unsup_format!("cannot read from {}", self.name());
159    }
160
161    /// Writes as much as possible from the given buffer `ptr`.
162    /// `len` indicates how many bytes we should try to write.
163    ///
164    /// When the write is done, `finish` will be called. Note that `write` itself may return before
165    /// that happens! Everything that should happen "after" the `write` needs to happen inside
166    /// `finish`.
167    fn write<'tcx>(
168        self: FileDescriptionRef<Self>,
169        _communicate_allowed: bool,
170        _ptr: Pointer,
171        _len: u64,
172        _ecx: &mut MiriInterpCx<'tcx>,
173        _finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
174    ) -> InterpResult<'tcx> {
175        throw_unsup_format!("cannot write to {}", self.name());
176    }
177
178    /// Determines whether this FD non-deterministically has its reads and writes shortened.
179    fn short_fd_operations(&self) -> bool {
180        // We only enable this for FD kinds where we think short accesses gain useful test coverage.
181        false
182    }
183
184    /// Seeks to the given offset (which can be relative to the beginning, end, or current position).
185    /// Returns the new position from the start of the stream.
186    fn seek<'tcx>(
187        &self,
188        _communicate_allowed: bool,
189        _offset: SeekFrom,
190    ) -> InterpResult<'tcx, io::Result<u64>> {
191        throw_unsup_format!("cannot seek on {}", self.name());
192    }
193
194    /// Returns the metadata for this FD, if available.
195    /// This is either host metadata, or a non-file-backed-FD type.
196    /// The latter is for now represented as a string storing the `libc` name of the mode so we only
197    /// support that kind of metadata on Unix targets.
198    fn metadata<'tcx>(
199        &self,
200        _communicate_allowed: bool,
201    ) -> InterpResult<'tcx, Either<io::Result<fs::Metadata>, &'static str>> {
202        throw_unsup_format!("obtaining metadata is not supported on {}", self.name());
203    }
204
205    fn is_tty(&self, _communicate_allowed: bool) -> bool {
206        // Most FDs are not tty's and the consequence of a wrong `false` are minor,
207        // so we use a default impl here.
208        false
209    }
210
211    /// Converts this FD into a unix file description. Must succeed for all FD types that can be
212    /// created on Unix targets!
213    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
214        panic!("Not a unix file description: {}", self.name());
215    }
216
217    /// Get the `ReadinessWatched` of the file description.
218    fn readiness_watched(&self) -> Option<&ReadinessWatched> {
219        None
220    }
221
222    /// Get the current I/O readiness of the file description.
223    fn readiness(&self) -> Readiness {
224        panic!("FD type {} implements `readiness_watched` but not `readiness`", self.name());
225    }
226}
227
228#[derive(Debug)]
229pub struct Stdin {
230    stdin: io::Stdin,
231    watched: ReadinessWatched,
232}
233
234impl Stdin {
235    fn new() -> Self {
236        Self { stdin: io::stdin(), watched: ReadinessWatched::default() }
237    }
238}
239
240impl FileDescription for Stdin {
241    fn name(&self) -> &'static str {
242        "stdin"
243    }
244
245    fn read<'tcx>(
246        self: FileDescriptionRef<Self>,
247        communicate_allowed: bool,
248        ptr: Pointer,
249        len: u64,
250        ecx: &mut MiriInterpCx<'tcx>,
251        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
252    ) -> InterpResult<'tcx> {
253        if !communicate_allowed {
254            // We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
255            helpers::isolation_abort_error("`read` from stdin")?;
256        }
257
258        // FIXME: this can block on the host, halting the entire interpreter.
259        let result = ecx.read_from_host(ptr, len, |buf| (&mut &self.stdin).read(buf))?;
260        finish.call(ecx, result)
261    }
262
263    fn metadata<'tcx>(
264        &self,
265        communicate_allowed: bool,
266    ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
267        let ftype = if self.is_tty(communicate_allowed) { "S_IFCHR" } else { "S_IFIFO" };
268        interp_ok(Either::Right(ftype))
269    }
270
271    fn is_tty(&self, communicate_allowed: bool) -> bool {
272        // Without communication we assume that it is a terminal.
273        !communicate_allowed || self.stdin.is_terminal()
274    }
275
276    fn readiness_watched(&self) -> Option<&ReadinessWatched> {
277        Some(&self.watched)
278    }
279
280    fn readiness(&self) -> Readiness {
281        // Stdin is readable (we never return EWOULDBLOCK above) and also writable (since that never
282        // blocks either). This matches what we see on Linux.
283        let mut readiness = Readiness::EMPTY;
284        readiness.readable = true;
285        readiness.writable = true;
286        readiness
287    }
288
289    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
290        self
291    }
292}
293
294#[derive(Debug)]
295pub struct Stdout {
296    stdout: io::Stdout,
297    watched: ReadinessWatched,
298}
299
300impl Stdout {
301    fn new() -> Self {
302        Self { stdout: io::stdout(), watched: ReadinessWatched::default() }
303    }
304}
305
306impl FileDescription for Stdout {
307    fn name(&self) -> &'static str {
308        "stdout"
309    }
310
311    fn write<'tcx>(
312        self: FileDescriptionRef<Self>,
313        _communicate_allowed: bool,
314        ptr: Pointer,
315        len: u64,
316        ecx: &mut MiriInterpCx<'tcx>,
317        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
318    ) -> InterpResult<'tcx> {
319        // We allow writing to stdout even with isolation enabled.
320        let result = ecx.write_to_host(ptr, len, |buf| (&self.stdout).write(buf))?;
321        // Stdout is buffered, flush to make sure it appears on the
322        // screen.  This is the write() syscall of the interpreted
323        // program, we want it to correspond to a write() syscall on
324        // the host -- there is no good in adding extra buffering
325        // here.
326        io::stdout().flush().unwrap();
327
328        finish.call(ecx, result)
329    }
330
331    fn metadata<'tcx>(
332        &self,
333        communicate_allowed: bool,
334    ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
335        let ftype = if self.is_tty(communicate_allowed) { "S_IFCHR" } else { "S_IFIFO" };
336        interp_ok(Either::Right(ftype))
337    }
338
339    fn is_tty(&self, communicate_allowed: bool) -> bool {
340        // Without communication we assume that it is a terminal.
341        !communicate_allowed || self.stdout.is_terminal()
342    }
343
344    fn readiness_watched(&self) -> Option<&ReadinessWatched> {
345        Some(&self.watched)
346    }
347
348    fn readiness(&self) -> Readiness {
349        // stdout can always be written (we never return EWOULDBLOCK there) and never be read.
350        let mut readiness = Readiness::EMPTY;
351        readiness.writable = true;
352        readiness
353    }
354
355    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
356        self
357    }
358}
359
360#[derive(Debug)]
361pub struct Stderr {
362    stderr: io::Stderr,
363    watched: ReadinessWatched,
364}
365
366impl Stderr {
367    fn new() -> Self {
368        Self { stderr: io::stderr(), watched: ReadinessWatched::default() }
369    }
370}
371
372impl FileDescription for Stderr {
373    fn name(&self) -> &'static str {
374        "stderr"
375    }
376
377    fn write<'tcx>(
378        self: FileDescriptionRef<Self>,
379        _communicate_allowed: bool,
380        ptr: Pointer,
381        len: u64,
382        ecx: &mut MiriInterpCx<'tcx>,
383        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
384    ) -> InterpResult<'tcx> {
385        // We allow writing to stderr even with isolation enabled.
386        let result = ecx.write_to_host(ptr, len, |buf| (&self.stderr).write(buf))?;
387        // No need to flush, stderr is not buffered.
388        finish.call(ecx, result)
389    }
390
391    fn metadata<'tcx>(
392        &self,
393        communicate_allowed: bool,
394    ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
395        let ftype = if self.is_tty(communicate_allowed) { "S_IFCHR" } else { "S_IFIFO" };
396        interp_ok(Either::Right(ftype))
397    }
398
399    fn is_tty(&self, communicate_allowed: bool) -> bool {
400        // Without communication we assume that it is a terminal.
401        !communicate_allowed || self.stderr.is_terminal()
402    }
403
404    fn readiness_watched(&self) -> Option<&ReadinessWatched> {
405        Some(&self.watched)
406    }
407
408    fn readiness(&self) -> Readiness {
409        // stderr can always be written (we never return EWOULDBLOCK there) and never be read.
410        let mut readiness = Readiness::EMPTY;
411        readiness.writable = true;
412        readiness
413    }
414
415    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
416        self
417    }
418}
419
420/// Like /dev/null
421#[derive(Debug)]
422pub struct NullOutput {
423    watched: ReadinessWatched,
424}
425
426impl NullOutput {
427    fn new() -> Self {
428        Self { watched: ReadinessWatched::default() }
429    }
430}
431
432impl FileDescription for NullOutput {
433    fn name(&self) -> &'static str {
434        "null output"
435    }
436
437    fn write<'tcx>(
438        self: FileDescriptionRef<Self>,
439        _communicate_allowed: bool,
440        _ptr: Pointer,
441        len: u64,
442        ecx: &mut MiriInterpCx<'tcx>,
443        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
444    ) -> InterpResult<'tcx> {
445        // We just don't write anything, but report to the user that we did.
446        finish.call(ecx, Ok(len))
447    }
448
449    fn metadata<'tcx>(
450        &self,
451        _communicate_allowed: bool,
452    ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
453        interp_ok(Either::Right("S_IFIFO"))
454    }
455
456    fn readiness_watched(&self) -> Option<&ReadinessWatched> {
457        Some(&self.watched)
458    }
459
460    fn readiness(&self) -> Readiness {
461        // null output can always be written (we never return EWOULDBLOCK there) and never be read.
462        let mut readiness = Readiness::EMPTY;
463        readiness.writable = true;
464        readiness
465    }
466
467    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
468        self
469    }
470}
471
472#[derive(Debug)]
473pub struct FileHandle {
474    pub(crate) file: fs::File,
475    pub(crate) file_type: fs::FileType,
476    pub(crate) readable: bool,
477    pub(crate) writable: bool,
478    pub(crate) append: bool,
479}
480
481impl FileDescription for FileHandle {
482    fn name(&self) -> &'static str {
483        "file"
484    }
485
486    fn read<'tcx>(
487        self: FileDescriptionRef<Self>,
488        communicate_allowed: bool,
489        ptr: Pointer,
490        len: u64,
491        ecx: &mut MiriInterpCx<'tcx>,
492        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
493    ) -> InterpResult<'tcx> {
494        assert!(communicate_allowed, "isolation should have prevented even opening a file");
495
496        if !self.readable {
497            // Unix returns EBADF, Windows something that translates to `PermissionDenied`.
498            let err = if ecx.target_os_is_unix() {
499                LibcError("EBADF")
500            } else {
501                ErrorKind::PermissionDenied.into()
502            };
503            return finish.call(ecx, Err(err));
504        }
505
506        let mut file = &self.file;
507        let result = ecx.read_from_host(ptr, len, |buf| file.read(buf))?;
508        finish.call(ecx, result)
509    }
510
511    fn write<'tcx>(
512        self: FileDescriptionRef<Self>,
513        communicate_allowed: bool,
514        ptr: Pointer,
515        len: u64,
516        ecx: &mut MiriInterpCx<'tcx>,
517        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
518    ) -> InterpResult<'tcx> {
519        assert!(communicate_allowed, "isolation should have prevented even opening a file");
520
521        if !self.writable {
522            // Unix returns EBADF, Windows something that translates to `PermissionDenied`.
523            let err = if ecx.target_os_is_unix() {
524                LibcError("EBADF")
525            } else {
526                ErrorKind::PermissionDenied.into()
527            };
528            return finish.call(ecx, Err(err));
529        }
530        let result = ecx.write_to_host(ptr, len, |buf| (&self.file).write(buf))?;
531        finish.call(ecx, result)
532    }
533
534    fn seek<'tcx>(
535        &self,
536        communicate_allowed: bool,
537        offset: SeekFrom,
538    ) -> InterpResult<'tcx, io::Result<u64>> {
539        assert!(communicate_allowed, "isolation should have prevented even opening a file");
540        interp_ok((&mut &self.file).seek(offset))
541    }
542
543    fn metadata<'tcx>(
544        &self,
545        communicate_allowed: bool,
546    ) -> InterpResult<'tcx, Either<io::Result<fs::Metadata>, &'static str>> {
547        assert!(communicate_allowed);
548        interp_ok(Either::Left(
549            self.file.metadata().inspect(|m| assert_eq!(m.file_type(), self.file_type)),
550        ))
551    }
552
553    fn is_tty(&self, communicate_allowed: bool) -> bool {
554        assert!(communicate_allowed);
555        self.file.is_terminal()
556    }
557
558    fn short_fd_operations(&self) -> bool {
559        // While short accesses on file-backed FDs are very rare (at least for sufficiently small
560        // accesses), they can realistically happen when a signal interrupts the syscall.
561        // Checking `is_file` excludes named pipes and other special files.
562        self.file_type.is_file()
563    }
564
565    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
566        self
567    }
568}
569
570#[derive(Debug)]
571pub struct DirHandle {
572    pub(super) dir: fs::Dir,
573}
574
575impl FileDescription for DirHandle {
576    fn name(&self) -> &'static str {
577        "directory"
578    }
579
580    fn metadata<'tcx>(
581        &self,
582        communicate_allowed: bool,
583    ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
584        assert!(communicate_allowed);
585
586        interp_ok(Either::Left(self.dir.self_metadata()))
587    }
588
589    fn read<'tcx>(
590        self: FileDescriptionRef<Self>,
591        _communicate_allowed: bool,
592        _ptr: Pointer,
593        _len: u64,
594        ecx: &mut MiriInterpCx<'tcx>,
595        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
596    ) -> InterpResult<'tcx> {
597        if ecx.target_os_is_unix() {
598            finish.call(ecx, Err(LibcError("EISDIR")))
599        } else {
600            // No idea what this should do on Windows.
601            throw_unsup_format!("reading directories is not supported on this target");
602        }
603    }
604
605    fn write<'tcx>(
606        self: FileDescriptionRef<Self>,
607        _communicate_allowed: bool,
608        _ptr: Pointer,
609        _len: u64,
610        ecx: &mut MiriInterpCx<'tcx>,
611        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
612    ) -> InterpResult<'tcx> {
613        if ecx.target_os_is_unix() {
614            // Directories are opened for reading, so writing returns EBADF.
615            finish.call(ecx, Err(LibcError("EBADF")))
616        } else {
617            // No idea what this should do on Windows.
618            throw_unsup_format!("writing directories is not supported on this target");
619        }
620    }
621
622    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
623        self
624    }
625}
626
627/// The file descriptor table
628#[derive(Debug)]
629pub struct FdTable {
630    fds: BTreeMap<FdNum, DynFileDescriptionRef>,
631    /// Unique identifier for file description, used to differentiate between various file description.
632    next_file_description_id: FdId,
633}
634
635impl VisitProvenance for FdTable {
636    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
637        // All our FileDescription instances do not have any provenance.
638    }
639}
640
641impl FdTable {
642    fn new() -> Self {
643        FdTable { fds: BTreeMap::new(), next_file_description_id: FdId(0) }
644    }
645    pub(crate) fn init(mute_stdout_stderr: bool) -> FdTable {
646        let mut fds = FdTable::new();
647        fds.insert_new(Stdin::new());
648        if mute_stdout_stderr {
649            assert_eq!(fds.insert_new(NullOutput::new()).unwrap(), 1);
650            assert_eq!(fds.insert_new(NullOutput::new()).unwrap(), 2);
651        } else {
652            assert_eq!(fds.insert_new(Stdout::new()).unwrap(), 1);
653            assert_eq!(fds.insert_new(Stderr::new()).unwrap(), 2);
654        }
655        fds
656    }
657
658    pub fn new_ref<T: FileDescription>(&mut self, fd: T) -> FileDescriptionRef<T> {
659        let file_handle =
660            FileDescriptionRef(Rc::new(FdIdWith { id: self.next_file_description_id, inner: fd }));
661        self.next_file_description_id = FdId(self.next_file_description_id.0.strict_add(1));
662        file_handle
663    }
664
665    pub fn fd_num_valid(fd_num: FdNum) -> bool {
666        (0..FD_LIMIT).contains(&fd_num)
667    }
668
669    /// Insert a new file description to the FdTable.
670    pub fn insert_new(&mut self, fd: impl FileDescription) -> Option<FdNum> {
671        let fd_ref = self.new_ref(fd);
672        self.insert(fd_ref)
673    }
674
675    /// Insert an alias to an existing file description to the FdTable.
676    pub fn insert(&mut self, fd_ref: DynFileDescriptionRef) -> Option<FdNum> {
677        self.insert_with_min_num(fd_ref, 0)
678    }
679
680    /// Insert a file description, giving it a file descriptor that is at least `min_fd_num`.
681    pub fn insert_with_min_num(
682        &mut self,
683        file_handle: DynFileDescriptionRef,
684        min_fd_num: FdNum,
685    ) -> Option<FdNum> {
686        let mut candidate = min_fd_num;
687        for (&fd_num, _) in self.fds.range(min_fd_num..) {
688            if fd_num == candidate {
689                // This one is taken. Try the next one.
690                candidate = candidate.strict_add(1);
691            } else {
692                // We found a gap! Use this candidate.
693                break;
694            }
695        }
696        // If we exhaust the loop, the table is a solid block starting at `min_fd_num` until the
697        // end, and `candidate` is now the first number after that block -- exactly what we need.
698
699        // Ensure the resulting FD number is valid.
700        if !Self::fd_num_valid(candidate) {
701            return None;
702        }
703
704        self.fds.try_insert(candidate, file_handle).unwrap();
705        Some(candidate)
706    }
707
708    pub fn get(&self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
709        let fd = self.fds.get(&fd_num)?;
710        Some(fd.clone())
711    }
712
713    pub fn remove(&mut self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
714        self.fds.remove(&fd_num)
715    }
716
717    pub fn is_fd_num(&self, fd_num: FdNum) -> bool {
718        self.fds.contains_key(&fd_num)
719    }
720}
721
722impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
723pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
724    /// Read data from a host `Read` type, store the result into machine memory,
725    /// and return whether that worked.
726    fn read_from_host(
727        &mut self,
728        ptr: Pointer,
729        len: u64,
730        read_cb: impl FnOnce(&mut [u8]) -> io::Result<usize>,
731    ) -> InterpResult<'tcx, Result<u64, IoError>> {
732        let ecx = self.eval_context_mut();
733
734        let len = usize::saturating_cast_from(len);
735        let mut bytes = vec![0; len];
736        let result = read_cb(&mut bytes);
737        match result {
738            Ok(read_size) => {
739                // If reading to `bytes` did not fail, we write those bytes to the buffer.
740                // Crucially, if fewer than `bytes.len()` bytes were read, only write
741                // that much into the output buffer!
742                ecx.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
743                interp_ok(Ok(read_size.to_u64()))
744            }
745            Err(e) => interp_ok(Err(IoError::HostError(e))),
746        }
747    }
748
749    /// Write data to a host `Write` type, with the bytes taken from machine memory.
750    fn write_to_host(
751        &self,
752        ptr: Pointer,
753        len: u64,
754        write_cb: impl FnOnce(&[u8]) -> io::Result<usize>,
755    ) -> InterpResult<'tcx, Result<u64, IoError>> {
756        let ecx = self.eval_context_ref();
757
758        let len = usize::saturating_cast_from(len);
759        let bytes = ecx.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
760        let result = write_cb(bytes);
761        interp_ok(result.map_err(IoError::HostError).map(|written_size| written_size.to_u64()))
762    }
763}
764
765/// Open something for which we don't know ahead of time whether it is a file or a directory.
766///
767/// Note that on Windows hosts, `custom_flags` is ignored if `root` is `Some`!
768pub fn open_file_or_dir(
769    root: Option<&fs::Dir>,
770    path: &std::path::Path,
771    opts: &fs::OpenOptions,
772) -> io::Result<(Either<fs::File, fs::Dir>, fs::FileType)> {
773    // On Unix, `open`/`openat` works for files and directories.
774    // On Windows, that fails with `PermissionDenied`, so we need to open an `fs::Dir` instead.
775    // (But that may succeed even on a file! So we still have to check the metadata.)
776    let file = match root {
777        Some(root) => root.open_file_with(path, opts),
778        None => opts.open(path),
779    };
780    #[cfg(windows)]
781    let file = file.or_else(|err| {
782        use std::os::windows::io::OwnedHandle;
783
784        if err.kind() == io::ErrorKind::PermissionDenied {
785            // Retry via `fs::Dir`. Opening a directory via `Dir::open_file` does not work so we
786            // have to use `open_dir`.
787            let dir = match root {
788                Some(root) => root.open_dir_with(path, opts),
789                None => fs::Dir::open_with(path, opts),
790            };
791            match dir {
792                // Convert back to file so it always has the same type.
793                Ok(dir) => Ok(fs::File::from(OwnedHandle::from(dir))),
794                Err(err2) => {
795                    // It's possible that we lost a race twice if this keeps being changed from
796                    // directory to file and back. However, in that case it was entirely
797                    // non-existent for a little while, so returning an error is still fine.
798                    // If this 2nd attempt says "not a directory", preserve the original error.
799                    Err(if err2.kind() == io::ErrorKind::NotADirectory { err } else { err2 })
800                }
801            }
802        } else {
803            Err(err)
804        }
805    });
806    let file = file?;
807
808    let file_type = file.metadata().expect("just-opened file/dir should have metadata").file_type();
809    #[cfg(not(bootstrap))]
810    assert!(!file_type.is_symlink()); // we either follow symlinks or error, never open them
811    if file_type.is_dir() {
812        // Convert to dir.
813        cfg_select! {
814            unix => {
815                use std::os::fd::OwnedFd;
816                Ok((Either::Right(OwnedFd::from(file).into()), file_type))
817            }
818            windows => {
819                use std::os::windows::io::OwnedHandle;
820                Ok((Either::Right(OwnedHandle::from(file).into()), file_type))
821            }
822        }
823    } else {
824        Ok((Either::Left(file), file_type))
825    }
826}