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 is the name
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                // Remove entry from the global epoll_event_interest table.
111                ecx.machine.epoll_interests.remove(fd.id);
112
113                fd.inner.close(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    /// Close the file descriptor.
187    fn close<'tcx>(
188        self,
189        _communicate_allowed: bool,
190        _ecx: &mut MiriInterpCx<'tcx>,
191    ) -> InterpResult<'tcx, io::Result<()>>
192    where
193        Self: Sized,
194    {
195        throw_unsup_format!("cannot close {}", self.name());
196    }
197
198    fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<fs::Metadata>> {
199        throw_unsup_format!("obtaining metadata is only supported on file-backed file descriptors");
200    }
201
202    fn is_tty(&self, _communicate_allowed: bool) -> bool {
203        // Most FDs are not tty's and the consequence of a wrong `false` are minor,
204        // so we use a default impl here.
205        false
206    }
207
208    fn as_unix<'tcx>(&self, _ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
209        panic!("Not a unix file descriptor: {}", self.name());
210    }
211
212    /// Implementation of fcntl(F_GETFL) for this FD.
213    fn get_flags<'tcx>(&self, _ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
214        throw_unsup_format!("fcntl: {} is not supported for F_GETFL", self.name());
215    }
216
217    /// Implementation of fcntl(F_SETFL) for this FD.
218    fn set_flags<'tcx>(
219        &self,
220        _flag: i32,
221        _ecx: &mut MiriInterpCx<'tcx>,
222    ) -> InterpResult<'tcx, Scalar> {
223        throw_unsup_format!("fcntl: {} is not supported for F_SETFL", self.name());
224    }
225}
226
227impl FileDescription for io::Stdin {
228    fn name(&self) -> &'static str {
229        "stdin"
230    }
231
232    fn read<'tcx>(
233        self: FileDescriptionRef<Self>,
234        communicate_allowed: bool,
235        ptr: Pointer,
236        len: usize,
237        ecx: &mut MiriInterpCx<'tcx>,
238        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
239    ) -> InterpResult<'tcx> {
240        if !communicate_allowed {
241            // We want isolation mode to be deterministic, so we have to disallow all reads, even stdin.
242            helpers::isolation_abort_error("`read` from stdin")?;
243        }
244
245        let result = ecx.read_from_host(&*self, len, ptr)?;
246        finish.call(ecx, result)
247    }
248
249    fn is_tty(&self, communicate_allowed: bool) -> bool {
250        communicate_allowed && self.is_terminal()
251    }
252}
253
254impl FileDescription for io::Stdout {
255    fn name(&self) -> &'static str {
256        "stdout"
257    }
258
259    fn write<'tcx>(
260        self: FileDescriptionRef<Self>,
261        _communicate_allowed: bool,
262        ptr: Pointer,
263        len: usize,
264        ecx: &mut MiriInterpCx<'tcx>,
265        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
266    ) -> InterpResult<'tcx> {
267        // We allow writing to stdout even with isolation enabled.
268        let result = ecx.write_to_host(&*self, len, ptr)?;
269        // Stdout is buffered, flush to make sure it appears on the
270        // screen.  This is the write() syscall of the interpreted
271        // program, we want it to correspond to a write() syscall on
272        // the host -- there is no good in adding extra buffering
273        // here.
274        io::stdout().flush().unwrap();
275
276        finish.call(ecx, result)
277    }
278
279    fn is_tty(&self, communicate_allowed: bool) -> bool {
280        communicate_allowed && self.is_terminal()
281    }
282}
283
284impl FileDescription for io::Stderr {
285    fn name(&self) -> &'static str {
286        "stderr"
287    }
288
289    fn write<'tcx>(
290        self: FileDescriptionRef<Self>,
291        _communicate_allowed: bool,
292        ptr: Pointer,
293        len: usize,
294        ecx: &mut MiriInterpCx<'tcx>,
295        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
296    ) -> InterpResult<'tcx> {
297        // We allow writing to stderr even with isolation enabled.
298        let result = ecx.write_to_host(&*self, len, ptr)?;
299        // No need to flush, stderr is not buffered.
300        finish.call(ecx, result)
301    }
302
303    fn is_tty(&self, communicate_allowed: bool) -> bool {
304        communicate_allowed && self.is_terminal()
305    }
306}
307
308#[derive(Debug)]
309pub struct FileHandle {
310    pub(crate) file: File,
311    pub(crate) writable: bool,
312}
313
314impl FileDescription for FileHandle {
315    fn name(&self) -> &'static str {
316        "file"
317    }
318
319    fn read<'tcx>(
320        self: FileDescriptionRef<Self>,
321        communicate_allowed: bool,
322        ptr: Pointer,
323        len: usize,
324        ecx: &mut MiriInterpCx<'tcx>,
325        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
326    ) -> InterpResult<'tcx> {
327        assert!(communicate_allowed, "isolation should have prevented even opening a file");
328
329        let result = ecx.read_from_host(&self.file, len, ptr)?;
330        finish.call(ecx, result)
331    }
332
333    fn write<'tcx>(
334        self: FileDescriptionRef<Self>,
335        communicate_allowed: bool,
336        ptr: Pointer,
337        len: usize,
338        ecx: &mut MiriInterpCx<'tcx>,
339        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
340    ) -> InterpResult<'tcx> {
341        assert!(communicate_allowed, "isolation should have prevented even opening a file");
342
343        if !self.writable {
344            // Linux hosts return EBADF here which we can't translate via the platform-independent
345            // code since it does not map to any `io::ErrorKind` -- so if we don't do anything
346            // special, we'd throw an "unsupported error code" here. Windows returns something that
347            // gets translated to `PermissionDenied`. That seems like a good value so let's just use
348            // this everywhere, even if it means behavior on Unix targets does not match the real
349            // thing.
350            return finish.call(ecx, Err(ErrorKind::PermissionDenied.into()));
351        }
352        let result = ecx.write_to_host(&self.file, len, ptr)?;
353        finish.call(ecx, result)
354    }
355
356    fn seek<'tcx>(
357        &self,
358        communicate_allowed: bool,
359        offset: SeekFrom,
360    ) -> InterpResult<'tcx, io::Result<u64>> {
361        assert!(communicate_allowed, "isolation should have prevented even opening a file");
362        interp_ok((&mut &self.file).seek(offset))
363    }
364
365    fn close<'tcx>(
366        self,
367        communicate_allowed: bool,
368        _ecx: &mut MiriInterpCx<'tcx>,
369    ) -> InterpResult<'tcx, io::Result<()>> {
370        assert!(communicate_allowed, "isolation should have prevented even opening a file");
371        // We sync the file if it was opened in a mode different than read-only.
372        if self.writable {
373            // `File::sync_all` does the checks that are done when closing a file. We do this to
374            // to handle possible errors correctly.
375            let result = self.file.sync_all();
376            // Now we actually close the file and return the result.
377            drop(self.file);
378            interp_ok(result)
379        } else {
380            // We drop the file, this closes it but ignores any errors
381            // produced when closing it. This is done because
382            // `File::sync_all` cannot be done over files like
383            // `/dev/urandom` which are read-only. Check
384            // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439
385            // for a deeper discussion.
386            drop(self.file);
387            interp_ok(Ok(()))
388        }
389    }
390
391    fn metadata<'tcx>(&self) -> InterpResult<'tcx, io::Result<Metadata>> {
392        interp_ok(self.file.metadata())
393    }
394
395    fn is_tty(&self, communicate_allowed: bool) -> bool {
396        communicate_allowed && self.file.is_terminal()
397    }
398
399    fn short_fd_operations(&self) -> bool {
400        // While short accesses on file-backed FDs are very rare (at least for sufficiently small
401        // accesses), they can realistically happen when a signal interrupts the syscall.
402        // FIXME: we should return `false` if this is a named pipe...
403        true
404    }
405
406    fn as_unix<'tcx>(&self, ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
407        assert!(
408            ecx.target_os_is_unix(),
409            "unix file operations are only available for unix targets"
410        );
411        self
412    }
413}
414
415/// Like /dev/null
416#[derive(Debug)]
417pub struct NullOutput;
418
419impl FileDescription for NullOutput {
420    fn name(&self) -> &'static str {
421        "stderr and stdout"
422    }
423
424    fn write<'tcx>(
425        self: FileDescriptionRef<Self>,
426        _communicate_allowed: bool,
427        _ptr: Pointer,
428        len: usize,
429        ecx: &mut MiriInterpCx<'tcx>,
430        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
431    ) -> InterpResult<'tcx> {
432        // We just don't write anything, but report to the user that we did.
433        finish.call(ecx, Ok(len))
434    }
435}
436
437/// Internal type of a file-descriptor - this is what [`FdTable`] expects
438pub type FdNum = i32;
439
440/// The file descriptor table
441#[derive(Debug)]
442pub struct FdTable {
443    pub fds: BTreeMap<FdNum, DynFileDescriptionRef>,
444    /// Unique identifier for file description, used to differentiate between various file description.
445    next_file_description_id: FdId,
446}
447
448impl VisitProvenance for FdTable {
449    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
450        // All our FileDescription instances do not have any tags.
451    }
452}
453
454impl FdTable {
455    fn new() -> Self {
456        FdTable { fds: BTreeMap::new(), next_file_description_id: FdId(0) }
457    }
458    pub(crate) fn init(mute_stdout_stderr: bool) -> FdTable {
459        let mut fds = FdTable::new();
460        fds.insert_new(io::stdin());
461        if mute_stdout_stderr {
462            assert_eq!(fds.insert_new(NullOutput), 1);
463            assert_eq!(fds.insert_new(NullOutput), 2);
464        } else {
465            assert_eq!(fds.insert_new(io::stdout()), 1);
466            assert_eq!(fds.insert_new(io::stderr()), 2);
467        }
468        fds
469    }
470
471    pub fn new_ref<T: FileDescription>(&mut self, fd: T) -> FileDescriptionRef<T> {
472        let file_handle =
473            FileDescriptionRef(Rc::new(FdIdWith { id: self.next_file_description_id, inner: fd }));
474        self.next_file_description_id = FdId(self.next_file_description_id.0.strict_add(1));
475        file_handle
476    }
477
478    /// Insert a new file description to the FdTable.
479    pub fn insert_new(&mut self, fd: impl FileDescription) -> FdNum {
480        let fd_ref = self.new_ref(fd);
481        self.insert(fd_ref)
482    }
483
484    pub fn insert(&mut self, fd_ref: DynFileDescriptionRef) -> FdNum {
485        self.insert_with_min_num(fd_ref, 0)
486    }
487
488    /// Insert a file description, giving it a file descriptor that is at least `min_fd_num`.
489    pub fn insert_with_min_num(
490        &mut self,
491        file_handle: DynFileDescriptionRef,
492        min_fd_num: FdNum,
493    ) -> FdNum {
494        // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in
495        // between used FDs, the find_map combinator will return it. If the first such unused FD
496        // is after all other used FDs, the find_map combinator will return None, and we will use
497        // the FD following the greatest FD thus far.
498        let candidate_new_fd =
499            self.fds.range(min_fd_num..).zip(min_fd_num..).find_map(|((fd_num, _fd), counter)| {
500                if *fd_num != counter {
501                    // There was a gap in the fds stored, return the first unused one
502                    // (note that this relies on BTreeMap iterating in key order)
503                    Some(counter)
504                } else {
505                    // This fd is used, keep going
506                    None
507                }
508            });
509        let new_fd_num = candidate_new_fd.unwrap_or_else(|| {
510            // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
511            // maximum fd in the map
512            self.fds.last_key_value().map(|(fd_num, _)| fd_num.strict_add(1)).unwrap_or(min_fd_num)
513        });
514
515        self.fds.try_insert(new_fd_num, file_handle).unwrap();
516        new_fd_num
517    }
518
519    pub fn get(&self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
520        let fd = self.fds.get(&fd_num)?;
521        Some(fd.clone())
522    }
523
524    pub fn remove(&mut self, fd_num: FdNum) -> Option<DynFileDescriptionRef> {
525        self.fds.remove(&fd_num)
526    }
527
528    pub fn is_fd_num(&self, fd_num: FdNum) -> bool {
529        self.fds.contains_key(&fd_num)
530    }
531}
532
533impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
534pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
535    /// Read data from a host `Read` type, store the result into machine memory,
536    /// and return whether that worked.
537    fn read_from_host(
538        &mut self,
539        mut file: impl io::Read,
540        len: usize,
541        ptr: Pointer,
542    ) -> InterpResult<'tcx, Result<usize, IoError>> {
543        let this = self.eval_context_mut();
544
545        let mut bytes = vec![0; len];
546        let result = file.read(&mut bytes);
547        match result {
548            Ok(read_size) => {
549                // If reading to `bytes` did not fail, we write those bytes to the buffer.
550                // Crucially, if fewer than `bytes.len()` bytes were read, only write
551                // that much into the output buffer!
552                this.write_bytes_ptr(ptr, bytes[..read_size].iter().copied())?;
553                interp_ok(Ok(read_size))
554            }
555            Err(e) => interp_ok(Err(IoError::HostError(e))),
556        }
557    }
558
559    /// Write data to a host `Write` type, withthe bytes taken from machine memory.
560    fn write_to_host(
561        &mut self,
562        mut file: impl io::Write,
563        len: usize,
564        ptr: Pointer,
565    ) -> InterpResult<'tcx, Result<usize, IoError>> {
566        let this = self.eval_context_mut();
567
568        let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
569        let result = file.write(bytes);
570        interp_ok(result.map_err(IoError::HostError))
571    }
572}