1 use std::collections::HashMap;
2 use std::fs::{File, OpenOptions};
3 use std::io::{Read, Write};
5 use rustc::ty::layout::Size;
7 use crate::stacked_borrows::Tag;
10 pub struct FileHandle {
15 pub struct FileHandler {
16 handles: HashMap<i32, FileHandle>,
20 impl Default for FileHandler {
21 fn default() -> Self {
23 handles: Default::default(),
24 // 0, 1 and 2 are reserved for stdin, stdout and stderr
30 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
31 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
34 path_op: OpTy<'tcx, Tag>,
35 flag_op: OpTy<'tcx, Tag>,
36 ) -> InterpResult<'tcx, i32> {
37 let this = self.eval_context_mut();
39 if !this.machine.communicate {
40 throw_unsup_format!("`open` not available when isolation is enabled")
43 let flag = this.read_scalar(flag_op)?.to_i32()?;
45 let mut options = OpenOptions::new();
47 // The first two bits of the flag correspond to the access mode of the file in linux.
48 let access_mode = flag & 0b11;
50 if access_mode == this.eval_libc_i32("O_RDONLY")? {
52 } else if access_mode == this.eval_libc_i32("O_WRONLY")? {
54 } else if access_mode == this.eval_libc_i32("O_RDWR")? {
55 options.read(true).write(true);
57 throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
60 if flag & this.eval_libc_i32("O_APPEND")? != 0 {
63 if flag & this.eval_libc_i32("O_TRUNC")? != 0 {
64 options.truncate(true);
66 if flag & this.eval_libc_i32("O_CREAT")? != 0 {
72 .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
73 let path = std::str::from_utf8(path_bytes)
74 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
76 let fd = options.open(path).map(|file| {
77 let mut fh = &mut this.machine.file_handler;
79 fh.handles.insert(fh.low, FileHandle { file, flag });
83 this.consume_result(fd)
88 fd_op: OpTy<'tcx, Tag>,
89 cmd_op: OpTy<'tcx, Tag>,
90 arg_op: Option<OpTy<'tcx, Tag>>,
91 ) -> InterpResult<'tcx, i32> {
92 let this = self.eval_context_mut();
94 if !this.machine.communicate {
95 throw_unsup_format!("`fcntl` not available when isolation is enabled")
98 let fd = this.read_scalar(fd_op)?.to_i32()?;
99 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
101 if cmd == this.eval_libc_i32("F_SETFD")? {
102 // This does not affect the file itself. Certain flags might require changing the file
103 // or the way it is accessed somehow.
104 let flag = this.read_scalar(arg_op.unwrap())?.to_i32()?;
105 // The only usage of this in stdlib at the moment is to enable the `FD_CLOEXEC` flag.
106 let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
107 if let Some(FileHandle { flag: old_flag, .. }) =
108 this.machine.file_handler.handles.get_mut(&fd)
110 if flag ^ *old_flag == fd_cloexec {
113 throw_unsup_format!("Unsupported arg {:#x} for `F_SETFD`", flag);
117 } else if cmd == this.eval_libc_i32("F_GETFD")? {
118 this.get_handle_and(fd, |handle| Ok(handle.flag))
120 throw_unsup_format!("Unsupported command {:#x}", cmd);
124 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
125 let this = self.eval_context_mut();
127 if !this.machine.communicate {
128 throw_unsup_format!("`close` not available when isolation is enabled")
131 let fd = this.read_scalar(fd_op)?.to_i32()?;
133 this.remove_handle_and(fd, |handle, this| {
134 this.consume_result(handle.file.sync_all().map(|_| 0i32))
140 fd_op: OpTy<'tcx, Tag>,
141 buf_op: OpTy<'tcx, Tag>,
142 count_op: OpTy<'tcx, Tag>,
143 ) -> InterpResult<'tcx, i64> {
144 let this = self.eval_context_mut();
146 if !this.machine.communicate {
147 throw_unsup_format!("`read` not available when isolation is enabled")
150 let tcx = &{ this.tcx.tcx };
152 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
153 // Reading zero bytes should not change `buf`
157 let fd = this.read_scalar(fd_op)?.to_i32()?;
158 let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
160 // Remove the file handle to avoid borrowing issues
161 this.remove_handle_and(fd, |mut handle, this| {
162 // Don't use `?` to avoid returning before reinserting the handle
163 let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
165 .get_mut(buf.alloc_id)?
166 .get_bytes_mut(tcx, buf, Size::from_bytes(count))
167 .map(|buffer| handle.file.read(buffer))
169 // Reinsert the file handle
170 this.machine.file_handler.handles.insert(fd, handle);
171 this.consume_result(bytes?.map(|bytes| bytes as i64))
177 fd_op: OpTy<'tcx, Tag>,
178 buf_op: OpTy<'tcx, Tag>,
179 count_op: OpTy<'tcx, Tag>,
180 ) -> InterpResult<'tcx, i64> {
181 let this = self.eval_context_mut();
183 if !this.machine.communicate {
184 throw_unsup_format!("`write` not available when isolation is enabled")
187 let tcx = &{ this.tcx.tcx };
189 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
190 // Writing zero bytes should not change `buf`
194 let fd = this.read_scalar(fd_op)?.to_i32()?;
195 let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
197 this.remove_handle_and(fd, |mut handle, this| {
198 let bytes = this.memory().get(buf.alloc_id).and_then(|alloc| {
200 .get_bytes(tcx, buf, Size::from_bytes(count))
201 .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
203 this.machine.file_handler.handles.insert(fd, handle);
204 this.consume_result(bytes?)
208 /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
209 /// using the `f` closure.
211 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
212 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
214 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
215 /// functions return different integer types (like `read`, that returns an `i64`)
216 fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
218 F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
220 let this = self.eval_context_mut();
221 if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
224 this.machine.last_error = this.eval_libc_i32("EBADF")? as u32;
229 /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
230 /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
231 /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
234 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
235 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
237 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
238 /// functions return different integer types (like `read`, that returns an `i64`)
239 fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
241 F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
243 let this = self.eval_context_mut();
244 if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
247 this.machine.last_error = this.eval_libc_i32("EBADF")? as u32;
252 /// Helper function that consumes an `std::io::Result<T>` and returns an
253 /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
254 /// OS error using `std::io::Error::raw_os_error`.
256 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
257 /// functions return different integer types (like `read`, that returns an `i64`)
258 fn consume_result<T: From<i32>>(
260 result: std::io::Result<T>,
261 ) -> InterpResult<'tcx, T> {
265 self.eval_context_mut().machine.last_error = e.raw_os_error().unwrap() as u32;