]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Error when there is an unsupported flag
[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. This
48         // is done this way because `O_RDONLY` is zero in several platforms.
49         let access_mode = flag & 0b11;
50
51         if access_mode == this.eval_libc_i32("O_RDONLY")? {
52             options.read(true);
53         } else if access_mode == this.eval_libc_i32("O_WRONLY")? {
54             options.write(true);
55         } else if access_mode == this.eval_libc_i32("O_RDWR")? {
56             options.read(true).write(true);
57         } else {
58             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
59         }
60         // We need to check that there aren't unsupported options in `flag`. For this we try to
61         // reproduce the content of `flag` in the `mirror` variable using only the supported
62         // options.
63         let mut mirror = access_mode;
64
65         let o_append = this.eval_libc_i32("O_APPEND")?;
66         if flag & o_append != 0 {
67             options.append(true);
68             mirror |= o_append;
69         }
70         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
71         if flag & o_trunc != 0 {
72             options.truncate(true);
73             mirror |= o_trunc;
74         }
75         let o_creat = this.eval_libc_i32("O_CREAT")?;
76         if flag & o_creat != 0 {
77             options.create(true);
78             mirror |= o_creat;
79         }
80         let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
81         if flag & o_cloexec != 0 {
82             // This flag is a noop for now because `std` already sets it.
83             mirror |= o_cloexec;
84         }
85         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
86         // then we throw an error.
87         if flag != mirror {
88             throw_unsup_format!("unsupported flags {:#x}", flag);
89         }
90
91         let path_bytes = this
92             .memory()
93             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
94         let path = std::str::from_utf8(path_bytes)
95             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
96
97         let fd = options.open(path).map(|file| {
98             let mut fh = &mut this.machine.file_handler;
99             fh.low += 1;
100             fh.handles.insert(fh.low, FileHandle { file, flag });
101             fh.low
102         });
103
104         this.consume_result(fd)
105     }
106
107     fn fcntl(
108         &mut self,
109         fd_op: OpTy<'tcx, Tag>,
110         cmd_op: OpTy<'tcx, Tag>,
111         arg_op: Option<OpTy<'tcx, Tag>>,
112     ) -> InterpResult<'tcx, i32> {
113         let this = self.eval_context_mut();
114
115         if !this.machine.communicate {
116             throw_unsup_format!("`fcntl` not available when isolation is enabled")
117         }
118
119         let fd = this.read_scalar(fd_op)?.to_i32()?;
120         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
121
122         if cmd == this.eval_libc_i32("F_SETFD")? {
123             // This does not affect the file itself. Certain flags might require changing the file
124             // or the way it is accessed somehow.
125             let flag = this.read_scalar(arg_op.unwrap())?.to_i32()?;
126             // The only usage of this in stdlib at the moment is to enable the `FD_CLOEXEC` flag.
127             let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
128             if let Some(FileHandle { flag: old_flag, .. }) =
129                 this.machine.file_handler.handles.get_mut(&fd)
130             {
131                 // Check that the only difference between the old flag and the current flag is
132                 // exactly the `FD_CLOEXEC` value.
133                 if flag ^ *old_flag == fd_cloexec {
134                     *old_flag = flag;
135                 } else {
136                     throw_unsup_format!("Unsupported arg {:#x} for `F_SETFD`", flag);
137                 }
138             }
139             Ok(0)
140         } else if cmd == this.eval_libc_i32("F_GETFD")? {
141             this.get_handle_and(fd, |handle| Ok(handle.flag))
142         } else {
143             throw_unsup_format!("Unsupported command {:#x}", cmd);
144         }
145     }
146
147     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
148         let this = self.eval_context_mut();
149
150         if !this.machine.communicate {
151             throw_unsup_format!("`close` not available when isolation is enabled")
152         }
153
154         let fd = this.read_scalar(fd_op)?.to_i32()?;
155
156         this.remove_handle_and(fd, |handle, this| {
157             this.consume_result(handle.file.sync_all().map(|_| 0i32))
158         })
159     }
160
161     fn read(
162         &mut self,
163         fd_op: OpTy<'tcx, Tag>,
164         buf_op: OpTy<'tcx, Tag>,
165         count_op: OpTy<'tcx, Tag>,
166     ) -> InterpResult<'tcx, i64> {
167         let this = self.eval_context_mut();
168
169         if !this.machine.communicate {
170             throw_unsup_format!("`read` not available when isolation is enabled")
171         }
172
173         let tcx = &{ this.tcx.tcx };
174
175         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
176         // Reading zero bytes should not change `buf`
177         if count == 0 {
178             return Ok(0);
179         }
180         let fd = this.read_scalar(fd_op)?.to_i32()?;
181         let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
182
183         // Remove the file handle to avoid borrowing issues
184         this.remove_handle_and(fd, |mut handle, this| {
185             // Don't use `?` to avoid returning before reinserting the handle
186             let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
187                 this.memory_mut()
188                     .get_mut(buf.alloc_id)?
189                     .get_bytes_mut(tcx, buf, Size::from_bytes(count))
190                     .map(|buffer| handle.file.read(buffer))
191             });
192             // Reinsert the file handle
193             this.machine.file_handler.handles.insert(fd, handle);
194             this.consume_result(bytes?.map(|bytes| bytes as i64))
195         })
196     }
197
198     fn write(
199         &mut self,
200         fd_op: OpTy<'tcx, Tag>,
201         buf_op: OpTy<'tcx, Tag>,
202         count_op: OpTy<'tcx, Tag>,
203     ) -> InterpResult<'tcx, i64> {
204         let this = self.eval_context_mut();
205
206         if !this.machine.communicate {
207             throw_unsup_format!("`write` not available when isolation is enabled")
208         }
209
210         let tcx = &{ this.tcx.tcx };
211
212         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
213         // Writing zero bytes should not change `buf`
214         if count == 0 {
215             return Ok(0);
216         }
217         let fd = this.read_scalar(fd_op)?.to_i32()?;
218         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
219
220         this.remove_handle_and(fd, |mut handle, this| {
221             let bytes = this.memory().get(buf.alloc_id).and_then(|alloc| {
222                 alloc
223                     .get_bytes(tcx, buf, Size::from_bytes(count))
224                     .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
225             });
226             this.machine.file_handler.handles.insert(fd, handle);
227             this.consume_result(bytes?)
228         })
229     }
230
231     fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
232         let this = self.eval_context_mut();
233
234         if !this.machine.communicate {
235             throw_unsup_format!("`write` not available when isolation is enabled")
236         }
237
238         let path_bytes = this
239             .memory()
240             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
241         let path = std::str::from_utf8(path_bytes)
242             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
243
244         let result = remove_file(path).map(|_| 0);
245
246         this.consume_result(result)
247     }
248
249     /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
250     /// using the `f` closure.
251     ///
252     /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
253     /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
254     ///
255     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
256     /// functions return different integer types (like `read`, that returns an `i64`)
257     fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
258     where
259         F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
260     {
261         let this = self.eval_context_mut();
262         if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
263             f(handle)
264         } else {
265             let ebadf = this.eval_libc("EBADF")?;
266             this.set_last_error(ebadf)?;
267             Ok((-1).into())
268         }
269     }
270
271     /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
272     /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
273     /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
274     /// using `f`.
275     ///
276     /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
277     /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
278     ///
279     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
280     /// functions return different integer types (like `read`, that returns an `i64`)
281     fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
282     where
283         F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
284     {
285         let this = self.eval_context_mut();
286         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
287             f(handle, this)
288         } else {
289             let ebadf = this.eval_libc("EBADF")?;
290             this.set_last_error(ebadf)?;
291             Ok((-1).into())
292         }
293     }
294
295     /// Helper function that consumes an `std::io::Result<T>` and returns an
296     /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
297     /// OS error using `std::io::Error::raw_os_error`.
298     ///
299     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
300     /// functions return different integer types (like `read`, that returns an `i64`)
301     fn consume_result<T: From<i32>>(
302         &mut self,
303         result: std::io::Result<T>,
304     ) -> InterpResult<'tcx, T> {
305         match result {
306             Ok(ok) => Ok(ok),
307             Err(e) => {
308                 self.eval_context_mut().consume_io_error(e)?;
309                 Ok((-1).into())
310             }
311         }
312     }
313 }