]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
891474bc3bdb6bd90e8214daa9596896530a716d
[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 pub struct FileHandle {
11     file: File,
12 }
13
14 pub struct FileHandler {
15     handles: HashMap<i32, FileHandle>,
16     low: i32,
17 }
18
19 impl Default for FileHandler {
20     fn default() -> Self {
21         FileHandler {
22             handles: Default::default(),
23             // 0, 1 and 2 are reserved for stdin, stdout and stderr
24             low: 3,
25         }
26     }
27 }
28
29 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
30 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
31     fn open(
32         &mut self,
33         path_op: OpTy<'tcx, Tag>,
34         flag_op: OpTy<'tcx, Tag>,
35     ) -> InterpResult<'tcx, i32> {
36         let this = self.eval_context_mut();
37
38         this.check_no_isolation("open")?;
39
40         let flag = this.read_scalar(flag_op)?.to_i32()?;
41
42         let mut options = OpenOptions::new();
43
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");
52         }
53         // Now we check the access mode
54         let access_mode = flag & 0b11;
55
56         if access_mode == o_rdonly {
57             options.read(true);
58         } else if access_mode == o_wronly {
59             options.write(true);
60         } else if access_mode == o_rdwr {
61             options.read(true).write(true);
62         } else {
63             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
64         }
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
67         // options.
68         let mut mirror = access_mode;
69
70         let o_append = this.eval_libc_i32("O_APPEND")?;
71         if flag & o_append != 0 {
72             options.append(true);
73             mirror |= o_append;
74         }
75         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
76         if flag & o_trunc != 0 {
77             options.truncate(true);
78             mirror |= o_trunc;
79         }
80         let o_creat = this.eval_libc_i32("O_CREAT")?;
81         if flag & o_creat != 0 {
82             options.create(true);
83             mirror |= o_creat;
84         }
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.)
89             mirror |= o_cloexec;
90         }
91         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
92         // then we throw an error.
93         if flag != mirror {
94             throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
95         }
96
97         let path_bytes = this
98             .memory
99             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
100         let path = std::str::from_utf8(path_bytes)
101             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
102
103         let fd = options.open(path).map(|file| {
104             let mut fh = &mut this.machine.file_handler;
105             fh.low += 1;
106             fh.handles.insert(fh.low, FileHandle { file });
107             fh.low
108         });
109
110         this.consume_result(fd)
111     }
112
113     fn fcntl(
114         &mut self,
115         fd_op: OpTy<'tcx, Tag>,
116         cmd_op: OpTy<'tcx, Tag>,
117         _arg1_op: Option<OpTy<'tcx, Tag>>,
118     ) -> InterpResult<'tcx, i32> {
119         let this = self.eval_context_mut();
120
121         this.check_no_isolation("fcntl")?;
122
123         let fd = this.read_scalar(fd_op)?.to_i32()?;
124         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
125         // We only support getting the flags for a descriptor
126         if cmd == this.eval_libc_i32("F_GETFD")? {
127             // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
128             // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
129             // always sets this flag when opening a file. However we still need to check that the
130             // file itself is open.
131             let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
132             this.get_handle_and(fd, |_| Ok(fd_cloexec))
133         } else {
134             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
135         }
136     }
137
138     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
139         let this = self.eval_context_mut();
140
141         this.check_no_isolation("close")?;
142
143         let fd = this.read_scalar(fd_op)?.to_i32()?;
144
145         this.remove_handle_and(fd, |handle, this| {
146             this.consume_result(handle.file.sync_all().map(|_| 0i32))
147         })
148     }
149
150     fn read(
151         &mut self,
152         fd_op: OpTy<'tcx, Tag>,
153         buf_op: OpTy<'tcx, Tag>,
154         count_op: OpTy<'tcx, Tag>,
155     ) -> InterpResult<'tcx, i64> {
156         let this = self.eval_context_mut();
157
158         this.check_no_isolation("read")?;
159
160         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
161         // Reading zero bytes should not change `buf`
162         if count == 0 {
163             return Ok(0);
164         }
165         let fd = this.read_scalar(fd_op)?.to_i32()?;
166         let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
167
168         // Remove the file handle to avoid borrowing issues
169         this.remove_handle_and(fd, |mut handle, this| {
170             // Don't use `?` to avoid returning before reinserting the handle
171             let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
172                 this.memory
173                     .get_mut(buf.alloc_id)?
174                     .get_bytes_mut(&*this.tcx, buf, Size::from_bytes(count))
175                     .map(|buffer| handle.file.read(buffer))
176             });
177             // Reinsert the file handle
178             this.machine.file_handler.handles.insert(fd, handle);
179             this.consume_result(bytes?.map(|bytes| bytes as i64))
180         })
181     }
182
183     fn write(
184         &mut self,
185         fd_op: OpTy<'tcx, Tag>,
186         buf_op: OpTy<'tcx, Tag>,
187         count_op: OpTy<'tcx, Tag>,
188     ) -> InterpResult<'tcx, i64> {
189         let this = self.eval_context_mut();
190
191         this.check_no_isolation("write")?;
192
193         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
194         // Writing zero bytes should not change `buf`
195         if count == 0 {
196             return Ok(0);
197         }
198         let fd = this.read_scalar(fd_op)?.to_i32()?;
199         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
200
201         this.remove_handle_and(fd, |mut handle, this| {
202             let bytes = this.memory.get(buf.alloc_id).and_then(|alloc| {
203                 alloc
204                     .get_bytes(&*this.tcx, buf, Size::from_bytes(count))
205                     .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
206             });
207             this.machine.file_handler.handles.insert(fd, handle);
208             this.consume_result(bytes?)
209         })
210     }
211
212     fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
213         let this = self.eval_context_mut();
214
215         this.check_no_isolation("unlink")?;
216
217         let path_bytes = this
218             .memory
219             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
220         let path = std::str::from_utf8(path_bytes)
221             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
222
223         let result = remove_file(path).map(|_| 0);
224
225         this.consume_result(result)
226     }
227
228     /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
229     /// using the `f` closure.
230     ///
231     /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
232     /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
233     ///
234     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
235     /// functions return different integer types (like `read`, that returns an `i64`)
236     fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
237     where
238         F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
239     {
240         let this = self.eval_context_mut();
241         if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
242             f(handle)
243         } else {
244             let ebadf = this.eval_libc("EBADF")?;
245             this.set_last_error(ebadf)?;
246             Ok((-1).into())
247         }
248     }
249
250     /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
251     /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
252     /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
253     /// using `f`.
254     ///
255     /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
256     /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
257     ///
258     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
259     /// functions return different integer types (like `read`, that returns an `i64`)
260     fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
261     where
262         F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
263     {
264         let this = self.eval_context_mut();
265         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
266             f(handle, this)
267         } else {
268             let ebadf = this.eval_libc("EBADF")?;
269             this.set_last_error(ebadf)?;
270             Ok((-1).into())
271         }
272     }
273
274     /// Helper function that consumes an `std::io::Result<T>` and returns an
275     /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
276     /// OS error using `std::io::Error::raw_os_error`.
277     ///
278     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
279     /// functions return different integer types (like `read`, that returns an `i64`)
280     fn consume_result<T: From<i32>>(
281         &mut self,
282         result: std::io::Result<T>,
283     ) -> InterpResult<'tcx, T> {
284         match result {
285             Ok(ok) => Ok(ok),
286             Err(e) => {
287                 self.eval_context_mut().consume_io_error(e)?;
288                 Ok((-1).into())
289             }
290         }
291     }
292 }