From d2625408574944c715dfcf32f556a4c0842de001 Mon Sep 17 00:00:00 2001 From: Rob Bradford Date: Thu, 16 Jul 2020 10:20:22 +0100 Subject: [PATCH] virtio-devices: Introduce helper for implementing read_config() Add a helper function to share code between implementations that can use a slice accessible data structure for configuration data. Signed-off-by: Rob Bradford --- virtio-devices/src/device.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/virtio-devices/src/device.rs b/virtio-devices/src/device.rs index 7e5ac1be5..1e35e4b53 100644 --- a/virtio-devices/src/device.rs +++ b/virtio-devices/src/device.rs @@ -8,6 +8,7 @@ use crate::{ActivateResult, Error, Queue}; use std::collections::HashMap; +use std::io::Write; use std::num::Wrapping; use std::sync::Arc; use vm_memory::{GuestAddress, GuestMemoryAtomic, GuestMemoryMmap, GuestUsize}; @@ -149,6 +150,26 @@ pub trait VirtioDevice: Send { fn counters(&self) -> Option>> { None } + + /// Helper to allow common implementation of read_config + fn read_config_from_slice(&self, config: &[u8], offset: u64, mut data: &mut [u8]) { + let config_len = config.len() as u64; + let data_len = data.len() as u64; + if offset + data_len > config_len { + error!( + "Out-of-bound access to configuration: config_len = {} offset = {:x} length = {} for {}", + config_len, + offset, + data_len, + self.device_type() + ); + return; + } + if let Some(end) = offset.checked_add(data.len() as u64) { + data.write_all(&config[offset as usize..std::cmp::min(end, config_len) as usize]) + .unwrap(); + } + } } /// Trait providing address translation the same way a physical DMA remapping