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 {
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. This
48 // is done this way because `O_RDONLY` is zero in several platforms.
49 let access_mode = flag & 0b11;
51 if access_mode == this.eval_libc_i32("O_RDONLY")? {
53 } else if access_mode == this.eval_libc_i32("O_WRONLY")? {
55 } else if access_mode == this.eval_libc_i32("O_RDWR")? {
56 options.read(true).write(true);
58 throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
60 // We need to check that there aren't unsupported options in `flag`. For this we try to
61 // reproduce the content of `flag` in the `mirror` variable using only the supported
63 let mut mirror = access_mode;
65 let o_append = this.eval_libc_i32("O_APPEND")?;
66 if flag & o_append != 0 {
70 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
71 if flag & o_trunc != 0 {
72 options.truncate(true);
75 let o_creat = this.eval_libc_i32("O_CREAT")?;
76 if flag & o_creat != 0 {
80 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
81 if flag & o_cloexec != 0 {
82 // This flag is a noop for now because `std` already sets it.
85 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
86 // then we throw an error.
88 throw_unsup_format!("unsupported flags {:#x}", flag);
93 .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
94 let path = std::str::from_utf8(path_bytes)
95 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
97 let fd = options.open(path).map(|file| {
98 let mut fh = &mut this.machine.file_handler;
100 fh.handles.insert(fh.low, FileHandle { file, flag });
104 this.consume_result(fd)
109 fd_op: OpTy<'tcx, Tag>,
110 cmd_op: OpTy<'tcx, Tag>,
111 arg_op: Option<OpTy<'tcx, Tag>>,
112 ) -> InterpResult<'tcx, i32> {
113 let this = self.eval_context_mut();
115 if !this.machine.communicate {
116 throw_unsup_format!("`fcntl` not available when isolation is enabled")
119 let fd = this.read_scalar(fd_op)?.to_i32()?;
120 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
122 if cmd == this.eval_libc_i32("F_SETFD")? {
123 // This does not affect the file itself. Certain flags might require changing the file
124 // or the way it is accessed somehow.
125 let flag = this.read_scalar(arg_op.unwrap())?.to_i32()?;
126 // The only usage of this in stdlib at the moment is to enable the `FD_CLOEXEC` flag.
127 let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
128 if let Some(FileHandle { flag: old_flag, .. }) =
129 this.machine.file_handler.handles.get_mut(&fd)
131 // Check that the only difference between the old flag and the current flag is
132 // exactly the `FD_CLOEXEC` value.
133 if flag ^ *old_flag == fd_cloexec {
136 throw_unsup_format!("Unsupported arg {:#x} for `F_SETFD`", flag);
140 } else if cmd == this.eval_libc_i32("F_GETFD")? {
141 this.get_handle_and(fd, |handle| Ok(handle.flag))
143 throw_unsup_format!("Unsupported command {:#x}", cmd);
147 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
148 let this = self.eval_context_mut();
150 if !this.machine.communicate {
151 throw_unsup_format!("`close` not available when isolation is enabled")
154 let fd = this.read_scalar(fd_op)?.to_i32()?;
156 this.remove_handle_and(fd, |handle, this| {
157 this.consume_result(handle.file.sync_all().map(|_| 0i32))
163 fd_op: OpTy<'tcx, Tag>,
164 buf_op: OpTy<'tcx, Tag>,
165 count_op: OpTy<'tcx, Tag>,
166 ) -> InterpResult<'tcx, i64> {
167 let this = self.eval_context_mut();
169 if !this.machine.communicate {
170 throw_unsup_format!("`read` not available when isolation is enabled")
173 let tcx = &{ this.tcx.tcx };
175 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
176 // Reading zero bytes should not change `buf`
180 let fd = this.read_scalar(fd_op)?.to_i32()?;
181 let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
183 // Remove the file handle to avoid borrowing issues
184 this.remove_handle_and(fd, |mut handle, this| {
185 // Don't use `?` to avoid returning before reinserting the handle
186 let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
188 .get_mut(buf.alloc_id)?
189 .get_bytes_mut(tcx, buf, Size::from_bytes(count))
190 .map(|buffer| handle.file.read(buffer))
192 // Reinsert the file handle
193 this.machine.file_handler.handles.insert(fd, handle);
194 this.consume_result(bytes?.map(|bytes| bytes as i64))
200 fd_op: OpTy<'tcx, Tag>,
201 buf_op: OpTy<'tcx, Tag>,
202 count_op: OpTy<'tcx, Tag>,
203 ) -> InterpResult<'tcx, i64> {
204 let this = self.eval_context_mut();
206 if !this.machine.communicate {
207 throw_unsup_format!("`write` not available when isolation is enabled")
210 let tcx = &{ this.tcx.tcx };
212 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
213 // Writing zero bytes should not change `buf`
217 let fd = this.read_scalar(fd_op)?.to_i32()?;
218 let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
220 this.remove_handle_and(fd, |mut handle, this| {
221 let bytes = this.memory().get(buf.alloc_id).and_then(|alloc| {
223 .get_bytes(tcx, buf, Size::from_bytes(count))
224 .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
226 this.machine.file_handler.handles.insert(fd, handle);
227 this.consume_result(bytes?)
231 fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
232 let this = self.eval_context_mut();
234 if !this.machine.communicate {
235 throw_unsup_format!("`write` not available when isolation is enabled")
238 let path_bytes = this
240 .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
241 let path = std::str::from_utf8(path_bytes)
242 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
244 let result = remove_file(path).map(|_| 0);
246 this.consume_result(result)
249 /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
250 /// using the `f` closure.
252 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
253 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
255 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
256 /// functions return different integer types (like `read`, that returns an `i64`)
257 fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
259 F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
261 let this = self.eval_context_mut();
262 if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
265 let ebadf = this.eval_libc("EBADF")?;
266 this.set_last_error(ebadf)?;
271 /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
272 /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
273 /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
276 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
277 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
279 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
280 /// functions return different integer types (like `read`, that returns an `i64`)
281 fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
283 F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
285 let this = self.eval_context_mut();
286 if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
289 let ebadf = this.eval_libc("EBADF")?;
290 this.set_last_error(ebadf)?;
295 /// Helper function that consumes an `std::io::Result<T>` and returns an
296 /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
297 /// OS error using `std::io::Error::raw_os_error`.
299 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
300 /// functions return different integer types (like `read`, that returns an `i64`)
301 fn consume_result<T: From<i32>>(
303 result: std::io::Result<T>,
304 ) -> InterpResult<'tcx, T> {
308 self.eval_context_mut().consume_io_error(e)?;