1 // Copyright 2020 The Chromium OS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 use data_model::VolatileSlice; 6 use remain::sorted; 7 use thiserror::Error as ThisError; 8 9 #[sorted] 10 #[derive(ThisError, Debug)] 11 pub enum Error { 12 /// Invalid offset or length given for an iovec in backing memory. 13 #[error("Invalid offset/len for getting a slice from {0} with len {1}.")] 14 InvalidOffset(u64, usize), 15 } 16 pub type Result<T> = std::result::Result<T, Error>; 17 18 /// Used to index subslices of backing memory. Like an iovec, but relative to the start of the 19 /// memory region instead of an absolute pointer. 20 /// The backing memory referenced by the region can be an array, an mmapped file, or guest memory. 21 /// The offset is a u64 to allow having file or guest offsets >4GB when run on a 32bit host. 22 #[derive(Copy, Clone, Debug)] 23 pub struct MemRegion { 24 pub offset: u64, 25 pub len: usize, 26 } 27 28 /// Trait for memory that can yeild both iovecs in to the backing memory. 29 /// Must be OK to modify the backing memory without owning a mut able reference. For example, 30 /// this is safe for GuestMemory and VolatileSlices in crosvm as those types guarantee they are 31 /// dealt with as volatile. 32 pub unsafe trait BackingMemory { 33 /// Returns VolatileSlice pointing to the backing memory. This is most commonly unsafe. 34 /// To implement this safely the implementor must guarantee that the backing memory can be 35 /// modified out of band without affecting safety guarantees. get_volatile_slice(&self, mem_range: MemRegion) -> Result<VolatileSlice>36 fn get_volatile_slice(&self, mem_range: MemRegion) -> Result<VolatileSlice>; 37 } 38 39 /// Wrapper to be used for passing a Vec in as backing memory for asynchronous operations. The 40 /// wrapper owns a Vec according to the borrow checker. It is loaning this vec out to the kernel(or 41 /// other modifiers) through the `BackingMemory` trait. This allows multiple modifiers of the array 42 /// in the `Vec` while this struct is alive. The data in the Vec is loaned to the kernel not the 43 /// data structure itself, the length, capacity, and pointer to memory cannot be modified. 44 /// To ensure that those operations can be done safely, no access is allowed to the `Vec`'s memory 45 /// starting at the time that `VecIoWrapper` is constructed until the time it is turned back in to a 46 /// `Vec` using `to_inner`. The returned `Vec` is guaranteed to be valid as any combination of bits 47 /// in a `Vec` of `u8` is valid. 48 pub(crate) struct VecIoWrapper { 49 inner: Box<[u8]>, 50 } 51 52 impl From<Vec<u8>> for VecIoWrapper { from(vec: Vec<u8>) -> Self53 fn from(vec: Vec<u8>) -> Self { 54 VecIoWrapper { inner: vec.into() } 55 } 56 } 57 58 impl From<VecIoWrapper> for Vec<u8> { from(v: VecIoWrapper) -> Vec<u8>59 fn from(v: VecIoWrapper) -> Vec<u8> { 60 v.inner.into() 61 } 62 } 63 64 impl VecIoWrapper { 65 /// Get the length of the Vec that is wrapped. len(&self) -> usize66 pub fn len(&self) -> usize { 67 self.inner.len() 68 } 69 70 // Check that the offsets are all valid in the backing vec. check_addrs(&self, mem_range: &MemRegion) -> Result<()>71 fn check_addrs(&self, mem_range: &MemRegion) -> Result<()> { 72 let end = mem_range 73 .offset 74 .checked_add(mem_range.len as u64) 75 .ok_or(Error::InvalidOffset(mem_range.offset, mem_range.len))?; 76 if end > self.inner.len() as u64 { 77 return Err(Error::InvalidOffset(mem_range.offset, mem_range.len)); 78 } 79 Ok(()) 80 } 81 } 82 83 // Safe to implement BackingMemory as the vec is only accessible inside the wrapper and these iovecs 84 // are the only thing allowed to modify it. Nothing else can get a reference to the vec until all 85 // iovecs are dropped because they borrow Self. Nothing can borrow the owned inner vec until self 86 // is consumed by `into`, which can't happen if there are outstanding mut borrows. 87 unsafe impl BackingMemory for VecIoWrapper { get_volatile_slice(&self, mem_range: MemRegion) -> Result<VolatileSlice<'_>>88 fn get_volatile_slice(&self, mem_range: MemRegion) -> Result<VolatileSlice<'_>> { 89 self.check_addrs(&mem_range)?; 90 // Safe because the mem_range range is valid in the backing memory as checked above. 91 unsafe { 92 Ok(VolatileSlice::from_raw_parts( 93 self.inner.as_ptr().add(mem_range.offset as usize) as *mut _, 94 mem_range.len, 95 )) 96 } 97 } 98 } 99