]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Cap `count`
[rust.git] / src / shims / fs.rs
1 use std::collections::HashMap;
2 use std::convert::TryFrom;
3 use std::fs::{remove_file, File, OpenOptions};
4 use std::io::{Read, Write};
5
6 use rustc::ty::layout::Size;
7
8 use crate::stacked_borrows::Tag;
9 use crate::*;
10
11 #[derive(Debug)]
12 pub struct FileHandle {
13     file: File,
14 }
15
16 pub struct FileHandler {
17     handles: HashMap<i32, FileHandle>,
18     low: i32,
19 }
20
21 impl Default for FileHandler {
22     fn default() -> Self {
23         FileHandler {
24             handles: Default::default(),
25             // 0, 1 and 2 are reserved for stdin, stdout and stderr.
26             low: 3,
27         }
28     }
29 }
30
31 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
32 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
33     fn open(
34         &mut self,
35         path_op: OpTy<'tcx, Tag>,
36         flag_op: OpTy<'tcx, Tag>,
37     ) -> InterpResult<'tcx, i32> {
38         let this = self.eval_context_mut();
39
40         this.check_no_isolation("open")?;
41
42         let flag = this.read_scalar(flag_op)?.to_i32()?;
43
44         let mut options = OpenOptions::new();
45
46         let o_rdonly = this.eval_libc_i32("O_RDONLY")?;
47         let o_wronly = this.eval_libc_i32("O_WRONLY")?;
48         let o_rdwr = this.eval_libc_i32("O_RDWR")?;
49         // The first two bits of the flag correspond to the access mode in linux, macOS and
50         // windows. We need to check that in fact the access mode flags for the current platform
51         // only use these two bits, otherwise we are in an unsupported platform and should error.
52         if (o_rdonly | o_wronly | o_rdwr) & !0b11 != 0 {
53             throw_unsup_format!("Access mode flags on this platform are unsupported");
54         }
55         // Now we check the access mode
56         let access_mode = flag & 0b11;
57
58         if access_mode == o_rdonly {
59             options.read(true);
60         } else if access_mode == o_wronly {
61             options.write(true);
62         } else if access_mode == o_rdwr {
63             options.read(true).write(true);
64         } else {
65             throw_unsup_format!("Unsupported access mode {:#x}", access_mode);
66         }
67         // We need to check that there aren't unsupported options in `flag`. For this we try to
68         // reproduce the content of `flag` in the `mirror` variable using only the supported
69         // options.
70         let mut mirror = access_mode;
71
72         let o_append = this.eval_libc_i32("O_APPEND")?;
73         if flag & o_append != 0 {
74             options.append(true);
75             mirror |= o_append;
76         }
77         let o_trunc = this.eval_libc_i32("O_TRUNC")?;
78         if flag & o_trunc != 0 {
79             options.truncate(true);
80             mirror |= o_trunc;
81         }
82         let o_creat = this.eval_libc_i32("O_CREAT")?;
83         if flag & o_creat != 0 {
84             options.create(true);
85             mirror |= o_creat;
86         }
87         let o_cloexec = this.eval_libc_i32("O_CLOEXEC")?;
88         if flag & o_cloexec != 0 {
89             // We do not need to do anything for this flag because `std` already sets it.
90             // (Technically we do not support *not* setting this flag, but we ignore that.)
91             mirror |= o_cloexec;
92         }
93         // If `flag` is not equal to `mirror`, there is an unsupported option enabled in `flag`,
94         // then we throw an error.
95         if flag != mirror {
96             throw_unsup_format!("unsupported flags {:#x}", flag & !mirror);
97         }
98
99         let path = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?;
100
101         let fd = options.open(path).map(|file| {
102             let mut fh = &mut this.machine.file_handler;
103             fh.low += 1;
104             fh.handles.insert(fh.low, FileHandle { file }).unwrap_none();
105             fh.low
106         });
107
108         this.try_unwrap_io_result(fd)
109     }
110
111     fn fcntl(
112         &mut self,
113         fd_op: OpTy<'tcx, Tag>,
114         cmd_op: OpTy<'tcx, Tag>,
115         _arg1_op: Option<OpTy<'tcx, Tag>>,
116     ) -> InterpResult<'tcx, i32> {
117         let this = self.eval_context_mut();
118
119         this.check_no_isolation("fcntl")?;
120
121         let fd = this.read_scalar(fd_op)?.to_i32()?;
122         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
123         // We only support getting the flags for a descriptor.
124         if cmd == this.eval_libc_i32("F_GETFD")? {
125             // Currently this is the only flag that `F_GETFD` returns. It is OK to just return the
126             // `FD_CLOEXEC` value without checking if the flag is set for the file because `std`
127             // always sets this flag when opening a file. However we still need to check that the
128             // file itself is open.
129             if this.machine.file_handler.handles.contains_key(&fd) {
130                 Ok(this.eval_libc_i32("FD_CLOEXEC")?)
131             } else {
132                 this.handle_not_found()
133             }
134         } else {
135             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
136         }
137     }
138
139     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
140         let this = self.eval_context_mut();
141
142         this.check_no_isolation("close")?;
143
144         let fd = this.read_scalar(fd_op)?.to_i32()?;
145
146         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
147             // `File::sync_all` does the checks that are done when closing a file. We do this to
148             // to handle possible errors correctly.
149             let result = this.try_unwrap_io_result(handle.file.sync_all().map(|_| 0i32));
150             // Now we actually close the file.
151             drop(handle);
152             // And return the result.
153             result
154         } else {
155             this.handle_not_found()
156         }
157     }
158
159     fn read(
160         &mut self,
161         fd_op: OpTy<'tcx, Tag>,
162         buf_op: OpTy<'tcx, Tag>,
163         count_op: OpTy<'tcx, Tag>,
164     ) -> InterpResult<'tcx, i64> {
165         let this = self.eval_context_mut();
166
167         this.check_no_isolation("read")?;
168
169         let ptr_size = this.pointer_size().bits();
170
171         let count = this
172             .read_scalar(count_op)?
173             .to_machine_usize(&*this.tcx)?
174             .min(1 << (ptr_size - 1));
175         // Reading zero bytes should not change `buf`.
176         if count == 0 {
177             return Ok(0);
178         }
179         let fd = this.read_scalar(fd_op)?.to_i32()?;
180         let buf = this.read_scalar(buf_op)?.not_undef()?;
181
182         if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) {
183             let count = isize::try_from(count).unwrap();
184             // We want to read at most `count` bytes. We are sure that `count` is not negative
185             // because it was a target's `usize`. Also we are sure that its smaller than
186             // `usize::max_value()` because it is a host's `isize`.
187             let mut bytes = vec![0; count as usize];
188             let result = handle
189                 .file
190                 .read(&mut bytes)
191                 .map(|c| i64::try_from(c).unwrap());
192
193             match result {
194                 Ok(read_bytes) => {
195                     // If reading to `bytes` did not fail, we write those bytes to the buffer.
196                     this.memory.write_bytes(buf, bytes)?;
197                     Ok(read_bytes)
198                 }
199                 Err(e) => {
200                     this.set_last_error_from_io_error(e)?;
201                     Ok(-1)
202                 }
203             }
204         } else {
205             this.handle_not_found()
206         }
207     }
208
209     fn write(
210         &mut self,
211         fd_op: OpTy<'tcx, Tag>,
212         buf_op: OpTy<'tcx, Tag>,
213         count_op: OpTy<'tcx, Tag>,
214     ) -> InterpResult<'tcx, i64> {
215         let this = self.eval_context_mut();
216
217         this.check_no_isolation("write")?;
218
219         let ptr_size = this.pointer_size().bits();
220
221         let count = this
222             .read_scalar(count_op)?
223             .to_machine_usize(&*this.tcx)?
224             .min(1 << (ptr_size - 1));
225         // Writing zero bytes should not change `buf`.
226         if count == 0 {
227             return Ok(0);
228         }
229         let fd = this.read_scalar(fd_op)?.to_i32()?;
230         let buf = this.read_scalar(buf_op)?.not_undef()?;
231
232         if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) {
233             let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
234             let result = handle.file.write(&bytes).map(|c| i64::try_from(c).unwrap());
235             this.try_unwrap_io_result(result)
236         } else {
237             this.handle_not_found()
238         }
239     }
240
241     fn unlink(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
242         let this = self.eval_context_mut();
243
244         this.check_no_isolation("unlink")?;
245
246         let path = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?;
247
248         let result = remove_file(path).map(|_| 0);
249
250         this.try_unwrap_io_result(result)
251     }
252
253     /// Function used when a handle is not found inside `FileHandler`. It returns `Ok(-1)`and sets
254     /// the last OS error to `libc::EBADF` (invalid file descriptor). This function uses
255     /// `T: From<i32>` instead of `i32` directly because some fs functions return different integer
256     /// types (like `read`, that returns an `i64`).
257     fn handle_not_found<T: From<i32>>(&mut self) -> InterpResult<'tcx, T> {
258         let this = self.eval_context_mut();
259         let ebadf = this.eval_libc("EBADF")?;
260         this.set_last_error(ebadf)?;
261         Ok((-1).into())
262     }
263 }