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;
11 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 this.check_no_isolation("open")?;
41 let flag = this.read_scalar(flag_op)?.to_i32()?;
43 let mut options = OpenOptions::new();
45 let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
46 let o_wronly = this.eval_libc_i32("O_WRONLY")?;
47 let o_rdwr = this.eval_libc_i32("O_RDWR")?;
48 // The first two bits of the flag correspond to the access mode in linux, macOS and
49 // windows. We need to check that in fact the access mode flags for the current platform
50 // only use these two bits, otherwise we are in an unsupported platform and should error.
51 if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
52 throw_unsup_format!("Access mode flags on this platform are unsupported");
54 // Now we check the access mode
55 let access_mode = flag & 0b11;
57 if access_mode == o_rdonly {
59 } else if access_mode == o_wronly {
61 } else if access_mode == o_rdwr {
62 options.read(true).write(true);
64 throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
66 // We need to check that there aren't unsupported options in `flag`. For this we try to
67 // reproduce the content of `flag` in the `mirror` variable using only the supported
69 let mut mirror = access_mode;
71 let o_append = this.eval_libc_i32("O_APPEND")?;
72 if flag & o_append != 0 {
76 let o_trunc = this.eval_libc_i32("O_TRUNC")?;
77 if flag & o_trunc != 0 {
78 options.truncate(true);
81 let o_creat = this.eval_libc_i32("O_CREAT")?;
82 if flag & o_creat != 0 {
86 let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
87 if flag & o_cloexec != 0 {
88 // We do not need to do anything for this flag because `std` already sets it.
89 // (Technically we do not support *not* setting this flag, but we ignore that.)
92 // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
93 // then we throw an error.
95 throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
98 let path: std::path::PathBuf = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?.into();
100 let fd = options.open(path).map(|file| {
101 let mut fh = &mut this.machine.file_handler;
103 fh.handles.insert(fh.low, FileHandle { file }).unwrap_none();
107 this.try_unwrap_io_result(fd)
112 fd_op: OpTy<'tcx, Tag>,
113 cmd_op: OpTy<'tcx, Tag>,
114 _arg1_op: Option<OpTy<'tcx, Tag>>,
115 ) -> InterpResult<'tcx, i32> {
116 let this = self.eval_context_mut();
118 this.check_no_isolation("fcntl")?;
120 let fd = this.read_scalar(fd_op)?.to_i32()?;
121 let cmd = this.read_scalar(cmd_op)?.to_i32()?;
122 // We only support getting the flags for a descriptor.
123 if cmd == this.eval_libc_i32("F_GETFD")? {
124 // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
125 // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
126 // always sets this flag when opening a file. However we still need to check that the
127 // file itself is open.
128 let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
129 this.get_handle_and(fd, |_| Ok(fd_cloexec))
131 throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
135 fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
136 let this = self.eval_context_mut();
138 this.check_no_isolation("close")?;
140 let fd = this.read_scalar(fd_op)?.to_i32()?;
142 this.remove_handle_and(fd, |handle, this| {
143 this.try_unwrap_io_result(handle.file.sync_all().map(|_| 0i32))
149 fd_op: OpTy<'tcx, Tag>,
150 buf_op: OpTy<'tcx, Tag>,
151 count_op: OpTy<'tcx, Tag>,
152 ) -> InterpResult<'tcx, i64> {
153 let this = self.eval_context_mut();
155 this.check_no_isolation("read")?;
157 let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
158 // Reading zero bytes should not change `buf`.
162 let fd = this.read_scalar(fd_op)?.to_i32()?;
163 let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
165 // Remove the file handle to avoid borrowing issues.
166 this.remove_handle_and(fd, |mut handle, this| {
167 // Don't use `?` to avoid returning before reinserting the handle.
168 let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
170 .get_mut(buf.alloc_id)?
171 .get_bytes_mut(&*this.tcx, buf, Size::from_bytes(count))
172 .map(|buffer| handle.file.read(buffer))
174 this.machine.file_handler.handles.insert(fd, handle).unwrap_none();
175 this.try_unwrap_io_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).unwrap_none();
204 this.try_unwrap_io_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.try_unwrap_io_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)?;