Skip to content

Commit cb3825f

Browse files
volatile_memory: reduce unsafe code blocks
The only unsafe call in the read_from and write_to functions is the as_mut_slice. Handling the bytes is safe, so we don't need to have it in the unsafe block. Also updated the unsafe documentation to mention that we checked the offsets as well. Signed-off-by: Andreea Florescu <[email protected]>
1 parent 2edfa48 commit cb3825f

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

src/volatile_memory.rs

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -716,17 +716,16 @@ impl<B: BitmapSlice> Bytes<usize> for VolatileSlice<'_, B> {
716716
F: Read,
717717
{
718718
let end = self.compute_end_offset(addr, count)?;
719-
// SAFETY: It is safe to overwrite the volatile memory. Accessing the guest
719+
// SAFETY: We checked the addr and count so accessing the slice is safe.
720+
// Also, it is safe to overwrite the volatile memory. Accessing the guest
720721
// memory as a mutable slice is OK because nothing assumes another
721722
// thread won't change what is loaded.
722-
let bytes_read = unsafe {
723-
let dst = &mut self.as_mut_slice()[addr..end];
724-
loop {
725-
match src.read(dst) {
726-
Ok(n) => break n,
727-
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
728-
Err(e) => return Err(Error::IOError(e)),
729-
}
723+
let dst = unsafe { &mut self.as_mut_slice()[addr..end] };
724+
let bytes_read = loop {
725+
match src.read(dst) {
726+
Ok(n) => break n,
727+
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
728+
Err(e) => return Err(Error::IOError(e)),
730729
}
731730
};
732731

@@ -802,17 +801,16 @@ impl<B: BitmapSlice> Bytes<usize> for VolatileSlice<'_, B> {
802801
F: Write,
803802
{
804803
let end = self.compute_end_offset(addr, count)?;
805-
// SAFETY: It is safe to read from volatile memory. Accessing the guest
804+
// SAFETY: We checked the addr and count so accessing the slice is safe.
805+
// It is safe to read from volatile memory. Accessing the guest
806806
// memory as a slice is OK because nothing assumes another thread
807807
// won't change what is loaded.
808-
unsafe {
809-
let src = &self.as_slice()[addr..end];
810-
loop {
811-
match dst.write(src) {
812-
Ok(n) => break Ok(n),
813-
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
814-
Err(e) => break Err(Error::IOError(e)),
815-
}
808+
let src = unsafe { &self.as_slice()[addr..end] };
809+
loop {
810+
match dst.write(src) {
811+
Ok(n) => break Ok(n),
812+
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
813+
Err(e) => break Err(Error::IOError(e)),
816814
}
817815
}
818816
}

0 commit comments

Comments
 (0)