miri/shims/
files.rs

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