|
| 1 | +// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +//! Module containing versions of the standard library's [`Read`] and [`Write`] traits compatible |
| 4 | +//! with volatile memory accesses. |
| 5 | +
|
| 6 | +use crate::bitmap::BitmapSlice; |
| 7 | +use crate::volatile_memory::copy_slice_impl::{copy_from_volatile_slice, copy_to_volatile_slice}; |
| 8 | +use crate::{VolatileMemoryError, VolatileSlice}; |
| 9 | +use std::io::ErrorKind; |
| 10 | +use std::os::fd::AsRawFd; |
| 11 | + |
| 12 | +/// A version of the standard library's [`Read`] trait that operates on volatile memory instead of |
| 13 | +/// slices |
| 14 | +/// |
| 15 | +/// This trait is needed as rust slices (`&[u8]` and `&mut [u8]`) cannot be used when operating on |
| 16 | +/// guest memory [1]. |
| 17 | +/// |
| 18 | +/// [1]: https://github.com/rust-vmm/vm-memory/pull/217 |
| 19 | +pub trait ReadVolatile { |
| 20 | + /// Tries to read some bytes into the given [`VolatileSlice`] buffer, returning how many bytes |
| 21 | + /// were read. |
| 22 | + /// |
| 23 | + /// The behavior of implementations should be identical to [`Read::read`] |
| 24 | + fn read_volatile<B: BitmapSlice>( |
| 25 | + &mut self, |
| 26 | + buf: &mut VolatileSlice<B>, |
| 27 | + ) -> Result<usize, VolatileMemoryError>; |
| 28 | + |
| 29 | + /// Tries to fill the given [`VolatileSlice`] buffer by reading from `self` returning an error |
| 30 | + /// if insufficient bytes could be read. |
| 31 | + /// |
| 32 | + /// The default implementation is identical to that of [`Read::read_exact`] |
| 33 | + fn read_exact_volatile<B: BitmapSlice>( |
| 34 | + &mut self, |
| 35 | + buf: &mut VolatileSlice<B>, |
| 36 | + ) -> Result<(), VolatileMemoryError> { |
| 37 | + // Implementation based on https://github.com/rust-lang/rust/blob/7e7483d26e3cec7a44ef00cf7ae6c9c8c918bec6/library/std/src/io/mod.rs#L465 |
| 38 | + |
| 39 | + let mut partial_buf = buf.offset(0)?; |
| 40 | + |
| 41 | + while !partial_buf.is_empty() { |
| 42 | + match self.read_volatile(&mut partial_buf) { |
| 43 | + Err(VolatileMemoryError::IOError(err)) if err.kind() == ErrorKind::Interrupted => { |
| 44 | + continue |
| 45 | + } |
| 46 | + Ok(0) => { |
| 47 | + return Err(VolatileMemoryError::IOError(std::io::Error::new( |
| 48 | + ErrorKind::UnexpectedEof, |
| 49 | + "failed to fill whole buffer", |
| 50 | + ))) |
| 51 | + } |
| 52 | + Ok(bytes_read) => partial_buf = partial_buf.offset(bytes_read)?, |
| 53 | + Err(err) => return Err(err), |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + Ok(()) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/// A version of the standard library's [`Write`] trait that operates on volatile memory instead of |
| 62 | +/// slices |
| 63 | +/// |
| 64 | +/// This trait is needed as rust slices (`&[u8]` and `&mut [u8]`) cannot be used when operating on |
| 65 | +/// guest memory [1]. |
| 66 | +/// |
| 67 | +/// [1]: https://github.com/rust-vmm/vm-memory/pull/217 |
| 68 | +pub trait WriteVolatile { |
| 69 | + /// Tries to write some bytes from the given [`VolatileSlice`] buffer, returning how many bytes |
| 70 | + /// were written. |
| 71 | + /// |
| 72 | + /// The behavior of implementations should be identical to [`Write::write`] |
| 73 | + fn write_volatile<B: BitmapSlice>( |
| 74 | + &mut self, |
| 75 | + buf: &VolatileSlice<B>, |
| 76 | + ) -> Result<usize, VolatileMemoryError>; |
| 77 | + |
| 78 | + /// Tries write the entire content of the given [`VolatileSlice`] buffer to `self` returning an |
| 79 | + /// error if not all bytes could be written. |
| 80 | + /// |
| 81 | + /// The default implementation is identical to that of [`Write::write_all`] |
| 82 | + fn write_all_volatile<B: BitmapSlice>( |
| 83 | + &mut self, |
| 84 | + buf: &VolatileSlice<B>, |
| 85 | + ) -> Result<(), VolatileMemoryError> { |
| 86 | + // Based on https://github.com/rust-lang/rust/blob/7e7483d26e3cec7a44ef00cf7ae6c9c8c918bec6/library/std/src/io/mod.rs#L1570 |
| 87 | + |
| 88 | + let mut partial_buf = buf.offset(0)?; |
| 89 | + |
| 90 | + while !partial_buf.is_empty() { |
| 91 | + match self.write_volatile(&partial_buf) { |
| 92 | + Err(VolatileMemoryError::IOError(err)) if err.kind() == ErrorKind::Interrupted => { |
| 93 | + continue |
| 94 | + } |
| 95 | + Ok(0) => { |
| 96 | + return Err(VolatileMemoryError::IOError(std::io::Error::new( |
| 97 | + ErrorKind::WriteZero, |
| 98 | + "failed to write whole buffer", |
| 99 | + ))) |
| 100 | + } |
| 101 | + Ok(bytes_written) => partial_buf = partial_buf.offset(bytes_written)?, |
| 102 | + Err(err) => return Err(err), |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + Ok(()) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +// We explicitly implement our traits for [`std::fs::File`] and [`std::os::unix::net::UnixStream`] |
| 111 | +// instead of providing blanket implementation for [`AsRawFd`] due to trait coherence limitations: A |
| 112 | +// blanket implementation would prevent us from providing implementations for `&mut [u8]` below, as |
| 113 | +// "an upstream crate could implement AsRawFd for &mut [u8]`. |
| 114 | + |
| 115 | +macro_rules! impl_read_write_volatile_for_raw_fd { |
| 116 | + ($raw_fd_ty:ty) => { |
| 117 | + impl ReadVolatile for $raw_fd_ty { |
| 118 | + fn read_volatile<B: BitmapSlice>( |
| 119 | + &mut self, |
| 120 | + buf: &mut VolatileSlice<B>, |
| 121 | + ) -> Result<usize, VolatileMemoryError> { |
| 122 | + read_volatile_raw_fd(self, buf) |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + impl WriteVolatile for $raw_fd_ty { |
| 127 | + fn write_volatile<B: BitmapSlice>( |
| 128 | + &mut self, |
| 129 | + buf: &VolatileSlice<B>, |
| 130 | + ) -> Result<usize, VolatileMemoryError> { |
| 131 | + write_volatile_raw_fd(self, buf) |
| 132 | + } |
| 133 | + } |
| 134 | + }; |
| 135 | +} |
| 136 | + |
| 137 | +impl_read_write_volatile_for_raw_fd!(std::fs::File); |
| 138 | +impl_read_write_volatile_for_raw_fd!(std::os::unix::net::UnixStream); |
| 139 | +impl_read_write_volatile_for_raw_fd!(std::os::fd::OwnedFd); |
| 140 | +impl_read_write_volatile_for_raw_fd!(std::os::fd::BorrowedFd<'_>); |
| 141 | + |
| 142 | +/// Tries to do a single `read` syscall on the provided file descriptor, storing the data raed in |
| 143 | +/// the given [`VolatileSlice`]. |
| 144 | +/// |
| 145 | +/// Returns the numbers of bytes read. |
| 146 | +fn read_volatile_raw_fd<Fd: AsRawFd>( |
| 147 | + raw_fd: &mut Fd, |
| 148 | + buf: &mut VolatileSlice<impl BitmapSlice>, |
| 149 | +) -> Result<usize, VolatileMemoryError> { |
| 150 | + let fd = raw_fd.as_raw_fd(); |
| 151 | + let guard = buf.ptr_guard_mut(); |
| 152 | + |
| 153 | + let dst = guard.as_ptr().cast::<libc::c_void>(); |
| 154 | + |
| 155 | + // SAFETY: We got a valid file descriptor from `AsRawFd`. The memory pointed to by `dst` is |
| 156 | + // valid for writes of length `buf.len() by the invariants upheld by the constructor |
| 157 | + // of `VolatileSlice`. |
| 158 | + let bytes_read = unsafe { libc::read(fd, dst, buf.len()) }; |
| 159 | + |
| 160 | + if bytes_read < 0 { |
| 161 | + // We don't know if a partial read might have happened, so mark everything as dirty |
| 162 | + buf.bitmap().mark_dirty(0, buf.len()); |
| 163 | + |
| 164 | + Err(VolatileMemoryError::IOError(std::io::Error::last_os_error())) |
| 165 | + } else { |
| 166 | + let bytes_read = bytes_read.try_into().unwrap(); |
| 167 | + buf.bitmap().mark_dirty(0, bytes_read); |
| 168 | + Ok(bytes_read) |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +/// Tries to do a single `write` syscall on the provided file descriptor, attempting to write the |
| 173 | +/// data stored in the given [`VolatileSlice`]. |
| 174 | +/// |
| 175 | +/// Returns the numbers of bytes written. |
| 176 | +fn write_volatile_raw_fd<Fd: AsRawFd>( |
| 177 | + raw_fd: &mut Fd, |
| 178 | + buf: &VolatileSlice<impl BitmapSlice>, |
| 179 | +) -> Result<usize, VolatileMemoryError> { |
| 180 | + let fd = raw_fd.as_raw_fd(); |
| 181 | + let guard = buf.ptr_guard(); |
| 182 | + |
| 183 | + let src = guard.as_ptr().cast::<libc::c_void>(); |
| 184 | + |
| 185 | + // SAFETY: We got a valid file descriptor from `AsRawFd`. The memory pointed to by `src` is |
| 186 | + // valid for reads of length `buf.len() by the invariants upheld by the constructor |
| 187 | + // of `VolatileSlice`. |
| 188 | + let bytes_written = unsafe { libc::write(fd, src, buf.len()) }; |
| 189 | + |
| 190 | + if bytes_written < 0 { |
| 191 | + Err(VolatileMemoryError::IOError(std::io::Error::last_os_error())) |
| 192 | + } else { |
| 193 | + Ok(bytes_written.try_into().unwrap()) |
| 194 | + } |
| 195 | +} |
| 196 | + |
| 197 | +impl WriteVolatile for &mut [u8] { |
| 198 | + fn write_volatile<B: BitmapSlice>( |
| 199 | + &mut self, |
| 200 | + buf: &VolatileSlice<B>, |
| 201 | + ) -> Result<usize, VolatileMemoryError> { |
| 202 | + let total = buf.len().min(self.len()); |
| 203 | + let src = buf.subslice(0, total)?; |
| 204 | + |
| 205 | + // SAFETY: |
| 206 | + // We check above that `src` is contiguously allocated memory of length `total <= self.len())`. |
| 207 | + // Furthermore, both src and dst of the call to |
| 208 | + // copy_from_volatile_slice are valid for reads and writes respectively of length `total` |
| 209 | + // since total is the minimum of lengths of the memory areas pointed to. The areas do not |
| 210 | + // overlap, since `dst` is inside guest memory, and buf is a slice (no slices to guest |
| 211 | + // memory are possible without violating rust's aliasing rules). |
| 212 | + let written = unsafe { copy_from_volatile_slice(self.as_mut_ptr(), &src, total) }; |
| 213 | + |
| 214 | + // Advance the slice, just like the stdlib: https://doc.rust-lang.org/src/std/io/impls.rs.html#335 |
| 215 | + *self = std::mem::take(self).split_at_mut(written).1; |
| 216 | + |
| 217 | + Ok(written) |
| 218 | + } |
| 219 | + |
| 220 | + fn write_all_volatile<B: BitmapSlice>( |
| 221 | + &mut self, |
| 222 | + buf: &VolatileSlice<B>, |
| 223 | + ) -> Result<(), VolatileMemoryError> { |
| 224 | + // Based on https://github.com/rust-lang/rust/blob/f7b831ac8a897273f78b9f47165cf8e54066ce4b/library/std/src/io/impls.rs#L376-L382 |
| 225 | + if self.write_volatile(buf)? == buf.len() { |
| 226 | + Ok(()) |
| 227 | + } else { |
| 228 | + Err(VolatileMemoryError::IOError(std::io::Error::new( |
| 229 | + ErrorKind::WriteZero, |
| 230 | + "failed to write whole buffer", |
| 231 | + ))) |
| 232 | + } |
| 233 | + } |
| 234 | +} |
| 235 | + |
| 236 | +impl ReadVolatile for &[u8] { |
| 237 | + fn read_volatile<B: BitmapSlice>( |
| 238 | + &mut self, |
| 239 | + buf: &mut VolatileSlice<B>, |
| 240 | + ) -> Result<usize, VolatileMemoryError> { |
| 241 | + let total = buf.len().min(self.len()); |
| 242 | + let dst = buf.subslice(0, total)?; |
| 243 | + |
| 244 | + // SAFETY: |
| 245 | + // We check above that `dst` is contiguously allocated memory of length `total <= self.len())`. |
| 246 | + // Furthermore, both src and dst of the call to copy_to_volatile_slice are valid for reads |
| 247 | + // and writes respectively of length `total` since total is the minimum of lengths of the |
| 248 | + // memory areas pointed to. The areas do not overlap, since `dst` is inside guest memory, |
| 249 | + // and buf is a slice (no slices to guest memory are possible without violating rust's aliasing rules). |
| 250 | + let read = unsafe { copy_to_volatile_slice(&dst, self.as_ptr(), total) }; |
| 251 | + |
| 252 | + // Advance the slice, just like the stdlib: https://doc.rust-lang.org/src/std/io/impls.rs.html#232-310 |
| 253 | + *self = self.split_at(read).1; |
| 254 | + |
| 255 | + Ok(read) |
| 256 | + } |
| 257 | + |
| 258 | + fn read_exact_volatile<B: BitmapSlice>( |
| 259 | + &mut self, |
| 260 | + buf: &mut VolatileSlice<B>, |
| 261 | + ) -> Result<(), VolatileMemoryError> { |
| 262 | + // Based on https://github.com/rust-lang/rust/blob/f7b831ac8a897273f78b9f47165cf8e54066ce4b/library/std/src/io/impls.rs#L282-L302 |
| 263 | + if buf.len() > self.len() { |
| 264 | + return Err(VolatileMemoryError::IOError(std::io::Error::new( |
| 265 | + ErrorKind::UnexpectedEof, |
| 266 | + "failed to fill whole buffer", |
| 267 | + ))); |
| 268 | + } |
| 269 | + |
| 270 | + self.read_volatile(buf).map(|_| ()) |
| 271 | + } |
| 272 | +} |
0 commit comments