]> git.lizzy.rs Git - rust.git/blob - src/shims/fs.rs
Remove F_SETFD command
[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         // We only support getting the flags for a descriptor
122         if cmd == this.eval_libc_i32("F_GETFD")? {
123             this.get_handle_and(fd, |handle| Ok(handle.flag))
124         } else {
125             throw_unsup_format!("The {:#x} command is not supported for `fcntl`)", cmd);
126         }
127     }
128
129     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
130         let this = self.eval_context_mut();
131
132         if !this.machine.communicate {
133             throw_unsup_format!("`close` not available when isolation is enabled")
134         }
135
136         let fd = this.read_scalar(fd_op)?.to_i32()?;
137
138         this.remove_handle_and(fd, |handle, this| {
139             this.consume_result(handle.file.sync_all().map(|_| 0i32))
140         })
141     }
142
143     fn read(
144         &mut self,
145         fd_op: OpTy<'tcx, Tag>,
146         buf_op: OpTy<'tcx, Tag>,
147         count_op: OpTy<'tcx, Tag>,
148     ) -> InterpResult<'tcx, i64> {
149         let this = self.eval_context_mut();
150
151         if !this.machine.communicate {
152             throw_unsup_format!("`read` not available when isolation is enabled")
153         }
154
155         let tcx = &{ this.tcx.tcx };
156
157         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
158         // Reading zero bytes should not change `buf`
159         if count == 0 {
160             return Ok(0);
161         }
162         let fd = this.read_scalar(fd_op)?.to_i32()?;
163         let buf_scalar = this.read_scalar(buf_op)?.not_undef()?;
164
165         // Remove the file handle to avoid borrowing issues
166         this.remove_handle_and(fd, |mut handle, this| {
167             // Don't use `?` to avoid returning before reinserting the handle
168             let bytes = this.force_ptr(buf_scalar).and_then(|buf| {
169                 this.memory_mut()
170                     .get_mut(buf.alloc_id)?
171                     .get_bytes_mut(tcx, buf, Size::from_bytes(count))
172                     .map(|buffer| handle.file.read(buffer))
173             });
174             // Reinsert the file handle
175             this.machine.file_handler.handles.insert(fd, handle);
176             this.consume_result(bytes?.map(|bytes| bytes as i64))
177         })
178     }
179
180     fn write(
181         &mut self,
182         fd_op: OpTy<'tcx, Tag>,
183         buf_op: OpTy<'tcx, Tag>,
184         count_op: OpTy<'tcx, Tag>,
185     ) -> InterpResult<'tcx, i64> {
186         let this = self.eval_context_mut();
187
188         if !this.machine.communicate {
189             throw_unsup_format!("`write` not available when isolation is enabled")
190         }
191
192         let tcx = &{ this.tcx.tcx };
193
194         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
195         // Writing zero bytes should not change `buf`
196         if count == 0 {
197             return Ok(0);
198         }
199         let fd = this.read_scalar(fd_op)?.to_i32()?;
200         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
201
202         this.remove_handle_and(fd, |mut handle, this| {
203             let bytes = this.memory().get(buf.alloc_id).and_then(|alloc| {
204                 alloc
205                     .get_bytes(tcx, buf, Size::from_bytes(count))
206                     .map(|bytes| handle.file.write(bytes).map(|bytes| bytes as i64))
207             });
208             this.machine.file_handler.handles.insert(fd, handle);
209             this.consume_result(bytes?)
210         })
211     }
212
213     fn unlink( &mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
214         let this = self.eval_context_mut();
215
216         if !this.machine.communicate {
217             throw_unsup_format!("`write` not available when isolation is enabled")
218         }
219
220         let path_bytes = this
221             .memory()
222             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
223         let path = std::str::from_utf8(path_bytes)
224             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?;
225
226         let result = remove_file(path).map(|_| 0);
227
228         this.consume_result(result)
229     }
230
231     /// Helper function that gets a `FileHandle` immutable reference and allows to manipulate it
232     /// using the `f` closure.
233     ///
234     /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
235     /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
236     ///
237     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
238     /// functions return different integer types (like `read`, that returns an `i64`)
239     fn get_handle_and<F, T: From<i32>>(&mut self, fd: i32, f: F) -> InterpResult<'tcx, T>
240     where
241         F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
242     {
243         let this = self.eval_context_mut();
244         if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
245             f(handle)
246         } else {
247             let ebadf = this.eval_libc("EBADF")?;
248             this.set_last_error(ebadf)?;
249             Ok((-1).into())
250         }
251     }
252
253     /// Helper function that removes a `FileHandle` and allows to manipulate it using the `f`
254     /// closure. This function is quite useful when you need to modify a `FileHandle` but you need
255     /// to modify `MiriEvalContext` at the same time, so you can modify the handle and reinsert it
256     /// using `f`.
257     ///
258     /// If the `fd` file descriptor does not correspond to a file, this functions returns `Ok(-1)`
259     /// and sets `Evaluator::last_error` to `libc::EBADF` (invalid file descriptor).
260     ///
261     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
262     /// functions return different integer types (like `read`, that returns an `i64`)
263     fn remove_handle_and<F, T: From<i32>>(&mut self, fd: i32, mut f: F) -> InterpResult<'tcx, T>
264     where
265         F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
266     {
267         let this = self.eval_context_mut();
268         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
269             f(handle, this)
270         } else {
271             let ebadf = this.eval_libc("EBADF")?;
272             this.set_last_error(ebadf)?;
273             Ok((-1).into())
274         }
275     }
276
277     /// Helper function that consumes an `std::io::Result<T>` and returns an
278     /// `InterpResult<'tcx,T>::Ok` instead. It is expected that the result can be converted to an
279     /// OS error using `std::io::Error::raw_os_error`.
280     ///
281     /// This function uses `T: From<i32>` instead of `i32` directly because some IO related
282     /// functions return different integer types (like `read`, that returns an `i64`)
283     fn consume_result<T: From<i32>>(
284         &mut self,
285         result: std::io::Result<T>,
286     ) -> InterpResult<'tcx, T> {
287         match result {
288             Ok(ok) => Ok(ok),
289             Err(e) => {
290                 self.eval_context_mut().consume_io_error(e)?;
291                 Ok((-1).into())
292             }
293         }
294     }
295 }