forked from containers/libkrun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathport_io.rs
265 lines (218 loc) · 7.63 KB
/
port_io.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use std::fs::File;
use std::io::{self, ErrorKind};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO};
use log::Level;
use nix::errno::Errno;
use nix::poll::{poll, PollFd, PollFlags};
use nix::unistd::dup;
use utils::eventfd::EventFd;
use utils::eventfd::EFD_NONBLOCK;
use vm_memory::bitmap::Bitmap;
use vm_memory::{VolatileMemoryError, VolatileSlice, WriteVolatile};
pub trait PortInput {
fn read_volatile(&mut self, buf: &mut VolatileSlice) -> Result<usize, io::Error>;
fn wait_until_readable(&self, stopfd: Option<&EventFd>);
}
pub trait PortOutput {
fn write_volatile(&mut self, buf: &VolatileSlice) -> Result<usize, io::Error>;
fn wait_until_writable(&self);
}
pub fn stdin() -> Result<Box<dyn PortInput + Send>, nix::Error> {
let fd = dup_raw_fd_into_owned(STDIN_FILENO)?;
make_non_blocking(&fd)?;
Ok(Box::new(PortInputFd(fd)))
}
pub fn stdout() -> Result<Box<dyn PortOutput + Send>, nix::Error> {
output_to_raw_fd_dup(STDOUT_FILENO)
}
pub fn stderr() -> Result<Box<dyn PortOutput + Send>, nix::Error> {
output_to_raw_fd_dup(STDERR_FILENO)
}
pub fn input_empty() -> Result<Box<dyn PortInput + Send>, nix::Error> {
Ok(Box::new(PortInputEmpty {}))
}
pub fn output_file(file: File) -> Result<Box<dyn PortOutput + Send>, nix::Error> {
output_to_raw_fd_dup(file.as_raw_fd())
}
pub fn output_to_raw_fd_dup(fd: RawFd) -> Result<Box<dyn PortOutput + Send>, nix::Error> {
let fd = dup_raw_fd_into_owned(fd)?;
make_non_blocking(&fd)?;
Ok(Box::new(PortOutputFd(fd)))
}
pub fn output_to_log_as_err() -> Box<dyn PortOutput + Send> {
Box::new(PortOutputLog::new())
}
struct PortInputFd(OwnedFd);
impl AsRawFd for PortInputFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl PortInput for PortInputFd {
fn read_volatile(&mut self, buf: &mut VolatileSlice) -> io::Result<usize> {
// This source code is copied from vm-memory, except it fixes an issue, where
// the original code would does not handle handle EWOULDBLOCK
let fd = self.as_raw_fd();
let guard = buf.ptr_guard_mut();
let dst = guard.as_ptr().cast::<libc::c_void>();
// SAFETY: We got a valid file descriptor from `AsRawFd`. The memory pointed to by `dst` is
// valid for writes of length `buf.len() by the invariants upheld by the constructor
// of `VolatileSlice`.
let bytes_read = unsafe { libc::read(fd, dst, buf.len()) };
if bytes_read < 0 {
let err = std::io::Error::last_os_error();
if err.kind() != ErrorKind::WouldBlock {
// We don't know if a partial read might have happened, so mark everything as dirty
buf.bitmap().mark_dirty(0, buf.len());
}
Err(err)
} else {
let bytes_read = bytes_read.try_into().unwrap();
buf.bitmap().mark_dirty(0, bytes_read);
Ok(bytes_read)
}
}
fn wait_until_readable(&self, stopfd: Option<&EventFd>) {
let mut poll_fds = Vec::new();
poll_fds.push(PollFd::new(self.as_raw_fd(), PollFlags::POLLIN));
if let Some(stopfd) = stopfd {
poll_fds.push(PollFd::new(stopfd.as_raw_fd(), PollFlags::POLLIN));
}
poll(&mut poll_fds, -1).expect("Failed to poll");
}
}
struct PortOutputFd(OwnedFd);
impl AsRawFd for PortOutputFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl PortOutput for PortOutputFd {
fn write_volatile(&mut self, buf: &VolatileSlice) -> Result<usize, io::Error> {
self.0.write_volatile(buf).map_err(|e| match e {
VolatileMemoryError::IOError(e) => e,
e => {
log::error!("Unsuported error from write_volatile: {e:?}");
io::Error::other(e)
}
})
}
fn wait_until_writable(&self) {
let mut poll_fds = [PollFd::new(self.as_raw_fd(), PollFlags::POLLOUT)];
poll(&mut poll_fds, -1).expect("Failed to poll");
}
}
fn dup_raw_fd_into_owned(raw_fd: RawFd) -> Result<OwnedFd, nix::Error> {
let fd = dup(raw_fd)?;
// SAFETY: the fd is valid because dup succeeded
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
fn make_non_blocking(as_rw_fd: &impl AsRawFd) -> Result<(), nix::Error> {
let fd = as_rw_fd.as_raw_fd();
unsafe {
let flags = fcntl(fd, F_GETFL, 0);
if flags < 0 {
return Err(Errno::last());
}
if fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0 {
return Err(Errno::last());
}
}
Ok(())
}
// Utility to relay log from the VM (the kernel boot log and messages from init)
// to the rust log
#[derive(Default)]
pub struct PortOutputLog {
buf: Vec<u8>,
}
impl PortOutputLog {
const FORCE_FLUSH_TRESHOLD: usize = 512;
const LOG_TARGET: &'static str = "init_or_kernel";
fn new() -> Self {
Self::default()
}
fn force_flush(&mut self) {
log::log!(target: PortOutputLog::LOG_TARGET, Level::Error, "[missing newline]{}", String::from_utf8_lossy(&self.buf));
self.buf.clear();
}
}
impl PortOutput for PortOutputLog {
fn write_volatile(&mut self, buf: &VolatileSlice) -> Result<usize, io::Error> {
self.buf.write_volatile(buf).map_err(io::Error::other)?;
let mut start = 0;
for (i, ch) in self.buf.iter().cloned().enumerate() {
if ch == b'\n' {
log::log!(target: PortOutputLog::LOG_TARGET, Level::Error, "{}", String::from_utf8_lossy(&self.buf[start..i]));
start = i + 1;
}
}
self.buf.drain(0..start);
// Make sure to not grow the internal buffer forever!
if self.buf.len() > PortOutputLog::FORCE_FLUSH_TRESHOLD {
self.force_flush()
}
Ok(buf.len())
}
fn wait_until_writable(&self) {}
}
pub struct PortInputSigInt {
sigint_evt: EventFd,
}
impl PortInputSigInt {
pub fn new() -> Self {
PortInputSigInt {
sigint_evt: EventFd::new(EFD_NONBLOCK)
.expect("Failed to create EventFd for SIGINT signaling"),
}
}
pub fn sigint_evt(&self) -> &EventFd {
&self.sigint_evt
}
}
impl Default for PortInputSigInt {
fn default() -> Self {
Self::new()
}
}
impl PortInput for PortInputSigInt {
fn read_volatile(&mut self, buf: &mut VolatileSlice) -> Result<usize, io::Error> {
self.sigint_evt.read()?;
log::trace!("SIGINT received");
buf.copy_from(&[3u8]); //ASCII 'ETX' -> generates SIGINIT in a terminal
Ok(1)
}
fn wait_until_readable(&self, stopfd: Option<&EventFd>) {
let mut poll_fds = Vec::with_capacity(2);
poll_fds.push(PollFd::new(self.sigint_evt.as_raw_fd(), PollFlags::POLLIN));
if let Some(stopfd) = stopfd {
poll_fds.push(PollFd::new(stopfd.as_raw_fd(), PollFlags::POLLIN));
}
poll(&mut poll_fds, -1).expect("Failed to poll");
}
}
pub struct PortInputEmpty {}
impl PortInputEmpty {
pub fn new() -> Self {
PortInputEmpty {}
}
}
impl Default for PortInputEmpty {
fn default() -> Self {
Self::new()
}
}
impl PortInput for PortInputEmpty {
fn read_volatile(&mut self, _buf: &mut VolatileSlice) -> Result<usize, io::Error> {
Ok(0)
}
fn wait_until_readable(&self, stopfd: Option<&EventFd>) {
if let Some(stopfd) = stopfd {
let mut poll_fds = [PollFd::new(stopfd.as_raw_fd(), PollFlags::POLLIN)];
poll(&mut poll_fds, -1).expect("Failed to poll");
} else {
std::thread::sleep(std::time::Duration::MAX);
}
}
}