virtio-devices: proper bounds checks

Callers of get_host_address_range() rely on it returning a pointer to at
least size bytes of memory.  mem.get_host_address() is an overrideable
method of a safe trait, so it is better for safe code to not rely on its
correctness for safety.  Instead, use mem.get_slice(), which returns a
VolatileSlice whose invariants guarantee that it points to a sufficient
amount of memory.  If mem.check_range() succeeds but mem.get_slice()
returns a slice that is too small, this means that there is either a
logic error or a situation the code cannot support yet, so panic.

Signed-off-by: Demi Marie Obenour <demiobenour@gmail.com>
This commit is contained in:
Demi Marie Obenour
2025-06-27 22:06:50 -04:00
committed by Rob Bradford
parent 0e21b56aea
commit 021f450cdb

View File

@@ -170,7 +170,11 @@ pub fn get_host_address_range<M: GuestMemory + ?Sized>(
size: usize,
) -> Option<*mut u8> {
if mem.check_range(addr, size) {
Some(mem.get_host_address(addr).unwrap())
let slice = mem.get_slice(addr, size).unwrap();
assert!(slice.len() >= size);
// TODO: return a VolatileSlice and fix all callers.
#[allow(deprecated)]
Some(slice.as_ptr())
} else {
None
}