Skip to main content

miri/shims/
files.rs

1use std::any::Any;
2use std::collections::BTreeMap;
3use std::fs::{File, Metadata};
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/// A unique id for file descriptions. While we could use the address, considering that
16/// is definitely unique, the address would expose interpreter internal state when used
17/// for sorting things. So instead we generate a unique id per file description which is the same
18/// for all `dup`licates and is never reused.
19#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
20pub struct FdId(usize);
21
22impl FdId {
23    pub fn to_usize(self) -> usize {
24        self.0
25    }
26
27    /// Create a new fd id from a `usize` without checking if this fd exists.
28    pub fn new_unchecked(id: usize) -> Self {
29        Self(id)
30    }
31}
32
33#[derive(Debug, Clone)]
34struct FdIdWith<T: ?Sized> {
35    id: FdId,
36    inner: T,
37}
38
39/// A refcounted pointer to a file description, also tracking the
40/// globally unique ID of this file description.
41#[repr(transparent)]
42#[derive(CoercePointee, Debug)]
43pub struct FileDescriptionRef<T: ?Sized>(Rc<FdIdWith<T>>);
44
45impl<T: ?Sized> Clone for FileDescriptionRef<T> {
46    fn clone(&self) -> Self {
47        FileDescriptionRef(self.0.clone())
48    }
49}
50
51impl<T: ?Sized> Deref for FileDescriptionRef<T> {
52    type Target = T;
53    fn deref(&self) -> &T {
54        &self.0.inner
55    }
56}
57
58impl<T: ?Sized> FileDescriptionRef<T> {
59    pub fn id(&self) -> FdId {
60        self.0.id
61    }
62}
63
64/// Holds a weak reference to the actual file description.
65#[derive(Debug)]
66pub struct WeakFileDescriptionRef<T: ?Sized>(Weak<FdIdWith<T>>);
67
68impl<T: ?Sized> Clone for WeakFileDescriptionRef<T> {
69    fn clone(&self) -> Self {
70        WeakFileDescriptionRef(self.0.clone())
71    }
72}
73
74impl<T: ?Sized> FileDescriptionRef<T> {
75    pub fn downgrade(this: &Self) -> WeakFileDescriptionRef<T> {
76        WeakFileDescriptionRef(Rc::downgrade(&this.0))
77    }
78}
79
80impl<T: ?Sized> WeakFileDescriptionRef<T> {
81    pub fn upgrade(&self) -> Option<FileDescriptionRef<T>> {
82        self.0.upgrade().map(FileDescriptionRef)
83    }
84}
85
86impl<T> VisitProvenance for WeakFileDescriptionRef<T> {
87    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
88        // A weak reference can never be the only reference to some pointer or place.
89        // Since the actual file description is tracked by strong ref somewhere,
90        // it is ok to make this a NOP operation.
91    }
92}
93
94/// A helper trait to indirectly allow downcasting on `Rc<FdIdWith<dyn _>>`.
95/// Ideally we'd just add a `FdIdWith<Self>: Any` bound to the `FileDescription` trait,
96/// but that does not allow upcasting.
97pub trait FileDescriptionExt: 'static {
98    fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any>;
99
100    /// We wrap the regular `close` function generically, so both handle `Rc::into_inner`
101    /// and epoll interest management.
102    fn close_ref<'tcx>(
103        self: FileDescriptionRef<Self>,
104        communicate_allowed: bool,
105        ecx: &mut MiriInterpCx<'tcx>,
106    ) -> InterpResult<'tcx, io::Result<()>>;
107}
108
109impl<T: FileDescription + 'static> FileDescriptionExt for T {
110    fn into_rc_any(self: FileDescriptionRef<Self>) -> Rc<dyn Any> {
111        self.0
112    }
113
114    fn close_ref<'tcx>(
115        self: FileDescriptionRef<Self>,
116        communicate_allowed: bool,
117        ecx: &mut MiriInterpCx<'tcx>,
118    ) -> InterpResult<'tcx, io::Result<()>> {
119        match Rc::into_inner(self.0) {
120            Some(fd) => {
121                // There might have been epolls interested in this FD. Remove that.
122                ecx.machine.epoll_interests.remove_epolls(fd.id);
123
124                fd.inner.destroy(fd.id, communicate_allowed, ecx)
125            }
126            None => {
127                // Not the last reference.
128                interp_ok(Ok(()))
129            }
130        }
131    }
132}
133
134pub type DynFileDescriptionRef = FileDescriptionRef<dyn FileDescription>;
135
136impl FileDescriptionRef<dyn FileDescription> {
137    pub fn downcast<T: FileDescription + 'static>(self) -> Option<FileDescriptionRef<T>> {
138        let inner = self.into_rc_any().downcast::<FdIdWith<T>>().ok()?;
139        Some(FileDescriptionRef(inner))
140    }
141}
142
143/// Represents an open file description.
144pub trait FileDescription: std::fmt::Debug + FileDescriptionExt {
145    fn name(&self) -> &'static str;
146
147    /// Reads as much as possible into the given buffer `ptr`.
148    /// `len` indicates how many bytes we should try to read.
149    ///
150    /// When the read is done, `finish` will be called. Note that `read` itself may return before
151    /// that happens! Everything that should happen "after" the `read` needs to happen inside
152    /// `finish`.
153    fn read<'tcx>(
154        self: FileDescriptionRef<Self>,
155        _communicate_allowed: bool,
156        _ptr: Pointer,
157        _len: usize,
158        _ecx: &mut MiriInterpCx<'tcx>,
159        _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
160    ) -> InterpResult<'tcx> {
161        throw_unsup_format!("cannot read from {}", self.name());
162    }
163
164    /// Writes as much as possible from the given buffer `ptr`.
165    /// `len` indicates how many bytes we should try to write.
166    ///
167    /// When the write is done, `finish` will be called. Note that `write` itself may return before
168    /// that happens! Everything that should happen "after" the `write` needs to happen inside
169    /// `finish`.
170    fn write<'tcx>(
171        self: FileDescriptionRef<Self>,
172        _communicate_allowed: bool,
173        _ptr: Pointer,
174        _len: usize,
175        _ecx: &mut MiriInterpCx<'tcx>,
176        _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
177    ) -> InterpResult<'tcx> {
178        throw_unsup_format!("cannot write to {}", self.name());
179    }
180
181    /// Determines whether this FD non-deterministically has its reads and writes shortened.
182    fn short_fd_operations(&self) -> bool {
183        // We only enable this for FD kinds where we think short accesses gain useful test coverage.
184        false
185    }
186
187    /// Seeks to the given offset (which can be relative to the beginning, end, or current position).
188    /// Returns the new position from the start of the stream.
189    fn seek<'tcx>(
190        &self,
191        _communicate_allowed: bool,
192        _offset: SeekFrom,
193    ) -> InterpResult<'tcx, io::Result<u64>> {
194        throw_unsup_format!("cannot seek on {}", self.name());
195    }
196
197    /// Destroys the file description. Only called when the last duplicate file descriptor is closed.
198    ///
199    /// `self_addr` is the address that this file description used to be stored at.
200    fn destroy<'tcx>(
201        self,
202        _self_id: FdId,
203        _communicate_allowed: bool,
204        _ecx: &mut MiriInterpCx<'tcx>,
205    ) -> InterpResult<'tcx, io::Result<()>>
206    where
207        Self: Sized,
208    {
209        throw_unsup_format!("cannot close {}", self.name());
210    }
211
212    fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<fs::Metadata>> {
213        throw_unsup_format!("obtaining metadata is only supported on file-backed file descriptors");
214    }
215
216    fn is_tty(&self, _communicate_allowed: bool) -> bool {
217        // Most FDs are not tty's and the consequence of a wrong `false` are minor,
218        // so we use a default impl here.
219        false
220    }
221
222    fn as_unix<'tcx>(&self, _ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
223        panic!("Not a unix file descriptor: {}", self.name());
224    }
225
226    /// Implementation of fcntl(F_GETFL) for this FD.
227    fn get_flags<'tcx>(&self, _ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
228        throw_unsup_format!("fcntl: {} is not supported for F_GETFL", self.name());
229    }
230
231    /// Implementation of fcntl(F_SETFL) for this FD.
232    fn set_flags<'tcx>(
233        &self,
234        _flag: i32,
235        _ecx: &mut MiriInterpCx<'tcx>,
236    ) -> InterpResult<'tcx, Scalar> {
237        throw_unsup_format!("fcntl: {} is not supported for F_SETFL", self.name());
238    }
239}
240
241impl FileDescription for io::Stdin {
242    fn name(&self) -> &'static str {
243        "stdin"
244    }
245
246    fn read<'tcx>(
247        self: FileDescriptionRef<Self>,
248        communicate_allowed: bool,
249        ptr: Pointer,
250        len: usize,
251        ecx: &mut MiriInterpCx<'tcx>,
252        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
253    ) -> InterpResult<'tcx> {
254        if !communicate_allowed {
255            // We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
256            helpers::isolation_abort_error("`read` from stdin")?;
257        }
258
259        let mut stdin = &*self;
260        let result = ecx.read_from_host(|buf| stdin.read(buf), len, ptr)?;
261        finish.call(ecx, result)
262    }
263
264    fn destroy<'tcx>(
265        self,
266        _self_id: FdId,
267        _communicate_allowed: bool,
268        _ecx: &mut MiriInterpCx<'tcx>,
269    ) -> InterpResult<'tcx, io::Result<()>> {
270        interp_ok(Ok(()))
271    }
272
273    fn is_tty(&self, communicate_allowed: bool) -> bool {
274        communicate_allowed && self.is_terminal()
275    }
276}
277
278impl FileDescription for io::Stdout {
279    fn name(&self) -> &'static str {
280        "stdout"
281    }
282
283    fn write<'tcx>(
284        self: FileDescriptionRef<Self>,
285        _communicate_allowed: bool,
286        ptr: Pointer,
287        len: usize,
288        ecx: &mut MiriInterpCx<'tcx>,
289        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
290    ) -> InterpResult<'tcx> {
291        // We allow writing to stdout even with isolation enabled.
292        let result = ecx.write_to_host(&*self, len, ptr)?;
293        // Stdout is buffered, flush to make sure it appears on the
294        // screen.  This is the write() syscall of the interpreted
295        // program, we want it to correspond to a write() syscall on
296        // the host -- there is no good in adding extra buffering
297        // here.
298        io::stdout().flush().unwrap();
299
300        finish.call(ecx, result)
301    }
302
303    fn destroy<'tcx>(
304        self,
305        _self_id: FdId,
306        _communicate_allowed: bool,
307        _ecx: &mut MiriInterpCx<'tcx>,
308    ) -> InterpResult<'tcx, io::Result<()>> {
309        interp_ok(Ok(()))
310    }
311
312    fn is_tty(&self, communicate_allowed: bool) -> bool {
313        communicate_allowed && self.is_terminal()
314    }
315}
316
317impl FileDescription for io::Stderr {
318    fn name(&self) -> &'static str {
319        "stderr"
320    }
321
322    fn destroy<'tcx>(
323        self,
324        _self_id: FdId,
325        _communicate_allowed: bool,
326        _ecx: &mut MiriInterpCx<'tcx>,
327    ) -> InterpResult<'tcx, io::Result<()>> {
328        interp_ok(Ok(()))
329    }
330
331    fn write<'tcx>(
332        self: FileDescriptionRef<Self>,
333        _communicate_allowed: bool,
334        ptr: Pointer,
335        len: usize,
336        ecx: &mut MiriInterpCx<'tcx>,
337        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
338    ) -> InterpResult<'tcx> {
339        // We allow writing to stderr even with isolation enabled.
340        let result = ecx.write_to_host(&*self, len, ptr)?;
341        // No need to flush, stderr is not buffered.
342        finish.call(ecx, result)
343    }
344
345    fn is_tty(&self, communicate_allowed: bool) -> bool {
346        communicate_allowed && self.is_terminal()
347    }
348}
349
350#[derive(Debug)]
351pub struct FileHandle {
352    pub(crate) file: File,
353    pub(crate) writable: bool,
354}
355
356impl FileDescription for FileHandle {
357    fn name(&self) -> &'static str {
358        "file"
359    }
360
361    fn read<'tcx>(
362        self: FileDescriptionRef<Self>,
363        communicate_allowed: bool,
364        ptr: Pointer,
365        len: usize,
366        ecx: &mut MiriInterpCx<'tcx>,
367        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
368    ) -> InterpResult<'tcx> {
369        assert!(communicate_allowed, "isolation should have prevented even opening a file");
370
371        let mut file = &self.file;
372        let result = ecx.read_from_host(|buf| file.read(buf), len, ptr)?;
373        finish.call(ecx, result)
374    }
375
376    fn write<'tcx>(
377        self: FileDescriptionRef<Self>,
378        communicate_allowed: bool,
379        ptr: Pointer,
380        len: usize,
381        ecx: &mut MiriInterpCx<'tcx>,
382        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
383    ) -> InterpResult<'tcx> {
384        assert!(communicate_allowed, "isolation should have prevented even opening a file");
385
386        if !self.writable {
387            // Linux hosts return EBADF here which we can't translate via the platform-independent
388            // code since it does not map to any `io::ErrorKind` -- so if we don't do anything
389            // special, we'd throw an "unsupported error code" here. Windows returns something that
390            // gets translated to `PermissionDenied`. That seems like a good value so let's just use
391            // this everywhere, even if it means behavior on Unix targets does not match the real
392            // thing.
393            return finish.call(ecx, Err(ErrorKind::PermissionDenied.into()));
394        }
395        let result = ecx.write_to_host(&self.file, len, ptr)?;
396        finish.call(ecx, result)
397    }
398
399    fn seek<'tcx>(
400        &self,
401        communicate_allowed: bool,
402        offset: SeekFrom,
403    ) -> InterpResult<'tcx, io::Result<u64>> {
404        assert!(communicate_allowed, "isolation should have prevented even opening a file");
405        interp_ok((&mut &self.file).seek(offset))
406    }
407
408    fn destroy<'tcx>(
409        self,
410        _self_id: FdId,
411        communicate_allowed: bool,
412        _ecx: &mut MiriInterpCx<'tcx>,
413    ) -> InterpResult<'tcx, io::Result<()>> {
414        assert!(communicate_allowed, "isolation should have prevented even opening a file");
415        // We sync the file if it was opened in a mode different than read-only.
416        if self.writable {
417            // `File::sync_all` does the checks that are done when closing a file. We do this to
418            // to handle possible errors correctly.
419            let result = self.file.sync_all();
420            // Now we actually close the file and return the result.
421            drop(self.file);
422            interp_ok(result)
423        } else {
424            // We drop the file, this closes it but ignores any errors
425            // produced when closing it. This is done because
426            // `File::sync_all` cannot be done over files like
427            // `/dev/urandom` which are read-only. Check
428            // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
429            // for a deeper discussion.
430            drop(self.file);
431            interp_ok(Ok(()))
432        }
433    }
434
435    fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<Metadata>> {
436        interp_ok(self.file.metadata())
437    }
438
439    fn is_tty(&self, communicate_allowed: bool) -> bool {
440        communicate_allowed && self.file.is_terminal()
441    }
442
443    fn short_fd_operations(&self) -> bool {
444        // While short accesses on file-backed FDs are very rare (at least for sufficiently small
445        // accesses), they can realistically happen when a signal interrupts the syscall.
446        // FIXME: we should return `false` if this is a named pipe...
447        true
448    }
449
450    fn as_unix<'tcx>(&self, ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
451        assert!(
452            ecx.target_os_is_unix(),
453            "unix file operations are only available for unix targets"
454        );
455        self
456    }
457}
458
459/// Like /dev/null
460#[derive(Debug)]
461pub struct NullOutput;
462
463impl FileDescription for NullOutput {
464    fn name(&self) -> &'static str {
465        "stderr and stdout"
466    }
467
468    fn write<'tcx>(
469        self: FileDescriptionRef<Self>,
470        _communicate_allowed: bool,
471        _ptr: Pointer,
472        len: usize,
473        ecx: &mut MiriInterpCx<'tcx>,
474        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
475    ) -> InterpResult<'tcx> {
476        // We just don't write anything, but report to the user that we did.
477        finish.call(ecx, Ok(len))
478    }
479
480    fn destroy<'tcx>(
481        self,
482        _self_id: FdId,
483        _communicate_allowed: bool,
484        _ecx: &mut MiriInterpCx<'tcx>,
485    ) -> InterpResult<'tcx, io::Result<()>> {
486        interp_ok(Ok(()))
487    }
488}
489
490/// Internal type of a file-descriptor - this is what [`FdTable`] expects
491pub type FdNum = i32;
492
493/// The file descriptor table
494#[derive(Debug)]
495pub struct FdTable {
496    pub fds: BTreeMap<FdNum, DynFileDescriptionRef>,
497    /// Unique identifier for file description, used to differentiate between various file description.
498    next_file_description_id: FdId,
499}
500
501impl VisitProvenance for FdTable {
502    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
503        // All our FileDescription instances do not have any tags.
504    }
505}
506
507impl FdTable {
508    fn new() -> Self {
509        FdTable { fds: BTreeMap::new(), next_file_description_id: FdId(0) }
510    }
511    pub(crate) fn init(mute_stdout_stderr: bool) -> FdTable {
512        let mut fds = FdTable::new();
513        fds.insert_new(io::stdin());
514        if mute_stdout_stderr {
515            assert_eq!(fds.insert_new(NullOutput), 1);
516            assert_eq!(fds.insert_new(NullOutput), 2);
517        } else {
518            assert_eq!(fds.insert_new(io::stdout()), 1);
519            assert_eq!(fds.insert_new(io::stderr()), 2);
520        }
521        fds
522    }
523
524    pub fn new_ref<T: FileDescription>(&mut self, fd: T) -> FileDescriptionRef<T> {
525        let file_handle =
526            FileDescriptionRef(Rc::new(FdIdWith { id: self.next_file_description_id, inner: fd }));
527        self.next_file_description_id = FdId(self.next_file_description_id.0.strict_add(1));
528        file_handle
529    }
530
531    /// Insert a new file description to the FdTable.
532    pub fn insert_new(&mut self, fd: impl FileDescription) -> FdNum {
533        let fd_ref = self.new_ref(fd);
534        self.insert(fd_ref)
535    }
536
537    pub fn insert(&mut self, fd_ref: DynFileDescriptionRef) -> FdNum {
538        self.insert_with_min_num(fd_ref, 0)
539    }
540
541    /// Insert a file description, giving it a file descriptor that is at least `min_fd_num`.
542    pub fn insert_with_min_num(
543        &mut self,
544        file_handle: DynFileDescriptionRef,
545        min_fd_num: FdNum,
546    ) -> FdNum {
547        // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
548        // between used FDs, the find_map combinator will return it. If the first such unused FD
549        // is after all other used FDs, the find_map combinator will return None, and we will use
550        // the FD following the greatest FD thus far.
551        let candidate_new_fd =
552            self.fds.range(min_fd_num..).zip(min_fd_num..).find_map(|((fd_num, _fd), counter)| {
553                if *fd_num != counter {
554                    // There was a gap in the fds stored, return the first unused one
555                    // (note that this relies on BTreeMap iterating in key order)
556                    Some(counter)
557                } else {
558                    // This fd is used, keep going
559                    None
560                }
561            });
562        let new_fd_num = candidate_new_fd.unwrap_or_else(|| {
563            // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
564            // maximum fd in the map
565            self.fds.last_key_value().map(|(fd_num, _)| fd_num.strict_add(1)).unwrap_or(min_fd_num)
566        });
567
568        self.fds.try_insert(new_fd_num, file_handle).unwrap();
569        new_fd_num
570    }
571
572    pub fn get(&self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
573        let fd = self.fds.get(&fd_num)?;
574        Some(fd.clone())
575    }
576
577    pub fn remove(&mut self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
578        self.fds.remove(&fd_num)
579    }
580
581    pub fn is_fd_num(&self, fd_num: FdNum) -> bool {
582        self.fds.contains_key(&fd_num)
583    }
584}
585
586impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
587pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
588    /// Read data from a host `Read` type, store the result into machine memory,
589    /// and return whether that worked.
590    fn read_from_host(
591        &mut self,
592        mut read_cb: impl FnMut(&mut [u8]) -> io::Result<usize>,
593        len: usize,
594        ptr: Pointer,
595    ) -> InterpResult<'tcx, Result<usize, IoError>> {
596        let this = self.eval_context_mut();
597
598        let mut bytes = vec![0; len];
599        let result = read_cb(&mut bytes);
600        match result {
601            Ok(read_size) => {
602                // If reading to `bytes` did not fail, we write those bytes to the buffer.
603                // Crucially, if fewer than `bytes.len()` bytes were read, only write
604                // that much into the output buffer!
605                this.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
606                interp_ok(Ok(read_size))
607            }
608            Err(e) => interp_ok(Err(IoError::HostError(e))),
609        }
610    }
611
612    /// Write data to a host `Write` type, with the bytes taken from machine memory.
613    fn write_to_host(
614        &mut self,
615        mut file: impl io::Write,
616        len: usize,
617        ptr: Pointer,
618    ) -> InterpResult<'tcx, Result<usize, IoError>> {
619        let this = self.eval_context_mut();
620
621        let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
622        let result = file.write(bytes);
623        interp_ok(result.map_err(IoError::HostError))
624    }
625}