From 5bbbf610828e975fd308b90543359a85ef59b67f Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 1 Dec 2018 17:49:30 -0800 Subject: [PATCH] lint: Resolve the easier clippy lints Hopefully the changes are self-explanatory and uncontroversial. This eliminates much of the noise from `cargo clippy` and, for my purposes, gives me a reasonable way to use it as a tool when writing and reviewing code. Here is the Clippy invocation I was using: cargo +nightly clippy -- -W clippy::correctness -A renamed_and_removed_lints -Aclippy::{blacklisted_name,borrowed_box,cast_lossless,cast_ptr_alignment,enum_variant_names,identity_op,if_same_then_else,mut_from_ref,needless_pass_by_value,new_without_default,new_without_default_derive,or_fun_call,ptr_arg,should_implement_trait,single_match,too_many_arguments,trivially_copy_pass_by_ref,unreadable_literal,unsafe_vector_initialization,useless_transmute} TEST=cargo check --features wl-dmabuf,gpu,usb-emulation TEST=boot linux Change-Id: I55eb1b4a72beb2f762480e3333a921909314a0a2 Reviewed-on: https://chromium-review.googlesource.com/1356911 Commit-Ready: David Tolnay Tested-by: David Tolnay Reviewed-by: Dylan Reid --- arch/src/lib.rs | 24 +++-- data_model/src/volatile_memory.rs | 8 +- devices/src/pci/pci_configuration.rs | 2 +- devices/src/proxy.rs | 4 +- devices/src/virtio/balloon.rs | 46 +++++---- devices/src/virtio/block.rs | 18 ++-- devices/src/virtio/gpu/backend.rs | 2 +- devices/src/virtio/gpu/mod.rs | 4 +- devices/src/virtio/gpu/protocol.rs | 36 +++---- devices/src/virtio/net.rs | 37 +++---- devices/src/virtio/p9.rs | 26 +++-- devices/src/virtio/rng.rs | 2 +- devices/src/virtio/vhost/net.rs | 2 +- devices/src/virtio/vhost/vsock.rs | 2 +- devices/src/virtio/wl.rs | 46 ++++----- gpu_buffer/src/lib.rs | 25 ++--- gpu_buffer/src/rendernode.rs | 2 +- io_jail/src/lib.rs | 56 +++++------ kernel_loader/src/lib.rs | 27 +++--- kvm_sys/src/lib.rs | 1 + msg_socket/src/lib.rs | 4 +- msg_socket/src/msg_on_socket.rs | 6 +- net_sys/src/lib.rs | 1 + net_util/src/lib.rs | 20 ++-- qcow/src/qcow.rs | 13 ++- src/argument.rs | 37 ++++--- src/linux.rs | 139 ++++++++++++--------------- src/main.rs | 6 +- sys_util/src/guest_memory.rs | 10 +- sys_util/src/handle_eintr.rs | 4 +- sys_util/src/signal.rs | 2 +- sys_util/src/sock_ctrl_msg.rs | 5 +- sys_util/src/syslog.rs | 26 +++-- sys_util/src/tempdir.rs | 2 +- usb_util/src/error.rs | 30 +++--- usb_util/src/lib.rs | 1 + usb_util/src/libusb_context.rs | 4 +- vm_control/src/lib.rs | 22 ++--- x86_64/src/cpuid.rs | 4 +- x86_64/src/interrupts.rs | 4 +- x86_64/src/lib.rs | 55 +++++------ x86_64/src/mptable.rs | 20 ++-- x86_64/src/regs.rs | 20 ++-- 43 files changed, 371 insertions(+), 434 deletions(-) diff --git a/arch/src/lib.rs b/arch/src/lib.rs index bd061fdcc1..ee684d1104 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -102,35 +102,33 @@ pub enum DeviceRegistrationError { impl fmt::Display for DeviceRegistrationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &DeviceRegistrationError::AllocateIoAddrs(ref e) => { + DeviceRegistrationError::AllocateIoAddrs(e) => { write!(f, "Allocating IO addresses: {:?}", e) } - &DeviceRegistrationError::AllocateIrq => write!(f, "Allocating IRQ number"), - &DeviceRegistrationError::CreateMmioDevice(ref e) => { + DeviceRegistrationError::AllocateIrq => write!(f, "Allocating IRQ number"), + DeviceRegistrationError::CreateMmioDevice(e) => { write!(f, "failed to create mmio device: {:?}", e) } - &DeviceRegistrationError::Cmdline(ref e) => { + DeviceRegistrationError::Cmdline(e) => { write!(f, "unable to add device to kernel command line: {}", e) } - &DeviceRegistrationError::EventFdCreate(ref e) => { + DeviceRegistrationError::EventFdCreate(e) => { write!(f, "failed to create eventfd: {:?}", e) } - &DeviceRegistrationError::MmioInsert(ref e) => { + DeviceRegistrationError::MmioInsert(e) => { write!(f, "failed to add to mmio bus: {:?}", e) } - &DeviceRegistrationError::RegisterIoevent(ref e) => { + DeviceRegistrationError::RegisterIoevent(e) => { write!(f, "failed to register ioevent to VM: {:?}", e) } - &DeviceRegistrationError::RegisterIrqfd(ref e) => { + DeviceRegistrationError::RegisterIrqfd(e) => { write!(f, "failed to register irq eventfd to VM: {:?}", e) } - &DeviceRegistrationError::ProxyDeviceCreation(ref e) => { + DeviceRegistrationError::ProxyDeviceCreation(e) => { write!(f, "failed to create proxy device: {}", e) } - &DeviceRegistrationError::IrqsExhausted => write!(f, "no more IRQs are available"), - &DeviceRegistrationError::AddrsExhausted => { - write!(f, "no more addresses are available") - } + DeviceRegistrationError::IrqsExhausted => write!(f, "no more IRQs are available"), + DeviceRegistrationError::AddrsExhausted => write!(f, "no more addresses are available"), } } } diff --git a/data_model/src/volatile_memory.rs b/data_model/src/volatile_memory.rs index 5081fc671c..450d92ead7 100644 --- a/data_model/src/volatile_memory.rs +++ b/data_model/src/volatile_memory.rs @@ -44,10 +44,10 @@ pub enum VolatileMemoryError { impl fmt::Display for VolatileMemoryError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &VolatileMemoryError::OutOfBounds { addr } => { + VolatileMemoryError::OutOfBounds { addr } => { write!(f, "address 0x{:x} is out of bounds", addr) } - &VolatileMemoryError::Overflow { base, offset } => write!( + VolatileMemoryError::Overflow { base, offset } => write!( f, "address 0x{:x} offset by 0x{:x} would overflow", base, offset @@ -209,7 +209,7 @@ impl<'a> VolatileSlice<'a> { for v in buf.iter_mut().take(self.size as usize / size_of::()) { unsafe { *v = read_volatile(addr as *const T); - addr = addr.offset(size_of::() as isize); + addr = addr.add(size_of::()); } } } @@ -266,7 +266,7 @@ impl<'a> VolatileSlice<'a> { for &v in buf.iter().take(self.size as usize / size_of::()) { unsafe { write_volatile(addr as *mut T, v); - addr = addr.offset(size_of::() as isize); + addr = addr.add(size_of::()); } } } diff --git a/devices/src/pci/pci_configuration.rs b/devices/src/pci/pci_configuration.rs index bf6c3d1200..de96e85cd6 100644 --- a/devices/src/pci/pci_configuration.rs +++ b/devices/src/pci/pci_configuration.rs @@ -341,7 +341,7 @@ impl PciConfiguration { pub fn add_capability(&mut self, cap_data: &PciCapability) -> Option { let total_len = cap_data.bytes().len() + 2; // Check that the length is valid. - if cap_data.bytes().len() < 1 { + if cap_data.bytes().is_empty() { return None; } let (cap_offset, tail_offset) = match self.last_capability { diff --git a/devices/src/proxy.rs b/devices/src/proxy.rs index c7c28bbaaa..5867e58dbe 100644 --- a/devices/src/proxy.rs +++ b/devices/src/proxy.rs @@ -28,8 +28,8 @@ pub type Result = std::result::Result; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &Error::ForkingJail(_) => write!(f, "Failed to fork jail process"), - &Error::Io(ref e) => write!(f, "IO error configuring proxy device {}.", e), + Error::ForkingJail(_) => write!(f, "Failed to fork jail process"), + Error::Io(e) => write!(f, "IO error configuring proxy device {}.", e), } } } diff --git a/devices/src/virtio/balloon.rs b/devices/src/virtio/balloon.rs index 168e0c41bb..c7614c47f6 100644 --- a/devices/src/virtio/balloon.rs +++ b/devices/src/virtio/balloon.rs @@ -32,7 +32,7 @@ pub type Result = std::result::Result; // Balloon has three virt IO queues: Inflate, Deflate, and Stats. // Stats is currently not used. const QUEUE_SIZE: u16 = 128; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE, QUEUE_SIZE]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE, QUEUE_SIZE]; const VIRTIO_BALLOON_PFN_SHIFT: u32 = 12; @@ -73,29 +73,27 @@ impl Worker { let mut used_desc_heads = [0; QUEUE_SIZE as usize]; let mut used_count = 0; for avail_desc in queue.iter(&self.mem) { - if inflate { - if valid_inflate_desc(&avail_desc) { - let num_addrs = avail_desc.len / 4; - 'addr_loop: for i in 0..num_addrs as usize { - let addr = match avail_desc.addr.checked_add((i * 4) as u64) { - Some(a) => a, - None => break, - }; - let guest_input: u32 = match self.mem.read_obj_from_addr(addr) { - Ok(a) => a, - Err(_) => continue, - }; - let guest_address = - GuestAddress((guest_input as u64) << VIRTIO_BALLOON_PFN_SHIFT); + if inflate && valid_inflate_desc(&avail_desc) { + let num_addrs = avail_desc.len / 4; + for i in 0..num_addrs as usize { + let addr = match avail_desc.addr.checked_add((i * 4) as u64) { + Some(a) => a, + None => break, + }; + let guest_input: u32 = match self.mem.read_obj_from_addr(addr) { + Ok(a) => a, + Err(_) => continue, + }; + let guest_address = + GuestAddress((guest_input as u64) << VIRTIO_BALLOON_PFN_SHIFT); - if self - .mem - .remove_range(guest_address, 1 << VIRTIO_BALLOON_PFN_SHIFT) - .is_err() - { - warn!("Marking pages unused failed {:?}", guest_address); - continue; - } + if self + .mem + .remove_range(guest_address, 1 << VIRTIO_BALLOON_PFN_SHIFT) + .is_err() + { + warn!("Marking pages unused failed {:?}", guest_address); + continue; } } } @@ -302,7 +300,7 @@ impl VirtioDevice for Balloon { } fn ack_features(&mut self, value: u64) { - self.features = self.features & value; + self.features &= value; } fn activate( diff --git a/devices/src/virtio/block.rs b/devices/src/virtio/block.rs index 7d5fb028dd..f817e896bc 100644 --- a/devices/src/virtio/block.rs +++ b/devices/src/virtio/block.rs @@ -28,7 +28,7 @@ use super::{ }; const QUEUE_SIZE: u16 = 256; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; const SECTOR_SHIFT: u8 = 9; const SECTOR_SIZE: u64 = 0x01 << SECTOR_SHIFT; const MAX_DISCARD_SECTORS: u32 = u32::MAX; @@ -212,14 +212,14 @@ enum ExecuteError { impl ExecuteError { fn status(&self) -> u8 { match self { - &ExecuteError::Flush(_) => VIRTIO_BLK_S_IOERR, - &ExecuteError::Read { .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::Seek { .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::TimerFd(_) => VIRTIO_BLK_S_IOERR, - &ExecuteError::Write { .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::DiscardWriteZeroes { .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::ReadOnly { .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::Unsupported(_) => VIRTIO_BLK_S_UNSUPP, + ExecuteError::Flush(_) => VIRTIO_BLK_S_IOERR, + ExecuteError::Read { .. } => VIRTIO_BLK_S_IOERR, + ExecuteError::Seek { .. } => VIRTIO_BLK_S_IOERR, + ExecuteError::TimerFd(_) => VIRTIO_BLK_S_IOERR, + ExecuteError::Write { .. } => VIRTIO_BLK_S_IOERR, + ExecuteError::DiscardWriteZeroes { .. } => VIRTIO_BLK_S_IOERR, + ExecuteError::ReadOnly { .. } => VIRTIO_BLK_S_IOERR, + ExecuteError::Unsupported(_) => VIRTIO_BLK_S_UNSUPP, } } } diff --git a/devices/src/virtio/gpu/backend.rs b/devices/src/virtio/gpu/backend.rs index 00a327f529..634cc55103 100644 --- a/devices/src/virtio/gpu/backend.rs +++ b/devices/src/virtio/gpu/backend.rs @@ -494,7 +494,7 @@ impl Backend { } } - return response; + response } /// Copes the given rectangle of pixels of the given resource's backing memory to the host side diff --git a/devices/src/virtio/gpu/mod.rs b/devices/src/virtio/gpu/mod.rs index 5c1806bf68..f13c06d165 100644 --- a/devices/src/virtio/gpu/mod.rs +++ b/devices/src/virtio/gpu/mod.rs @@ -38,7 +38,7 @@ use self::protocol::*; // First queue is for virtio gpu commands. Second queue is for cursor commands, which we expect // there to be fewer of. -const QUEUE_SIZES: &'static [u16] = &[256, 16]; +const QUEUE_SIZES: &[u16] = &[256, 16]; const FENCE_POLL_MS: u64 = 1; struct QueueDescriptor { @@ -503,7 +503,7 @@ impl Worker { 'poll: loop { // If there are outstanding fences, wake up early to poll them. - let duration = if self.state.fence_descriptors.len() != 0 { + let duration = if !self.state.fence_descriptors.is_empty() { Duration::from_millis(FENCE_POLL_MS) } else { Duration::new(i64::MAX as u64, 0) diff --git a/devices/src/virtio/gpu/protocol.rs b/devices/src/virtio/gpu/protocol.rs index 2001cd7970..f3e53a89a8 100644 --- a/devices/src/virtio/gpu/protocol.rs +++ b/devices/src/virtio/gpu/protocol.rs @@ -613,8 +613,8 @@ impl GpuResponse { ctx_id: Le32::from(ctx_id), padding: Le32::from(0), }; - let len = match self { - &GpuResponse::OkDisplayInfo(ref info) => { + let len = match *self { + GpuResponse::OkDisplayInfo(ref info) => { if info.len() > VIRTIO_GPU_MAX_SCANOUTS { return Err(GpuResponseEncodeError::TooManyDisplays(info.len())); } @@ -630,7 +630,7 @@ impl GpuResponse { resp.get_ref(0)?.store(disp_info); size_of_val(&disp_info) } - &GpuResponse::OkCapsetInfo { id, version, size } => { + GpuResponse::OkCapsetInfo { id, version, size } => { resp.get_ref(0)?.store(virtio_gpu_resp_capset_info { hdr, capset_id: Le32::from(id), @@ -640,7 +640,7 @@ impl GpuResponse { }); size_of::() } - &GpuResponse::OkCapset(ref data) => { + GpuResponse::OkCapset(ref data) => { resp.get_ref(0)?.store(hdr); let resp_data_slice = resp.get_slice(size_of_val(&hdr) as u64, data.len() as u64)?; @@ -658,26 +658,26 @@ impl GpuResponse { /// Gets the `VIRTIO_GPU_*` enum value that corresponds to this variant. pub fn get_type(&self) -> u32 { match self { - &GpuResponse::OkNoData => VIRTIO_GPU_RESP_OK_NODATA, - &GpuResponse::OkDisplayInfo(_) => VIRTIO_GPU_RESP_OK_DISPLAY_INFO, - &GpuResponse::OkCapsetInfo { .. } => VIRTIO_GPU_RESP_OK_CAPSET_INFO, - &GpuResponse::OkCapset(_) => VIRTIO_GPU_RESP_OK_CAPSET, - &GpuResponse::ErrUnspec => VIRTIO_GPU_RESP_ERR_UNSPEC, - &GpuResponse::ErrOutOfMemory => VIRTIO_GPU_RESP_ERR_OUT_OF_MEMORY, - &GpuResponse::ErrInvalidScanoutId => VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID, - &GpuResponse::ErrInvalidResourceId => VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID, - &GpuResponse::ErrInvalidContextId => VIRTIO_GPU_RESP_ERR_INVALID_CONTEXT_ID, - &GpuResponse::ErrInvalidParameter => VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER, + GpuResponse::OkNoData => VIRTIO_GPU_RESP_OK_NODATA, + GpuResponse::OkDisplayInfo(_) => VIRTIO_GPU_RESP_OK_DISPLAY_INFO, + GpuResponse::OkCapsetInfo { .. } => VIRTIO_GPU_RESP_OK_CAPSET_INFO, + GpuResponse::OkCapset(_) => VIRTIO_GPU_RESP_OK_CAPSET, + GpuResponse::ErrUnspec => VIRTIO_GPU_RESP_ERR_UNSPEC, + GpuResponse::ErrOutOfMemory => VIRTIO_GPU_RESP_ERR_OUT_OF_MEMORY, + GpuResponse::ErrInvalidScanoutId => VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID, + GpuResponse::ErrInvalidResourceId => VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID, + GpuResponse::ErrInvalidContextId => VIRTIO_GPU_RESP_ERR_INVALID_CONTEXT_ID, + GpuResponse::ErrInvalidParameter => VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER, } } /// Returns true if this response indicates success. pub fn is_ok(&self) -> bool { match self { - &GpuResponse::OkNoData => true, - &GpuResponse::OkDisplayInfo(_) => true, - &GpuResponse::OkCapsetInfo { .. } => true, - &GpuResponse::OkCapset(_) => true, + GpuResponse::OkNoData => true, + GpuResponse::OkDisplayInfo(_) => true, + GpuResponse::OkCapsetInfo { .. } => true, + GpuResponse::OkCapset(_) => true, _ => false, } } diff --git a/devices/src/virtio/net.rs b/devices/src/virtio/net.rs index c127946ed7..8fa4d8dbf8 100644 --- a/devices/src/virtio/net.rs +++ b/devices/src/virtio/net.rs @@ -25,7 +25,7 @@ use super::{Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_NET}; /// http://docs.oasis-open.org/virtio/virtio/v1.0/virtio-v1.0.html#x1-1740003 const MAX_BUFFER_SIZE: usize = 65562; const QUEUE_SIZE: u16 = 256; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE, QUEUE_SIZE]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE, QUEUE_SIZE]; #[derive(Debug)] pub enum NetError { @@ -175,31 +175,24 @@ where let mut read_count = 0; // Copy buffer from across multiple descriptors. - loop { - match next_desc { - Some(desc) => { - if desc.is_write_only() { - break; - } - let limit = cmp::min(read_count + desc.len as usize, frame.len()); - let read_result = self - .mem - .read_slice_at_addr(&mut frame[read_count..limit as usize], desc.addr); - match read_result { - Ok(sz) => { - read_count += sz; - } - Err(e) => { - warn!("net: tx: failed to read slice: {:?}", e); - break; - } - } - next_desc = desc.next_descriptor(); + while let Some(desc) = next_desc { + if desc.is_write_only() { + break; + } + let limit = cmp::min(read_count + desc.len as usize, frame.len()); + let read_result = self + .mem + .read_slice_at_addr(&mut frame[read_count..limit as usize], desc.addr); + match read_result { + Ok(sz) => { + read_count += sz; } - None => { + Err(e) => { + warn!("net: tx: failed to read slice: {:?}", e); break; } } + next_desc = desc.next_descriptor(); } let write_result = self.tap.write(&frame[..read_count as usize]); diff --git a/devices/src/virtio/p9.rs b/devices/src/virtio/p9.rs index 19840962f6..2c1faa682f 100644 --- a/devices/src/virtio/p9.rs +++ b/devices/src/virtio/p9.rs @@ -22,7 +22,7 @@ use virtio_sys::vhost::VIRTIO_F_VERSION_1; use super::{DescriptorChain, Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_9P}; const QUEUE_SIZE: u16 = 128; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; // The only virtio_9p feature. const VIRTIO_9P_MOUNT_TAG: u8 = 0; @@ -61,39 +61,35 @@ impl error::Error for P9Error { impl fmt::Display for P9Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &P9Error::TagTooLong(len) => write!( + P9Error::TagTooLong(len) => write!( f, "P9 device tag is too long: len = {}, max = {}", len, ::std::u16::MAX ), - &P9Error::RootNotAbsolute(ref buf) => write!( + P9Error::RootNotAbsolute(buf) => write!( f, "P9 root directory is not absolute: root = {}", buf.display() ), - &P9Error::CreatePollContext(ref err) => { - write!(f, "failed to create PollContext: {:?}", err) - } - &P9Error::PollError(ref err) => write!(f, "failed to poll events: {:?}", err), - &P9Error::ReadQueueEventFd(ref err) => { + P9Error::CreatePollContext(err) => write!(f, "failed to create PollContext: {:?}", err), + P9Error::PollError(err) => write!(f, "failed to poll events: {:?}", err), + P9Error::ReadQueueEventFd(err) => { write!(f, "failed to read from virtio queue EventFd: {:?}", err) } - &P9Error::NoReadableDescriptors => { + P9Error::NoReadableDescriptors => { write!(f, "request does not have any readable descriptors") } - &P9Error::NoWritableDescriptors => { + P9Error::NoWritableDescriptors => { write!(f, "request does not have any writable descriptors") } - &P9Error::InvalidGuestAddress(addr, len) => write!( + P9Error::InvalidGuestAddress(addr, len) => write!( f, "descriptor contained invalid guest address range: address = {:?}, len = {}", addr, len ), - &P9Error::SignalUsedQueue(ref err) => { - write!(f, "failed to signal used queue: {:?}", err) - } - &P9Error::Internal(ref err) => write!(f, "P9 internal server error: {}", err), + P9Error::SignalUsedQueue(err) => write!(f, "failed to signal used queue: {:?}", err), + P9Error::Internal(err) => write!(f, "P9 internal server error: {}", err), } } } diff --git a/devices/src/virtio/rng.rs b/devices/src/virtio/rng.rs index 2aec07ed28..ee839802cc 100644 --- a/devices/src/virtio/rng.rs +++ b/devices/src/virtio/rng.rs @@ -15,7 +15,7 @@ use sys_util::{EventFd, GuestMemory, PollContext, PollToken}; use super::{Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_RNG}; const QUEUE_SIZE: u16 = 256; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; #[derive(Debug)] pub enum RngError { diff --git a/devices/src/virtio/vhost/net.rs b/devices/src/virtio/vhost/net.rs index d95a7dbb32..2b8c08bccd 100644 --- a/devices/src/virtio/vhost/net.rs +++ b/devices/src/virtio/vhost/net.rs @@ -22,7 +22,7 @@ use super::{Error, Result}; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 2; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE; NUM_QUEUES]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE; NUM_QUEUES]; pub struct Net> { workers_kill_evt: Option, diff --git a/devices/src/virtio/vhost/vsock.rs b/devices/src/virtio/vhost/vsock.rs index 4b8fe85b31..ff4e5757e3 100644 --- a/devices/src/virtio/vhost/vsock.rs +++ b/devices/src/virtio/vhost/vsock.rs @@ -19,7 +19,7 @@ use super::{Error, Result}; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 3; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE; NUM_QUEUES]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE; NUM_QUEUES]; pub struct Vsock { worker_kill_evt: Option, diff --git a/devices/src/virtio/wl.rs b/devices/src/virtio/wl.rs index a3a1ac04e5..9c4e424f64 100644 --- a/devices/src/virtio/wl.rs +++ b/devices/src/virtio/wl.rs @@ -101,7 +101,7 @@ const VIRTIO_WL_VFD_CONTROL: u32 = 0x4; const VIRTIO_WL_F_TRANS_FLAGS: u32 = 0x01; const QUEUE_SIZE: u16 = 16; -const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE, QUEUE_SIZE]; +const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE, QUEUE_SIZE]; const NEXT_VFD_ID_BASE: u32 = 0x40000000; const VFD_ID_HOST_MASK: u32 = NEXT_VFD_ID_BASE; @@ -486,7 +486,7 @@ impl VmRequester { fn request(&self, request: VmRequest) -> WlResult { let mut inner = self.inner.borrow_mut(); - let ref mut vm_socket = *inner; + let vm_socket = &mut *inner; vm_socket.send(&request).map_err(WlError::VmControl)?; vm_socket.recv().map_err(WlError::VmControl) } @@ -633,9 +633,9 @@ enum WlResp<'a> { impl<'a> WlResp<'a> { fn get_code(&self) -> u32 { - match self { - &WlResp::Ok => VIRTIO_WL_RESP_OK, - &WlResp::VfdNew { resp, .. } => { + match *self { + WlResp::Ok => VIRTIO_WL_RESP_OK, + WlResp::VfdNew { resp, .. } => { if resp { VIRTIO_WL_RESP_VFD_NEW } else { @@ -643,15 +643,15 @@ impl<'a> WlResp<'a> { } } #[cfg(feature = "wl-dmabuf")] - &WlResp::VfdNewDmabuf { .. } => VIRTIO_WL_RESP_VFD_NEW_DMABUF, - &WlResp::VfdRecv { .. } => VIRTIO_WL_CMD_VFD_RECV, - &WlResp::VfdHup { .. } => VIRTIO_WL_CMD_VFD_HUP, - &WlResp::Err(_) => VIRTIO_WL_RESP_ERR, - &WlResp::OutOfMemory => VIRTIO_WL_RESP_OUT_OF_MEMORY, - &WlResp::InvalidId => VIRTIO_WL_RESP_INVALID_ID, - &WlResp::InvalidType => VIRTIO_WL_RESP_INVALID_TYPE, - &WlResp::InvalidFlags => VIRTIO_WL_RESP_INVALID_FLAGS, - &WlResp::InvalidCommand => VIRTIO_WL_RESP_INVALID_CMD, + WlResp::VfdNewDmabuf { .. } => VIRTIO_WL_RESP_VFD_NEW_DMABUF, + WlResp::VfdRecv { .. } => VIRTIO_WL_CMD_VFD_RECV, + WlResp::VfdHup { .. } => VIRTIO_WL_CMD_VFD_HUP, + WlResp::Err(_) => VIRTIO_WL_RESP_ERR, + WlResp::OutOfMemory => VIRTIO_WL_RESP_OUT_OF_MEMORY, + WlResp::InvalidId => VIRTIO_WL_RESP_INVALID_ID, + WlResp::InvalidType => VIRTIO_WL_RESP_INVALID_TYPE, + WlResp::InvalidFlags => VIRTIO_WL_RESP_INVALID_FLAGS, + WlResp::InvalidCommand => VIRTIO_WL_RESP_INVALID_CMD, } } } @@ -1160,7 +1160,7 @@ impl WlState { let mut to_delete = Set::new(); for &(dest_vfd_id, ref q) in self.in_queue.iter() { if dest_vfd_id == vfd_id { - if let &WlRecv::Vfd { id } = q { + if let WlRecv::Vfd { id } = *q { to_delete.insert(id); } } @@ -1277,8 +1277,8 @@ impl WlState { fn next_recv(&self) -> Option { if let Some(q) = self.in_queue.front() { - match q { - &(vfd_id, WlRecv::Vfd { id }) => { + match *q { + (vfd_id, WlRecv::Vfd { id }) => { if self.current_recv_vfd.is_none() || self.current_recv_vfd == Some(vfd_id) { match self.vfds.get(&id) { Some(vfd) => Some(WlResp::VfdNew { @@ -1304,7 +1304,7 @@ impl WlState { }) } } - &(vfd_id, WlRecv::Data { ref buf }) => { + (vfd_id, WlRecv::Data { ref buf }) => { if self.current_recv_vfd.is_none() || self.current_recv_vfd == Some(vfd_id) { Some(WlResp::VfdRecv { id: vfd_id, @@ -1319,7 +1319,7 @@ impl WlState { }) } } - &(vfd_id, WlRecv::Hup) => Some(WlResp::VfdHup { id: vfd_id }), + (vfd_id, WlRecv::Hup) => Some(WlResp::VfdHup { id: vfd_id }), } } else { None @@ -1328,8 +1328,8 @@ impl WlState { fn pop_recv(&mut self) { if let Some(q) = self.in_queue.front() { - match q { - &(vfd_id, WlRecv::Vfd { id }) => { + match *q { + (vfd_id, WlRecv::Vfd { id }) => { if self.current_recv_vfd.is_none() || self.current_recv_vfd == Some(vfd_id) { self.recv_vfds.push(id); self.current_recv_vfd = Some(vfd_id); @@ -1339,14 +1339,14 @@ impl WlState { return; } } - &(vfd_id, WlRecv::Data { .. }) => { + (vfd_id, WlRecv::Data { .. }) => { self.recv_vfds.clear(); self.current_recv_vfd = None; if !(self.current_recv_vfd.is_none() || self.current_recv_vfd == Some(vfd_id)) { return; } } - &(_, WlRecv::Hup) => { + (_, WlRecv::Hup) => { self.recv_vfds.clear(); self.current_recv_vfd = None; } diff --git a/gpu_buffer/src/lib.rs b/gpu_buffer/src/lib.rs index e57053d0ce..ad8dd63124 100644 --- a/gpu_buffer/src/lib.rs +++ b/gpu_buffer/src/lib.rs @@ -236,7 +236,7 @@ impl Format { DRM_FORMAT_XRGB8888 => 4, _ => return None, }; - return Some(bpp); + Some(bpp) } } @@ -576,10 +576,10 @@ impl Buffer { let line_offset = checked_arithmetic!(yy * stride)?; let src_line = src .get_slice(line_offset, line_copy_size) - .map_err(|e| Error::Memcopy(e))?; + .map_err(Error::Memcopy)?; let dst_line = dst .get_slice(line_offset, line_copy_size) - .map_err(|e| Error::Memcopy(e))?; + .map_err(Error::Memcopy)?; src_line.copy_to_volatile_slice(dst_line); } } @@ -627,13 +627,11 @@ impl Buffer { let copy_sg_size = min(sg_size, copy_size); let src_slice = sg .get_slice(src_offset, copy_sg_size) - .map_err(|e| Error::Memcopy(e))?; + .map_err(Error::Memcopy)?; src_slice.copy_to_volatile_slice(dst_slice); src_offset = 0; - dst_slice = dst_slice - .offset(copy_sg_size) - .map_err(|e| Error::Memcopy(e))?; + dst_slice = dst_slice.offset(copy_sg_size).map_err(Error::Memcopy)?; copy_size -= copy_sg_size; if copy_size == 0 { break; @@ -647,8 +645,7 @@ impl Buffer { let line_end_skip = checked_arithmetic!(stride - line_copy_size)?; let mut remaining_line_copy_size = line_copy_size; let mut sg_opt = sgs.next(); - while !sg_opt.is_none() { - let sg = sg_opt.unwrap(); + while let Some(sg) = sg_opt { // Skip src_offset into this scatter gather item, or the entire thing if offset is // larger. let sg_size = match sg.size().checked_sub(src_offset) { @@ -662,13 +659,11 @@ impl Buffer { let copy_sg_size = min(sg_size, remaining_line_copy_size); let src_slice = sg .get_slice(src_offset, copy_sg_size) - .map_err(|e| Error::Memcopy(e))?; + .map_err(Error::Memcopy)?; src_slice.copy_to_volatile_slice(dst_slice); src_offset += copy_sg_size; - dst_slice = dst_slice - .offset(copy_sg_size) - .map_err(|e| Error::Memcopy(e))?; + dst_slice = dst_slice.offset(copy_sg_size).map_err(Error::Memcopy)?; remaining_line_copy_size -= copy_sg_size; if remaining_line_copy_size == 0 { remaining_line_copy_size = line_copy_size; @@ -678,9 +673,7 @@ impl Buffer { } src_offset += line_end_skip; - dst_slice = dst_slice - .offset(line_end_skip) - .map_err(|e| Error::Memcopy(e))?; + dst_slice = dst_slice.offset(line_end_skip).map_err(Error::Memcopy)?; } } } diff --git a/gpu_buffer/src/rendernode.rs b/gpu_buffer/src/rendernode.rs index 2c4c51baea..b9849e04f7 100644 --- a/gpu_buffer/src/rendernode.rs +++ b/gpu_buffer/src/rendernode.rs @@ -88,7 +88,7 @@ pub fn open_device(undesired: &[&str]) -> Result { const DRM_MAX_MINOR: u32 = 15; const RENDER_NODE_START: u32 = 128; - for n in RENDER_NODE_START..(RENDER_NODE_START + DRM_MAX_MINOR + 1) { + for n in RENDER_NODE_START..=RENDER_NODE_START + DRM_MAX_MINOR { let path = Path::new(DRM_DIR_NAME).join(format!("renderD{}", n)); if let Ok(fd) = OpenOptions::new().read(true).write(true).open(path) { diff --git a/io_jail/src/lib.rs b/io_jail/src/lib.rs index 773a3e9189..c50916e678 100644 --- a/io_jail/src/lib.rs +++ b/io_jail/src/lib.rs @@ -73,74 +73,62 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &Error::BindMount { - ref src, - ref dst, - errno, - } => write!( + Error::BindMount { src, dst, errno } => write!( f, "failed to accept bind mount {:?} -> {:?}: {}", src, dst, errno ), - &Error::Mount { + Error::Mount { errno, - ref src, - ref dest, - ref fstype, + src, + dest, + fstype, flags, - ref data, + data, } => write!( f, "failed to accept mount {:?} -> {:?} of type {:?} with flags 0x{:x} \ and data {:?}: {}", src, dest, fstype, flags, data, errno ), - &Error::CheckingMultiThreaded(ref e) => write!( + Error::CheckingMultiThreaded(e) => write!( f, "Failed to count the number of threads from /proc/self/tasks {}", e ), - &Error::CreatingMinijail => { - write!(f, "minjail_new failed due to an allocation failure") - } - &Error::ForkingMinijail(ref e) => write!(f, "minijail_fork failed with error {}", e), - &Error::ForkingWhileMultiThreaded => { + Error::CreatingMinijail => write!(f, "minjail_new failed due to an allocation failure"), + Error::ForkingMinijail(e) => write!(f, "minijail_fork failed with error {}", e), + Error::ForkingWhileMultiThreaded => { write!(f, "Attempt to call fork() while multithreaded") } - &Error::SeccompPath(ref p) => write!(f, "missing seccomp policy path: {:?}", p), - &Error::StrToCString(ref s) => { - write!(f, "failed to convert string into CString: {:?}", s) - } - &Error::PathToCString(ref s) => { - write!(f, "failed to convert path into CString: {:?}", s) - } - &Error::DupDevNull(errno) => write!( + Error::SeccompPath(p) => write!(f, "missing seccomp policy path: {:?}", p), + Error::StrToCString(s) => write!(f, "failed to convert string into CString: {:?}", s), + Error::PathToCString(s) => write!(f, "failed to convert path into CString: {:?}", s), + Error::DupDevNull(errno) => write!( f, "failed to call dup2 to set stdin, stdout, or stderr to /dev/null: {}", errno ), - &Error::OpenDevNull(ref e) => write!( + Error::OpenDevNull(e) => write!( f, "fail to open /dev/null for setting FDs 0, 1, or 2: {}", e ), - &Error::SetAltSyscallTable { ref name, errno } => { + Error::SetAltSyscallTable { name, errno } => { write!(f, "failed to set alt-syscall table {:?}: {}", name, errno) } - &Error::SettingChrootDirectory(errno, ref p) => { + Error::SettingChrootDirectory(errno, p) => { write!(f, "failed to set chroot {:?}: {}", p, errno) } - &Error::SettingPivotRootDirectory(errno, ref p) => { + Error::SettingPivotRootDirectory(errno, p) => { write!(f, "failed to set pivot root {:?}: {}", p, errno) } - &Error::ReadFdDirEntry(ref e) => { + Error::ReadFdDirEntry(e) => { write!(f, "failed to read an entry in /proc/self/fd: {}", e) } - &Error::ReadFdDir(ref e) => write!(f, "failed to open /proc/self/fd: {}", e), - &Error::ProcFd(ref s) => { - write!(f, "an entry in /proc/self/fd is not an integer: {}", s) - } - &Error::PreservingFd(ref e) => { + Error::ReadFdDir(e) => write!(f, "failed to open /proc/self/fd: {}", e), + Error::ProcFd(s) => write!(f, "an entry in /proc/self/fd is not an integer: {}", s), + Error::PreservingFd(e) => { write!(f, "fork failed in minijail_preserve_fd with error {}", e) } } diff --git a/kernel_loader/src/lib.rs b/kernel_loader/src/lib.rs index 23405d9bf5..42b43de6db 100644 --- a/kernel_loader/src/lib.rs +++ b/kernel_loader/src/lib.rs @@ -16,6 +16,7 @@ use sys_util::{GuestAddress, GuestMemory}; #[allow(non_camel_case_types)] #[allow(non_snake_case)] #[allow(non_upper_case_globals)] +#[cfg_attr(feature = "cargo-clippy", allow(clippy))] mod elf; #[derive(Debug, PartialEq)] @@ -39,21 +40,21 @@ pub type Result = std::result::Result; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::BigEndianElfOnLittle => { + Error::BigEndianElfOnLittle => { "Trying to load big-endian binary on little-endian machine" } - &Error::CommandLineCopy => "Failed writing command line to guest memory", - &Error::CommandLineOverflow => "Command line overflowed guest memory", - &Error::InvalidElfMagicNumber => "Invalid Elf magic number", - &Error::InvalidProgramHeaderSize => "Invalid program header size", - &Error::InvalidProgramHeaderOffset => "Invalid program header offset", - &Error::InvalidProgramHeaderAddress => "Invalid Program Header Address", - &Error::ReadElfHeader => "Unable to read elf header", - &Error::ReadKernelImage => "Unable to read kernel image", - &Error::ReadProgramHeader => "Unable to read program header", - &Error::SeekKernelStart => "Unable to seek to kernel start", - &Error::SeekElfStart => "Unable to seek to elf start", - &Error::SeekProgramHeader => "Unable to seek to program header", + Error::CommandLineCopy => "Failed writing command line to guest memory", + Error::CommandLineOverflow => "Command line overflowed guest memory", + Error::InvalidElfMagicNumber => "Invalid Elf magic number", + Error::InvalidProgramHeaderSize => "Invalid program header size", + Error::InvalidProgramHeaderOffset => "Invalid program header offset", + Error::InvalidProgramHeaderAddress => "Invalid Program Header Address", + Error::ReadElfHeader => "Unable to read elf header", + Error::ReadKernelImage => "Unable to read kernel image", + Error::ReadProgramHeader => "Unable to read program header", + Error::SeekKernelStart => "Unable to seek to kernel start", + Error::SeekElfStart => "Unable to seek to elf start", + Error::SeekProgramHeader => "Unable to seek to program header", } } } diff --git a/kvm_sys/src/lib.rs b/kvm_sys/src/lib.rs index 46d48b47c9..6ac589a4ef 100644 --- a/kvm_sys/src/lib.rs +++ b/kvm_sys/src/lib.rs @@ -17,6 +17,7 @@ pub const KVM_EXIT_IO_OUT: ::std::os::raw::c_uint = 1; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub mod x86 { // generated with bindgen /usr/include/linux/kvm.h --no-unstable-rust --constified-enum '*' --with-derive-default + #[cfg_attr(feature = "cargo-clippy", allow(clippy))] pub mod bindings; pub use bindings::*; diff --git a/msg_socket/src/lib.rs b/msg_socket/src/lib.rs index b86db1dbff..cc2cdc955d 100644 --- a/msg_socket/src/lib.rs +++ b/msg_socket/src/lib.rs @@ -169,7 +169,7 @@ pub trait MsgSender: AsRef { .map_err(|e| MsgError::Send(SysError::new(e.raw_os_error().unwrap_or(0))))?; } else { sock.send_with_fds(&msg_buffer[..], &fd_buffer[0..fd_size]) - .map_err(|e| MsgError::Send(e))?; + .map_err(MsgError::Send)?; } Ok(()) } @@ -193,7 +193,7 @@ pub trait MsgReceiver: AsRef { (size, 0) } else { sock.recv_with_fds(&mut msg_buffer, &mut fd_buffer) - .map_err(|e| MsgError::Recv(e))? + .map_err(MsgError::Recv)? } }; if msg_size != recv_msg_size { diff --git a/msg_socket/src/msg_on_socket.rs b/msg_socket/src/msg_on_socket.rs index 25619da142..c6e4413091 100644 --- a/msg_socket/src/msg_on_socket.rs +++ b/msg_socket/src/msg_on_socket.rs @@ -102,16 +102,16 @@ impl MsgOnSocket for RawFd { 1 } unsafe fn read_from_buffer(_buffer: &[u8], fds: &[RawFd]) -> MsgResult<(Self, usize)> { - if fds.len() < 1 { + if fds.is_empty() { return Err(MsgError::ExpectFd); } Ok((fds[0], 1)) } fn write_to_buffer(&self, _buffer: &mut [u8], fds: &mut [RawFd]) -> MsgResult { - if fds.len() < 1 { + if fds.is_empty() { return Err(MsgError::WrongFdBufferSize); } - fds[0] = self.clone(); + fds[0] = *self; Ok(1) } } diff --git a/net_sys/src/lib.rs b/net_sys/src/lib.rs index 5e2df00ffc..324fc3e9bb 100644 --- a/net_sys/src/lib.rs +++ b/net_sys/src/lib.rs @@ -16,6 +16,7 @@ extern crate sys_util; // Generated against Linux 4.11 to include fix "uapi: fix linux/if.h userspace // compilation errors". // Manual fixup of ifrn_name to be of type c_uchar instead of c_char. +#[cfg_attr(feature = "cargo-clippy", allow(clippy))] pub mod iff; // generated with bindgen /usr/include/linux/if_tun.h --no-unstable-rust // --constified-enum '*' --with-derive-default diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index 06c3f17fd3..78a0cb844c 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -36,11 +36,11 @@ pub type Result = std::result::Result; impl Error { pub fn sys_error(&self) -> SysError { - match self { - &Error::CreateSocket(e) => e, - &Error::OpenTun(e) => e, - &Error::CreateTap(e) => e, - &Error::IoctlError(e) => e, + match *self { + Error::CreateSocket(e) => e, + Error::OpenTun(e) => e, + Error::CreateTap(e) => e, + Error::IoctlError(e) => e, } } } @@ -107,7 +107,7 @@ pub struct MacAddress { impl MacAddress { pub fn octets(&self) -> [u8; 6usize] { - self.addr.clone() + self.addr } } @@ -115,7 +115,7 @@ impl FromStr for MacAddress { type Err = MacAddressError; fn from_str(s: &str) -> std::result::Result { - let octets: Vec<&str> = s.split(":").collect(); + let octets: Vec<&str> = s.split(':').collect(); if octets.len() != 6usize { return Err(MacAddressError::InvalidNumOctets(octets.len())); } @@ -209,7 +209,7 @@ impl TapT for Tap { // We just checked that the fd is valid. let tuntap = unsafe { File::from_raw_fd(fd) }; - const TUNTAP_DEV_FORMAT: &'static [u8; 8usize] = b"vmtap%d\0"; + const TUNTAP_DEV_FORMAT: &[u8; 8usize] = b"vmtap%d\0"; // This is pretty messy because of the unions used by ifreq. Since we // don't call as_mut on the same union field more than once, this block @@ -239,10 +239,10 @@ impl TapT for Tap { } } - // Safe since only the name is accessed, and it's cloned out. + // Safe since only the name is accessed, and it's copied out. Ok(Tap { tap_file: tuntap, - if_name: unsafe { ifreq.ifr_ifrn.ifrn_name.as_ref().clone() }, + if_name: unsafe { *ifreq.ifr_ifrn.ifrn_name.as_ref() }, }) } diff --git a/qcow/src/qcow.rs b/qcow/src/qcow.rs index db138bf734..640f469b98 100644 --- a/qcow/src/qcow.rs +++ b/qcow/src/qcow.rs @@ -358,11 +358,10 @@ impl QcowFile { } let l2_size = cluster_size / size_of::() as u64; - let num_clusters = div_round_up_u64(header.size, u64::from(cluster_size)); + let num_clusters = div_round_up_u64(header.size, cluster_size); let num_l2_clusters = div_round_up_u64(num_clusters, l2_size); - let l1_clusters = div_round_up_u64(num_l2_clusters, u64::from(cluster_size)); - let header_clusters = - div_round_up_u64(size_of::() as u64, u64::from(cluster_size)); + let l1_clusters = div_round_up_u64(num_l2_clusters, cluster_size); + let header_clusters = div_round_up_u64(size_of::() as u64, cluster_size); let l1_table = VecCache::from_vec( raw_file .read_pointer_table( @@ -372,7 +371,7 @@ impl QcowFile { ).map_err(Error::ReadingHeader)?, ); - let num_clusters = div_round_up_u64(header.size, u64::from(cluster_size)); + let num_clusters = div_round_up_u64(header.size, cluster_size); let refcount_clusters = max_refcount_clusters( header.refcount_order, cluster_size as u32, @@ -699,7 +698,7 @@ impl QcowFile { let refcount_bytes = div_round_up_u64(refcount_bits, 8); let refcount_block_entries = cluster_size / refcount_bytes; let pointers_per_cluster = cluster_size / size_of::() as u64; - let data_clusters = div_round_up_u64(header.size, u64::from(cluster_size)); + let data_clusters = div_round_up_u64(header.size, cluster_size); let l2_clusters = div_round_up_u64(data_clusters, pointers_per_cluster); let l1_clusters = div_round_up_u64(l2_clusters, cluster_size); let header_clusters = div_round_up_u64(size_of::() as u64, cluster_size); @@ -1433,7 +1432,7 @@ where .read(&mut buf[..this_count]) .map_err(Error::ReadingData)?; writer.write(&buf[..nread]).map_err(Error::WritingData)?; - read_count = read_count + nread as u64; + read_count += nread as u64; if nread == 0 || read_count == size { break; } diff --git a/src/argument.rs b/src/argument.rs index edcaadc38a..baadb02036 100644 --- a/src/argument.rs +++ b/src/argument.rs @@ -67,16 +67,15 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &Error::Syntax(ref s) => write!(f, "syntax error: {}", s), - &Error::UnknownArgument(ref s) => write!(f, "unknown argument: {}", s), - &Error::ExpectedArgument(ref s) => write!(f, "expected argument: {}", s), - &Error::InvalidValue { - ref value, - expected, - } => write!(f, "invalid value {:?}: {}", value, expected), - &Error::TooManyArguments(ref s) => write!(f, "too many arguments: {}", s), - &Error::ExpectedValue(ref s) => write!(f, "expected parameter value: {}", s), - &Error::PrintHelp => write!(f, "help was requested"), + Error::Syntax(s) => write!(f, "syntax error: {}", s), + Error::UnknownArgument(s) => write!(f, "unknown argument: {}", s), + Error::ExpectedArgument(s) => write!(f, "expected argument: {}", s), + Error::InvalidValue { value, expected } => { + write!(f, "invalid value {:?}: {}", value, expected) + } + Error::TooManyArguments(s) => write!(f, "too many arguments: {}", s), + Error::ExpectedValue(s) => write!(f, "expected parameter value: {}", s), + Error::PrintHelp => write!(f, "help was requested"), } } } @@ -217,20 +216,18 @@ where } f(name, Some(value))?; State::Top - } else { - if let Err(e) = f(param, None) { - if let Error::ExpectedValue(_) = e { - State::Value { - name: param.to_owned(), - } - } else { - return Err(e); + } else if let Err(e) = f(param, None) { + if let Error::ExpectedValue(_) = e { + State::Value { + name: param.to_owned(), } } else { - State::Top + return Err(e); } + } else { + State::Top } - } else if arg.starts_with("-") { + } else if arg.starts_with('-') { if arg.len() == 1 { return Err(Error::Syntax( "expected argument short name after `-`".to_owned(), diff --git a/src/linux.rs b/src/linux.rs index 44c2aefbe5..c208e3b76b 100644 --- a/src/linux.rs +++ b/src/linux.rs @@ -100,86 +100,72 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &Error::BalloonDeviceNew(ref e) => write!(f, "failed to create balloon: {:?}", e), - &Error::BlockDeviceNew(ref e) => write!(f, "failed to create block device: {:?}", e), - &Error::BlockSignal(ref e) => write!(f, "failed to block signal: {:?}", e), - &Error::BuildingVm(ref e) => { - write!(f, "The architecture failed to build the vm: {:?}", e) - } - &Error::CloneEventFd(ref e) => write!(f, "failed to clone eventfd: {:?}", e), - &Error::CreateEventFd(ref e) => write!(f, "failed to create eventfd: {:?}", e), - &Error::CreatePollContext(ref e) => write!(f, "failed to create poll context: {:?}", e), - &Error::CreateSignalFd(ref e) => write!(f, "failed to create signalfd: {:?}", e), - &Error::CreateSocket(ref e) => write!(f, "failed to create socket: {}", e), - &Error::CreateTimerFd(ref e) => write!(f, "failed to create timerfd: {}", e), - &Error::DetectImageType(ref e) => { - write!(f, "failed to detect disk image type: {:?}", e) - } - &Error::DeviceJail(ref e) => write!(f, "failed to jail device: {}", e), - &Error::DevicePivotRoot(ref e) => write!(f, "failed to pivot root device: {}", e), - &Error::Disk(ref e) => write!(f, "failed to load disk image: {}", e), - &Error::DiskImageLock(ref e) => write!(f, "failed to lock disk image: {:?}", e), - &Error::FailedCLOEXECCheck => { + Error::BalloonDeviceNew(e) => write!(f, "failed to create balloon: {:?}", e), + Error::BlockDeviceNew(e) => write!(f, "failed to create block device: {:?}", e), + Error::BlockSignal(e) => write!(f, "failed to block signal: {:?}", e), + Error::BuildingVm(e) => write!(f, "The architecture failed to build the vm: {:?}", e), + Error::CloneEventFd(e) => write!(f, "failed to clone eventfd: {:?}", e), + Error::CreateEventFd(e) => write!(f, "failed to create eventfd: {:?}", e), + Error::CreatePollContext(e) => write!(f, "failed to create poll context: {:?}", e), + Error::CreateSignalFd(e) => write!(f, "failed to create signalfd: {:?}", e), + Error::CreateSocket(e) => write!(f, "failed to create socket: {}", e), + Error::CreateTimerFd(e) => write!(f, "failed to create timerfd: {}", e), + Error::DetectImageType(e) => write!(f, "failed to detect disk image type: {:?}", e), + Error::DeviceJail(e) => write!(f, "failed to jail device: {}", e), + Error::DevicePivotRoot(e) => write!(f, "failed to pivot root device: {}", e), + Error::Disk(e) => write!(f, "failed to load disk image: {}", e), + Error::DiskImageLock(e) => write!(f, "failed to lock disk image: {:?}", e), + Error::FailedCLOEXECCheck => { write!(f, "/proc/self/fd argument failed check for CLOEXEC") } - &Error::FailedToDupFd => write!(f, "failed to dup fd from /proc/self/fd"), - &Error::InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"), - &Error::InvalidWaylandPath => { + Error::FailedToDupFd => write!(f, "failed to dup fd from /proc/self/fd"), + Error::InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"), + Error::InvalidWaylandPath => { write!(f, "wayland socket path has no parent or file name") } - &Error::NetDeviceNew(ref e) => write!(f, "failed to set up virtio networking: {:?}", e), - &Error::NoVarEmpty => write!(f, "/var/empty doesn't exist, can't jail devices."), - &Error::OpenKernel(ref p, ref e) => { - write!(f, "failed to open kernel image {:?}: {}", p, e) - } - &Error::P9DeviceNew(ref e) => write!(f, "failed to create 9p device: {}", e), - &Error::PollContextAdd(ref e) => write!(f, "failed to add fd to poll context: {:?}", e), - &Error::PollContextDelete(ref e) => { + Error::NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {:?}", e), + Error::NoVarEmpty => write!(f, "/var/empty doesn't exist, can't jail devices."), + Error::OpenKernel(p, e) => write!(f, "failed to open kernel image {:?}: {}", p, e), + Error::P9DeviceNew(e) => write!(f, "failed to create 9p device: {}", e), + Error::PollContextAdd(e) => write!(f, "failed to add fd to poll context: {:?}", e), + Error::PollContextDelete(e) => { write!(f, "failed to remove fd from poll context: {:?}", e) } - &Error::QcowDeviceCreate(ref e) => { - write!(f, "failed to read qcow formatted file {:?}", e) - } - &Error::ReadLowmemAvailable(ref e) => write!( + Error::QcowDeviceCreate(e) => write!(f, "failed to read qcow formatted file {:?}", e), + Error::ReadLowmemAvailable(e) => write!( f, "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}", e ), - &Error::ReadLowmemMargin(ref e) => write!( + Error::ReadLowmemMargin(e) => write!( f, "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}", e ), - &Error::RegisterBalloon(ref e) => { - write!(f, "error registering balloon device: {:?}", e) - } - &Error::RegisterBlock(ref e) => write!(f, "error registering block device: {:?}", e), - &Error::RegisterGpu(ref e) => write!(f, "error registering gpu device: {:?}", e), - &Error::RegisterNet(ref e) => write!(f, "error registering net device: {:?}", e), - &Error::RegisterP9(ref e) => write!(f, "error registering 9p device: {:?}", e), - &Error::RegisterRng(ref e) => write!(f, "error registering rng device: {:?}", e), - &Error::RegisterSignalHandler(ref e) => { + Error::RegisterBalloon(e) => write!(f, "error registering balloon device: {:?}", e), + Error::RegisterBlock(e) => write!(f, "error registering block device: {:?}", e), + Error::RegisterGpu(e) => write!(f, "error registering gpu device: {:?}", e), + Error::RegisterNet(e) => write!(f, "error registering net device: {:?}", e), + Error::RegisterP9(e) => write!(f, "error registering 9p device: {:?}", e), + Error::RegisterRng(e) => write!(f, "error registering rng device: {:?}", e), + Error::RegisterSignalHandler(e) => { write!(f, "error registering signal handler: {:?}", e) } - &Error::RegisterWayland(ref e) => write!(f, "error registering wayland device: {}", e), - &Error::ResetTimerFd(ref e) => write!(f, "failed to reset timerfd: {}", e), - &Error::RngDeviceNew(ref e) => write!(f, "failed to set up rng: {:?}", e), - &Error::SettingGidMap(ref e) => write!(f, "error setting GID map: {}", e), - &Error::SettingUidMap(ref e) => write!(f, "error setting UID map: {}", e), - &Error::SignalFd(ref e) => write!(f, "failed to read signal fd: {:?}", e), - &Error::SpawnVcpu(ref e) => write!(f, "failed to spawn VCPU thread: {:?}", e), - &Error::TimerFd(ref e) => write!(f, "failed to read timer fd: {:?}", e), - &Error::VhostNetDeviceNew(ref e) => { - write!(f, "failed to set up vhost networking: {:?}", e) - } - &Error::VhostVsockDeviceNew(ref e) => { + Error::RegisterWayland(e) => write!(f, "error registering wayland device: {}", e), + Error::ResetTimerFd(e) => write!(f, "failed to reset timerfd: {}", e), + Error::RngDeviceNew(e) => write!(f, "failed to set up rng: {:?}", e), + Error::SettingGidMap(e) => write!(f, "error setting GID map: {}", e), + Error::SettingUidMap(e) => write!(f, "error setting UID map: {}", e), + Error::SignalFd(e) => write!(f, "failed to read signal fd: {:?}", e), + Error::SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {:?}", e), + Error::TimerFd(e) => write!(f, "failed to read timer fd: {:?}", e), + Error::VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {:?}", e), + Error::VhostVsockDeviceNew(e) => { write!(f, "failed to set up virtual socket device: {:?}", e) } - &Error::VirtioPciDev(ref e) => write!(f, "failed to create virtio pci dev: {}", e), - &Error::WaylandDeviceNew(ref e) => { - write!(f, "failed to create wayland device: {:?}", e) - } - &Error::LoadKernel(ref e) => write!(f, "failed to load kernel: {}", e), + Error::VirtioPciDev(e) => write!(f, "failed to create virtio pci dev: {}", e), + Error::WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {:?}", e), + Error::LoadKernel(e) => write!(f, "failed to load kernel: {}", e), } } } @@ -216,7 +202,7 @@ fn validate_raw_fd(raw_fd: RawFd) -> std::result::Result Result { // All child jails run in a new user namespace without any users mapped, // they run as nobody unless otherwise configured. - let mut j = Minijail::new().map_err(|e| Error::DeviceJail(e))?; + let mut j = Minijail::new().map_err(Error::DeviceJail)?; j.namespace_pids(); j.namespace_user(); j.namespace_user_disable_setgroups(); @@ -224,8 +210,7 @@ fn create_base_minijail(root: &Path, seccomp_policy: &Path) -> Result j.use_caps(0); // Create a new mount namespace with an empty root FS. j.namespace_vfs(); - j.enter_pivot_root(root) - .map_err(|e| Error::DevicePivotRoot(e))?; + j.enter_pivot_root(root).map_err(Error::DevicePivotRoot)?; // Run in an empty network namespace. j.namespace_net(); // Apply the block device seccomp policy. @@ -236,7 +221,7 @@ fn create_base_minijail(root: &Path, seccomp_policy: &Path) -> Result #[cfg(debug_assertions)] j.log_seccomp_filter_failures(); j.parse_seccomp_filters(seccomp_policy) - .map_err(|e| Error::DeviceJail(e))?; + .map_err(Error::DeviceJail)?; j.use_seccomp_filter(); // Don't do init setup. j.run_as_init(); @@ -250,7 +235,7 @@ fn create_virtio_devs( wayland_device_socket: UnixDatagram, balloon_device_socket: UnixDatagram, ) -> std::result::Result, Option)>, Box> { - static DEFAULT_PIVOT_ROOT: &'static str = "/var/empty"; + static DEFAULT_PIVOT_ROOT: &str = "/var/empty"; let mut devs = Vec::new(); @@ -279,7 +264,7 @@ fn create_virtio_devs( .read(true) .write(!disk.read_only) .open(&disk.path) - .map_err(|e| Error::Disk(e))? + .map_err(Error::Disk)? }; // Lock the disk image to prevent other crosvm instances from using it. let lock_op = if disk.read_only { @@ -295,16 +280,15 @@ fn create_virtio_devs( // Access as a raw block device. Box::new( devices::virtio::Block::new(raw_image, disk.read_only) - .map_err(|e| Error::BlockDeviceNew(e))?, + .map_err(Error::BlockDeviceNew)?, ) } ImageType::Qcow2 => { // Valid qcow header present - let qcow_image = - QcowFile::from(raw_image).map_err(|e| Error::QcowDeviceCreate(e))?; + let qcow_image = QcowFile::from(raw_image).map_err(Error::QcowDeviceCreate)?; Box::new( devices::virtio::Block::new(qcow_image, disk.read_only) - .map_err(|e| Error::BlockDeviceNew(e))?, + .map_err(Error::BlockDeviceNew)?, ) } }; @@ -351,8 +335,7 @@ fn create_virtio_devs( if let Some(tap_fd) = cfg.tap_fd { // Safe because we ensure that we get a unique handle to the fd. let tap = unsafe { Tap::from_raw_fd(validate_raw_fd(tap_fd)?) }; - let net_box = - Box::new(devices::virtio::Net::from(tap).map_err(|e| Error::NetDeviceNew(e))?); + let net_box = Box::new(devices::virtio::Net::from(tap).map_err(Error::NetDeviceNew)?); let jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("net_device.policy"); @@ -373,12 +356,12 @@ fn create_virtio_devs( netmask, mac_address, &mem, - ).map_err(|e| Error::VhostNetDeviceNew(e))?, + ).map_err(Error::VhostNetDeviceNew)?, ) } else { Box::new( devices::virtio::Net::::new(host_ip, netmask, mac_address) - .map_err(|e| Error::NetDeviceNew(e))?, + .map_err(Error::NetDeviceNew)?, ) }; @@ -815,8 +798,8 @@ fn run_control( sigchld_fd: SignalFd, ) -> Result<()> { // Paths to get the currently available memory and the low memory threshold. - const LOWMEM_MARGIN: &'static str = "/sys/kernel/mm/chromeos-low_mem/margin"; - const LOWMEM_AVAILABLE: &'static str = "/sys/kernel/mm/chromeos-low_mem/available"; + const LOWMEM_MARGIN: &str = "/sys/kernel/mm/chromeos-low_mem/margin"; + const LOWMEM_AVAILABLE: &str = "/sys/kernel/mm/chromeos-low_mem/available"; // The amount of additional memory to claim back from the VM whenever the system is // low on memory. diff --git a/src/main.rs b/src/main.rs index 75ad172835..2f0320beb4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -137,7 +137,7 @@ fn wait_all_children() -> bool { } // If we've made it to this point, not all of the children have exited. - return false; + false } fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument::Result<()> { @@ -215,7 +215,7 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: } cfg.params.push(format!( "root=/dev/vd{} ro", - char::from('a' as u8 + cfg.disks.len() as u8) + char::from(b'a' + cfg.disks.len() as u8) )); } cfg.disks.push(DiskOption { @@ -628,12 +628,10 @@ fn create_qcow2(mut args: std::env::Args) -> std::result::Result<(), ()> { .open(&file_path) .map_err(|e| { error!("Failed opening qcow file at '{}': {:?}", file_path, e); - () })?; QcowFile::new(file, size).map_err(|e| { error!("Failed to create qcow file at '{}': {:?}", file_path, e); - () })?; Ok(()) diff --git a/sys_util/src/guest_memory.rs b/sys_util/src/guest_memory.rs index 604ef4925f..36220850d0 100644 --- a/sys_util/src/guest_memory.rs +++ b/sys_util/src/guest_memory.rs @@ -27,10 +27,10 @@ pub type Result = result::Result; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::InvalidGuestAddress(_) => "Invalid Guest Address", - &Error::MemoryAccess(_, _) => "Invalid Guest Memory Access", - &Error::MemoryMappingFailed(_) => "Failed to map guest memory", - &Error::MemoryRegionOverlap => "Memory regions overlap", + Error::InvalidGuestAddress(_) => "Invalid Guest Address", + Error::MemoryAccess(_, _) => "Invalid Guest Memory Access", + Error::MemoryMappingFailed(_) => "Failed to map guest memory", + Error::MemoryRegionOverlap => "Memory regions overlap", } } } @@ -386,7 +386,7 @@ impl GuestMemory { self.do_in_region(guest_addr, |mapping, offset| { // This is safe; `do_in_region` already checks that offset is in // bounds. - Ok(unsafe { mapping.as_ptr().offset(offset as isize) } as *const u8) + Ok(unsafe { mapping.as_ptr().add(offset) } as *const u8) }) } diff --git a/sys_util/src/handle_eintr.rs b/sys_util/src/handle_eintr.rs index 4faab07fb0..b570c364e0 100644 --- a/sys_util/src/handle_eintr.rs +++ b/sys_util/src/handle_eintr.rs @@ -18,7 +18,7 @@ pub trait InterruptibleResult { impl InterruptibleResult for ::Result { fn is_interrupted(&self) -> bool { match self { - &Err(e) if e.errno() == EINTR => true, + Err(e) if e.errno() == EINTR => true, _ => false, } } @@ -27,7 +27,7 @@ impl InterruptibleResult for ::Result { impl InterruptibleResult for io::Result { fn is_interrupted(&self) -> bool { match self { - &Err(ref e) if e.kind() == io::ErrorKind::Interrupted => true, + Err(e) if e.kind() == io::ErrorKind::Interrupted => true, _ => false, } } diff --git a/sys_util/src/signal.rs b/sys_util/src/signal.rs index 69e0fd086b..fe01dcf1b3 100644 --- a/sys_util/src/signal.rs +++ b/sys_util/src/signal.rs @@ -124,7 +124,7 @@ pub fn get_blocked_signals() -> SignalResult> { return Err(Error::RetrieveSignalMask(ret)); } - for num in 0..(SIGRTMAX() + 1) { + for num in 0..=SIGRTMAX() { if sigismember(&old_sigset, num) > 0 { mask.push(num); } diff --git a/sys_util/src/sock_ctrl_msg.rs b/sys_util/src/sock_ctrl_msg.rs index a21b64a84d..337dbb9707 100644 --- a/sys_util/src/sock_ctrl_msg.rs +++ b/sys_util/src/sock_ctrl_msg.rs @@ -54,8 +54,7 @@ fn CMSG_DATA(cmsg_buffer: *mut cmsghdr) -> *mut RawFd { // does some pointer arithmetic on cmsg_ptr. #[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))] fn get_next_cmsg(msghdr: &msghdr, cmsg: &cmsghdr, cmsg_ptr: *mut cmsghdr) -> *mut cmsghdr { - let next_cmsg = - (cmsg_ptr as *mut u8).wrapping_offset(CMSG_ALIGN!(cmsg.cmsg_len) as isize) as *mut cmsghdr; + let next_cmsg = (cmsg_ptr as *mut u8).wrapping_add(CMSG_ALIGN!(cmsg.cmsg_len)) as *mut cmsghdr; if next_cmsg .wrapping_offset(1) .wrapping_sub(msghdr.msg_control as usize) as usize @@ -311,6 +310,8 @@ pub unsafe trait IntoIovec { // Safe because this slice can not have another mutable reference and it's pointer and size are // guaranteed to be valid. unsafe impl<'a> IntoIovec for &'a [u8] { + // Clippy false positive: https://github.com/rust-lang/rust-clippy/issues/3480 + #[cfg_attr(feature = "cargo-clippy", allow(useless_asref))] fn as_ptr(&self) -> *const c_void { self.as_ref().as_ptr() as *const c_void } diff --git a/sys_util/src/syslog.rs b/sys_util/src/syslog.rs index c080041813..be85d2b57a 100644 --- a/sys_util/src/syslog.rs +++ b/sys_util/src/syslog.rs @@ -45,7 +45,7 @@ use libc::{ use getpid; -const SYSLOG_PATH: &'static str = "/dev/log"; +const SYSLOG_PATH: &str = "/dev/log"; /// The priority (i.e. severity) of a syslog message. /// @@ -65,14 +65,14 @@ pub enum Priority { impl fmt::Display for Priority { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &Priority::Emergency => write!(f, "EMERGENCY"), - &Priority::Alert => write!(f, "ALERT"), - &Priority::Critical => write!(f, "CRITICAL"), - &Priority::Error => write!(f, "ERROR"), - &Priority::Warning => write!(f, "WARNING"), - &Priority::Notice => write!(f, "NOTICE"), - &Priority::Info => write!(f, "INFO"), - &Priority::Debug => write!(f, "DEBUG"), + Priority::Emergency => write!(f, "EMERGENCY"), + Priority::Alert => write!(f, "ALERT"), + Priority::Critical => write!(f, "CRITICAL"), + Priority::Error => write!(f, "ERROR"), + Priority::Warning => write!(f, "WARNING"), + Priority::Notice => write!(f, "NOTICE"), + Priority::Info => write!(f, "INFO"), + Priority::Debug => write!(f, "DEBUG"), } } } @@ -417,7 +417,7 @@ fn get_localtime() -> tm { /// # } /// ``` pub fn log(pri: Priority, fac: Facility, file_name: &str, line: u32, args: fmt::Arguments) { - const MONTHS: [&'static str; 12] = [ + const MONTHS: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; @@ -457,11 +457,7 @@ pub fn log(pri: Priority, fac: Facility, file_name: &str, line: u32, args: fmt:: let (res, len) = { let mut buf_cursor = Cursor::new(&mut buf[..]); ( - write!( - &mut buf_cursor, - "[{}:{}:{}] {}\n", - pri, file_name, line, args - ), + writeln!(&mut buf_cursor, "[{}:{}:{}] {}", pri, file_name, line, args), buf_cursor.position() as usize, ) }; diff --git a/sys_util/src/tempdir.rs b/sys_util/src/tempdir.rs index 28f61c3bab..755865c65a 100644 --- a/sys_util/src/tempdir.rs +++ b/sys_util/src/tempdir.rs @@ -60,7 +60,7 @@ impl TempDir { /// will also remove the directory. Calling remove explicitly allows for better error handling. pub fn remove(mut self) -> Result<()> { let path = self.path.take(); - path.map_or(Ok(()), |ref p| fs::remove_dir_all(p))?; + path.map_or(Ok(()), fs::remove_dir_all)?; Ok(()) } diff --git a/usb_util/src/error.rs b/usb_util/src/error.rs index 6ba5421296..e819a52fac 100644 --- a/usb_util/src/error.rs +++ b/usb_util/src/error.rs @@ -27,24 +27,24 @@ pub enum Error { impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &Error::Success(_v) => write!(f, "Success (no error)"), - &Error::IO => write!(f, "Input/output error"), - &Error::InvalidParam => write!(f, "Invalid parameter"), - &Error::Access => write!(f, "Access denied (insufficient permissions)"), - &Error::NoDevice => write!(f, "No such device (it may have been disconnected)"), - &Error::NotFound => write!(f, "Entity not found"), - &Error::Busy => write!(f, "Resource busy"), - &Error::Timeout => write!(f, "Operation timed out"), - &Error::Overflow => write!(f, "Overflow"), - &Error::Pipe => write!(f, "Pipe error"), - &Error::Interrupted => write!(f, "System call interrupted (perhaps due to signal)"), - &Error::NoMem => write!(f, "Insufficient memory"), - &Error::NotSupported => write!( + match *self { + Error::Success(_v) => write!(f, "Success (no error)"), + Error::IO => write!(f, "Input/output error"), + Error::InvalidParam => write!(f, "Invalid parameter"), + Error::Access => write!(f, "Access denied (insufficient permissions)"), + Error::NoDevice => write!(f, "No such device (it may have been disconnected)"), + Error::NotFound => write!(f, "Entity not found"), + Error::Busy => write!(f, "Resource busy"), + Error::Timeout => write!(f, "Operation timed out"), + Error::Overflow => write!(f, "Overflow"), + Error::Pipe => write!(f, "Pipe error"), + Error::Interrupted => write!(f, "System call interrupted (perhaps due to signal)"), + Error::NoMem => write!(f, "Insufficient memory"), + Error::NotSupported => write!( f, "Operation not supported or unimplemented on this platform" ), - &Error::Other => write!(f, "Other error"), + Error::Other => write!(f, "Other error"), } } } diff --git a/usb_util/src/lib.rs b/usb_util/src/lib.rs index a0170f3b89..82d35b5029 100644 --- a/usb_util/src/lib.rs +++ b/usb_util/src/lib.rs @@ -7,6 +7,7 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] +#[cfg_attr(feature = "cargo-clippy", allow(clippy))] mod bindings; extern crate data_model; diff --git a/usb_util/src/libusb_context.rs b/usb_util/src/libusb_context.rs index 016ea2291c..65cd2cc4a7 100644 --- a/usb_util/src/libusb_context.rs +++ b/usb_util/src/libusb_context.rs @@ -191,8 +191,8 @@ impl Iterator for PollFdIter { } self.index += 1; - // Safe because 'current_ptr' is not null. - Some((**current_ptr).clone()) + // Safe because '*current_ptr' is not null. + Some(**current_ptr) } } } diff --git a/vm_control/src/lib.rs b/vm_control/src/lib.rs index deec07de2f..ab9af1d3cc 100644 --- a/vm_control/src/lib.rs +++ b/vm_control/src/lib.rs @@ -41,8 +41,8 @@ pub enum MaybeOwnedFd { impl AsRawFd for MaybeOwnedFd { fn as_raw_fd(&self) -> RawFd { match self { - &MaybeOwnedFd::Owned(ref f) => f.as_raw_fd(), - &MaybeOwnedFd::Borrowed(fd) => fd, + MaybeOwnedFd::Owned(f) => f.as_raw_fd(), + MaybeOwnedFd::Borrowed(fd) => *fd, } } } @@ -135,32 +135,32 @@ impl VmRequest { balloon_host_socket: &UnixDatagram, ) -> VmResponse { *running = true; - match self { - &VmRequest::Exit => { + match *self { + VmRequest::Exit => { *running = false; VmResponse::Ok } - &VmRequest::RegisterIoevent(ref evt, addr, datamatch) => { + VmRequest::RegisterIoevent(ref evt, addr, datamatch) => { match vm.register_ioevent(evt, addr, Datamatch::U32(Some(datamatch))) { Ok(_) => VmResponse::Ok, Err(e) => VmResponse::Err(e), } } - &VmRequest::RegisterIrqfd(ref evt, irq) => match vm.register_irqfd(evt, irq) { + VmRequest::RegisterIrqfd(ref evt, irq) => match vm.register_irqfd(evt, irq) { Ok(_) => VmResponse::Ok, - Err(e) => return VmResponse::Err(e), + Err(e) => VmResponse::Err(e), }, - &VmRequest::RegisterMemory(ref fd, size) => { + VmRequest::RegisterMemory(ref fd, size) => { match register_memory(vm, sys_allocator, fd, size) { Ok((pfn, slot)) => VmResponse::RegisterMemory { pfn, slot }, Err(e) => VmResponse::Err(e), } } - &VmRequest::UnregisterMemory(slot) => match vm.remove_device_memory(slot) { + VmRequest::UnregisterMemory(slot) => match vm.remove_device_memory(slot) { Ok(_) => VmResponse::Ok, Err(e) => VmResponse::Err(e), }, - &VmRequest::BalloonAdjust(num_pages) => { + VmRequest::BalloonAdjust(num_pages) => { let mut buf = [0u8; 4]; // write_i32 can't fail as the buffer is 4 bytes long. (&mut buf[0..]) @@ -171,7 +171,7 @@ impl VmRequest { Err(_) => VmResponse::Err(SysError::last()), } } - &VmRequest::AllocateAndRegisterGpuMemory { + VmRequest::AllocateAndRegisterGpuMemory { width, height, format, diff --git a/x86_64/src/cpuid.rs b/x86_64/src/cpuid.rs index 0cfa32efd4..6d875cb51e 100644 --- a/x86_64/src/cpuid.rs +++ b/x86_64/src/cpuid.rs @@ -19,8 +19,8 @@ pub type Result = result::Result; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::GetSupportedCpusFailed(_) => "GetSupportedCpus ioctl failed", - &Error::SetSupportedCpusFailed(_) => "SetSupportedCpus ioctl failed", + Error::GetSupportedCpusFailed(_) => "GetSupportedCpus ioctl failed", + Error::SetSupportedCpusFailed(_) => "SetSupportedCpus ioctl failed", } } } diff --git a/x86_64/src/interrupts.rs b/x86_64/src/interrupts.rs index 5c469c80d6..bcbb6f6e55 100644 --- a/x86_64/src/interrupts.rs +++ b/x86_64/src/interrupts.rs @@ -24,8 +24,8 @@ pub type Result = result::Result; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::GetLapic(_) => "GetLapic ioctl failed", - &Error::SetLapic(_) => "SetLapic ioctl failed", + Error::GetLapic(_) => "GetLapic ioctl failed", + Error::SetLapic(_) => "SetLapic ioctl failed", } } } diff --git a/x86_64/src/lib.rs b/x86_64/src/lib.rs index 700ba75cde..9862c47c54 100644 --- a/x86_64/src/lib.rs +++ b/x86_64/src/lib.rs @@ -43,6 +43,7 @@ mod msr_index; #[allow(dead_code)] #[allow(non_upper_case_globals)] #[allow(non_camel_case_types)] +#[cfg_attr(feature = "cargo-clippy", allow(clippy))] mod mpspec; // These mpspec types are only data, reading them from data is a safe initialization. unsafe impl data_model::DataInit for mpspec::mpc_bus {} @@ -114,22 +115,22 @@ pub enum Error { impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::ConfigureSystem => "Error configuring the system", - &Error::CloneEventFd(_) => "Unable to clone an EventFd", - &Error::Cmdline(_) => "the given kernel command line was invalid", - &Error::CreateEventFd(_) => "Unable to make an EventFd", - &Error::CreateKvm(_) => "failed to open /dev/kvm", - &Error::CreatePciRoot(_) => "failed to create a PCI root hub", - &Error::CreateSocket(_) => "failed to create socket", - &Error::CreateVcpu(_) => "failed to create VCPU", - &Error::KernelOffsetPastEnd => "The kernel extends past the end of RAM", - &Error::RegisterIrqfd(_) => "Error registering an IrqFd", - &Error::RegisterVsock(_) => "error registering virtual socket device", - &Error::LoadCmdline(_) => "Error Loading command line", - &Error::LoadKernel(_) => "Error Loading Kernel", - &Error::ZeroPageSetup => "Error writing the zero page of guest memory", - &Error::ZeroPagePastRamEnd => "The zero page extends past the end of guest_mem", - &Error::E820Configuration => "Invalid e820 setup params", + Error::ConfigureSystem => "Error configuring the system", + Error::CloneEventFd(_) => "Unable to clone an EventFd", + Error::Cmdline(_) => "the given kernel command line was invalid", + Error::CreateEventFd(_) => "Unable to make an EventFd", + Error::CreateKvm(_) => "failed to open /dev/kvm", + Error::CreatePciRoot(_) => "failed to create a PCI root hub", + Error::CreateSocket(_) => "failed to create socket", + Error::CreateVcpu(_) => "failed to create VCPU", + Error::KernelOffsetPastEnd => "The kernel extends past the end of RAM", + Error::RegisterIrqfd(_) => "Error registering an IrqFd", + Error::RegisterVsock(_) => "error registering virtual socket device", + Error::LoadCmdline(_) => "Error Loading command line", + Error::LoadKernel(_) => "Error Loading Kernel", + Error::ZeroPageSetup => "Error writing the zero page of guest memory", + Error::ZeroPagePastRamEnd => "The zero page extends past the end of guest_mem", + Error::E820Configuration => "Invalid e820 setup params", } } } @@ -462,12 +463,10 @@ impl X8664arch { let mut io_bus = devices::Bus::new(); - let com_evt_1_3 = EventFd::new().map_err(|e| Error::CreateEventFd(e))?; - let com_evt_2_4 = EventFd::new().map_err(|e| Error::CreateEventFd(e))?; + let com_evt_1_3 = EventFd::new().map_err(Error::CreateEventFd)?; + let com_evt_2_4 = EventFd::new().map_err(Error::CreateEventFd)?; let stdio_serial = Arc::new(Mutex::new(devices::Serial::new_out( - com_evt_1_3 - .try_clone() - .map_err(|e| Error::CloneEventFd(e))?, + com_evt_1_3.try_clone().map_err(Error::CloneEventFd)?, Box::new(stdout()), ))); let nul_device = Arc::new(Mutex::new(NoDevice)); @@ -477,9 +476,7 @@ impl X8664arch { io_bus .insert( Arc::new(Mutex::new(devices::Serial::new_sink( - com_evt_2_4 - .try_clone() - .map_err(|e| Error::CloneEventFd(e))?, + com_evt_2_4.try_clone().map_err(Error::CloneEventFd)?, ))), 0x2f8, 0x8, @@ -488,9 +485,7 @@ impl X8664arch { io_bus .insert( Arc::new(Mutex::new(devices::Serial::new_sink( - com_evt_1_3 - .try_clone() - .map_err(|e| Error::CloneEventFd(e))?, + com_evt_1_3.try_clone().map_err(Error::CloneEventFd)?, ))), 0x3e8, 0x8, @@ -499,9 +494,7 @@ impl X8664arch { io_bus .insert( Arc::new(Mutex::new(devices::Serial::new_sink( - com_evt_2_4 - .try_clone() - .map_err(|e| Error::CloneEventFd(e))?, + com_evt_2_4.try_clone().map_err(Error::CloneEventFd)?, ))), 0x2e8, 0x8, @@ -513,7 +506,7 @@ impl X8664arch { io_bus .insert( Arc::new(Mutex::new(devices::I8042Device::new( - exit_evt.try_clone().map_err(|e| Error::CloneEventFd(e))?, + exit_evt.try_clone().map_err(Error::CloneEventFd)?, ))), 0x061, 0x4, diff --git a/x86_64/src/mptable.rs b/x86_64/src/mptable.rs index b7842b03e6..1421c2c407 100644 --- a/x86_64/src/mptable.rs +++ b/x86_64/src/mptable.rs @@ -43,16 +43,16 @@ pub enum Error { impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::NotEnoughMemory => "There was too little guest memory to store the MP table", - &Error::AddressOverflow => "The MP table has too little address space to be stored", - &Error::Clear => "Failure while zeroing out the memory for the MP table", - &Error::WriteMpfIntel => "Failure to write the MP floating pointer", - &Error::WriteMpcCpu => "Failure to write MP CPU entry", - &Error::WriteMpcIoapic => "Failure to write MP ioapic entry", - &Error::WriteMpcBus => "Failure to write MP bus entry", - &Error::WriteMpcIntsrc => "Failure to write MP interrupt source entry", - &Error::WriteMpcLintsrc => "Failure to write MP local interrupt source entry", - &Error::WriteMpcTable => "Failure to write MP table header", + Error::NotEnoughMemory => "There was too little guest memory to store the MP table", + Error::AddressOverflow => "The MP table has too little address space to be stored", + Error::Clear => "Failure while zeroing out the memory for the MP table", + Error::WriteMpfIntel => "Failure to write the MP floating pointer", + Error::WriteMpcCpu => "Failure to write MP CPU entry", + Error::WriteMpcIoapic => "Failure to write MP ioapic entry", + Error::WriteMpcBus => "Failure to write MP bus entry", + Error::WriteMpcIntsrc => "Failure to write MP interrupt source entry", + Error::WriteMpcLintsrc => "Failure to write MP local interrupt source entry", + Error::WriteMpcTable => "Failure to write MP table header", } } } diff --git a/x86_64/src/regs.rs b/x86_64/src/regs.rs index 977e19fd68..3dd4754352 100644 --- a/x86_64/src/regs.rs +++ b/x86_64/src/regs.rs @@ -44,16 +44,16 @@ pub type Result = result::Result; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::MsrIoctlFailed(_) => "Setting up msrs failed", - &Error::FpuIoctlFailed(_) => "Failed to configure the FPU", - &Error::GetSRegsIoctlFailed(_) => "Failed to get sregs for this cpu", - &Error::SettingRegistersIoctl(_) => "Failed to set base registers for this cpu", - &Error::SetSRegsIoctlFailed(_) => "Failed to set sregs for this cpu", - &Error::WriteGDTFailure => "Writing the GDT to RAM failed", - &Error::WriteIDTFailure => "Writing the IDT to RAM failed", - &Error::WritePML4Address => "Writing PML4 to RAM failed", - &Error::WritePDPTEAddress => "Writing PDPTE to RAM failed", - &Error::WritePDEAddress => "Writing PDE to RAM failed", + Error::MsrIoctlFailed(_) => "Setting up msrs failed", + Error::FpuIoctlFailed(_) => "Failed to configure the FPU", + Error::GetSRegsIoctlFailed(_) => "Failed to get sregs for this cpu", + Error::SettingRegistersIoctl(_) => "Failed to set base registers for this cpu", + Error::SetSRegsIoctlFailed(_) => "Failed to set sregs for this cpu", + Error::WriteGDTFailure => "Writing the GDT to RAM failed", + Error::WriteIDTFailure => "Writing the IDT to RAM failed", + Error::WritePML4Address => "Writing PML4 to RAM failed", + Error::WritePDPTEAddress => "Writing PDPTE to RAM failed", + Error::WritePDEAddress => "Writing PDE to RAM failed", } } }