]> git.lizzy.rs Git - rust.git/blob - src/shims/io.rs
0cb2d7eeeabd4e60e28ffae28395fa404fe32440
[rust.git] / src / shims / io.rs
1 use std::collections::HashMap;
2 use std::fs::File;
3 use std::io::Read;
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         if flag != this.eval_libc_i32("O_RDONLY")? && flag != this.eval_libc_i32("O_CLOEXEC")? {
46             throw_unsup_format!("Unsupported flag {:#x}", flag);
47         }
48
49         let path_bytes = this
50             .memory()
51             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
52         let path = std::str::from_utf8(path_bytes)
53             .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?
54             .to_owned();
55         let fd = File::open(&path).map(|file| {
56             let mut fh = &mut this.machine.file_handler;
57             fh.low += 1;
58             fh.handles.insert(fh.low, FileHandle { file, flag });
59             fh.low
60         });
61
62         this.consume_result::<i32>(fd, -1)
63     }
64
65     fn fcntl(
66         &mut self,
67         fd_op: OpTy<'tcx, Tag>,
68         cmd_op: OpTy<'tcx, Tag>,
69         arg_op: Option<OpTy<'tcx, Tag>>,
70     ) -> InterpResult<'tcx, i32> {
71         let this = self.eval_context_mut();
72
73         if !this.machine.communicate {
74             throw_unsup_format!("`open` not available when isolation is enabled")
75         }
76
77         let fd = this.read_scalar(fd_op)?.to_i32()?;
78         let cmd = this.read_scalar(cmd_op)?.to_i32()?;
79
80         if cmd == this.eval_libc_i32("F_SETFD")? {
81             // This does not affect the file itself. Certain flags might require changing the file
82             // or the way it is accessed somehow.
83             let flag = this.read_scalar(arg_op.unwrap())?.to_i32()?;
84             // The only usage of this in stdlib at the moment is to enable the `FD_CLOEXEC` flag.
85             let fd_cloexec = this.eval_libc_i32("FD_CLOEXEC")?;
86             if let Some(FileHandle { flag: old_flag, .. }) =
87                 this.machine.file_handler.handles.get_mut(&fd)
88             {
89                 if flag ^ *old_flag == fd_cloexec {
90                     *old_flag = flag;
91                 } else {
92                     throw_unsup_format!("Unsupported arg {:#x} for `F_SETFD`", flag);
93                 }
94             }
95             Ok(0)
96         } else if cmd == this.eval_libc_i32("F_GETFD")? {
97             this.get_handle_and(fd, |handle| Ok(handle.flag), -1)
98         } else {
99             throw_unsup_format!("Unsupported command {:#x}", cmd);
100         }
101     }
102
103     fn close(&mut self, fd_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
104         let this = self.eval_context_mut();
105
106         if !this.machine.communicate {
107             throw_unsup_format!("`open` not available when isolation is enabled")
108         }
109
110         let fd = this.read_scalar(fd_op)?.to_i32()?;
111
112         this.remove_handle_and(
113             fd,
114             |handle, this| this.consume_result::<i32>(handle.file.sync_all().map(|_| 0), -1),
115             -1,
116         )
117     }
118
119     fn read(
120         &mut self,
121         fd_op: OpTy<'tcx, Tag>,
122         buf_op: OpTy<'tcx, Tag>,
123         count_op: OpTy<'tcx, Tag>,
124     ) -> InterpResult<'tcx, i64> {
125         let this = self.eval_context_mut();
126
127         if !this.machine.communicate {
128             throw_unsup_format!("`open` not available when isolation is enabled")
129         }
130
131         let tcx = &{ this.tcx.tcx };
132
133         let fd = this.read_scalar(fd_op)?.to_i32()?;
134         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
135         let count = this.read_scalar(count_op)?.to_usize(&*this.tcx)?;
136
137         // Remove the file handle to avoid borrowing issues
138         this.remove_handle_and(
139             fd,
140             |mut handle, this| {
141                 let bytes = handle
142                     .file
143                     .read(this.memory_mut().get_mut(buf.alloc_id)?.get_bytes_mut(
144                         tcx,
145                         buf,
146                         Size::from_bytes(count),
147                     )?)
148                     .map(|bytes| bytes as i64);
149                 // Reinsert the file handle
150                 this.machine.file_handler.handles.insert(fd, handle);
151                 this.consume_result::<i64>(bytes, -1)
152             },
153             -1,
154         )
155     }
156
157     fn get_handle_and<F, T>(&mut self, fd: i32, f: F, t: T) -> InterpResult<'tcx, T>
158     where
159         F: Fn(&FileHandle) -> InterpResult<'tcx, T>,
160     {
161         let this = self.eval_context_mut();
162         if let Some(handle) = this.machine.file_handler.handles.get(&fd) {
163             f(handle)
164         } else {
165             this.machine.last_error = this.eval_libc_i32("EBADF")? as u32;
166             Ok(t)
167         }
168     }
169
170     fn remove_handle_and<F, T>(&mut self, fd: i32, mut f: F, t: T) -> InterpResult<'tcx, T>
171     where
172         F: FnMut(FileHandle, &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx, T>,
173     {
174         let this = self.eval_context_mut();
175         if let Some(handle) = this.machine.file_handler.handles.remove(&fd) {
176             f(handle, this)
177         } else {
178             this.machine.last_error = this.eval_libc_i32("EBADF")? as u32;
179             Ok(t)
180         }
181     }
182
183     fn consume_result<T>(&mut self, result: std::io::Result<T>, t: T) -> InterpResult<'tcx, T> {
184         match result {
185             Ok(ok) => Ok(ok),
186             Err(e) => {
187                 self.eval_context_mut().machine.last_error = e.raw_os_error().unwrap() as u32;
188                 Ok(t)
189             }
190         }
191     }
192 }