miri/shims/unix/
fd.rs

1//! General management of file descriptors, and support for
2//! standard file descriptors (stdin/stdout/stderr).
3
4use std::io;
5use std::io::ErrorKind;
6
7use rustc_abi::Size;
8
9use crate::helpers::check_min_vararg_count;
10use crate::shims::files::FileDescription;
11use crate::shims::unix::linux_like::epoll::EpollReadyEvents;
12use crate::shims::unix::*;
13use crate::*;
14
15#[derive(Debug, Clone, Copy, Eq, PartialEq)]
16pub(crate) enum FlockOp {
17    SharedLock { nonblocking: bool },
18    ExclusiveLock { nonblocking: bool },
19    Unlock,
20}
21
22/// Represents unix-specific file descriptions.
23pub trait UnixFileDescription: FileDescription {
24    /// Reads as much as possible into the given buffer `ptr` from a given offset.
25    /// `len` indicates how many bytes we should try to read.
26    /// `dest` is where the return value should be stored: number of bytes read, or `-1` in case of error.
27    fn pread<'tcx>(
28        &self,
29        _communicate_allowed: bool,
30        _offset: u64,
31        _ptr: Pointer,
32        _len: usize,
33        _ecx: &mut MiriInterpCx<'tcx>,
34        _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
35    ) -> InterpResult<'tcx> {
36        throw_unsup_format!("cannot pread from {}", self.name());
37    }
38
39    /// Writes as much as possible from the given buffer `ptr` starting at a given offset.
40    /// `ptr` is the pointer to the user supplied read buffer.
41    /// `len` indicates how many bytes we should try to write.
42    /// `dest` is where the return value should be stored: number of bytes written, or `-1` in case of error.
43    fn pwrite<'tcx>(
44        &self,
45        _communicate_allowed: bool,
46        _ptr: Pointer,
47        _len: usize,
48        _offset: u64,
49        _ecx: &mut MiriInterpCx<'tcx>,
50        _finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
51    ) -> InterpResult<'tcx> {
52        throw_unsup_format!("cannot pwrite to {}", self.name());
53    }
54
55    fn flock<'tcx>(
56        &self,
57        _communicate_allowed: bool,
58        _op: FlockOp,
59    ) -> InterpResult<'tcx, io::Result<()>> {
60        throw_unsup_format!("cannot flock {}", self.name());
61    }
62
63    /// Check the readiness of file description.
64    fn get_epoll_ready_events<'tcx>(&self) -> InterpResult<'tcx, EpollReadyEvents> {
65        throw_unsup_format!("{}: epoll does not support this file description", self.name());
66    }
67}
68
69impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
70pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
71    fn dup(&mut self, old_fd_num: i32) -> InterpResult<'tcx, Scalar> {
72        let this = self.eval_context_mut();
73
74        let Some(fd) = this.machine.fds.get(old_fd_num) else {
75            return this.set_last_error_and_return_i32(LibcError("EBADF"));
76        };
77        interp_ok(Scalar::from_i32(this.machine.fds.insert(fd)))
78    }
79
80    fn dup2(&mut self, old_fd_num: i32, new_fd_num: i32) -> InterpResult<'tcx, Scalar> {
81        let this = self.eval_context_mut();
82
83        let Some(fd) = this.machine.fds.get(old_fd_num) else {
84            return this.set_last_error_and_return_i32(LibcError("EBADF"));
85        };
86        if new_fd_num != old_fd_num {
87            // Close new_fd if it is previously opened.
88            // If old_fd and new_fd point to the same description, then `dup_fd` ensures we keep the underlying file description alive.
89            if let Some(old_new_fd) = this.machine.fds.fds.insert(new_fd_num, fd) {
90                // Ignore close error (not interpreter's) according to dup2() doc.
91                old_new_fd.close_ref(this.machine.communicate(), this)?.ok();
92            }
93        }
94        interp_ok(Scalar::from_i32(new_fd_num))
95    }
96
97    fn flock(&mut self, fd_num: i32, op: i32) -> InterpResult<'tcx, Scalar> {
98        let this = self.eval_context_mut();
99        let Some(fd) = this.machine.fds.get(fd_num) else {
100            return this.set_last_error_and_return_i32(LibcError("EBADF"));
101        };
102
103        // We need to check that there aren't unsupported options in `op`.
104        let lock_sh = this.eval_libc_i32("LOCK_SH");
105        let lock_ex = this.eval_libc_i32("LOCK_EX");
106        let lock_nb = this.eval_libc_i32("LOCK_NB");
107        let lock_un = this.eval_libc_i32("LOCK_UN");
108
109        use FlockOp::*;
110        let parsed_op = if op == lock_sh {
111            SharedLock { nonblocking: false }
112        } else if op == lock_sh | lock_nb {
113            SharedLock { nonblocking: true }
114        } else if op == lock_ex {
115            ExclusiveLock { nonblocking: false }
116        } else if op == lock_ex | lock_nb {
117            ExclusiveLock { nonblocking: true }
118        } else if op == lock_un {
119            Unlock
120        } else {
121            throw_unsup_format!("unsupported flags {:#x}", op);
122        };
123
124        let result = fd.as_unix().flock(this.machine.communicate(), parsed_op)?;
125        // return `0` if flock is successful
126        let result = result.map(|()| 0i32);
127        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
128    }
129
130    fn fcntl(
131        &mut self,
132        fd_num: &OpTy<'tcx>,
133        cmd: &OpTy<'tcx>,
134        varargs: &[OpTy<'tcx>],
135    ) -> InterpResult<'tcx, Scalar> {
136        let this = self.eval_context_mut();
137
138        let fd_num = this.read_scalar(fd_num)?.to_i32()?;
139        let cmd = this.read_scalar(cmd)?.to_i32()?;
140
141        let f_getfd = this.eval_libc_i32("F_GETFD");
142        let f_dupfd = this.eval_libc_i32("F_DUPFD");
143        let f_dupfd_cloexec = this.eval_libc_i32("F_DUPFD_CLOEXEC");
144
145        // We only support getting the flags for a descriptor.
146        match cmd {
147            cmd if cmd == f_getfd => {
148                // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
149                // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
150                // always sets this flag when opening a file. However we still need to check that the
151                // file itself is open.
152                if !this.machine.fds.is_fd_num(fd_num) {
153                    this.set_last_error_and_return_i32(LibcError("EBADF"))
154                } else {
155                    interp_ok(this.eval_libc("FD_CLOEXEC"))
156                }
157            }
158            cmd if cmd == f_dupfd || cmd == f_dupfd_cloexec => {
159                // Note that we always assume the FD_CLOEXEC flag is set for every open file, in part
160                // because exec() isn't supported. The F_DUPFD and F_DUPFD_CLOEXEC commands only
161                // differ in whether the FD_CLOEXEC flag is pre-set on the new file descriptor,
162                // thus they can share the same implementation here.
163                let cmd_name = if cmd == f_dupfd {
164                    "fcntl(fd, F_DUPFD, ...)"
165                } else {
166                    "fcntl(fd, F_DUPFD_CLOEXEC, ...)"
167                };
168
169                let [start] = check_min_vararg_count(cmd_name, varargs)?;
170                let start = this.read_scalar(start)?.to_i32()?;
171
172                if let Some(fd) = this.machine.fds.get(fd_num) {
173                    interp_ok(Scalar::from_i32(this.machine.fds.insert_with_min_num(fd, start)))
174                } else {
175                    this.set_last_error_and_return_i32(LibcError("EBADF"))
176                }
177            }
178            cmd if this.tcx.sess.target.os == "macos"
179                && cmd == this.eval_libc_i32("F_FULLFSYNC") =>
180            {
181                // Reject if isolation is enabled.
182                if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
183                    this.reject_in_isolation("`fcntl`", reject_with)?;
184                    return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
185                }
186
187                this.ffullsync_fd(fd_num)
188            }
189            cmd => {
190                throw_unsup_format!("fcntl: unsupported command {cmd:#x}");
191            }
192        }
193    }
194
195    fn close(&mut self, fd_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
196        let this = self.eval_context_mut();
197
198        let fd_num = this.read_scalar(fd_op)?.to_i32()?;
199
200        let Some(fd) = this.machine.fds.remove(fd_num) else {
201            return this.set_last_error_and_return_i32(LibcError("EBADF"));
202        };
203        let result = fd.close_ref(this.machine.communicate(), this)?;
204        // return `0` if close is successful
205        let result = result.map(|()| 0i32);
206        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
207    }
208
209    /// Read data from `fd` into buffer specified by `buf` and `count`.
210    ///
211    /// If `offset` is `None`, reads data from current cursor position associated with `fd`
212    /// and updates cursor position on completion. Otherwise, reads from the specified offset
213    /// and keeps the cursor unchanged.
214    fn read(
215        &mut self,
216        fd_num: i32,
217        buf: Pointer,
218        count: u64,
219        offset: Option<i128>,
220        dest: &MPlaceTy<'tcx>,
221    ) -> InterpResult<'tcx> {
222        let this = self.eval_context_mut();
223
224        // Isolation check is done via `FileDescription` trait.
225
226        trace!("Reading from FD {}, size {}", fd_num, count);
227
228        // Check that the *entire* buffer is actually valid memory.
229        this.check_ptr_access(buf, Size::from_bytes(count), CheckInAllocMsg::MemoryAccessTest)?;
230
231        // We cap the number of read bytes to the largest value that we are able to fit in both the
232        // host's and target's `isize`. This saves us from having to handle overflows later.
233        let count = count
234            .min(u64::try_from(this.target_isize_max()).unwrap())
235            .min(u64::try_from(isize::MAX).unwrap());
236        let count = usize::try_from(count).unwrap(); // now it fits in a `usize`
237        let communicate = this.machine.communicate();
238
239        // Get the FD.
240        let Some(fd) = this.machine.fds.get(fd_num) else {
241            trace!("read: FD not found");
242            return this.set_last_error_and_return(LibcError("EBADF"), dest);
243        };
244
245        trace!("read: FD mapped to {fd:?}");
246        // We want to read at most `count` bytes. We are sure that `count` is not negative
247        // because it was a target's `usize`. Also we are sure that its smaller than
248        // `usize::MAX` because it is bounded by the host's `isize`.
249
250        let finish = {
251            let dest = dest.clone();
252            callback!(
253                @capture<'tcx> {
254                    count: usize,
255                    dest: MPlaceTy<'tcx>,
256                }
257                |this, result: Result<usize, IoError>| {
258                    match result {
259                        Ok(read_size) => {
260                            assert!(read_size <= count);
261                            // This must fit since `count` fits.
262                            this.write_int(u64::try_from(read_size).unwrap(), &dest)
263                        }
264                        Err(e) => {
265                            this.set_last_error_and_return(e, &dest)
266                        }
267                }}
268            )
269        };
270        match offset {
271            None => fd.read(communicate, buf, count, this, finish)?,
272            Some(offset) => {
273                let Ok(offset) = u64::try_from(offset) else {
274                    return this.set_last_error_and_return(LibcError("EINVAL"), dest);
275                };
276                fd.as_unix().pread(communicate, offset, buf, count, this, finish)?
277            }
278        };
279        interp_ok(())
280    }
281
282    fn write(
283        &mut self,
284        fd_num: i32,
285        buf: Pointer,
286        count: u64,
287        offset: Option<i128>,
288        dest: &MPlaceTy<'tcx>,
289    ) -> InterpResult<'tcx> {
290        let this = self.eval_context_mut();
291
292        // Isolation check is done via `FileDescription` trait.
293
294        // Check that the *entire* buffer is actually valid memory.
295        this.check_ptr_access(buf, Size::from_bytes(count), CheckInAllocMsg::MemoryAccessTest)?;
296
297        // We cap the number of written bytes to the largest value that we are able to fit in both the
298        // host's and target's `isize`. This saves us from having to handle overflows later.
299        let count = count
300            .min(u64::try_from(this.target_isize_max()).unwrap())
301            .min(u64::try_from(isize::MAX).unwrap());
302        let count = usize::try_from(count).unwrap(); // now it fits in a `usize`
303        let communicate = this.machine.communicate();
304
305        // We temporarily dup the FD to be able to retain mutable access to `this`.
306        let Some(fd) = this.machine.fds.get(fd_num) else {
307            return this.set_last_error_and_return(LibcError("EBADF"), dest);
308        };
309
310        let finish = {
311            let dest = dest.clone();
312            callback!(
313                @capture<'tcx> {
314                    count: usize,
315                    dest: MPlaceTy<'tcx>,
316                }
317                |this, result: Result<usize, IoError>| {
318                    match result {
319                        Ok(write_size) => {
320                            assert!(write_size <= count);
321                            // This must fit since `count` fits.
322                            this.write_int(u64::try_from(write_size).unwrap(), &dest)
323                        }
324                        Err(e) => {
325                            this.set_last_error_and_return(e, &dest)
326                        }
327                }}
328            )
329        };
330        match offset {
331            None => fd.write(communicate, buf, count, this, finish)?,
332            Some(offset) => {
333                let Ok(offset) = u64::try_from(offset) else {
334                    return this.set_last_error_and_return(LibcError("EINVAL"), dest);
335                };
336                fd.as_unix().pwrite(communicate, buf, count, offset, this, finish)?
337            }
338        };
339        interp_ok(())
340    }
341}