1 use std::collections::HashMap;
2 use std::fs::{File, OpenOptions, remove_file};
3 use std::io::{Read, Write};
5 use rustc::ty::layout::Size;
7 use crate::stacked_borrows::Tag;
10 pub struct FileHandle {
14 pub struct FileHandler {
15 handles: HashMap<i32, FileHandle>,
19 impl Default for FileHandler {
20 fn default() -> Self {
22 handles: Default::default(),
23 // 0, 1 and 2 are reserved for stdin, stdout and stderr
29 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
30 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
33 path_op: OpTy<'tcx, Tag>,
34 flag_op: OpTy<'tcx, Tag>,
35 ) -> InterpResult<'tcx, i32> {
36 let this = self.eval_context_mut();
38 this.check_no_isolation("open")?;
40 let flag = this.read_scalar(flag_op)?.to_i32()?;
42 let mut options = OpenOptions::new();
44 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
45 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
46 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
47 // The first two bits of the flag correspond to the access mode in linux, macOS and
48 // windows. We need to check that in fact the access mode flags for the current platform
49 // only use these two bits, otherwise we are in an unsupported platform and should error.
50 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
51 throw_unsup_format!("Access mode flags on this platform are unsupported");
53 // Now we check the access mode
54 let access_mode = flag & 0b11;
56 if access_mode == o_rdonly {
58 } else if access_mode == o_wronly {
60 } else if access_mode == o_rdwr {
61 options.read(true).write(true);
63 throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
65 // We need to check that there aren't unsupported options in `flag`. For this we try to
66 // reproduce the content of `flag` in the `mirror` variable using only the supported
68 let mut mirror = access_mode;
70 let o_append = this.eval_libc_i32("O_APPEND")?;
71 if flag & o_append != 0 {
75 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
76 if flag & o_trunc != 0 {
77 options.truncate(true);
80 let o_creat = this.eval_libc_i32("O_CREAT")?;
81 if flag & o_creat != 0 {
85 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
86 if flag & o_cloexec != 0 {
87 // We do not need to do anything for this flag because `std` already sets it.
88 // (Technically we do not support *not* setting this flag, but we ignore that.)
91 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
92 // then we throw an error.
94 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
99 .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
100 let path = std::str::from_utf8(path_bytes)
101 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
103 let fd = options.open(path).map(|file| {
104 let mut fh = &mut this.machine.file_handler;
106 fh.handles.insert(fh.low, FileHandle { file });
110 this.consume_result(fd)
115 fd_op: OpTy<'tcx, Tag>,
116 cmd_op: OpTy<'tcx, Tag>,
117 _arg1_op: Option<OpTy<'tcx, Tag>>,
118 ) -> InterpResult<'tcx, i32> {
119 let this = self.eval_context_mut();
121 this.check_no_isolation("fcntl")?;
123 let fd = this.read_scalar(fd_op)?.to_i32()?;
124 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
125 // We only support getting the flags for a descriptor
126 if cmd == this.eval_libc_i32("F_GETFD")? {
127 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
128 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
129 // always sets this flag when opening a file. However we still need to check that the
130 // file itself is open.
131 let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
132 this.get_handle_and(fd, |_| Ok(fd_cloexec))
134 throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
138 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
139 let this = self.eval_context_mut();
141 this.check_no_isolation("close")?;
143 let fd = this.read_scalar(fd_op)?.to_i32()?;
145 this.remove_handle_and(fd, |handle, this| {
146 this.consume_result(handle.file.sync_all().map(|_| 0i32))
152 fd_op: OpTy<'tcx, Tag>,
153 buf_op: OpTy<'tcx, Tag>,
154 count_op: OpTy<'tcx, Tag>,
155 ) -> InterpResult<'tcx, i64> {
156 let this = self.eval_context_mut();
158 this.check_no_isolation("read")?;
160 let tcx = &{ this.tcx.tcx };
162 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
163 // Reading zero bytes should not change `buf`
167 let fd = this.read_scalar(fd_op)?.to_i32()?;
168 let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
170 // Remove the file handle to avoid borrowing issues
171 this.remove_handle_and(fd, |mut handle, this| {
172 // Don't use `?` to avoid returning before reinserting the handle
173 let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
175 .get_mut(buf.alloc_id)?
176 .get_bytes_mut(tcx, buf, Size::from_bytes(count))
177 .map(|buffer| handle.file.read(buffer))
179 // Reinsert the file handle
180 this.machine.file_handler.handles.insert(fd, handle);
181 this.consume_result(bytes?.map(|bytes| bytes as i64))
187 fd_op: OpTy<'tcx, Tag>,
188 buf_op: OpTy<'tcx, Tag>,
189 count_op: OpTy<'tcx, Tag>,
190 ) -> InterpResult<'tcx, i64> {
191 let this = self.eval_context_mut();
193 this.check_no_isolation("write")?;
195 let tcx = &{ this.tcx.tcx };
197 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
198 // Writing zero bytes should not change `buf`
202 let fd = this.read_scalar(fd_op)?.to_i32()?;
203 let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
205 this.remove_handle_and(fd, |mut handle, this| {
206 let bytes = this.memory.get(buf.alloc_id).and_then(|alloc| {
208 .get_bytes(tcx, buf, Size::from_bytes(count))
209 .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
211 this.machine.file_handler.handles.insert(fd, handle);
212 this.consume_result(bytes?)
216 fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
217 let this = self.eval_context_mut();
219 this.check_no_isolation("unlink")?;
221 let path_bytes = this
223 .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
224 let path = std::str::from_utf8(path_bytes)
225 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
227 let result = remove_file(path).map(|_| 0);
229 this.consume_result(result)
232 /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
233 /// using the `f` closure.
235 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
236 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
238 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
239 /// functions return different integer types (like `read`, that returns an `i64`)
240 fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
242 F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
244 let this = self.eval_context_mut();
245 if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
248 let ebadf = this.eval_libc("EBADF")?;
249 this.set_last_error(ebadf)?;
254 /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
255 /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
256 /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
259 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
260 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
262 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
263 /// functions return different integer types (like `read`, that returns an `i64`)
264 fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
266 F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
268 let this = self.eval_context_mut();
269 if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
272 let ebadf = this.eval_libc("EBADF")?;
273 this.set_last_error(ebadf)?;
278 /// Helper function that consumes an `std::io::Result<T>` and returns an
279 /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
280 /// OS error using `std::io::Error::raw_os_error`.
282 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
283 /// functions return different integer types (like `read`, that returns an `i64`)
284 fn consume_result<T: From<i32>>(
286 result: std::io::Result<T>,
287 ) -> InterpResult<'tcx, T> {
291 self.eval_context_mut().consume_io_error(e)?;