]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
7e684489b5c9c8f361acffc13dfdf8ecb366ad78
[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     flag: i32,
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         if !this.machine.communicate {
40             throw_unsup_format!("`open` not available when isolation is enabled")
41         }
42
43         let flag = this.read_scalar(flag_op)?.to_i32()?;
44
45         let mut options = OpenOptions::new();
46
47         // The first two bits of the flag correspond to the access mode of the file in linux.
48         let access_mode = flag & 0b11;
49
50         if access_mode == this.eval_libc_i32("O_RDONLY")? {
51             options.read(true);
52         } else if access_mode == this.eval_libc_i32("O_WRONLY")? {
53             options.write(true);
54         } else if access_mode == this.eval_libc_i32("O_RDWR")? {
55             options.read(true).write(true);
56         } else {
57             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
58         }
59
60         if flag & this.eval_libc_i32("O_APPEND")? != 0 {
61             options.append(true);
62         }
63         if flag & this.eval_libc_i32("O_TRUNC")? != 0 {
64             options.truncate(true);
65         }
66         if flag & this.eval_libc_i32("O_CREAT")? != 0 {
67             options.create(true);
68         }
69
70         let path_bytes = this
71             .memory()
72             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
73         let path = std::str::from_utf8(path_bytes)
74             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
75
76         let fd = options.open(path).map(|file| {
77             let mut fh = &mut this.machine.file_handler;
78             fh.low += 1;
79             fh.handles.insert(fh.low, FileHandle { file, flag });
80             fh.low
81         });
82
83         this.consume_result(fd)
84     }
85
86     fn fcntl(
87         &mut self,
88         fd_op: OpTy<'tcx, Tag>,
89         cmd_op: OpTy<'tcx, Tag>,
90         arg_op: Option<OpTy<'tcx, Tag>>,
91     ) -> InterpResult<'tcx, i32> {
92         let this = self.eval_context_mut();
93
94         if !this.machine.communicate {
95             throw_unsup_format!("`fcntl` not available when isolation is enabled")
96         }
97
98         let fd = this.read_scalar(fd_op)?.to_i32()?;
99         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
100
101         if cmd == this.eval_libc_i32("F_SETFD")? {
102             // This does not affect the file itself. Certain flags might require changing the file
103             // or the way it is accessed somehow.
104             let flag = this.read_scalar(arg_op.unwrap())?.to_i32()?;
105             // The only usage of this in stdlib at the moment is to enable the `FD_CLOEXEC` flag.
106             let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
107             if let Some(FileHandle { flag: old_flag, .. }) =
108                 this.machine.file_handler.handles.get_mut(&fd)
109             {
110                 // Check that the only difference between the old flag and the current flag is
111                 // exactly the `FD_CLOEXEC` value.
112                 if flag ^ *old_flag == fd_cloexec {
113                     *old_flag = flag;
114                 } else {
115                     throw_unsup_format!("Unsupported arg {:#x} for `F_SETFD`", flag);
116                 }
117             }
118             Ok(0)
119         } else if cmd == this.eval_libc_i32("F_GETFD")? {
120             this.get_handle_and(fd, |handle| Ok(handle.flag))
121         } else {
122             throw_unsup_format!("Unsupported command {:#x}", cmd);
123         }
124     }
125
126     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
127         let this = self.eval_context_mut();
128
129         if !this.machine.communicate {
130             throw_unsup_format!("`close` not available when isolation is enabled")
131         }
132
133         let fd = this.read_scalar(fd_op)?.to_i32()?;
134
135         this.remove_handle_and(fd, |handle, this| {
136             this.consume_result(handle.file.sync_all().map(|_| 0i32))
137         })
138     }
139
140     fn read(
141         &mut self,
142         fd_op: OpTy<'tcx, Tag>,
143         buf_op: OpTy<'tcx, Tag>,
144         count_op: OpTy<'tcx, Tag>,
145     ) -> InterpResult<'tcx, i64> {
146         let this = self.eval_context_mut();
147
148         if !this.machine.communicate {
149             throw_unsup_format!("`read` not available when isolation is enabled")
150         }
151
152         let tcx = &{ this.tcx.tcx };
153
154         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
155         // Reading zero bytes should not change `buf`
156         if count == 0 {
157             return Ok(0);
158         }
159         let fd = this.read_scalar(fd_op)?.to_i32()?;
160         let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
161
162         // Remove the file handle to avoid borrowing issues
163         this.remove_handle_and(fd, |mut handle, this| {
164             // Don't use `?` to avoid returning before reinserting the handle
165             let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
166                 this.memory_mut()
167                     .get_mut(buf.alloc_id)?
168                     .get_bytes_mut(tcx, buf, Size::from_bytes(count))
169                     .map(|buffer| handle.file.read(buffer))
170             });
171             // Reinsert the file handle
172             this.machine.file_handler.handles.insert(fd, handle);
173             this.consume_result(bytes?.map(|bytes| bytes as i64))
174         })
175     }
176
177     fn write(
178         &mut self,
179         fd_op: OpTy<'tcx, Tag>,
180         buf_op: OpTy<'tcx, Tag>,
181         count_op: OpTy<'tcx, Tag>,
182     ) -> InterpResult<'tcx, i64> {
183         let this = self.eval_context_mut();
184
185         if !this.machine.communicate {
186             throw_unsup_format!("`write` not available when isolation is enabled")
187         }
188
189         let tcx = &{ this.tcx.tcx };
190
191         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
192         // Writing zero bytes should not change `buf`
193         if count == 0 {
194             return Ok(0);
195         }
196         let fd = this.read_scalar(fd_op)?.to_i32()?;
197         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
198
199         this.remove_handle_and(fd, |mut handle, this| {
200             let bytes = this.memory().get(buf.alloc_id).and_then(|alloc| {
201                 alloc
202                     .get_bytes(tcx, buf, Size::from_bytes(count))
203                     .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
204             });
205             this.machine.file_handler.handles.insert(fd, handle);
206             this.consume_result(bytes?)
207         })
208     }
209
210     fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
211         let this = self.eval_context_mut();
212
213         if !this.machine.communicate {
214             throw_unsup_format!("`write` not available when isolation is enabled")
215         }
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 }