linters: Fix clippy issues

Latest clippy version complains about our existing code for the
following reasons:

- trait objects without an explicit `dyn` are deprecated
- `...` range patterns are deprecated
- lint `clippy::const_static_lifetime` has been renamed to
  `clippy::redundant_static_lifetimes`
- unnecessary `unsafe` block
- unneeded return statement

All these issues have been fixed through this patch, and rustfmt has
been run to cleanup potential formatting errors due to those changes.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
This commit is contained in:
Sebastien Boeuf 2019-08-15 08:41:40 -07:00
parent c8364172a3
commit 658c076eb2
14 changed files with 54 additions and 53 deletions

View File

@ -3,7 +3,7 @@
#![allow( #![allow(
clippy::unreadable_literal, clippy::unreadable_literal,
clippy::const_static_lifetime, clippy::redundant_static_lifetimes,
clippy::cast_lossless, clippy::cast_lossless,
clippy::transmute_ptr_to_ptr, clippy::transmute_ptr_to_ptr,
clippy::cast_ptr_alignment clippy::cast_ptr_alignment

View File

@ -10,7 +10,7 @@
#[allow(non_snake_case)] #[allow(non_snake_case)]
#[allow( #[allow(
clippy::unreadable_literal, clippy::unreadable_literal,
clippy::const_static_lifetime, clippy::redundant_static_lifetimes,
clippy::trivially_copy_pass_by_ref, clippy::trivially_copy_pass_by_ref,
clippy::useless_transmute, clippy::useless_transmute,
clippy::should_implement_trait, clippy::should_implement_trait,
@ -19,8 +19,8 @@
pub mod bootparam; pub mod bootparam;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
#[allow(non_upper_case_globals)] #[allow(non_upper_case_globals)]
#[allow(clippy::unreadable_literal, clippy::const_static_lifetime)] #[allow(clippy::unreadable_literal, clippy::redundant_static_lifetimes)]
pub mod mpspec; pub mod mpspec;
#[allow(non_upper_case_globals)] #[allow(non_upper_case_globals)]
#[allow(clippy::unreadable_literal, clippy::const_static_lifetime)] #[allow(clippy::unreadable_literal, clippy::redundant_static_lifetimes)]
pub mod msr_index; pub mod msr_index;

View File

@ -77,7 +77,7 @@ impl PartialOrd for BusRange {
/// only restriction is that no two devices can overlap in this address space. /// only restriction is that no two devices can overlap in this address space.
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct Bus { pub struct Bus {
devices: BTreeMap<BusRange, Arc<Mutex<BusDevice>>>, devices: BTreeMap<BusRange, Arc<Mutex<dyn BusDevice>>>,
} }
impl Bus { impl Bus {
@ -88,7 +88,7 @@ impl Bus {
} }
} }
fn first_before(&self, addr: u64) -> Option<(BusRange, &Mutex<BusDevice>)> { fn first_before(&self, addr: u64) -> Option<(BusRange, &Mutex<dyn BusDevice>)> {
let (range, dev) = self let (range, dev) = self
.devices .devices
.range(..=BusRange { base: addr, len: 1 }) .range(..=BusRange { base: addr, len: 1 })
@ -97,7 +97,7 @@ impl Bus {
Some((*range, dev)) Some((*range, dev))
} }
pub fn resolve(&self, addr: u64) -> Option<(u64, u64, &Mutex<BusDevice>)> { pub fn resolve(&self, addr: u64) -> Option<(u64, u64, &Mutex<dyn BusDevice>)> {
if let Some((range, dev)) = self.first_before(addr) { if let Some((range, dev)) = self.first_before(addr) {
let offset = addr - range.base; let offset = addr - range.base;
if offset < range.len { if offset < range.len {
@ -108,7 +108,7 @@ impl Bus {
} }
/// Puts the given device at the given address space. /// Puts the given device at the given address space.
pub fn insert(&mut self, device: Arc<Mutex<BusDevice>>, base: u64, len: u64) -> Result<()> { pub fn insert(&mut self, device: Arc<Mutex<dyn BusDevice>>, base: u64, len: u64) -> Result<()> {
if len == 0 { if len == 0 {
return Err(Error::Overlap); return Err(Error::Overlap);
} }

View File

@ -188,7 +188,6 @@ impl BusDevice for Ioapic {
IOWIN_OFF => self.ioapic_write(value), IOWIN_OFF => self.ioapic_write(value),
_ => { _ => {
error!("IOAPIC: failed writing at offset {}", offset); error!("IOAPIC: failed writing at offset {}", offset);
return;
} }
} }
} }

View File

@ -55,7 +55,7 @@ const DEFAULT_BAUD_DIVISOR: u16 = 12; // 9600 bps
pub struct Serial { pub struct Serial {
interrupt_enable: u8, interrupt_enable: u8,
interrupt_identification: u8, interrupt_identification: u8,
interrupt: Box<Interrupt>, interrupt: Box<dyn Interrupt>,
line_control: u8, line_control: u8,
line_status: u8, line_status: u8,
modem_control: u8, modem_control: u8,
@ -63,11 +63,11 @@ pub struct Serial {
scratch: u8, scratch: u8,
baud_divisor: u16, baud_divisor: u16,
in_buffer: VecDeque<u8>, in_buffer: VecDeque<u8>,
out: Option<Box<io::Write + Send>>, out: Option<Box<dyn io::Write + Send>>,
} }
impl Serial { impl Serial {
pub fn new(interrupt: Box<Interrupt>, out: Option<Box<io::Write + Send>>) -> Serial { pub fn new(interrupt: Box<dyn Interrupt>, out: Option<Box<dyn io::Write + Send>>) -> Serial {
Serial { Serial {
interrupt_enable: 0, interrupt_enable: 0,
interrupt_identification: DEFAULT_INTERRUPT_IDENTIFICATION, interrupt_identification: DEFAULT_INTERRUPT_IDENTIFICATION,
@ -84,12 +84,12 @@ impl Serial {
} }
/// Constructs a Serial port ready for output. /// Constructs a Serial port ready for output.
pub fn new_out(interrupt: Box<Interrupt>, out: Box<io::Write + Send>) -> Serial { pub fn new_out(interrupt: Box<dyn Interrupt>, out: Box<dyn io::Write + Send>) -> Serial {
Self::new(interrupt, Some(out)) Self::new(interrupt, Some(out))
} }
/// Constructs a Serial port with no connected output. /// Constructs a Serial port with no connected output.
pub fn new_sink(interrupt: Box<Interrupt>) -> Serial { pub fn new_sink(interrupt: Box<dyn Interrupt>) -> Serial {
Self::new(interrupt, None) Self::new(interrupt, None)
} }

View File

@ -192,8 +192,8 @@ impl BusDevice for PciConfigIo {
fn read(&mut self, _base: u64, offset: u64, data: &mut [u8]) { fn read(&mut self, _base: u64, offset: u64, data: &mut [u8]) {
// `offset` is relative to 0xcf8 // `offset` is relative to 0xcf8
let value = match offset { let value = match offset {
0...3 => self.config_address, 0..=3 => self.config_address,
4...7 => self.config_space_read(), 4..=7 => self.config_space_read(),
_ => 0xffff_ffff, _ => 0xffff_ffff,
}; };
@ -214,8 +214,8 @@ impl BusDevice for PciConfigIo {
fn write(&mut self, _base: u64, offset: u64, data: &[u8]) { fn write(&mut self, _base: u64, offset: u64, data: &[u8]) {
// `offset` is relative to 0xcf8 // `offset` is relative to 0xcf8
match offset { match offset {
o @ 0...3 => self.set_config_address(o, data), o @ 0..=3 => self.set_config_address(o, data),
o @ 4...7 => self.config_space_write(o - 4, data), o @ 4..=7 => self.config_space_write(o - 4, data),
_ => (), _ => (),
}; };
} }

View File

@ -18,7 +18,7 @@ pub struct InterruptParameters<'a> {
} }
pub type InterruptDelivery = pub type InterruptDelivery =
Box<Fn(InterruptParameters) -> std::result::Result<(), std::io::Error> + Send + Sync>; Box<dyn Fn(InterruptParameters) -> std::result::Result<(), std::io::Error> + Send + Sync>;
#[derive(Debug)] #[derive(Debug)]
pub enum Error { pub enum Error {

View File

@ -1087,10 +1087,10 @@ impl QcowFile {
let max_valid_cluster_offset = self.refcounts.max_valid_cluster_offset(); let max_valid_cluster_offset = self.refcounts.max_valid_cluster_offset();
if let Some(new_cluster) = self.raw_file.add_cluster_end(max_valid_cluster_offset)? { if let Some(new_cluster) = self.raw_file.add_cluster_end(max_valid_cluster_offset)? {
return Ok(new_cluster); Ok(new_cluster)
} else { } else {
error!("No free clusters in get_new_cluster()"); error!("No free clusters in get_new_cluster()");
return Err(std::io::Error::from_raw_os_error(ENOSPC)); Err(std::io::Error::from_raw_os_error(ENOSPC))
} }
} }

View File

@ -15,7 +15,7 @@ use std::sync::Mutex;
use vmm::config; use vmm::config;
struct Logger { struct Logger {
output: Mutex<Box<std::io::Write + Send>>, output: Mutex<Box<dyn std::io::Write + Send>>,
start: std::time::Instant, start: std::time::Instant,
} }
@ -195,7 +195,7 @@ fn main() {
_ => LevelFilter::Trace, _ => LevelFilter::Trace,
}; };
let log_file: Box<std::io::Write + Send> = let log_file: Box<dyn std::io::Write + Send> =
if let Some(file) = cmd_arguments.value_of("log-file") { if let Some(file) = cmd_arguments.value_of("log-file") {
Box::new( Box::new(
std::fs::File::create(std::path::Path::new(file)).expect("Error creating log file"), std::fs::File::create(std::path::Path::new(file)).expect("Error creating log file"),
@ -285,7 +285,7 @@ mod tests {
struct Guest<'a> { struct Guest<'a> {
tmp_dir: TempDir, tmp_dir: TempDir,
disk_config: &'a DiskConfig, disk_config: &'a dyn DiskConfig,
fw_path: String, fw_path: String,
network: GuestNetworkConfig, network: GuestNetworkConfig,
} }
@ -549,7 +549,7 @@ mod tests {
} }
impl<'a> Guest<'a> { impl<'a> Guest<'a> {
fn new_from_ip_range(disk_config: &'a mut DiskConfig, class: &str, id: u8) -> Self { fn new_from_ip_range(disk_config: &'a mut dyn DiskConfig, class: &str, id: u8) -> Self {
let tmp_dir = TempDir::new("ch").unwrap(); let tmp_dir = TempDir::new("ch").unwrap();
let mut workload_path = dirs::home_dir().unwrap(); let mut workload_path = dirs::home_dir().unwrap();
@ -576,7 +576,7 @@ mod tests {
} }
} }
fn new(disk_config: &'a mut DiskConfig) -> Self { fn new(disk_config: &'a mut dyn DiskConfig) -> Self {
let mut guard = NEXT_VM_ID.lock().unwrap(); let mut guard = NEXT_VM_ID.lock().unwrap();
let id = *guard; let id = *guard;
*guard = id + 1; *guard = id + 1;
@ -767,8 +767,8 @@ mod tests {
let mut bionic = BionicDiskConfig::new(); let mut bionic = BionicDiskConfig::new();
vec![ vec![
&mut clear as &mut DiskConfig, &mut clear as &mut dyn DiskConfig,
&mut bionic as &mut DiskConfig, &mut bionic as &mut dyn DiskConfig,
] ]
.iter_mut() .iter_mut()
.for_each(|disk_config| { .for_each(|disk_config| {

View File

@ -388,11 +388,9 @@ impl VfioPciDevice {
..Default::default() ..Default::default()
}; };
unsafe { entry.u.msi.address_lo = route.msi_vector.msg_addr_lo;
entry.u.msi.address_lo = route.msi_vector.msg_addr_lo; entry.u.msi.address_hi = route.msi_vector.msg_addr_hi;
entry.u.msi.address_hi = route.msi_vector.msg_addr_hi; entry.u.msi.data = route.msi_vector.msg_data;
entry.u.msi.data = route.msi_vector.msg_data;
};
entry_vec.push(entry); entry_vec.push(entry);
} }

View File

@ -57,7 +57,7 @@ struct ConsoleEpollHandler {
mem: GuestMemoryMmap, mem: GuestMemoryMmap,
interrupt_cb: Arc<VirtioInterrupt>, interrupt_cb: Arc<VirtioInterrupt>,
in_buffer: Arc<Mutex<VecDeque<u8>>>, in_buffer: Arc<Mutex<VecDeque<u8>>>,
out: Box<io::Write + Send>, out: Box<dyn io::Write + Send>,
input_queue_evt: EventFd, input_queue_evt: EventFd,
output_queue_evt: EventFd, output_queue_evt: EventFd,
input_evt: EventFd, input_evt: EventFd,
@ -321,13 +321,13 @@ pub struct Console {
acked_features: u64, acked_features: u64,
config: Arc<Mutex<VirtioConsoleConfig>>, config: Arc<Mutex<VirtioConsoleConfig>>,
input: Arc<ConsoleInput>, input: Arc<ConsoleInput>,
out: Option<Box<io::Write + Send>>, out: Option<Box<dyn io::Write + Send>>,
} }
impl Console { impl Console {
/// Create a new virtio console device that gets random data from /dev/urandom. /// Create a new virtio console device that gets random data from /dev/urandom.
pub fn new( pub fn new(
out: Option<Box<io::Write + Send>>, out: Option<Box<dyn io::Write + Send>>,
cols: u16, cols: u16,
rows: u16, rows: u16,
) -> io::Result<(Console, Arc<ConsoleInput>)> { ) -> io::Result<(Console, Arc<ConsoleInput>)> {

View File

@ -17,7 +17,7 @@ pub enum VirtioInterruptType {
} }
pub type VirtioInterrupt = Box< pub type VirtioInterrupt = Box<
Fn(&VirtioInterruptType, Option<&Queue>) -> std::result::Result<(), std::io::Error> dyn Fn(&VirtioInterruptType, Option<&Queue>) -> std::result::Result<(), std::io::Error>
+ Send + Send
+ Sync, + Sync,
>; >;

View File

@ -223,7 +223,7 @@ pub struct VirtioPciDevice {
msix_num: u16, msix_num: u16,
// Virtio device reference and status // Virtio device reference and status
device: Box<VirtioDevice>, device: Box<dyn VirtioDevice>,
device_activated: bool, device_activated: bool,
// PCI interrupts. // PCI interrupts.
@ -243,7 +243,11 @@ pub struct VirtioPciDevice {
impl VirtioPciDevice { impl VirtioPciDevice {
/// Constructs a new PCI transport for the given virtio device. /// Constructs a new PCI transport for the given virtio device.
pub fn new(memory: GuestMemoryMmap, device: Box<VirtioDevice>, msix_num: u16) -> Result<Self> { pub fn new(
memory: GuestMemoryMmap,
device: Box<dyn VirtioDevice>,
msix_num: u16,
) -> Result<Self> {
let mut queue_evts = Vec::new(); let mut queue_evts = Vec::new();
for _ in device.queue_max_sizes().iter() { for _ in device.queue_max_sizes().iter() {
queue_evts.push(EventFd::new(EFD_NONBLOCK)?) queue_evts.push(EventFd::new(EFD_NONBLOCK)?)
@ -267,15 +271,15 @@ impl VirtioPciDevice {
let (class, subclass) = match VirtioDeviceType::from(device.device_type()) { let (class, subclass) = match VirtioDeviceType::from(device.device_type()) {
VirtioDeviceType::TYPE_NET => ( VirtioDeviceType::TYPE_NET => (
PciClassCode::NetworkController, PciClassCode::NetworkController,
&PciNetworkControllerSubclass::EthernetController as &PciSubclass, &PciNetworkControllerSubclass::EthernetController as &dyn PciSubclass,
), ),
VirtioDeviceType::TYPE_BLOCK => ( VirtioDeviceType::TYPE_BLOCK => (
PciClassCode::MassStorage, PciClassCode::MassStorage,
&PciMassStorageSubclass::MassStorage as &PciSubclass, &PciMassStorageSubclass::MassStorage as &dyn PciSubclass,
), ),
_ => ( _ => (
PciClassCode::Other, PciClassCode::Other,
&PciVirtioSubclass::NonTransitionalBase as &PciSubclass, &PciVirtioSubclass::NonTransitionalBase as &dyn PciSubclass,
), ),
}; };

View File

@ -97,10 +97,10 @@ pub enum DebugIoPortRange {
impl DebugIoPortRange { impl DebugIoPortRange {
fn from_u8(value: u8) -> DebugIoPortRange { fn from_u8(value: u8) -> DebugIoPortRange {
match value { match value {
0x00...0x1f => DebugIoPortRange::Firmware, 0x00..=0x1f => DebugIoPortRange::Firmware,
0x20...0x3f => DebugIoPortRange::Bootloader, 0x20..=0x3f => DebugIoPortRange::Bootloader,
0x40...0x5f => DebugIoPortRange::Kernel, 0x40..=0x5f => DebugIoPortRange::Kernel,
0x60...0x7f => DebugIoPortRange::Userspace, 0x60..=0x7f => DebugIoPortRange::Userspace,
_ => DebugIoPortRange::Custom, _ => DebugIoPortRange::Custom,
} }
} }
@ -641,7 +641,7 @@ impl DeviceManager {
ioapic: &ioapic, ioapic: &ioapic,
}; };
let serial_writer: Option<Box<io::Write + Send>> = match vm_info.vm_cfg.serial.mode { let serial_writer: Option<Box<dyn io::Write + Send>> = match vm_info.vm_cfg.serial.mode {
ConsoleOutputMode::File => Some(Box::new( ConsoleOutputMode::File => Some(Box::new(
File::create(vm_info.vm_cfg.serial.file.unwrap()) File::create(vm_info.vm_cfg.serial.file.unwrap())
.map_err(DeviceManagerError::SerialOutputFileOpen)?, .map_err(DeviceManagerError::SerialOutputFileOpen)?,
@ -652,7 +652,7 @@ impl DeviceManager {
let serial = if vm_info.vm_cfg.serial.mode != ConsoleOutputMode::Off { let serial = if vm_info.vm_cfg.serial.mode != ConsoleOutputMode::Off {
// Serial is tied to IRQ #4 // Serial is tied to IRQ #4
let serial_irq = 4; let serial_irq = 4;
let interrupt: Box<devices::Interrupt> = if let Some(ioapic) = &ioapic { let interrupt: Box<dyn devices::Interrupt> = if let Some(ioapic) = &ioapic {
Box::new(UserIoapicIrq::new(ioapic.clone(), serial_irq)) Box::new(UserIoapicIrq::new(ioapic.clone(), serial_irq))
} else { } else {
let serial_evt = EventFd::new(EFD_NONBLOCK).map_err(DeviceManagerError::EventFd)?; let serial_evt = EventFd::new(EFD_NONBLOCK).map_err(DeviceManagerError::EventFd)?;
@ -681,7 +681,7 @@ impl DeviceManager {
let pci_root = PciRoot::new(None); let pci_root = PciRoot::new(None);
let mut pci = PciConfigIo::new(pci_root); let mut pci = PciConfigIo::new(pci_root);
let console_writer: Option<Box<io::Write + Send>> = match vm_info.vm_cfg.console.mode { let console_writer: Option<Box<dyn io::Write + Send>> = match vm_info.vm_cfg.console.mode {
ConsoleOutputMode::File => Some(Box::new( ConsoleOutputMode::File => Some(Box::new(
File::create(vm_info.vm_cfg.console.file.unwrap()) File::create(vm_info.vm_cfg.console.file.unwrap())
.map_err(DeviceManagerError::ConsoleOutputFileOpen)?, .map_err(DeviceManagerError::ConsoleOutputFileOpen)?,
@ -798,7 +798,7 @@ impl DeviceManager {
let dev = let dev =
vm_virtio::Block::new(raw_img, disk_cfg.path.to_path_buf(), false) vm_virtio::Block::new(raw_img, disk_cfg.path.to_path_buf(), false)
.map_err(DeviceManagerError::CreateVirtioBlock)?; .map_err(DeviceManagerError::CreateVirtioBlock)?;
Box::new(dev) as Box<vm_virtio::VirtioDevice> Box::new(dev) as Box<dyn vm_virtio::VirtioDevice>
} }
ImageType::Qcow2 => { ImageType::Qcow2 => {
let qcow_img = QcowFile::from(raw_img) let qcow_img = QcowFile::from(raw_img)
@ -806,7 +806,7 @@ impl DeviceManager {
let dev = let dev =
vm_virtio::Block::new(qcow_img, disk_cfg.path.to_path_buf(), false) vm_virtio::Block::new(qcow_img, disk_cfg.path.to_path_buf(), false)
.map_err(DeviceManagerError::CreateVirtioBlock)?; .map_err(DeviceManagerError::CreateVirtioBlock)?;
Box::new(dev) as Box<vm_virtio::VirtioDevice> Box::new(dev) as Box<dyn vm_virtio::VirtioDevice>
} }
}; };
@ -835,7 +835,7 @@ impl DeviceManager {
// Add virtio-net if required // Add virtio-net if required
if let Some(net_list_cfg) = &vm_info.vm_cfg.net { if let Some(net_list_cfg) = &vm_info.vm_cfg.net {
for net_cfg in net_list_cfg.iter() { for net_cfg in net_list_cfg.iter() {
let mut virtio_net_device: vm_virtio::Net; let virtio_net_device: vm_virtio::Net;
if let Some(tap_if_name) = net_cfg.tap { if let Some(tap_if_name) = net_cfg.tap {
let tap = Tap::open_named(tap_if_name).map_err(DeviceManagerError::OpenTap)?; let tap = Tap::open_named(tap_if_name).map_err(DeviceManagerError::OpenTap)?;
@ -1112,7 +1112,7 @@ impl DeviceManager {
} }
fn add_virtio_pci_device( fn add_virtio_pci_device(
virtio_device: Box<vm_virtio::VirtioDevice>, virtio_device: Box<dyn vm_virtio::VirtioDevice>,
memory: GuestMemoryMmap, memory: GuestMemoryMmap,
allocator: &mut SystemAllocator, allocator: &mut SystemAllocator,
vm_fd: &Arc<VmFd>, vm_fd: &Arc<VmFd>,