]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Rename write/read os string functions
[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: std::path::PathBuf = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?.into();
98
99         let fd = options.open(path).map(|file| {
100             let mut fh = &mut this.machine.file_handler;
101             fh.low += 1;
102             fh.handles.insert(fh.low, FileHandle { file });
103             fh.low
104         });
105
106         this.consume_result(fd)
107     }
108
109     fn fcntl(
110         &mut self,
111         fd_op: OpTy<'tcx, Tag>,
112         cmd_op: OpTy<'tcx, Tag>,
113         _arg1_op: Option<OpTy<'tcx, Tag>>,
114     ) -> InterpResult<'tcx, i32> {
115         let this = self.eval_context_mut();
116
117         this.check_no_isolation("fcntl")?;
118
119         let fd = this.read_scalar(fd_op)?.to_i32()?;
120         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
121         // We only support getting the flags for a descriptor
122         if cmd == this.eval_libc_i32("F_GETFD")? {
123             // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
124             // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
125             // always sets this flag when opening a file. However we still need to check that the
126             // file itself is open.
127             let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
128             this.get_handle_and(fd, |_| Ok(fd_cloexec))
129         } else {
130             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
131         }
132     }
133
134     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
135         let this = self.eval_context_mut();
136
137         this.check_no_isolation("close")?;
138
139         let fd = this.read_scalar(fd_op)?.to_i32()?;
140
141         this.remove_handle_and(fd, |handle, this| {
142             this.consume_result(handle.file.sync_all().map(|_| 0i32))
143         })
144     }
145
146     fn read(
147         &mut self,
148         fd_op: OpTy<'tcx, Tag>,
149         buf_op: OpTy<'tcx, Tag>,
150         count_op: OpTy<'tcx, Tag>,
151     ) -> InterpResult<'tcx, i64> {
152         let this = self.eval_context_mut();
153
154         this.check_no_isolation("read")?;
155
156         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
157         // Reading zero bytes should not change `buf`
158         if count == 0 {
159             return Ok(0);
160         }
161         let fd = this.read_scalar(fd_op)?.to_i32()?;
162         let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
163
164         // Remove the file handle to avoid borrowing issues
165         this.remove_handle_and(fd, |mut handle, this| {
166             // Don't use `?` to avoid returning before reinserting the handle
167             let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
168                 this.memory
169                     .get_mut(buf.alloc_id)?
170                     .get_bytes_mut(&*this.tcx, buf, Size::from_bytes(count))
171                     .map(|buffer| handle.file.read(buffer))
172             });
173             // Reinsert the file handle
174             this.machine.file_handler.handles.insert(fd, handle);
175             this.consume_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);
204             this.consume_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.consume_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
266     /// Helper function that consumes an `std::io::Result<T>` and returns an
267     /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
268     /// OS error using `std::io::Error::raw_os_error`.
269     ///
270     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
271     /// functions return different integer types (like `read`, that returns an `i64`)
272     fn consume_result<T: From<i32>>(
273         &mut self,
274         result: std::io::Result<T>,
275     ) -> InterpResult<'tcx, T> {
276         match result {
277             Ok(ok) => Ok(ok),
278             Err(e) => {
279                 self.eval_context_mut().consume_io_error(e)?;
280                 Ok((-1).into())
281             }
282         }
283     }
284 }