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);
97 let path: std::path::PathBuf = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?.into();
99 let fd = options.open(path).map(|file| {
100 let mut fh = &mut this.machine.file_handler;
102 fh.handles.insert(fh.low, FileHandle { file });
106 this.consume_result(fd)
111 fd_op: OpTy<'tcx, Tag>,
112 cmd_op: OpTy<'tcx, Tag>,
113 _arg1_op: Option<OpTy<'tcx, Tag>>,
114 ) -> InterpResult<'tcx, i32> {
115 let this = self.eval_context_mut();
117 this.check_no_isolation("fcntl")?;
119 let fd = this.read_scalar(fd_op)?.to_i32()?;
120 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
121 // We only support getting the flags for a descriptor
122 if cmd == this.eval_libc_i32("F_GETFD")? {
123 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
124 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
125 // always sets this flag when opening a file. However we still need to check that the
126 // file itself is open.
127 let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
128 this.get_handle_and(fd, |_| Ok(fd_cloexec))
130 throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
134 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
135 let this = self.eval_context_mut();
137 this.check_no_isolation("close")?;
139 let fd = this.read_scalar(fd_op)?.to_i32()?;
141 this.remove_handle_and(fd, |handle, this| {
142 this.consume_result(handle.file.sync_all().map(|_| 0i32))
148 fd_op: OpTy<'tcx, Tag>,
149 buf_op: OpTy<'tcx, Tag>,
150 count_op: OpTy<'tcx, Tag>,
151 ) -> InterpResult<'tcx, i64> {
152 let this = self.eval_context_mut();
154 this.check_no_isolation("read")?;
156 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
157 // Reading zero bytes should not change `buf`
161 let fd = this.read_scalar(fd_op)?.to_i32()?;
162 let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
164 // Remove the file handle to avoid borrowing issues
165 this.remove_handle_and(fd, |mut handle, this| {
166 // Don't use `?` to avoid returning before reinserting the handle
167 let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
169 .get_mut(buf.alloc_id)?
170 .get_bytes_mut(&*this.tcx, buf, Size::from_bytes(count))
171 .map(|buffer| handle.file.read(buffer))
173 // Reinsert the file handle
174 this.machine.file_handler.handles.insert(fd, handle);
175 this.consume_result(bytes?.map(|bytes| bytes as i64))
181 fd_op: OpTy<'tcx, Tag>,
182 buf_op: OpTy<'tcx, Tag>,
183 count_op: OpTy<'tcx, Tag>,
184 ) -> InterpResult<'tcx, i64> {
185 let this = self.eval_context_mut();
187 this.check_no_isolation("write")?;
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(&*this.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 fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
209 let this = self.eval_context_mut();
211 this.check_no_isolation("unlink")?;
213 let path = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?;
215 let result = remove_file(path).map(|_| 0);
217 this.consume_result(result)
220 /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
221 /// using the `f` closure.
223 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
224 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
226 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
227 /// functions return different integer types (like `read`, that returns an `i64`)
228 fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
230 F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
232 let this = self.eval_context_mut();
233 if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
236 let ebadf = this.eval_libc("EBADF")?;
237 this.set_last_error(ebadf)?;
242 /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
243 /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
244 /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
247 /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
248 /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
250 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
251 /// functions return different integer types (like `read`, that returns an `i64`)
252 fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
254 F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
256 let this = self.eval_context_mut();
257 if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
260 let ebadf = this.eval_libc("EBADF")?;
261 this.set_last_error(ebadf)?;
266 /// Helper function that consumes an `std::io::Result<T>` and returns an
267 /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
268 /// OS error using `std::io::Error::raw_os_error`.
270 /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
271 /// functions return different integer types (like `read`, that returns an `i64`)
272 fn consume_result<T: From<i32>>(
274 result: std::io::Result<T>,
275 ) -> InterpResult<'tcx, T> {
279 self.eval_context_mut().consume_io_error(e)?;