]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Fix merge conflicts
[rust.git] / src / shims / fs.rs
1 use std::collections::HashMap;
2 use std::fs::{File, OpenOptions, remove_file};
3 use std::io::{Read, Write};
4
5 use rustc::ty::layout::Size;
6
7 use crate::stacked_borrows::Tag;
8 use crate::*;
9
10 #[derive(Debug)]
11 pub struct FileHandle {
12     file: File,
13 }
14
15 pub struct FileHandler {
16     handles: HashMap<i32, FileHandle>,
17     low: i32,
18 }
19
20 impl Default for FileHandler {
21     fn default() -> Self {
22         FileHandler {
23             handles: Default::default(),
24             // 0, 1 and 2 are reserved for stdin, stdout and stderr.
25             low: 3,
26         }
27     }
28 }
29
30 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
31 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
32     fn open(
33         &mut self,
34         path_op: OpTy<'tcx, Tag>,
35         flag_op: OpTy<'tcx, Tag>,
36     ) -> InterpResult<'tcx, i32> {
37         let this = self.eval_context_mut();
38
39         this.check_no_isolation("open")?;
40
41         let flag = this.read_scalar(flag_op)?.to_i32()?;
42
43         let mut options = OpenOptions::new();
44
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");
53         }
54         // Now we check the access mode
55         let access_mode = flag & 0b11;
56
57         if access_mode == o_rdonly {
58             options.read(true);
59         } else if access_mode == o_wronly {
60             options.write(true);
61         } else if access_mode == o_rdwr {
62             options.read(true).write(true);
63         } else {
64             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
65         }
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
68         // options.
69         let mut mirror = access_mode;
70
71         let o_append = this.eval_libc_i32("O_APPEND")?;
72         if flag & o_append != 0 {
73             options.append(true);
74             mirror |= o_append;
75         }
76         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
77         if flag & o_trunc != 0 {
78             options.truncate(true);
79             mirror |= o_trunc;
80         }
81         let o_creat = this.eval_libc_i32("O_CREAT")?;
82         if flag & o_creat != 0 {
83             options.create(true);
84             mirror |= o_creat;
85         }
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.)
90             mirror |= o_cloexec;
91         }
92         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
93         // then we throw an error.
94         if flag != mirror {
95             throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
96         }
97
98         let path: std::path::PathBuf = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?.into();
99
100         let fd = options.open(path).map(|file| {
101             let mut fh = &mut this.machine.file_handler;
102             fh.low += 1;
103             fh.handles.insert(fh.low, FileHandle { file }).unwrap_none();
104             fh.low
105         });
106
107         this.try_unwrap_io_result(fd)
108     }
109
110     fn fcntl(
111         &mut self,
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();
117
118         this.check_no_isolation("fcntl")?;
119
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))
130         } else {
131             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
132         }
133     }
134
135     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
136         let this = self.eval_context_mut();
137
138         this.check_no_isolation("close")?;
139
140         let fd = this.read_scalar(fd_op)?.to_i32()?;
141
142         this.remove_handle_and(fd, |handle, this| {
143             this.try_unwrap_io_result(handle.file.sync_all().map(|_| 0i32))
144         })
145     }
146
147     fn read(
148         &mut self,
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();
154
155         this.check_no_isolation("read")?;
156
157         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
158         // Reading zero bytes should not change `buf`.
159         if count == 0 {
160             return Ok(0);
161         }
162         let fd = this.read_scalar(fd_op)?.to_i32()?;
163         let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
164
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| {
169                 this.memory
170                     .get_mut(buf.alloc_id)?
171                     .get_bytes_mut(&*this.tcx, buf, Size::from_bytes(count))
172                     .map(|buffer| handle.file.read(buffer))
173             });
174             this.machine.file_handler.handles.insert(fd, handle).unwrap_none();
175             this.try_unwrap_io_result(bytes?.map(|bytes| bytes as i64))
176         })
177     }
178
179     fn write(
180         &mut self,
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();
186
187         this.check_no_isolation("write")?;
188
189         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
190         // Writing zero bytes should not change `buf`.
191         if count == 0 {
192             return Ok(0);
193         }
194         let fd = this.read_scalar(fd_op)?.to_i32()?;
195         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
196
197         this.remove_handle_and(fd, |mut handle, this| {
198             let bytes = this.memory.get(buf.alloc_id).and_then(|alloc| {
199                 alloc
200                     .get_bytes(&*this.tcx, buf, Size::from_bytes(count))
201                     .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
202             });
203             this.machine.file_handler.handles.insert(fd, handle).unwrap_none();
204             this.try_unwrap_io_result(bytes?)
205         })
206     }
207
208     fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
209         let this = self.eval_context_mut();
210
211         this.check_no_isolation("unlink")?;
212
213         let path = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?;
214
215         let result = remove_file(path).map(|_| 0);
216
217         this.try_unwrap_io_result(result)
218     }
219
220     /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
221     /// using the `f` closure.
222     ///
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).
225     ///
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>
229     where
230         F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
231     {
232         let this = self.eval_context_mut();
233         if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
234             f(handle)
235         } else {
236             let ebadf = this.eval_libc("EBADF")?;
237             this.set_last_error(ebadf)?;
238             Ok((-1).into())
239         }
240     }
241
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
245     /// using `f`.
246     ///
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).
249     ///
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>
253     where
254         F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
255     {
256         let this = self.eval_context_mut();
257         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
258             f(handle, this)
259         } else {
260             let ebadf = this.eval_libc("EBADF")?;
261             this.set_last_error(ebadf)?;
262             Ok((-1).into())
263         }
264     }
265 }