Skip to content

Commit 6c922b5

Browse files
Jonathan Woollett-Lightandreeaflorescu
authored andcommitted
fix: thiserror::Error
Implements the`thiserror::Error` derive macro. Signed-off-by: Jonathan Woollett-Light <[email protected]>
1 parent 8d804d0 commit 6c922b5

File tree

7 files changed

+31
-120
lines changed

7 files changed

+31
-120
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ backend-atomic = ["arc-swap"]
2020
[dependencies]
2121
libc = "0.2.39"
2222
arc-swap = { version = "1.0.0", optional = true }
23+
thiserror = "1.0.40"
2324

2425
[target.'cfg(windows)'.dependencies.winapi]
2526
version = "0.3"

coverage_config_x86_64.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"coverage_score": 89.7,
2+
"coverage_score": 91.1,
33
"exclude_path": "mmap_windows.rs",
44
"crate_features": "backend-mmap,backend-atomic,backend-bitmap"
55
}

src/guest_memory.rs

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
//! `VolatileSlice`, `VolatileRef`, or `VolatileArrayRef`.
4343
4444
use std::convert::From;
45-
use std::fmt::{self, Display};
4645
use std::fs::File;
4746
use std::io::{self, Read, Write};
4847
use std::ops::{BitAnd, BitOr, Deref};
@@ -59,17 +58,22 @@ static MAX_ACCESS_CHUNK: usize = 4096;
5958

6059
/// Errors associated with handling guest memory accesses.
6160
#[allow(missing_docs)]
62-
#[derive(Debug)]
61+
#[derive(Debug, thiserror::Error)]
6362
pub enum Error {
6463
/// Failure in finding a guest address in any memory regions mapped by this guest.
64+
#[error("Guest memory error: invalid guest address {}",.0.raw_value())]
6565
InvalidGuestAddress(GuestAddress),
6666
/// Couldn't read/write from the given source.
67+
#[error("Guest memory error: {0}")]
6768
IOError(io::Error),
6869
/// Incomplete read or write.
70+
#[error("Guest memory error: only used {completed} bytes in {expected} long buffer")]
6971
PartialBuffer { expected: usize, completed: usize },
7072
/// Requested backend address is out of range.
73+
#[error("Guest memory error: invalid backend address")]
7174
InvalidBackendAddress,
7275
/// Host virtual address not available.
76+
#[error("Guest memory error: host virtual address not available")]
7377
HostAddressNotAvailable,
7478
}
7579

@@ -95,30 +99,6 @@ impl From<volatile_memory::Error> for Error {
9599
/// Result of guest memory operations.
96100
pub type Result<T> = std::result::Result<T, Error>;
97101

98-
impl std::error::Error for Error {}
99-
100-
impl Display for Error {
101-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102-
write!(f, "Guest memory error: ")?;
103-
match self {
104-
Error::InvalidGuestAddress(addr) => {
105-
write!(f, "invalid guest address {}", addr.raw_value())
106-
}
107-
Error::IOError(error) => write!(f, "{}", error),
108-
Error::PartialBuffer {
109-
expected,
110-
completed,
111-
} => write!(
112-
f,
113-
"only used {} bytes in {} long buffer",
114-
completed, expected,
115-
),
116-
Error::InvalidBackendAddress => write!(f, "invalid backend address"),
117-
Error::HostAddressNotAvailable => write!(f, "host virtual address not available"),
118-
}
119-
}
120-
}
121-
122102
/// Represents a guest physical address (GPA).
123103
///
124104
/// # Notes:

src/mmap.rs

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
//! This implementation is mmap-ing the memory of the guest into the current process.
1414
1515
use std::borrow::Borrow;
16-
use std::error;
17-
use std::fmt;
1816
use std::io::{Read, Write};
1917
#[cfg(unix)]
2018
use std::io::{Seek, SeekFrom};
@@ -51,43 +49,26 @@ impl NewBitmap for () {
5149
}
5250

5351
/// Errors that can occur when creating a memory map.
54-
#[derive(Debug)]
52+
#[derive(Debug, thiserror::Error)]
5553
pub enum Error {
5654
/// Adding the guest base address to the length of the underlying mapping resulted
5755
/// in an overflow.
56+
#[error("Adding the guest base address to the length of the underlying mapping resulted in an overflow")]
5857
InvalidGuestRegion,
5958
/// Error creating a `MmapRegion` object.
59+
#[error("{0}")]
6060
MmapRegion(MmapRegionError),
6161
/// No memory region found.
62+
#[error("No memory region found")]
6263
NoMemoryRegion,
6364
/// Some of the memory regions intersect with each other.
65+
#[error("Some of the memory regions intersect with each other")]
6466
MemoryRegionOverlap,
6567
/// The provided memory regions haven't been sorted.
68+
#[error("The provided memory regions haven't been sorted")]
6669
UnsortedMemoryRegions,
6770
}
6871

69-
impl fmt::Display for Error {
70-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71-
match self {
72-
Error::InvalidGuestRegion => write!(
73-
f,
74-
"Adding the guest base address to the length of the underlying mapping \
75-
resulted in an overflow"
76-
),
77-
Error::MmapRegion(e) => write!(f, "{}", e),
78-
Error::NoMemoryRegion => write!(f, "No memory region found"),
79-
Error::MemoryRegionOverlap => {
80-
write!(f, "Some of the memory regions intersect with each other")
81-
}
82-
Error::UnsortedMemoryRegions => {
83-
write!(f, "The provided memory regions haven't been sorted")
84-
}
85-
}
86-
}
87-
}
88-
89-
impl error::Error for Error {}
90-
9172
// TODO: use this for Windows as well after we redefine the Error type there.
9273
#[cfg(unix)]
9374
/// Checks if a mapping of `size` bytes fits at the provided `file_offset`.

src/mmap_unix.rs

Lines changed: 9 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@
1010

1111
//! Helper structure for working with mmaped memory regions in Unix.
1212
13-
use std::error;
14-
use std::fmt;
1513
use std::io;
1614
use std::os::unix::io::AsRawFd;
1715
use std::ptr::null_mut;
@@ -23,55 +21,34 @@ use crate::mmap::{check_file_offset, NewBitmap};
2321
use crate::volatile_memory::{self, VolatileMemory, VolatileSlice};
2422

2523
/// Error conditions that may arise when creating a new `MmapRegion` object.
26-
#[derive(Debug)]
24+
#[derive(Debug, thiserror::Error)]
2725
pub enum Error {
2826
/// The specified file offset and length cause overflow when added.
27+
#[error("The specified file offset and length cause overflow when added")]
2928
InvalidOffsetLength,
3029
/// The specified pointer to the mapping is not page-aligned.
30+
#[error("The specified pointer to the mapping is not page-aligned")]
3131
InvalidPointer,
3232
/// The forbidden `MAP_FIXED` flag was specified.
33+
#[error("The forbidden `MAP_FIXED` flag was specified")]
3334
MapFixed,
3435
/// Mappings using the same fd overlap in terms of file offset and length.
36+
#[error("Mappings using the same fd overlap in terms of file offset and length")]
3537
MappingOverlap,
3638
/// A mapping with offset + length > EOF was attempted.
39+
#[error("The specified file offset and length is greater then file length")]
3740
MappingPastEof,
3841
/// The `mmap` call returned an error.
42+
#[error("{0}")]
3943
Mmap(io::Error),
4044
/// Seeking the end of the file returned an error.
45+
#[error("Error seeking the end of the file: {0}")]
4146
SeekEnd(io::Error),
4247
/// Seeking the start of the file returned an error.
48+
#[error("Error seeking the start of the file: {0}")]
4349
SeekStart(io::Error),
4450
}
4551

46-
impl fmt::Display for Error {
47-
fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
48-
match self {
49-
Error::InvalidOffsetLength => write!(
50-
f,
51-
"The specified file offset and length cause overflow when added"
52-
),
53-
Error::InvalidPointer => write!(
54-
f,
55-
"The specified pointer to the mapping is not page-aligned",
56-
),
57-
Error::MapFixed => write!(f, "The forbidden `MAP_FIXED` flag was specified"),
58-
Error::MappingOverlap => write!(
59-
f,
60-
"Mappings using the same fd overlap in terms of file offset and length"
61-
),
62-
Error::MappingPastEof => write!(
63-
f,
64-
"The specified file offset and length is greater then file length"
65-
),
66-
Error::Mmap(error) => write!(f, "{}", error),
67-
Error::SeekEnd(error) => write!(f, "Error seeking the end of the file: {}", error),
68-
Error::SeekStart(error) => write!(f, "Error seeking the start of the file: {}", error),
69-
}
70-
}
71-
}
72-
73-
impl error::Error for Error {}
74-
7552
pub type Result<T> = result::Result<T, Error>;
7653

7754
/// A factory struct to build `MmapRegion` objects.

src/volatile_memory.rs

Lines changed: 7 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424
//! not reordered or elided the access.
2525
2626
use std::cmp::min;
27-
use std::error;
28-
use std::fmt;
2927
use std::io::{self, Read, Write};
3028
use std::marker::PhantomData;
3129
use std::mem::{align_of, size_of};
@@ -43,54 +41,28 @@ use copy_slice_impl::copy_slice;
4341

4442
/// `VolatileMemory` related errors.
4543
#[allow(missing_docs)]
46-
#[derive(Debug)]
44+
#[derive(Debug, thiserror::Error)]
4745
pub enum Error {
4846
/// `addr` is out of bounds of the volatile memory slice.
47+
#[error("address 0x{addr:x} is out of bounds")]
4948
OutOfBounds { addr: usize },
5049
/// Taking a slice at `base` with `offset` would overflow `usize`.
50+
#[error("address 0x{base:x} offset by 0x{offset:x} would overflow")]
5151
Overflow { base: usize, offset: usize },
5252
/// Taking a slice whose size overflows `usize`.
53+
#[error("{nelements:?} elements of size {size:?} would overflow a usize")]
5354
TooBig { nelements: usize, size: usize },
5455
/// Trying to obtain a misaligned reference.
56+
#[error("address 0x{addr:x} is not aligned to {alignment:?}")]
5557
Misaligned { addr: usize, alignment: usize },
5658
/// Writing to memory failed
59+
#[error("{0}")]
5760
IOError(io::Error),
5861
/// Incomplete read or write
62+
#[error("only used {completed} bytes in {expected} long buffer")]
5963
PartialBuffer { expected: usize, completed: usize },
6064
}
6165

62-
impl fmt::Display for Error {
63-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64-
match self {
65-
Error::OutOfBounds { addr } => write!(f, "address 0x{:x} is out of bounds", addr),
66-
Error::Overflow { base, offset } => write!(
67-
f,
68-
"address 0x{:x} offset by 0x{:x} would overflow",
69-
base, offset
70-
),
71-
Error::TooBig { nelements, size } => write!(
72-
f,
73-
"{:?} elements of size {:?} would overflow a usize",
74-
nelements, size
75-
),
76-
Error::Misaligned { addr, alignment } => {
77-
write!(f, "address 0x{:x} is not aligned to {:?}", addr, alignment)
78-
}
79-
Error::IOError(error) => write!(f, "{}", error),
80-
Error::PartialBuffer {
81-
expected,
82-
completed,
83-
} => write!(
84-
f,
85-
"only used {} bytes in {} long buffer",
86-
completed, expected
87-
),
88-
}
89-
}
90-
}
91-
92-
impl error::Error for Error {}
93-
9466
/// Result of volatile memory operations.
9567
pub type Result<T> = result::Result<T, Error>;
9668

0 commit comments

Comments
 (0)