diff options
43 files changed, 804 insertions, 321 deletions
diff --git a/arch/src/lib.rs b/arch/src/lib.rs index 8a9c2d8..74545a5 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -120,26 +120,24 @@ impl fmt::Display for DeviceRegistrationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { DeviceRegistrationError::AllocateIoAddrs(e) => { - write!(f, "Allocating IO addresses: {:?}", e) + write!(f, "Allocating IO addresses: {}", e) } DeviceRegistrationError::AllocateIrq => write!(f, "Allocating IRQ number"), DeviceRegistrationError::CreateMmioDevice(e) => { - write!(f, "failed to create mmio device: {:?}", e) + write!(f, "failed to create mmio device: {}", e) } DeviceRegistrationError::Cmdline(e) => { write!(f, "unable to add device to kernel command line: {}", e) } DeviceRegistrationError::EventFdCreate(e) => { - write!(f, "failed to create eventfd: {:?}", e) - } - DeviceRegistrationError::MmioInsert(e) => { - write!(f, "failed to add to mmio bus: {:?}", e) + write!(f, "failed to create eventfd: {}", e) } + DeviceRegistrationError::MmioInsert(e) => write!(f, "failed to add to mmio bus: {}", e), DeviceRegistrationError::RegisterIoevent(e) => { - write!(f, "failed to register ioevent to VM: {:?}", e) + write!(f, "failed to register ioevent to VM: {}", e) } DeviceRegistrationError::RegisterIrqfd(e) => { - write!(f, "failed to register irq eventfd to VM: {:?}", e) + write!(f, "failed to register irq eventfd to VM: {}", e) } DeviceRegistrationError::ProxyDeviceCreation(e) => { write!(f, "failed to create proxy device: {}", e) @@ -223,14 +221,12 @@ pub enum LoadImageError { impl fmt::Display for LoadImageError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::LoadImageError::*; + match self { - LoadImageError::Seek(e) => write!(f, "Seek failed: {:?}", e), - LoadImageError::ImageSizeTooLarge(size) => { - write!(f, "Image size too large: {:?}", size) - } - LoadImageError::ReadToMemory(e) => { - write!(f, "Reading image into memory failed: {:?}", e) - } + Seek(e) => write!(f, "Seek failed: {}", e), + ImageSizeTooLarge(size) => write!(f, "Image size too large: {}", size), + ReadToMemory(e) => write!(f, "Reading image into memory failed: {}", e), } } } diff --git a/devices/src/bus.rs b/devices/src/bus.rs index 1c21661..1b3481b 100644 --- a/devices/src/bus.rs +++ b/devices/src/bus.rs @@ -6,6 +6,7 @@ use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use std::collections::btree_map::BTreeMap; +use std::fmt::{self, Display}; use std::result; use std::sync::Arc; @@ -42,6 +43,16 @@ pub enum Error { Overlap, } +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + Overlap => write!(f, "new device overlaps with an old device"), + } + } +} + pub type Result<T> = result::Result<T, Error>; /// Holds a base and length representing the address space occupied by a `BusDevice`. diff --git a/devices/src/i8042.rs b/devices/src/i8042.rs index 0d0c31d..5e35a5a 100644 --- a/devices/src/i8042.rs +++ b/devices/src/i8042.rs @@ -39,7 +39,7 @@ impl BusDevice for I8042Device { fn write(&mut self, offset: u64, data: &[u8]) { if data.len() == 1 && data[0] == 0xfe && offset == 3 { if let Err(e) = self.reset_evt.write(1) { - error!("failed to trigger i8042 reset event: {:?}", e); + error!("failed to trigger i8042 reset event: {}", e); } } } diff --git a/devices/src/pci/ac97_bus_master.rs b/devices/src/pci/ac97_bus_master.rs index 190fdce..b67450e 100644 --- a/devices/src/pci/ac97_bus_master.rs +++ b/devices/src/pci/ac97_bus_master.rs @@ -82,17 +82,15 @@ impl Error for PlaybackError {} impl Display for PlaybackError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::PlaybackError::*; + match self { - PlaybackError::ReadingGuestBufferAddress(e) => { - write!(f, "Failed to get the address of the audio buffer: {:?}.", e) - } - PlaybackError::ReadingGuestSamples(e) => { - write!(f, "Failed to read samples from guest memory: {:?}.", e) - } - PlaybackError::StreamError(e) => { - write!(f, "Failed to get a buffer from the stream: {:?}", e) + ReadingGuestBufferAddress(e) => { + write!(f, "Failed to get the address of the audio buffer: {}.", e) } - PlaybackError::WritingOutput(e) => write!(f, "Failed to write audio output: {:?}.", e), + ReadingGuestSamples(e) => write!(f, "Failed to read samples from guest memory: {}.", e), + StreamError(e) => write!(f, "Failed to get a buffer from the stream: {}", e), + WritingOutput(e) => write!(f, "Failed to write audio output: {}.", e), } } } @@ -151,8 +149,8 @@ impl Ac97BusMaster { loop { if let Err(e) = irq_resample_evt.read() { error!( - "Failed to read the irq event from the resample thread: {:?}.", - e + "Failed to read the irq event from the resample thread: {}.", + e, ); break; } @@ -163,7 +161,7 @@ impl Ac97BusMaster { if regs.func_regs(Ac97Function::Output).sr & int_mask != 0 { if let Some(irq_evt) = regs.irq_evt.as_ref() { if let Err(e) = irq_evt.write(1) { - error!("Failed to set the irq from the resample thread: {:?}.", e); + error!("Failed to set the irq from the resample thread: {}.", e); break; } } @@ -440,7 +438,7 @@ impl Ac97BusMaster { if let Err(e) = audio_out_thread(thread_regs, thread_mem, &thread_run, output_stream) { - error!("Playback error: {:?}", e); + error!("Playback error: {}", e); } thread_run.store(false, Ordering::Relaxed); })); diff --git a/devices/src/pci/pci_device.rs b/devices/src/pci/pci_device.rs index 5ccdfef..b27dc47 100644 --- a/devices/src/pci/pci_device.rs +++ b/devices/src/pci/pci_device.rs @@ -5,6 +5,7 @@ use byteorder::{ByteOrder, LittleEndian}; use std; +use std::fmt::{self, Display}; use std::os::unix::io::RawFd; use kvm::Datamatch; @@ -24,6 +25,19 @@ pub enum Error { } pub type Result<T> = std::result::Result<T, Error>; +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + IoAllocationFailed(size) => { + write!(f, "failed to allocate space for an IO BAR, size={}", size) + } + IoRegistrationFailed(addr) => write!(f, "failed to register an IO BAR, addr={}", addr), + } + } +} + pub trait PciDevice: Send { /// Returns a label suitable for debug output. fn debug_label(&self) -> String; diff --git a/devices/src/pit.rs b/devices/src/pit.rs index aa8161f..c01888c 100644 --- a/devices/src/pit.rs +++ b/devices/src/pit.rs @@ -161,15 +161,17 @@ pub enum PitError { impl fmt::Display for PitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::PitError::*; + match self { - PitError::TimerFdCreateError(e) => { - write!(f, "failed to create pit counter due to timer fd: {:?}", e) + TimerFdCreateError(e) => { + write!(f, "failed to create pit counter due to timer fd: {}", e) } - PitError::CreatePollContext(e) => write!(f, "failed to create poll context: {:?}", e), - PitError::PollError(err) => write!(f, "failed to poll events: {:?}", err), - PitError::SpawnThread(err) => write!(f, "failed to spawn thread: {:?}", err), - PitError::CreateEventFd(err) => write!(f, "failed to create event fd: {:?}", err), - PitError::CloneEventFd(err) => write!(f, "failed to clone event fd: {:?}", err), + CreatePollContext(e) => write!(f, "failed to create poll context: {}", e), + PollError(err) => write!(f, "failed to poll events: {}", err), + SpawnThread(err) => write!(f, "failed to spawn thread: {}", err), + CreateEventFd(err) => write!(f, "failed to create event fd: {}", err), + CloneEventFd(err) => write!(f, "failed to clone event fd: {}", err), } } } @@ -195,7 +197,7 @@ pub struct Pit { impl Drop for Pit { fn drop(&mut self) { if let Err(e) = self.kill_evt.write(1) { - error!("failed to kill PIT worker threads: {:?}", e); + error!("failed to kill PIT worker threads: {}", e); return; } if let Some(thread) = self.worker_thread.take() { diff --git a/devices/src/proxy.rs b/devices/src/proxy.rs index 907f33c..4bc3405 100644 --- a/devices/src/proxy.rs +++ b/devices/src/proxy.rs @@ -72,7 +72,7 @@ fn child_proc(sock: UnixDatagram, device: &mut BusDevice) { let cmd = match sock.recv() { Ok(cmd) => cmd, Err(err) => { - error!("child device process failed recv: {:?}", err); + error!("child device process failed recv: {}", err); break; } }; @@ -108,7 +108,7 @@ fn child_proc(sock: UnixDatagram, device: &mut BusDevice) { } }; if let Err(e) = res { - error!("child device process failed send: {:?}", e); + error!("child device process failed send: {}", e); } } } @@ -175,15 +175,15 @@ impl ProxyDevice { let res = self.sock.send(&cmd); if let Err(e) = res { error!( - "failed write to child device process {}: {:?}", - self.debug_label, e + "failed write to child device process {}: {}", + self.debug_label, e, ); }; match self.sock.recv() { Err(e) => { error!( - "failed read from child device process {}: {:?}", - self.debug_label, e + "failed read from child device process {}: {}", + self.debug_label, e, ); None } diff --git a/devices/src/serial.rs b/devices/src/serial.rs index b2a5651..c4c5a8b 100644 --- a/devices/src/serial.rs +++ b/devices/src/serial.rs @@ -195,7 +195,7 @@ impl BusDevice for Serial { } if let Err(e) = self.handle_write(offset as u8, data[0]) { - error!("serial failed write: {:?}", e); + error!("serial failed write: {}", e); } } diff --git a/devices/src/virtio/balloon.rs b/devices/src/virtio/balloon.rs index d67c532..1dfb72c 100644 --- a/devices/src/virtio/balloon.rs +++ b/devices/src/virtio/balloon.rs @@ -4,6 +4,7 @@ use std; use std::cmp; +use std::fmt::{self, Display}; use std::io::Write; use std::mem; use std::os::unix::io::{AsRawFd, RawFd}; @@ -29,6 +30,17 @@ pub enum BalloonError { } pub type Result<T> = std::result::Result<T, BalloonError>; +impl Display for BalloonError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::BalloonError::*; + + match self { + NotEnoughPages => write!(f, "not enough pages"), + WritingConfigEvent(e) => write!(f, "failed to write config event: {}", e), + } + } +} + // Balloon has three virt IO queues: Inflate, Deflate, and Stats. // Stats is currently not used. const QUEUE_SIZE: u16 = 128; @@ -92,7 +104,7 @@ impl Worker { .remove_range(guest_address, 1 << VIRTIO_BALLOON_PFN_SHIFT) .is_err() { - warn!("Marking pages unused failed {:?}", guest_address); + warn!("Marking pages unused failed; addr={}", guest_address); continue; } } @@ -148,7 +160,7 @@ impl Worker { { Ok(pc) => pc, Err(e) => { - error!("failed creating PollContext: {:?}", e); + error!("failed creating PollContext: {}", e); return; } }; @@ -157,7 +169,7 @@ impl Worker { let events = match poll_ctx.wait() { Ok(v) => v, Err(e) => { - error!("failed polling for events: {:?}", e); + error!("failed polling for events: {}", e); break; } }; @@ -167,14 +179,14 @@ impl Worker { match event.token() { Token::Inflate => { if let Err(e) = inflate_queue_evt.read() { - error!("failed reading inflate queue EventFd: {:?}", e); + error!("failed reading inflate queue EventFd: {}", e); break 'poll; } needs_interrupt |= self.process_inflate_deflate(true); } Token::Deflate => { if let Err(e) = deflate_queue_evt.read() { - error!("failed reading deflate queue EventFd: {:?}", e); + error!("failed reading deflate queue EventFd: {}", e); break 'poll; } needs_interrupt |= self.process_inflate_deflate(false); @@ -321,7 +333,7 @@ impl VirtioDevice for Balloon { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("failed to create kill EventFd pair: {:?}", e); + error!("failed to create kill EventFd pair: {}", e); return; } }; diff --git a/devices/src/virtio/block.rs b/devices/src/virtio/block.rs index 223fe1f..9dcf828 100644 --- a/devices/src/virtio/block.rs +++ b/devices/src/virtio/block.rs @@ -3,6 +3,7 @@ // found in the LICENSE file. use std::cmp; +use std::fmt::{self, Display}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::mem::{size_of, size_of_val}; use std::os::unix::io::{AsRawFd, RawFd}; @@ -128,6 +129,21 @@ enum RequestType { Unsupported(u32), } +impl Display for RequestType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::RequestType::*; + + match self { + In => write!(f, "in"), + Out => write!(f, "out"), + Flush => write!(f, "flush"), + Discard => write!(f, "discard"), + WriteZeroes => write!(f, "write zeroes"), + Unsupported(n) => write!(f, "unsupported({})", n), + } + } +} + #[derive(Debug)] enum ParseError { /// Guest gave us bad memory addresses @@ -144,6 +160,21 @@ enum ParseError { DescriptorLengthTooSmall, } +impl Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::ParseError::*; + + match self { + GuestMemory(e) => write!(f, "bad guest memory address: {}", e), + CheckedOffset(addr, offset) => write!(f, "{}+{} would overflow a usize", addr, offset), + UnexpectedWriteOnlyDescriptor => write!(f, "unexpected write-only descriptor"), + UnexpectedReadOnlyDescriptor => write!(f, "unexpected read-only descriptor"), + DescriptorChainTooShort => write!(f, "descriptor chain too short"), + DescriptorLengthTooSmall => write!(f, "descriptor length too small"), + } + } +} + fn request_type( mem: &GuestMemory, desc_addr: GuestAddress, @@ -214,6 +245,61 @@ enum ExecuteError { Unsupported(u32), } +impl Display for ExecuteError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::ExecuteError::*; + + match self { + Flush(e) => write!(f, "failed to flush: {}", e), + Read { + addr, + length, + sector, + guestmemerr, + } => write!( + f, + "failed to read {} bytes from address {} sector {}: {}", + length, addr, sector, guestmemerr, + ), + Seek { ioerr, sector } => write!(f, "failed to seek to sector {}: {}", sector, ioerr), + TimerFd(e) => write!(f, "{}", e), + Write { + addr, + length, + sector, + guestmemerr, + } => write!( + f, + "failed to write {} bytes to address {} sector {}: {}", + length, addr, sector, guestmemerr, + ), + DiscardWriteZeroes { + ioerr: Some(ioerr), + sector, + num_sectors, + flags, + } => write!( + f, + "failed to perform discard or write zeroes; sector={} num_sectors={} flags={}; {}", + sector, num_sectors, flags, ioerr, + ), + DiscardWriteZeroes { + ioerr: None, + sector, + num_sectors, + flags, + } => write!( + f, + "failed to perform discard or write zeroes; sector={} num_sectors={} flags={}", + sector, num_sectors, flags, + ), + ReadOnly { request_type } => write!(f, "read only; request_type={}", request_type), + OutOfRange => write!(f, "out of range"), + Unsupported(n) => write!(f, "unsupported ({})", n), + } + } +} + impl ExecuteError { fn status(&self) -> u8 { match self { @@ -551,7 +637,7 @@ impl<T: DiskFile> Worker<T> { VIRTIO_BLK_S_OK } Err(e) => { - error!("failed executing disk request: {:?}", e); + error!("failed executing disk request: {}", e); len = 1; // 1 byte for the status e.status() } @@ -563,7 +649,7 @@ impl<T: DiskFile> Worker<T> { .unwrap(); } Err(e) => { - error!("failed processing available descriptor chain: {:?}", e); + error!("failed processing available descriptor chain: {}", e); len = 0; } } @@ -622,7 +708,7 @@ impl<T: DiskFile> Worker<T> { let mut flush_timer = match TimerFd::new() { Ok(t) => t, Err(e) => { - error!("Failed to create the flush timer: {:?}", e); + error!("Failed to create the flush timer: {}", e); return; } }; @@ -642,7 +728,7 @@ impl<T: DiskFile> Worker<T> { { Ok(pc) => pc, Err(e) => { - error!("failed creating PollContext: {:?}", e); + error!("failed creating PollContext: {}", e); return; } }; @@ -651,7 +737,7 @@ impl<T: DiskFile> Worker<T> { let events = match poll_ctx.wait() { Ok(v) => v, Err(e) => { - error!("failed polling for events: {:?}", e); + error!("failed polling for events: {}", e); break; } }; @@ -662,17 +748,17 @@ impl<T: DiskFile> Worker<T> { match event.token() { Token::FlushTimer => { if let Err(e) = self.disk_image.flush() { - error!("Failed to flush the disk: {:?}", e); + error!("Failed to flush the disk: {}", e); break 'poll; } if let Err(e) = flush_timer.wait() { - error!("Failed to clear flush timer: {:?}", e); + error!("Failed to clear flush timer: {}", e); break 'poll; } } Token::QueueAvailable => { if let Err(e) = queue_evt.read() { - error!("failed reading queue EventFd: {:?}", e); + error!("failed reading queue EventFd: {}", e); break 'poll; } needs_interrupt |= @@ -682,7 +768,7 @@ impl<T: DiskFile> Worker<T> { let req = match control_socket.recv() { Ok(req) => req, Err(e) => { - error!("control socket failed recv: {:?}", e); + error!("control socket failed recv: {}", e); break 'poll; } }; @@ -703,7 +789,7 @@ impl<T: DiskFile> Worker<T> { }; if let Err(e) = control_socket.send(&resp) { - error!("control socket failed send: {:?}", e); + error!("control socket failed send: {}", e); break 'poll; } } @@ -860,7 +946,7 @@ impl<T: 'static + AsRawFd + DiskFile + Send> VirtioDevice for Block<T> { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("failed creating kill EventFd pair: {:?}", e); + error!("failed creating kill EventFd pair: {}", e); return; } }; diff --git a/devices/src/virtio/gpu/backend.rs b/devices/src/virtio/gpu/backend.rs index b8f98e4..fad8223 100644 --- a/devices/src/virtio/gpu/backend.rs +++ b/devices/src/virtio/gpu/backend.rs @@ -258,7 +258,7 @@ impl VirglResource for BackedBuffer { Some(import_id) } Err(e) => { - error!("failed to import dmabuf for display: {:?}", e); + error!("failed to import dmabuf for display: {}", e); None } } @@ -292,13 +292,13 @@ impl VirglResource for BackedBuffer { .map(|&(addr, len)| mem.get_slice(addr.offset(), len as u64).unwrap_or_default()), ); if let Err(e) = res { - error!("failed to write to resource from guest memory: {:?}", e) + error!("failed to write to resource from guest memory: {}", e) } } fn read_to_volatile(&mut self, x: u32, y: u32, width: u32, height: u32, dst: VolatileSlice) { if let Err(e) = self.buffer.read_to_volatile(x, y, width, height, 0, dst) { - error!("failed to copy resource: {:?}", e); + error!("failed to copy resource: {}", e); } } } @@ -356,7 +356,7 @@ impl Backend { let request = match resource_bridge.recv() { Ok(msg) => msg, Err(e) => { - error!("error receiving resource bridge request: {:?}", e); + error!("error receiving resource bridge request: {}", e); return; } }; @@ -372,7 +372,7 @@ impl Backend { }; if let Err(e) = resource_bridge.send(&response) { - error!("error sending resource bridge request: {:?}", e); + error!("error sending resource bridge request: {}", e); } } @@ -442,7 +442,7 @@ impl Backend { if self.scanout_surface.is_none() { match display.create_surface(None, DEFAULT_WIDTH, DEFAULT_HEIGHT) { Ok(surface) => self.scanout_surface = Some(surface), - Err(e) => error!("failed to create display surface: {:?}", e), + Err(e) => error!("failed to create display surface: {}", e), } } GpuResponse::OkNoData @@ -591,7 +591,7 @@ impl Backend { ) { Ok(surface) => self.cursor_surface = Some(surface), Err(e) => { - error!("failed to create cursor surface: {:?}", e); + error!("failed to create cursor surface: {}", e); return GpuResponse::ErrUnspec; } } @@ -613,7 +613,7 @@ impl Backend { if let Err(e) = buffer.read_to_volatile(0, 0, buffer.width(), buffer.height(), 0, fb) { - error!("failed to copy resource to cursor: {:?}", e); + error!("failed to copy resource to cursor: {}", e); return GpuResponse::ErrInvalidParameter; } } diff --git a/devices/src/virtio/gpu/mod.rs b/devices/src/virtio/gpu/mod.rs index 8da15f5..c8d4dcd 100644 --- a/devices/src/virtio/gpu/mod.rs +++ b/devices/src/virtio/gpu/mod.rs @@ -365,14 +365,14 @@ impl Frontend { Ok(data_mem) => { resp = self.process_gpu_command(mem, cmd, Some(data_mem)) } - Err(e) => debug!("ctrl queue invalid data descriptor: {:?}", e), + Err(e) => debug!("ctrl queue invalid data descriptor: {}", e), } } None => resp = self.process_gpu_command(mem, cmd, None), } gpu_cmd = Some(cmd); } - Err(e) => debug!("ctrl queue decode error: {:?}", e), + Err(e) => debug!("ctrl queue decode error: {}", e), } } if resp.is_err() { @@ -402,7 +402,7 @@ impl Frontend { // fence is complete. match resp.encode(flags, fence_id, ctx_id, ret_desc_mem) { Ok(l) => len = l, - Err(e) => debug!("ctrl queue response encode error: {:?}", e), + Err(e) => debug!("ctrl queue response encode error: {}", e), } if flags & VIRTIO_GPU_FLAG_FENCE != 0 { @@ -505,14 +505,14 @@ impl Worker { { Ok(pc) => pc, Err(e) => { - error!("failed creating PollContext: {:?}", e); + error!("failed creating PollContext: {}", e); return; } }; if let Some(ref resource_bridge) = self.resource_bridge { if let Err(e) = poll_ctx.add(resource_bridge, Token::ResourceBridge) { - error!("failed to add resource bridge to PollContext: {:?}", e); + error!("failed to add resource bridge to PollContext: {}", e); } } @@ -527,7 +527,7 @@ impl Worker { let events = match poll_ctx.wait_timeout(duration) { Ok(v) => v, Err(e) => { - error!("failed polling for events: {:?}", e); + error!("failed polling for events: {}", e); break; } }; @@ -722,7 +722,7 @@ impl VirtioDevice for Gpu { let exit_evt = match self.exit_evt.try_clone() { Ok(e) => e, Err(e) => { - error!("error cloning exit eventfd: {:?}", e); + error!("error cloning exit eventfd: {}", e); return; } }; @@ -730,7 +730,7 @@ impl VirtioDevice for Gpu { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("error creating kill EventFd pair: {:?}", e); + error!("error creating kill EventFd pair: {}", e); return; } }; @@ -750,8 +750,8 @@ impl VirtioDevice for Gpu { const UNDESIRED_CARDS: &[&str] = &["vgem", "pvr"]; let drm_card = match gpu_buffer::rendernode::open_device(UNDESIRED_CARDS) { Ok(f) => f, - Err(e) => { - error!("failed to open card: {:?}", e); + Err(()) => { + error!("failed to open card"); return; } }; @@ -767,7 +767,7 @@ impl VirtioDevice for Gpu { let display = match GpuDisplay::new(socket_path) { Ok(c) => c, Err(e) => { - error!("failed to open display: {:?}", e); + error!("failed to open display: {}", e); return; } }; diff --git a/devices/src/virtio/gpu/protocol.rs b/devices/src/virtio/gpu/protocol.rs index 8ed6b02..f0dcad8 100644 --- a/devices/src/virtio/gpu/protocol.rs +++ b/devices/src/virtio/gpu/protocol.rs @@ -2,7 +2,7 @@ #![allow(non_camel_case_types)] use std::cmp::min; -use std::fmt; +use std::fmt::{self, Display}; use std::marker::PhantomData; use std::mem::{size_of, size_of_val}; use std::str::from_utf8; @@ -493,6 +493,21 @@ pub enum GpuCommandDecodeError { InvalidType(u32), } +impl Display for GpuCommandDecodeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::GpuCommandDecodeError::*; + + match self { + Memory(e) => write!( + f, + "command referenced an inaccessible area of memory: {}", + e, + ), + InvalidType(n) => write!(f, "invalid command type ({})", n), + } + } +} + impl From<VolatileMemoryError> for GpuCommandDecodeError { fn from(e: VolatileMemoryError) -> GpuCommandDecodeError { GpuCommandDecodeError::Memory(e) @@ -625,6 +640,22 @@ pub enum GpuResponseEncodeError { TooManyPlanes(usize), } +impl Display for GpuResponseEncodeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::GpuResponseEncodeError::*; + + match self { + Memory(e) => write!( + f, + "response was encoded to an inaccessible area of memory: {}", + e, + ), + TooManyDisplays(n) => write!(f, "{} is more displays than are valid", n), + TooManyPlanes(n) => write!(f, "{} is more planes than are valid", n), + } + } +} + impl From<VolatileMemoryError> for GpuResponseEncodeError { fn from(e: VolatileMemoryError) -> GpuResponseEncodeError { GpuResponseEncodeError::Memory(e) diff --git a/devices/src/virtio/input/mod.rs b/devices/src/virtio/input/mod.rs index 82c15c0..22ef168 100644 --- a/devices/src/virtio/input/mod.rs +++ b/devices/src/virtio/input/mod.rs @@ -19,6 +19,7 @@ use self::event_source::{input_event, EvdevEventSource, EventSource, SocketEvent use super::{Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_INPUT}; use std::cmp::min; use std::collections::BTreeMap; +use std::fmt::{self, Display}; use std::io::Read; use std::io::Write; use std::mem::size_of; @@ -53,6 +54,28 @@ pub enum InputError { } pub type Result<T> = std::result::Result<T, InputError>; +impl Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::InputError::*; + + match self { + EventsWriteError(e) => write!(f, "failed to write events to the source: {}", e), + EventsReadError(e) => write!(f, "failed to read events from the source: {}", e), + EvdevIdError(e) => write!(f, "failed to get id of event device: {}", e), + EvdevNameError(e) => write!(f, "failed to get name of event device: {}", e), + EvdevSerialError(e) => write!(f, "failed to get serial name of event device: {}", e), + EvdevPropertiesError(e) => write!(f, "failed to get properties of event device: {}", e), + EvdevEventTypesError(e) => { + write!(f, "failed to get event types supported by device: {}", e) + } + EvdevAbsInfoError(e) => { + write!(f, "failed to get axis information of event device: {}", e) + } + EvdevGrabError(e) => write!(f, "failed to grab event device: {}", e), + } + } +} + #[derive(Copy, Clone, Default, Debug)] #[repr(C)] pub struct virtio_input_device_ids { @@ -405,7 +428,7 @@ impl<T: EventSource> Worker<T> { // Read is guaranteed to succeed here, so the only possible failure would be // writing outside the guest memory region, which would mean the address and // length given in the queue descriptor are wrong. - panic!("failed reading events into guest memory: {:?}", e); + panic!("failed reading events into guest memory: {}", e); } used_desc_heads[used_count] = (avail_desc.index, len as u32); used_count += 1; @@ -457,7 +480,7 @@ impl<T: EventSource> Worker<T> { kill_evt: EventFd, ) { if let Err(e) = self.event_source.init() { - error!("failed initializing event source: {:?}", e); + error!("failed initializing event source: {}", e); return; } @@ -490,7 +513,7 @@ impl<T: EventSource> Worker<T> { { Ok(poll_ctx) => poll_ctx, Err(e) => { - error!("failed creating PollContext: {:?}", e); + error!("failed creating PollContext: {}", e); return; } }; @@ -499,7 +522,7 @@ impl<T: EventSource> Worker<T> { let poll_events = match poll_ctx.wait() { Ok(poll_events) => poll_events, Err(e) => { - error!("failed polling for events: {:?}", e); + error!("failed polling for events: {}", e); break; } }; @@ -509,23 +532,23 @@ impl<T: EventSource> Worker<T> { match poll_event.token() { Token::EventQAvailable => { if let Err(e) = event_queue_evt_fd.read() { - error!("failed reading event queue EventFd: {:?}", e); + error!("failed reading event queue EventFd: {}", e); break 'poll; } needs_interrupt |= self.send_events(); } Token::StatusQAvailable => { if let Err(e) = status_queue_evt_fd.read() { - error!("failed reading status queue EventFd: {:?}", e); + error!("failed reading status queue EventFd: {}", e); break 'poll; } match self.process_status_queue() { Ok(b) => needs_interrupt |= b, - Err(e) => error!("failed processing status events: {:?}", e), + Err(e) => error!("failed processing status events: {}", e), } } Token::InputEventsAvailable => match self.event_source.receive_events() { - Err(e) => error!("error receiving events: {:?}", e), + Err(e) => error!("error receiving events: {}", e), Ok(_cnt) => needs_interrupt |= self.send_events(), }, Token::InterruptResample => { @@ -546,7 +569,7 @@ impl<T: EventSource> Worker<T> { } if let Err(e) = self.event_source.finalize() { - error!("failed finalizing event source: {:?}", e); + error!("failed finalizing event source: {}", e); return; } } @@ -612,7 +635,7 @@ where let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("failed to create kill EventFd pair: {:?}", e); + error!("failed to create kill EventFd pair: {}", e); return; } }; diff --git a/devices/src/virtio/net.rs b/devices/src/virtio/net.rs index 84249ab..088c2b8 100644 --- a/devices/src/virtio/net.rs +++ b/devices/src/virtio/net.rs @@ -3,6 +3,7 @@ // found in the LICENSE file. use std::cmp; +use std::fmt::{self, Display}; use std::mem; use std::net::Ipv4Addr; use std::os::unix::io::{AsRawFd, RawFd}; @@ -53,6 +54,26 @@ pub enum NetError { PollError(SysError), } +impl Display for NetError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::NetError::*; + + match self { + CreateKillEventFd(e) => write!(f, "failed to create kill eventfd: {}", e), + CreatePollContext(e) => write!(f, "failed to create poll context: {}", e), + CloneKillEventFd(e) => write!(f, "failed to clone kill eventfd: {}", e), + TapOpen(e) => write!(f, "failed to open tap device: {}", e), + TapSetIp(e) => write!(f, "failed to set tap IP: {}", e), + TapSetNetmask(e) => write!(f, "failed to set tap netmask: {}", e), + TapSetMacAddress(e) => write!(f, "failed to set tap mac address: {}", e), + TapSetOffload(e) => write!(f, "failed to set tap interface offload flags: {}", e), + TapSetVnetHdrSize(e) => write!(f, "failed to set vnet header size: {}", e), + TapEnable(e) => write!(f, "failed to enable tap interface: {}", e), + PollError(e) => write!(f, "error while polling for events: {}", e), + } + } +} + struct Worker<T: TapT> { mem: GuestMemory, rx_queue: Queue, @@ -110,7 +131,7 @@ where write_count += sz; } Err(e) => { - warn!("net: rx: failed to write slice: {:?}", e); + warn!("net: rx: failed to write slice: {}", e); break; } }; @@ -156,7 +177,7 @@ where // The tap device is nonblocking, so any error aside from EAGAIN is // unexpected. if e.raw_os_error().unwrap() != EAGAIN { - warn!("net: rx: failed to read tap: {:?}", e); + warn!("net: rx: failed to read tap: {}", e); } break; } @@ -188,7 +209,7 @@ where read_count += sz; } Err(e) => { - warn!("net: tx: failed to read slice: {:?}", e); + warn!("net: tx: failed to read slice: {}", e); break; } } @@ -199,7 +220,7 @@ where match write_result { Ok(_) => {} Err(e) => { - warn!("net: tx: error failed to write to tap: {:?}", e); + warn!("net: tx: error failed to write to tap: {}", e); } }; @@ -263,7 +284,7 @@ where } Token::RxQueue => { if let Err(e) = rx_queue_evt.read() { - error!("net: error reading rx queue EventFd: {:?}", e); + error!("net: error reading rx queue EventFd: {}", e); break 'poll; } // There should be a buffer available now to receive the frame into. @@ -273,7 +294,7 @@ where } Token::TxQueue => { if let Err(e) = tx_queue_evt.read() { - error!("net: error reading tx queue EventFd: {:?}", e); + error!("net: error reading tx queue EventFd: {}", e); break 'poll; } self.process_tx(); @@ -453,7 +474,7 @@ where let tx_queue_evt = queue_evts.remove(0); let result = worker.run(rx_queue_evt, tx_queue_evt, kill_evt); if let Err(e) = result { - error!("net worker thread exited with error: {:?}", e); + error!("net worker thread exited with error: {}", e); } }); diff --git a/devices/src/virtio/p9.rs b/devices/src/virtio/p9.rs index 50ceedb..be461a0 100644 --- a/devices/src/virtio/p9.rs +++ b/devices/src/virtio/p9.rs @@ -60,36 +60,32 @@ impl error::Error for P9Error { impl fmt::Display for P9Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::P9Error::*; + match self { - P9Error::TagTooLong(len) => write!( + TagTooLong(len) => write!( f, "P9 device tag is too long: len = {}, max = {}", len, ::std::u16::MAX ), - P9Error::RootNotAbsolute(buf) => write!( + RootNotAbsolute(buf) => write!( f, "P9 root directory is not absolute: root = {}", buf.display() ), - 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 => { - write!(f, "request does not have any readable descriptors") - } - P9Error::NoWritableDescriptors => { - write!(f, "request does not have any writable descriptors") - } - P9Error::InvalidGuestAddress(addr, len) => write!( + CreatePollContext(err) => write!(f, "failed to create PollContext: {}", err), + PollError(err) => write!(f, "failed to poll events: {}", err), + ReadQueueEventFd(err) => write!(f, "failed to read from virtio queue EventFd: {}", err), + NoReadableDescriptors => write!(f, "request does not have any readable descriptors"), + NoWritableDescriptors => write!(f, "request does not have any writable descriptors"), + InvalidGuestAddress(addr, len) => write!( f, - "descriptor contained invalid guest address range: address = {:?}, len = {}", + "descriptor contained invalid guest address range: address = {}, len = {}", addr, len ), - P9Error::SignalUsedQueue(err) => write!(f, "failed to signal used queue: {:?}", err), - P9Error::Internal(err) => write!(f, "P9 internal server error: {}", err), + SignalUsedQueue(err) => write!(f, "failed to signal used queue: {}", err), + Internal(err) => write!(f, "P9 internal server error: {}", err), } } } @@ -402,7 +398,7 @@ impl VirtioDevice for P9 { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("failed creating kill EventFd pair: {:?}", e); + error!("failed creating kill EventFd pair: {}", e); return; } }; @@ -427,7 +423,7 @@ impl VirtioDevice for P9 { match worker_result { Ok(worker) => self.worker = Some(worker), - Err(e) => error!("failed to spawn virtio_9p worker: {:?}", e), + Err(e) => error!("failed to spawn virtio_9p worker: {}", e), } } } @@ -437,7 +433,7 @@ impl Drop for P9 { fn drop(&mut self) { if let Some(kill_evt) = self.kill_evt.take() { if let Err(e) = kill_evt.write(1) { - error!("failed to kill virtio_9p worker thread: {:?}", e); + error!("failed to kill virtio_9p worker thread: {}", e); return; } diff --git a/devices/src/virtio/rng.rs b/devices/src/virtio/rng.rs index 96d0d4f..7b3d9f7 100644 --- a/devices/src/virtio/rng.rs +++ b/devices/src/virtio/rng.rs @@ -3,6 +3,7 @@ // found in the LICENSE file. use std; +use std::fmt::{self, Display}; use std::fs::File; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; @@ -24,6 +25,16 @@ pub enum RngError { } pub type Result<T> = std::result::Result<T, RngError>; +impl Display for RngError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::RngError::*; + + match self { + AccessingRandomDev(e) => write!(f, "failed to access /dev/urandom: {}", e), + } + } +} + struct Worker { queue: Queue, mem: GuestMemory, @@ -92,7 +103,7 @@ impl Worker { { Ok(pc) => pc, Err(e) => { - error!("failed creating PollContext: {:?}", e); + error!("failed creating PollContext: {}", e); return; } }; @@ -101,7 +112,7 @@ impl Worker { let events = match poll_ctx.wait() { Ok(v) => v, Err(e) => { - error!("failed polling for events: {:?}", e); + error!("failed polling for events: {}", e); break; } }; @@ -111,7 +122,7 @@ impl Worker { match event.token() { Token::QueueAvailable => { if let Err(e) = queue_evt.read() { - error!("failed reading queue EventFd: {:?}", e); + error!("failed reading queue EventFd: {}", e); break 'poll; } needs_interrupt |= self.process_queue(); @@ -193,7 +204,7 @@ impl VirtioDevice for Rng { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("failed to create kill EventFd pair: {:?}", e); + error!("failed to create kill EventFd pair: {}", e); return; } }; diff --git a/devices/src/virtio/tpm.rs b/devices/src/virtio/tpm.rs index 66574e2..0cc2e91 100644 --- a/devices/src/virtio/tpm.rs +++ b/devices/src/virtio/tpm.rs @@ -133,7 +133,7 @@ impl Worker { { Ok(pc) => pc, Err(e) => { - error!("vtpm failed creating PollContext: {:?}", e); + error!("vtpm failed creating PollContext: {}", e); return; } }; @@ -142,7 +142,7 @@ impl Worker { let events = match poll_ctx.wait() { Ok(v) => v, Err(e) => { - error!("vtpm failed polling for events: {:?}", e); + error!("vtpm failed polling for events: {}", e); break; } }; @@ -152,7 +152,7 @@ impl Worker { match event.token() { Token::QueueAvailable => { if let Err(e) = queue_evt.read() { - error!("vtpm failed reading queue EventFd: {:?}", e); + error!("vtpm failed reading queue EventFd: {}", e); break 'poll; } needs_interrupt |= self.process_queue(); @@ -231,7 +231,7 @@ impl VirtioDevice for Tpm { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(err) => { - error!("vtpm failed to create kill EventFd pair: {:?}", err); + error!("vtpm failed to create kill EventFd pair: {}", err); return; } }; diff --git a/devices/src/virtio/vhost/mod.rs b/devices/src/virtio/vhost/mod.rs index 0fe15df..f96bebb 100644 --- a/devices/src/virtio/vhost/mod.rs +++ b/devices/src/virtio/vhost/mod.rs @@ -5,6 +5,7 @@ //! Implements vhost-based virtio devices. use std; +use std::fmt::{self, Display}; use net_util::Error as TapError; use sys_util::Error as SysError; @@ -74,3 +75,38 @@ pub enum Error { } pub type Result<T> = std::result::Result<T, Error>; + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + CreateKillEventFd(e) => write!(f, "failed to create kill eventfd: {}", e), + CreatePollContext(e) => write!(f, "failed to create poll context: {}", e), + CloneKillEventFd(e) => write!(f, "failed to clone kill eventfd: {}", e), + PollError(e) => write!(f, "failed polling for events: {}", e), + TapOpen(e) => write!(f, "failed to open tap device: {}", e), + TapSetIp(e) => write!(f, "failed to set tap IP: {}", e), + TapSetNetmask(e) => write!(f, "failed to set tap netmask: {}", e), + TapSetMacAddress(e) => write!(f, "failed to set tap mac address: {}", e), + TapSetOffload(e) => write!(f, "failed to set tap interface offload flags: {}", e), + TapSetVnetHdrSize(e) => write!(f, "failed to set vnet header size: {}", e), + TapEnable(e) => write!(f, "failed to enable tap interface: {}", e), + VhostOpen(e) => write!(f, "failed to open vhost device: {}", e), + VhostSetOwner(e) => write!(f, "failed to set owner: {}", e), + VhostGetFeatures(e) => write!(f, "failed to get features: {}", e), + VhostSetFeatures(e) => write!(f, "failed to set features: {}", e), + VhostSetMemTable(e) => write!(f, "failed to set mem table: {}", e), + VhostSetVringNum(e) => write!(f, "failed to set vring num: {}", e), + VhostSetVringAddr(e) => write!(f, "failed to set vring addr: {}", e), + VhostSetVringBase(e) => write!(f, "failed to set vring base: {}", e), + VhostSetVringCall(e) => write!(f, "failed to set vring call: {}", e), + VhostSetVringKick(e) => write!(f, "failed to set vring kick: {}", e), + VhostNetSetBackend(e) => write!(f, "net set backend failed: {}", e), + VhostVsockSetCid(e) => write!(f, "failed to set CID for guest: {}", e), + VhostVsockStart(e) => write!(f, "failed to start vhost-vsock driver: {}", e), + VhostIrqCreate(e) => write!(f, "failed to create vhost eventfd: {}", e), + VhostIrqRead(e) => write!(f, "failed to read vhost eventfd: {}", e), + } + } +} diff --git a/devices/src/virtio/vhost/net.rs b/devices/src/virtio/vhost/net.rs index 4727bbc..b8e518d 100644 --- a/devices/src/virtio/vhost/net.rs +++ b/devices/src/virtio/vhost/net.rs @@ -202,7 +202,7 @@ where let result = worker.run(queue_evts, QUEUE_SIZES, kill_evt, activate_vqs); if let Err(e) = result { - error!("net worker thread exited with error: {:?}", e); + error!("net worker thread exited with error: {}", e); } }); diff --git a/devices/src/virtio/wl.rs b/devices/src/virtio/wl.rs index 332f7c6..4d43825 100644 --- a/devices/src/virtio/wl.rs +++ b/devices/src/virtio/wl.rs @@ -1163,14 +1163,14 @@ impl WlState { let events = match self.poll_ctx.wait_timeout(Duration::from_secs(0)) { Ok(v) => v.to_owned(), Err(e) => { - error!("failed polling for vfd evens: {:?}", e); + error!("failed polling for vfd evens: {}", e); return; } }; for event in events.as_ref().iter_readable() { if let Err(e) = self.recv(event.token()) { - error!("failed to recv from vfd: {:?}", e) + error!("failed to recv from vfd: {}", e) } } @@ -1179,7 +1179,7 @@ impl WlState { let vfd_id = event.token(); if let Some(fd) = self.vfds.get(&vfd_id).and_then(|vfd| vfd.poll_fd()) { if let Err(e) = self.poll_ctx.delete(fd) { - warn!("failed to remove hungup vfd from poll context: {:?}", e); + warn!("failed to remove hungup vfd from poll context: {}", e); } } self.in_queue.push_back((vfd_id, WlRecv::Hup)); @@ -1263,7 +1263,7 @@ impl WlState { .unwrap() .send(&ResourceRequest::GetResource { id }) { - error!("error sending resource bridge request: {:?}", e); + error!("error sending resource bridge request: {}", e); return Ok(WlResp::InvalidId); } match self.resource_bridge.as_ref().unwrap().recv() { @@ -1276,7 +1276,7 @@ impl WlState { return Ok(WlResp::InvalidId); } Err(e) => { - error!("error receiving resource bridge response: {:?}", e); + error!("error receiving resource bridge response: {}", e); // If there was an error with the resource bridge, it can no longer be // trusted to continue to function. self.resource_bridge = None; @@ -1538,7 +1538,7 @@ impl Worker { }) { Ok(pc) => pc, Err(e) => { - error!("failed creating PollContext: {:?}", e); + error!("failed creating PollContext: {}", e); return; } }; @@ -1548,7 +1548,7 @@ impl Worker { let events = match poll_ctx.wait() { Ok(v) => v, Err(e) => { - error!("failed polling for events: {:?}", e); + error!("failed polling for events: {}", e); break; } }; @@ -1654,7 +1654,7 @@ impl Worker { len } Err(e) => { - error!("failed to encode response to descriptor chain: {:?}", e); + error!("failed to encode response to descriptor chain: {}", e); 0 } }; @@ -1756,7 +1756,7 @@ impl VirtioDevice for Wl { let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { Ok(v) => v, Err(e) => { - error!("failed creating kill EventFd pair: {:?}", e); + error!("failed creating kill EventFd pair: {}", e); return; } }; diff --git a/gpu_buffer/src/lib.rs b/gpu_buffer/src/lib.rs index be8fb72..112b086 100644 --- a/gpu_buffer/src/lib.rs +++ b/gpu_buffer/src/lib.rs @@ -78,7 +78,7 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::GbmFailed => write!(f, "internal GBM failure"), - Error::ExportFailed(e) => write!(f, "export failed: {:?}", e), + Error::ExportFailed(e) => write!(f, "export failed: {}", e), Error::MapFailed => write!(f, "map failed"), Error::CheckedArithmetic { field1: (label1, value1), diff --git a/gpu_display/src/lib.rs b/gpu_display/src/lib.rs index 6b93bbc..01cef5e 100644 --- a/gpu_display/src/lib.rs +++ b/gpu_display/src/lib.rs @@ -12,6 +12,7 @@ mod dwl; use std::cell::Cell; use std::collections::HashMap; use std::ffi::{CStr, CString}; +use std::fmt::{self, Display}; use std::os::unix::io::{AsRawFd, RawFd}; use std::path::Path; use std::ptr::null_mut; @@ -45,6 +46,23 @@ pub enum GpuDisplayError { InvalidPath, } +impl Display for GpuDisplayError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::GpuDisplayError::*; + + match self { + Allocate => write!(f, "internal allocation failed"), + Connect => write!(f, "failed to connect to compositor"), + CreateShm(e) => write!(f, "failed to create shared memory: {}", e), + SetSize(e) => write!(f, "failed to set size of shared memory: {}", e), + CreateSurface => write!(f, "failed to crate surface on the compositor"), + FailedImport => write!(f, "failed to import a buffer to the compositor"), + InvalidSurfaceId => write!(f, "invalid surface ID"), + InvalidPath => write!(f, "invalid path"), + } + } +} + struct DwlContext(*mut dwl_context); impl Drop for DwlContext { fn drop(&mut self) { diff --git a/io_jail/src/lib.rs b/io_jail/src/lib.rs index 53c6533..b56924d 100644 --- a/io_jail/src/lib.rs +++ b/io_jail/src/lib.rs @@ -75,8 +75,10 @@ impl fmt::Display for Error { match self { Error::BindMount { src, dst, errno } => write!( f, - "failed to accept bind mount {:?} -> {:?}: {}", - src, dst, errno + "failed to accept bind mount {} -> {}: {}", + src.display(), + dst.display(), + io::Error::from_raw_os_error(*errno), ), Error::Mount { errno, @@ -87,9 +89,14 @@ impl fmt::Display for Error { data, } => write!( f, - "failed to accept mount {:?} -> {:?} of type {:?} with flags 0x{:x} \ + "failed to accept mount {} -> {} of type {:?} with flags 0x{:x} \ and data {:?}: {}", - src, dest, fstype, flags, data, errno + src.display(), + dest.display(), + fstype, + flags, + data, + io::Error::from_raw_os_error(*errno), ), Error::CheckingMultiThreaded(e) => write!( f, @@ -101,28 +108,39 @@ impl fmt::Display for Error { Error::ForkingWhileMultiThreaded => { write!(f, "Attempt to call fork() while multithreaded") } - 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::SeccompPath(p) => write!(f, "missing seccomp policy path: {}", p.display()), + Error::StrToCString(s) => write!(f, "failed to convert string into CString: {}", s), + Error::PathToCString(s) => { + write!(f, "failed to convert path into CString: {}", s.display()) + } Error::DupDevNull(errno) => write!( f, "failed to call dup2 to set stdin, stdout, or stderr to /dev/null: {}", - errno + io::Error::from_raw_os_error(*errno), ), Error::OpenDevNull(e) => write!( f, "fail to open /dev/null for setting FDs 0, 1, or 2: {}", - e + e, + ), + Error::SetAltSyscallTable { name, errno } => write!( + f, + "failed to set alt-syscall table {}: {}", + name, + io::Error::from_raw_os_error(*errno), + ), + Error::SettingChrootDirectory(errno, p) => write!( + f, + "failed to set chroot {}: {}", + p.display(), + io::Error::from_raw_os_error(*errno), + ), + Error::SettingPivotRootDirectory(errno, p) => write!( + f, + "failed to set pivot root {}: {}", + p.display(), + io::Error::from_raw_os_error(*errno), ), - Error::SetAltSyscallTable { name, errno } => { - write!(f, "failed to set alt-syscall table {:?}: {}", name, errno) - } - Error::SettingChrootDirectory(errno, p) => { - write!(f, "failed to set chroot {:?}: {}", p, errno) - } - Error::SettingPivotRootDirectory(errno, p) => { - write!(f, "failed to set pivot root {:?}: {}", p, errno) - } Error::ReadFdDirEntry(e) => { write!(f, "failed to read an entry in /proc/self/fd: {}", e) } diff --git a/msg_socket/src/msg_on_socket.rs b/msg_socket/src/msg_on_socket.rs index c6e4413..493c57c 100644 --- a/msg_socket/src/msg_on_socket.rs +++ b/msg_socket/src/msg_on_socket.rs @@ -4,6 +4,7 @@ use data_model::*; use std; +use std::fmt::{self, Display}; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::result; use sys_util::{Error as SysError, EventFd}; @@ -38,6 +39,23 @@ pub enum MsgError { pub type MsgResult<T> = result::Result<T, MsgError>; +impl Display for MsgError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::MsgError::*; + + match self { + Send(e) => write!(f, "failed to send request or response: {}", e), + Recv(e) => write!(f, "failed to receive request or response: {}", e), + InvalidType => write!(f, "invalid type"), + BadRecvSize(n) => write!(f, "wrong amount of data received; expected {} bytes", n), + ExpectFd => write!(f, "missing associated file descriptor for request"), + NotExpectFd => write!(f, "unexpected file descriptor is unused"), + WrongFdBufferSize => write!(f, "fd buffer size too small"), + WrongMsgBufferSize => write!(f, "msg buffer size too small"), + } + } +} + /// A msg that could be serialized to and deserialize from array in little endian. /// /// For structs, we always have fixed size of bytes and fixed count of fds. diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index 4dfcd39..790fbc3 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -6,7 +6,7 @@ extern crate libc; extern crate net_sys; extern crate sys_util; -use std::fmt; +use std::fmt::{self, Display}; use std::fs::File; use std::io::{Read, Result as IoResult, Write}; use std::mem; @@ -34,6 +34,19 @@ pub enum Error { } pub type Result<T> = std::result::Result<T, Error>; +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + CreateSocket(e) => write!(f, "failed to create a socket: {}", e), + OpenTun(e) => write!(f, "failed to open /dev/net/tun: {}", e), + CreateTap(e) => write!(f, "failed to create tap interface: {}", e), + IoctlError(e) => write!(f, "ioctl failed: {}", e), + } + } +} + impl Error { pub fn sys_error(&self) -> SysError { match *self { @@ -92,7 +105,7 @@ impl fmt::Display for MacAddressError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { MacAddressError::InvalidNumOctets(n) => write!(f, "invalid number of octets: {}", n), - MacAddressError::ParseOctet(ref e) => write!(f, "failed to parse octet: {:?}", e), + MacAddressError::ParseOctet(ref e) => write!(f, "failed to parse octet: {}", e), } } } @@ -636,7 +649,7 @@ mod tests { // We won't have permission in test environments; allow that Ok(_t) => {} Err(Error::IoctlError(ref e)) if e.errno() == EPERM => {} - Err(e) => panic!("Unexpected Error:\n{:?}", e), + Err(e) => panic!("Unexpected Error:\n{}", e), } } } diff --git a/qcow/src/qcow.rs b/qcow/src/qcow.rs index cba4e06..23aefd6 100644 --- a/qcow/src/qcow.rs +++ b/qcow/src/qcow.rs @@ -19,6 +19,7 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use libc::{EINVAL, ENOSPC, ENOTSUP}; use std::cmp::min; +use std::fmt::{self, Display}; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::mem::size_of; @@ -61,6 +62,45 @@ pub enum Error { } pub type Result<T> = std::result::Result<T, Error>; +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + BackingFilesNotSupported => write!(f, "backing files not supported"), + CompressedBlocksNotSupported => write!(f, "compressed blocks not supported"), + GettingFileSize(e) => write!(f, "failed to get file size: {}", e), + GettingRefcount(e) => write!(f, "failed to get refcount: {}", e), + EvictingCache(e) => write!(f, "failed to evict cache: {}", e), + InvalidClusterIndex => write!(f, "invalid cluster index"), + InvalidClusterSize => write!(f, "invalid cluster size"), + InvalidIndex => write!(f, "invalid index"), + InvalidL1TableOffset => write!(f, "invalid L1 table offset"), + InvalidMagic => write!(f, "invalid magic"), + InvalidOffset(_) => write!(f, "invalid offset"), + InvalidRefcountTableOffset => write!(f, "invalid refcount table offset"), + InvalidRefcountTableSize => write!(f, "invalid refcount table size"), + NoFreeClusters => write!(f, "no free clusters"), + NoRefcountClusters => write!(f, "no refcount clusters"), + OpeningFile(e) => write!(f, "failed to open file: {}", e), + ReadingData(e) => write!(f, "failed to read data: {}", e), + ReadingHeader(e) => write!(f, "failed to read header: {}", e), + ReadingPointers(e) => write!(f, "failed to read pointers: {}", e), + ReadingRefCounts(e) => write!(f, "failed to read ref counts: {}", e), + ReadingRefCountBlock(e) => write!(f, "failed to read ref count block: {}", e), + RebuildingRefCounts(e) => write!(f, "failed to rebuild ref counts: {}", e), + SeekingFile(e) => write!(f, "failed to seek file: {}", e), + SettingFileSize(e) => write!(f, "failed to set file size: {}", e), + SettingRefcountRefcount(e) => write!(f, "failed to set refcount refcount: {}", e), + SizeTooSmallForNumberOfClusters => write!(f, "size too small for number of clusters"), + WritingHeader(e) => write!(f, "failed to write header: {}", e), + UnsupportedRefcountOrder => write!(f, "unsupported refcount order"), + UnsupportedVersion(v) => write!(f, "unsupported version: {}", v), + WritingData(e) => write!(f, "failed to write data: {}", e), + } + } +} + pub enum ImageType { Raw, Qcow2, diff --git a/qcow/src/refcount.rs b/qcow/src/refcount.rs index a64d218..e5b4e73 100644 --- a/qcow/src/refcount.rs +++ b/qcow/src/refcount.rs @@ -3,6 +3,7 @@ // found in the LICENSE file. use std; +use std::fmt::{self, Display}; use std::io; use libc::EINVAL; @@ -26,6 +27,26 @@ pub enum Error { pub type Result<T> = std::result::Result<T, Error>; +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + EvictingRefCounts(e) => write!( + f, + "failed to write a refblock from the cache to disk: {}", + e + ), + InvalidIndex => write!(f, "address requested is not within the range of the disk"), + NeedCluster(addr) => write!(f, "cluster with addr={} needs to be read", addr), + NeedNewCluster => write!(f, "new cluster needs to be allocated for refcounts"), + ReadingRefCounts(e) => { + write!(f, "failed to read the file into the refcount cache: {}", e) + } + } + } +} + /// Represents the refcount entries for an open qcow file. #[derive(Debug)] pub struct RefCount { diff --git a/src/linux.rs b/src/linux.rs index 762b882..0391f9d 100644 --- a/src/linux.rs +++ b/src/linux.rs @@ -105,39 +105,44 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - 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::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::CreateTapDevice(e) => write!(f, "failed to create tap device: {:?}", e), + Error::CreateTapDevice(e) => write!(f, "failed to create tap device: {}", e), Error::CreateTimerFd(e) => write!(f, "failed to create timerfd: {}", e), - Error::DetectImageType(e) => write!(f, "failed to detect disk image type: {:?}", 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::DiskImageLock(e) => write!(f, "failed to lock disk image: {}", e), 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(e) => write!(f, "failed to set up virtio networking: {:?}", 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::OpenInitrd(p, e) => write!(f, "failed to open initrd {:?}: {}", p, e), - Error::OpenKernel(p, e) => write!(f, "failed to open kernel image {:?}: {}", p, e), - Error::OpenAndroidFstab(ref p, ref e) => { - write!(f, "failed to open android fstab file {:?}: {}", p, e) + Error::OpenInitrd(p, e) => write!(f, "failed to open initrd {}: {}", p.display(), e), + Error::OpenKernel(p, e) => { + write!(f, "failed to open kernel image {}: {}", p.display(), e) } + Error::OpenAndroidFstab(ref p, ref e) => write!( + f, + "failed to open android fstab file {}: {}", + p.display(), + 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::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) + write!(f, "failed to remove fd from poll context: {}", e) } - Error::QcowDeviceCreate(e) => write!(f, "failed to read qcow formatted file {:?}", e), + 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: {}", @@ -148,32 +153,30 @@ impl fmt::Display for Error { "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}", 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::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(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::InputDeviceNew(ref e) => write!(f, "failed to set up input device: {:?}", e), - Error::InputEventsOpen(ref e) => write!(f, "failed to open event device: {:?}", e), + Error::RngDeviceNew(e) => write!(f, "failed to set up rng: {}", e), + Error::InputDeviceNew(ref e) => write!(f, "failed to set up input device: {}", e), + Error::InputEventsOpen(ref e) => write!(f, "failed to open event device: {}", 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::ValidateRawFd(e) => write!(f, "failed to validate raw fd: {:?}", e), - Error::VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {:?}", 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::ValidateRawFd(e) => write!(f, "failed to validate raw 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) + write!(f, "failed to set up virtual socket device: {}", 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::WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {}", e), Error::LoadKernel(e) => write!(f, "failed to load kernel: {}", e), } } @@ -345,7 +348,7 @@ fn create_virtio_devs( }); } Err(e) => { - error!("failed configuring virtio trackpad: {:?}", e); + error!("failed configuring virtio trackpad: {}", e); return Err(e); } } @@ -368,7 +371,7 @@ fn create_virtio_devs( }); } Err(e) => { - error!("failed configuring virtio mouse: {:?}", e); + error!("failed configuring virtio mouse: {}", e); return Err(e); } } @@ -391,7 +394,7 @@ fn create_virtio_devs( }); } Err(e) => { - error!("failed configuring virtio keyboard: {:?}", e); + error!("failed configuring virtio keyboard: {}", e); return Err(e); } } @@ -554,14 +557,14 @@ fn create_virtio_devs( let crosvm_uid = match get_user_id(&crosvm_user_group) { Ok(u) => u, Err(e) => { - warn!("falling back to current user id for gpu: {:?}", e); + warn!("falling back to current user id for gpu: {}", e); geteuid() } }; let crosvm_gid = match get_group_id(&crosvm_user_group) { Ok(u) => u, Err(e) => { - warn!("falling back to current group id for gpu: {:?}", e); + warn!("falling back to current group id for gpu: {}", e); getegid() } }; @@ -632,14 +635,14 @@ fn create_virtio_devs( let crosvm_uid = match get_user_id(&crosvm_user_group) { Ok(u) => u, Err(e) => { - warn!("falling back to current user id for Wayland: {:?}", e); + warn!("falling back to current user id for Wayland: {}", e); geteuid() } }; let crosvm_gid = match get_group_id(&crosvm_user_group) { Ok(u) => u, Err(e) => { - warn!("falling back to current group id for Wayland: {:?}", e); + warn!("falling back to current group id for Wayland: {}", e); getegid() } }; @@ -680,14 +683,14 @@ fn create_virtio_devs( let chronos_uid = match get_user_id(&chronos_user_group) { Ok(u) => u, Err(e) => { - warn!("falling back to current user id for 9p: {:?}", e); + warn!("falling back to current user id for 9p: {}", e); geteuid() } }; let chronos_gid = match get_group_id(&chronos_user_group) { Ok(u) => u, Err(e) => { - warn!("falling back to current group id for 9p: {:?}", e); + warn!("falling back to current group id for 9p: {}", e); getegid() } }; @@ -829,7 +832,7 @@ fn run_vcpu( v.retain(|&x| x != SIGRTMIN() + 0); if let Err(e) = vcpu.set_signal_mask(&v) { error!( - "Failed to set the KVM_SIGNAL_MASK for vcpu {} : {:?}", + "Failed to set the KVM_SIGNAL_MASK for vcpu {} : {}", cpu_id, e ); sig_ok = false; @@ -837,7 +840,7 @@ fn run_vcpu( } Err(e) => { error!( - "Failed to retrieve signal mask for vcpu {} : {:?}", + "Failed to retrieve signal mask for vcpu {} : {}", cpu_id, e ); sig_ok = false; @@ -858,7 +861,7 @@ fn run_vcpu( } io_bus.read(port as u64, &mut data[..size]); if let Err(e) = vcpu.set_data(&data[..size]) { - error!("failed to set return data for IoIn: {:?}", e); + error!("failed to set return data for IoIn: {}", e); } } Ok(VcpuExit::IoOut { @@ -893,7 +896,7 @@ fn run_vcpu( libc::EINTR => interrupted_by_signal = true, libc::EAGAIN => {} _ => { - error!("vcpu hit unknown error: {:?}", e); + error!("vcpu hit unknown error: {}", e); break; } }, @@ -903,7 +906,7 @@ fn run_vcpu( // Try to clear the signal that we use to kick VCPU if it is pending before // attempting to handle pause requests. if let Err(e) = clear_signal(SIGRTMIN() + 0) { - error!("failed to clear pending signal: {:?}", e); + error!("failed to clear pending signal: {}", e); break; } let mut run_mode_lock = run_mode_arc.mtx.lock(); @@ -918,7 +921,7 @@ fn run_vcpu( // VCPU resumes, which could happen days later in realtime. if requires_kvmclock_ctrl { if let Err(e) = vcpu.kvmclock_ctrl() { - error!("failed to signal to kvm that vcpu {} is being suspended: {:?}", cpu_id, e); + error!("failed to signal to kvm that vcpu {} is being suspended: {}", cpu_id, e); } } } @@ -1091,7 +1094,7 @@ fn run_control( .add(&linux.exit_evt, Token::Exit) .map_err(Error::PollContextAdd)?; if let Err(e) = poll_ctx.add(&stdin_handle, Token::Stdin) { - warn!("failed to add stdin to poll context: {:?}", e); + warn!("failed to add stdin to poll context: {}", e); } poll_ctx .add(&sigchld_fd, Token::ChildSignal) @@ -1157,7 +1160,7 @@ fn run_control( match poll_ctx.wait() { Ok(v) => v, Err(e) => { - error!("failed to poll: {:?}", e); + error!("failed to poll: {}", e); break; } } @@ -1176,7 +1179,7 @@ fn run_control( let _ = poll_ctx.delete(&stdin_handle); } Err(e) => { - warn!("error while reading stdin: {:?}", e); + warn!("error while reading stdin: {}", e); let _ = poll_ctx.delete(&stdin_handle); } Ok(count) => { @@ -1294,10 +1297,10 @@ fn run_control( disk_host_sockets, ); if let Err(e) = socket.send(&response) { - error!("failed to send VmResponse: {:?}", e); + error!("failed to send VmResponse: {}", e); } if let Some(run_mode) = run_mode_opt { - info!("control socket changed run mode to {:?}", run_mode); + info!("control socket changed run mode to {}", run_mode); match run_mode { VmRunMode::Exiting => { break 'poll; @@ -1311,7 +1314,7 @@ fn run_control( } } } - Err(e) => error!("failed to recv VmRequest: {:?}", e), + Err(e) => error!("failed to recv VmRequest: {}", e), } } } @@ -1350,7 +1353,7 @@ fn run_control( error!("failed to join vcpu thread: {:?}", e); } } - Err(e) => error!("failed to kill vcpu thread: {:?}", e), + Err(e) => error!("failed to kill vcpu thread: {}", e), } } diff --git a/src/main.rs b/src/main.rs index 3e3afef..d0c1e7d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -174,7 +174,7 @@ fn wait_all_children() -> bool { // We expect ECHILD which indicates that there were no children left. Err(e) if e.errno() == libc::ECHILD => return true, Err(e) => { - warn!("error while waiting for children: {:?}", e); + warn!("error while waiting for children: {}", e); return false; } // We reaped one child, so continue reaping. @@ -724,7 +724,7 @@ fn vms_request( let sender = Sender::<VmRequest>::new(s); if let Err(e) = sender.send(request) { error!( - "failed to send request to socket at '{}': {:?}", + "failed to send request to socket at '{}': {}", socket_path, e ); } @@ -789,7 +789,7 @@ fn balloon_vms(mut args: std::env::Args) -> std::result::Result<(), ()> { let sender = Sender::<VmRequest>::new(s); if let Err(e) = sender.send(&VmRequest::BalloonAdjust(num_bytes)) { error!( - "failed to send balloon request to socket at '{}': {:?}", + "failed to send balloon request to socket at '{}': {}", socket_path, e ); } @@ -824,11 +824,11 @@ fn create_qcow2(mut args: std::env::Args) -> std::result::Result<(), ()> { .write(true) .open(&file_path) .map_err(|e| { - error!("Failed opening qcow file at '{}': {:?}", file_path, 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); + error!("Failed to create qcow file at '{}': {}", file_path, e); })?; Ok(()) @@ -882,7 +882,7 @@ fn disk_cmd(mut args: std::env::Args) -> std::result::Result<(), ()> { let sender = Sender::<VmRequest>::new(s); if let Err(e) = sender.send(&request) { error!( - "failed to send disk request to socket at '{}': {:?}", + "failed to send disk request to socket at '{}': {}", socket_path, e ); } @@ -908,7 +908,7 @@ fn print_usage() { fn crosvm_main() -> std::result::Result<(), ()> { if let Err(e) = syslog::init() { - println!("failed to initialize syslog: {:?}", e); + println!("failed to initialize syslog: {}", e); return Err(()); } @@ -948,7 +948,7 @@ fn crosvm_main() -> std::result::Result<(), ()> { warn!("not all child processes have exited; sending SIGKILL"); if let Err(e) = kill_process_group() { // We're now at the mercy of the OS to clean up after us. - warn!("unable to kill all child processes: {:?}", e); + warn!("unable to kill all child processes: {}", e); } } diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index d886f0d..9ad0fd7 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -105,66 +105,49 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Error::CloneEventFd(ref e) => write!(f, "failed to clone eventfd: {:?}", e), - Error::CloneVcpuSocket(ref e) => write!(f, "failed to clone vcpu socket: {:?}", e), - Error::CreateEventFd(ref e) => write!(f, "failed to create eventfd: {:?}", e), - Error::CreateIrqChip(ref e) => write!(f, "failed to create kvm irqchip: {:?}", e), - Error::CreateJail(ref e) => write!(f, "failed to create jail: {}", e), - Error::CreateKvm(ref e) => write!(f, "error creating Kvm: {:?}", e), - Error::CreateMainSocket(ref e) => { - write!(f, "error creating main request socket: {:?}", e) - } - Error::CreatePIT(ref e) => write!(f, "failed to create kvm PIT: {:?}", 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::CreateSocketPair(ref e) => write!(f, "failed to create socket pair: {}", e), - Error::CreateTapFd(ref e) => { - write!(f, "failed to create tap device from raw fd: {:?}", e) - } - Error::CreateVcpu(ref e) => write!(f, "error creating vcpu: {:?}", e), - Error::CreateVcpuSocket(ref e) => { - write!(f, "error creating vcpu request socket: {:?}", e) - } - Error::CreateVm(ref e) => write!(f, "error creating vm: {:?}", e), - Error::DecodeRequest(ref e) => write!(f, "failed to decode plugin request: {}", e), - Error::EncodeResponse(ref e) => write!(f, "failed to encode plugin response: {}", e), - Error::Mount(ref e) => write!(f, "failed to mount: {}", e), - Error::MountDev(ref e) => write!(f, "failed to mount: {}", e), - Error::MountLib(ref e) => write!(f, "failed to mount: {}", e), - Error::MountLib64(ref e) => write!(f, "failed to mount: {}", e), - Error::MountPlugin(ref e) => write!(f, "failed to mount: {}", e), - Error::MountPluginLib(ref e) => write!(f, "failed to mount: {}", e), - Error::MountRoot(ref e) => write!(f, "failed to mount: {}", e), - Error::NoRootDir => { - write!(f, "no root directory for jailed process to pivot root into") - } - Error::ParsePivotRoot(ref e) => write!(f, "failed to set jail pivot root: {}", e), - Error::ParseSeccomp(ref e) => write!(f, "failed to parse jail seccomp filter: {}", e), - Error::PluginFailed(ref e) => write!(f, "plugin exited with error: {}", e), - Error::PluginKill(ref e) => write!(f, "error sending kill signal to plugin: {:?}", e), - Error::PluginKilled(ref e) => write!(f, "plugin exited with signal {}", e), - Error::PluginRunJail(ref e) => write!(f, "failed to run jail: {}", e), - Error::PluginSocketHup => write!(f, "plugin request socket has been hung up"), - Error::PluginSocketPoll(ref e) => { - write!(f, "failed to poll plugin request sockets: {:?}", e) - } - Error::PluginSocketRecv(ref e) => { - write!(f, "failed to recv from plugin request socket: {:?}", e) - } - Error::PluginSocketSend(ref e) => { - write!(f, "failed to send to plugin request socket: {:?}", e) - } - Error::PluginSpawn(ref e) => write!(f, "failed to spawn plugin: {}", e), - Error::PluginTimeout => write!(f, "plugin did not exit within timeout"), - Error::PluginWait(ref e) => write!(f, "error waiting for plugin to exit: {:?}", e), - Error::Poll(ref e) => write!(f, "failed to poll all FDs: {:?}", e), - Error::PollContextAdd(ref e) => write!(f, "failed to add fd to poll context: {:?}", e), - Error::RootNotAbsolute => write!(f, "path to the root directory must be absolute"), - Error::RootNotDir => write!(f, "specified root directory is not a directory"), - Error::SetGidMap(ref e) => write!(f, "failed to set gidmap for jail: {}", e), - Error::SetUidMap(ref e) => write!(f, "failed to set uidmap for jail: {}", e), - Error::SigChild { + use self::Error::*; + + match self { + CloneEventFd(e) => write!(f, "failed to clone eventfd: {}", e), + CloneVcpuSocket(e) => write!(f, "failed to clone vcpu socket: {}", e), + CreateEventFd(e) => write!(f, "failed to create eventfd: {}", e), + CreateIrqChip(e) => write!(f, "failed to create kvm irqchip: {}", e), + CreateJail(e) => write!(f, "failed to create jail: {}", e), + CreateKvm(e) => write!(f, "error creating Kvm: {}", e), + CreateMainSocket(e) => write!(f, "error creating main request socket: {}", e), + CreatePIT(e) => write!(f, "failed to create kvm PIT: {}", e), + CreatePollContext(e) => write!(f, "failed to create poll context: {}", e), + CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e), + CreateSocketPair(e) => write!(f, "failed to create socket pair: {}", e), + CreateTapFd(e) => write!(f, "failed to create tap device from raw fd: {}", e), + CreateVcpu(e) => write!(f, "error creating vcpu: {}", e), + CreateVcpuSocket(e) => write!(f, "error creating vcpu request socket: {}", e), + CreateVm(e) => write!(f, "error creating vm: {}", e), + DecodeRequest(e) => write!(f, "failed to decode plugin request: {}", e), + EncodeResponse(e) => write!(f, "failed to encode plugin response: {}", e), + Mount(e) | MountDev(e) | MountLib(e) | MountLib64(e) | MountPlugin(e) + | MountPluginLib(e) | MountRoot(e) => write!(f, "failed to mount: {}", e), + NoRootDir => write!(f, "no root directory for jailed process to pivot root into"), + ParsePivotRoot(e) => write!(f, "failed to set jail pivot root: {}", e), + ParseSeccomp(e) => write!(f, "failed to parse jail seccomp filter: {}", e), + PluginFailed(e) => write!(f, "plugin exited with error: {}", e), + PluginKill(e) => write!(f, "error sending kill signal to plugin: {}", e), + PluginKilled(e) => write!(f, "plugin exited with signal {}", e), + PluginRunJail(e) => write!(f, "failed to run jail: {}", e), + PluginSocketHup => write!(f, "plugin request socket has been hung up"), + PluginSocketPoll(e) => write!(f, "failed to poll plugin request sockets: {}", e), + PluginSocketRecv(e) => write!(f, "failed to recv from plugin request socket: {}", e), + PluginSocketSend(e) => write!(f, "failed to send to plugin request socket: {}", e), + PluginSpawn(e) => write!(f, "failed to spawn plugin: {}", e), + PluginTimeout => write!(f, "plugin did not exit within timeout"), + PluginWait(e) => write!(f, "error waiting for plugin to exit: {}", e), + Poll(e) => write!(f, "failed to poll all FDs: {}", e), + PollContextAdd(e) => write!(f, "failed to add fd to poll context: {}", e), + RootNotAbsolute => write!(f, "path to the root directory must be absolute"), + RootNotDir => write!(f, "specified root directory is not a directory"), + SetGidMap(e) => write!(f, "failed to set gidmap for jail: {}", e), + SetUidMap(e) => write!(f, "failed to set uidmap for jail: {}", e), + SigChild { pid, signo, status, @@ -174,14 +157,14 @@ impl fmt::Display for Error { "process {} died with signal {}, status {}, and code {}", pid, signo, status, code ), - Error::SignalFd(ref e) => write!(f, "failed to read signal fd: {:?}", e), - Error::SpawnVcpu(ref e) => write!(f, "error spawning vcpu thread: {}", e), - Error::TapOpen(ref e) => write!(f, "error opening tap device: {:?}", e), - Error::TapSetIp(ref e) => write!(f, "error setting tap ip: {:?}", e), - Error::TapSetNetmask(ref e) => write!(f, "error setting tap netmask: {:?}", e), - Error::TapSetMacAddress(ref e) => write!(f, "error setting tap mac address: {:?}", e), - Error::TapEnable(ref e) => write!(f, "error enabling tap device: {:?}", e), - Error::ValidateTapFd(ref e) => write!(f, "failed to validate raw tap fd: {:?}", e), + SignalFd(e) => write!(f, "failed to read signal fd: {}", e), + SpawnVcpu(e) => write!(f, "error spawning vcpu thread: {}", e), + TapOpen(e) => write!(f, "error opening tap device: {}", e), + TapSetIp(e) => write!(f, "error setting tap ip: {}", e), + TapSetNetmask(e) => write!(f, "error setting tap netmask: {}", e), + TapSetMacAddress(e) => write!(f, "error setting tap mac address: {}", e), + TapEnable(e) => write!(f, "error enabling tap device: {}", e), + ValidateTapFd(e) => write!(f, "failed to validate raw tap fd: {}", e), } } } @@ -368,7 +351,7 @@ pub fn run_vcpus( let res = vcpu_plugin.init(&vcpu); vcpu_thread_barrier.wait(); if let Err(e) = res { - error!("failed to initialize vcpu {}: {:?}", cpu_id, e); + error!("failed to initialize vcpu {}: {}", cpu_id, e); } else { loop { let run_res = vcpu.run(); @@ -382,7 +365,7 @@ pub fn run_vcpus( } vcpu_plugin.io_read(port as u64, &mut data[..size], &vcpu); if let Err(e) = vcpu.set_data(&data[..size]) { - error!("failed to set return data for IoIn: {:?}", e); + error!("failed to set return data for IoIn: {}", e); } } VcpuExit::IoOut { @@ -428,7 +411,7 @@ pub fn run_vcpus( Err(e) => match e.errno() { EAGAIN | EINTR => {} _ => { - error!("vcpu hit unknown error: {:?}", e); + error!("vcpu hit unknown error: {}", e); break; } }, @@ -442,7 +425,7 @@ pub fn run_vcpus( clear_signal(SIGRTMIN() + 0).expect("failed to clear pending signal"); if let Err(e) = vcpu_plugin.pre_run(&vcpu) { - error!("failed to process pause on vcpu {}: {:?}", cpu_id, e); + error!("failed to process pause on vcpu {}: {}", cpu_id, e); break; } } @@ -723,7 +706,7 @@ pub fn run_config(cfg: Config) -> Result<()> { error!("failed to join vcpu thread: {:?}", e); } } - Err(e) => error!("failed to kill vcpu thread: {:?}", e), + Err(e) => error!("failed to kill vcpu thread: {}", e), } } diff --git a/src/plugin/process.rs b/src/plugin/process.rs index 2f3560d..2df9284 100644 --- a/src/plugin/process.rs +++ b/src/plugin/process.rs @@ -412,7 +412,7 @@ impl Process { if cpu_mask & (1 << cpu_id) != 0 { per_cpu_state.lock().request_pause(user_data); if let Err(e) = handle.kill(SIGRTMIN() + 0) { - error!("failed to interrupt vcpu {}: {:?}", cpu_id, e); + error!("failed to interrupt vcpu {}: {}", cpu_id, e); } } } @@ -425,7 +425,7 @@ impl Process { // Log any NetError so that the cause can be found later, but extract and return the // underlying errno for the client as well. fn map_net_error(s: &str, e: NetError) -> SysError { - error!("failed to get {}: {:?}", s, e); + error!("failed to get {}: {}", s, e); e.sys_error() } @@ -683,7 +683,7 @@ impl Drop for Process { fn drop(&mut self) { // Ignore the result because there is nothing we can do about it. if let Err(e) = self.signal_kill() { - error!("failed to signal kill event for plugin: {:?}", e); + error!("failed to signal kill event for plugin: {}", e); } } } diff --git a/src/plugin/vcpu.rs b/src/plugin/vcpu.rs index 70cf914..c2350a6 100644 --- a/src/plugin/vcpu.rs +++ b/src/plugin/vcpu.rs @@ -329,7 +329,7 @@ impl PluginVcpu { let vcpu_state_lock = match self.shared_vcpu_state.read() { Ok(l) => l, Err(e) => { - error!("error read locking shared cpu state: {:?}", e); + error!("error read locking shared cpu state: {}", e); return false; } }; @@ -360,7 +360,7 @@ impl PluginVcpu { match self.handle_until_resume(vcpu) { Ok(resume_data) => data.copy_from_slice(&resume_data), Err(e) if e.errno() == EPIPE => {} - Err(e) => error!("failed to process vcpu requests: {:?}", e), + Err(e) => error!("failed to process vcpu requests: {}", e), } true } diff --git a/sys_util/src/errno.rs b/sys_util/src/errno.rs index 0f9b5f2..023b162 100644 --- a/sys_util/src/errno.rs +++ b/sys_util/src/errno.rs @@ -49,7 +49,7 @@ impl error::Error for Error { impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Error: {}", self.errno()) + io::Error::from_raw_os_error(self.0).fmt(f) } } diff --git a/sys_util/src/guest_address.rs b/sys_util/src/guest_address.rs index 1048c6d..3e521ff 100644 --- a/sys_util/src/guest_address.rs +++ b/sys_util/src/guest_address.rs @@ -5,6 +5,7 @@ //! Represents an address in the guest's memory space. use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; +use std::fmt::{self, Display}; use std::ops::{BitAnd, BitOr}; /// Represents an Address in the guest's memory. @@ -89,6 +90,12 @@ impl PartialOrd for GuestAddress { } } +impl Display for GuestAddress { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:#x}", self.0) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/sys_util/src/lib.rs b/sys_util/src/lib.rs index cb0374b..29aa489 100644 --- a/sys_util/src/lib.rs +++ b/sys_util/src/lib.rs @@ -233,7 +233,7 @@ pub fn fallocate( /// continue /// }, /// Err(e) if e.errno() == libc::ECHILD => println!("no children left"), -/// Err(e) => println!("error reaping children: {:?}", e), +/// Err(e) => println!("error reaping children: {}", e), /// } /// break /// } @@ -298,7 +298,7 @@ impl Drop for UnlinkUnixDatagram { if let Ok(addr) = self.0.local_addr() { if let Some(path) = addr.as_pathname() { if let Err(e) = remove_file(path) { - warn!("failed to remove control socket file: {:?}", e); + warn!("failed to remove control socket file: {}", e); } } } diff --git a/sys_util/src/mmap.rs b/sys_util/src/mmap.rs index 5de433c..07815ca 100644 --- a/sys_util/src/mmap.rs +++ b/sys_util/src/mmap.rs @@ -6,6 +6,7 @@ //! mmap object leaves scope. use std; +use std::fmt::{self, Display}; use std::io::{Read, Write}; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; @@ -36,6 +37,26 @@ pub enum Error { } pub type Result<T> = std::result::Result<T, Error>; +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + InvalidAddress => write!(f, "requested memory out of range"), + InvalidOffset => write!(f, "requested offset is out of range of off_t"), + InvalidRange(offset, count) => write!( + f, + "requested memory range spans past the end of the region: offset={} count={}", + offset, count, + ), + ReadFromSource(e) => write!(f, "failed to read from the given source: {}", e), + SystemCallFailed(e) => write!(f, "mmap system call failed: {}", e), + WriteToMemory(e) => write!(f, "failed to write to memory: {}", e), + ReadFromMemory(e) => write!(f, "failed to read from memory: {}", e), + } + } +} + /// Wraps an anonymous shared memory mapping in the current process. #[derive(Debug)] pub struct MemoryMapping { @@ -75,7 +96,7 @@ impl MemoryMapping { // return value. We only warn about an error because failure here is not fatal to the mmap. if unsafe { libc::madvise(addr, size, libc::MADV_DONTDUMP) } == -1 { warn!( - "failed madvise(MADV_DONTDUMP) on mmap: {:?}", + "failed madvise(MADV_DONTDUMP) on mmap: {}", errno::Error::last() ); } @@ -123,7 +144,7 @@ impl MemoryMapping { // return value. We only warn about an error because failure here is not fatal to the mmap. if unsafe { libc::madvise(addr, size, libc::MADV_DONTDUMP) } == -1 { warn!( - "failed madvise(MADV_DONTDUMP) on mmap: {:?}", + "failed madvise(MADV_DONTDUMP) on mmap: {}", errno::Error::last() ); } @@ -414,7 +435,7 @@ mod tests { if let Error::SystemCallFailed(e) = res { assert_eq!(e.errno(), libc::EINVAL); } else { - panic!("unexpected error: {:?}", res); + panic!("unexpected error: {}", res); } } @@ -425,7 +446,7 @@ mod tests { if let Error::SystemCallFailed(e) = res { assert_eq!(e.errno(), libc::EBADF); } else { - panic!("unexpected error: {:?}", res); + panic!("unexpected error: {}", res); } } @@ -485,7 +506,7 @@ mod tests { .unwrap_err(); match res { Error::InvalidOffset => {} - e => panic!("unexpected error: {:?}", e), + e => panic!("unexpected error: {}", e), } } } diff --git a/sys_util/src/signal.rs b/sys_util/src/signal.rs index fe01dcf..737d7f5 100644 --- a/sys_util/src/signal.rs +++ b/sys_util/src/signal.rs @@ -8,6 +8,8 @@ use libc::{ SIG_BLOCK, SIG_UNBLOCK, }; +use std::fmt::{self, Display}; +use std::io; use std::mem; use std::os::unix::thread::JoinHandleExt; use std::ptr::{null, null_mut}; @@ -38,6 +40,36 @@ pub enum Error { ClearCheckPending(errno::Error), } +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + CreateSigset(e) => write!(f, "couldn't create a sigset: {}", e), + SignalAlreadyBlocked(num) => write!(f, "signal {} already blocked", num), + CompareBlockedSignals(e) => write!( + f, + "failed to check whether requested signal is in the blocked set: {}", + e, + ), + BlockSignal(e) => write!(f, "signal could not be blocked: {}", e), + RetrieveSignalMask(errno) => write!( + f, + "failed to retrieve signal mask: {}", + io::Error::from_raw_os_error(*errno), + ), + UnblockSignal(e) => write!(f, "signal could not be unblocked: {}", e), + ClearWaitPending(e) => write!(f, "failed to wait for given signal: {}", e), + ClearGetPending(e) => write!(f, "failed to get pending signals: {}", e), + ClearCheckPending(e) => write!( + f, + "failed to check whether given signal is in the pending set: {}", + e, + ), + } + } +} + pub type SignalResult<T> = result::Result<T, Error>; #[link(name = "c")] diff --git a/sys_util/src/signalfd.rs b/sys_util/src/signalfd.rs index c4fd92d..479972e 100644 --- a/sys_util/src/signalfd.rs +++ b/sys_util/src/signalfd.rs @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fmt::{self, Display}; use std::fs::File; use std::mem; use std::os::raw::c_int; @@ -29,6 +30,32 @@ pub enum Error { SignalFdPartialRead(usize), } +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + CreateSigset(e) => write!( + f, + "failed to construct sigset when creating signalfd: {}", + e, + ), + CreateSignalFd(e) => write!(f, "failed to create a new signalfd: {}", e), + CreateBlockSignal(e) => write!( + f, + "failed to block the signal when creating signalfd: {}", + e, + ), + SignalFdRead(e) => write!(f, "unable to read from signalfd: {}", e), + SignalFdPartialRead(read) => write!( + f, + "signalfd failed to return a full siginfo struct, read only {} bytes", + read, + ), + } + } +} + pub type Result<T> = result::Result<T, Error>; /// A safe wrapper around a Linux signalfd (man 2 signalfd). @@ -114,7 +141,7 @@ impl Drop for SignalFd { // was promised - unmasking the signal when we go out of scope. let res = signal::unblock_signal(self.signal); if let Err(e) = res { - error!("signalfd failed to unblock signal {}: {:?}", self.signal, e); + error!("signalfd failed to unblock signal {}: {}", self.signal, e); } } } diff --git a/sys_util/src/syslog.rs b/sys_util/src/syslog.rs index afe6828..f31ff11 100644 --- a/sys_util/src/syslog.rs +++ b/sys_util/src/syslog.rs @@ -16,17 +16,17 @@ //! //! fn main() { //! if let Err(e) = syslog::init() { -//! println!("failed to initiailize syslog: {:?}", e); +//! println!("failed to initiailize syslog: {}", e); //! return; //! } //! warn!("this is your {} warning", "final"); -//! error!("something went horribly wrong: {:?}", "out of RAMs"); +//! error!("something went horribly wrong: {}", "out of RAMs"); //! } //! ``` use std::env; use std::ffi::{OsStr, OsString}; -use std::fmt; +use std::fmt::{self, Display}; use std::fs::File; use std::io; use std::io::{stderr, Cursor, ErrorKind, Write}; @@ -119,6 +119,21 @@ pub enum Error { InvalidFd, } +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + NeverInitialized => write!(f, "initialization was never attempted"), + Poisoned => write!(f, "initialization previously failed and cannot be retried"), + Socket(e) => write!(f, "failed to create socket: {}", e), + Connect(e) => write!(f, "failed to connect socket: {}", e), + GetLowestFd(e) => write!(f, "failed to get lowest file descriptor: {}", e), + InvalidFd => write!(f, "guess of fd for syslog connection was invalid"), + } + } +} + fn get_hostname() -> Result<String, ()> { let mut hostname: [u8; 256] = [b'\0'; 256]; // Safe because we give a valid pointer to a buffer of the indicated length and check for the @@ -409,7 +424,7 @@ fn get_localtime() -> tm { /// # use sys_util::syslog; /// # fn main() { /// # if let Err(e) = syslog::init() { -/// # println!("failed to initiailize syslog: {:?}", e); +/// # println!("failed to initiailize syslog: {}", e); /// # return; /// # } /// syslog::log(syslog::Priority::Error, diff --git a/tests/plugins.rs b/tests/plugins.rs index 6176a32..e95cc07 100644 --- a/tests/plugins.rs +++ b/tests/plugins.rs @@ -24,7 +24,7 @@ struct RemovePath(PathBuf); impl Drop for RemovePath { fn drop(&mut self) { if let Err(e) = remove_file(&self.0) { - eprintln!("failed to remove path: {:?}", e); + eprintln!("failed to remove path: {}", e); } } } diff --git a/vhost/src/lib.rs b/vhost/src/lib.rs index 552f546..f980bd9 100644 --- a/vhost/src/lib.rs +++ b/vhost/src/lib.rs @@ -14,6 +14,7 @@ pub use net::Net; pub use net::NetT; pub use vsock::Vsock; +use std::fmt::{self, Display}; use std::io::Error as IoError; use std::mem; use std::os::unix::io::AsRawFd; @@ -41,6 +42,22 @@ pub enum Error { } pub type Result<T> = std::result::Result<T, Error>; +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + VhostOpen(e) => write!(f, "failed to open vhost device: {}", e), + IoctlError(e) => write!(f, "failed to run ioctl: {}", e), + InvalidQueue => write!(f, "invalid queue"), + DescriptorTableAddress(e) => write!(f, "invalid descriptor table address: {}", e), + UsedAddress(e) => write!(f, "invalid used address: {}", e), + AvailAddress(e) => write!(f, "invalid available address: {}", e), + LogAddress(e) => write!(f, "invalid log address: {}", e), + } + } +} + fn ioctl_result<T>() -> Result<T> { Err(Error::IoctlError(IoError::last_os_error())) } @@ -331,7 +348,7 @@ mod tests { // FakeNet won't respond to ioctl's Ok(_t) => {} Err(Error::IoctlError(ref ioe)) if ioe.raw_os_error().unwrap() == 25 => {} - Err(e) => panic!("Unexpected Error:\n{:?}", e), + Err(e) => panic!("Unexpected Error:\n{}", e), } } diff --git a/vm_control/src/lib.rs b/vm_control/src/lib.rs index 09e1ea2..514a964 100644 --- a/vm_control/src/lib.rs +++ b/vm_control/src/lib.rs @@ -18,6 +18,7 @@ extern crate resources; #[macro_use] extern crate sys_util; +use std::fmt::{self, Display}; use std::fs::File; use std::io::{Seek, SeekFrom}; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; @@ -78,6 +79,18 @@ pub enum VmRunMode { Exiting, } +impl Display for VmRunMode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::VmRunMode::*; + + match self { + Running => write!(f, "running"), + Suspending => write!(f, "suspending"), + Exiting => write!(f, "exiting"), + } + } +} + impl Default for VmRunMode { fn default() -> Self { VmRunMode::Running @@ -239,13 +252,13 @@ impl VmRequest { // Forward the request to the block device process via its control socket. if let Some(sock) = disk_host_sockets.get(disk_index) { if let Err(e) = sock.send(self) { - error!("disk socket send failed: {:?}", e); + error!("disk socket send failed: {}", e); VmResponse::Err(SysError::new(EINVAL)) } else { match sock.recv() { Ok(result) => result, Err(e) => { - error!("disk socket recv failed: {:?}", e); + error!("disk socket recv failed: {}", e); VmResponse::Err(SysError::new(EINVAL)) } } |