Skip to content

Commit 33ae0b3

Browse files
committed
refactor: clean up region collection related errors
Turn the error type defined in region.rs into one specifically to GuestRegionCollections, and move the non-collection related errors into a new error type that is specific to the `from_ranges*` family of functions (these are the only functions that can return both a region construction error, as well as a collection error). The `from_ranges*` family of functions is publicly exported, but in reality only used in tests, so breakage of this should be limited. Since we're breaking things anyway, remove the reexport of GuestRegionCollectionError as `vm_memory::Error`. It made no sense for this one to have this special designation. Signed-off-by: Patrick Roy <[email protected]>
1 parent dd023ad commit 33ae0b3

File tree

3 files changed

+54
-44
lines changed

3 files changed

+54
-44
lines changed

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub use guest_memory::{
5252

5353
pub mod region;
5454
pub use region::{
55-
GuestMemoryRegion, GuestMemoryRegionBytes, GuestRegionCollection, GuestRegionError as Error,
55+
GuestMemoryRegion, GuestMemoryRegionBytes, GuestRegionCollection, GuestRegionCollectionError,
5656
};
5757

5858
pub mod io;

src/mmap/mod.rs

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@ use std::result;
1919
use crate::address::Address;
2020
use crate::bitmap::{Bitmap, BS};
2121
use crate::guest_memory::{self, FileOffset, GuestAddress, GuestUsize, MemoryRegionAddress};
22-
use crate::region::{GuestMemoryRegion, GuestMemoryRegionBytes};
22+
use crate::region::{
23+
GuestMemoryRegion, GuestMemoryRegionBytes, GuestRegionCollection, GuestRegionCollectionError,
24+
};
2325
use crate::volatile_memory::{VolatileMemory, VolatileSlice};
24-
use crate::{Error, GuestRegionCollection};
2526

2627
// re-export for backward compat, as the trait used to be defined in mmap.rs
2728
pub use crate::bitmap::NewBitmap;
@@ -87,15 +88,14 @@ impl<B: NewBitmap> GuestRegionMmap<B> {
8788
addr: GuestAddress,
8889
size: usize,
8990
file: Option<FileOffset>,
90-
) -> result::Result<Self, Error> {
91+
) -> result::Result<Self, FromRangesError> {
9192
let region = if let Some(ref f_off) = file {
92-
MmapRegion::from_file(f_off.clone(), size)
93+
MmapRegion::from_file(f_off.clone(), size)?
9394
} else {
94-
MmapRegion::new(size)
95-
}
96-
.map_err(Error::MmapRegion)?;
95+
MmapRegion::new(size)?
96+
};
9797

98-
Self::new(region, addr).ok_or(Error::InvalidGuestRegion)
98+
Self::new(region, addr).ok_or(FromRangesError::InvalidGuestRegion)
9999
}
100100
}
101101

@@ -107,11 +107,11 @@ impl<B: NewBitmap> GuestRegionMmap<B> {
107107
addr: GuestAddress,
108108
size: usize,
109109
file: Option<FileOffset>,
110-
) -> result::Result<Self, Error> {
110+
) -> result::Result<Self, FromRangesError> {
111111
let range = MmapRange::new_unix(size, file, addr);
112112

113-
let region = MmapRegion::from_range(range).map_err(Error::MmapRegion)?;
114-
Self::new(region, addr).ok_or(Error::InvalidGuestRegion)
113+
let region = MmapRegion::from_range(range)?;
114+
Self::new(region, addr).ok_or(FromRangesError::InvalidGuestRegion)
115115
}
116116
}
117117

@@ -171,19 +171,33 @@ impl<B: Bitmap> GuestMemoryRegionBytes for GuestRegionMmap<B> {}
171171
/// virtual address space of the calling process.
172172
pub type GuestMemoryMmap<B = ()> = GuestRegionCollection<GuestRegionMmap<B>>;
173173

174+
/// Errors that can happen during [`GuestMemoryMap::from_ranges`] and related functions.
175+
#[derive(Debug, thiserror::Error)]
176+
pub enum FromRangesError {
177+
/// Error during construction of [`GuestMemoryMmap`]
178+
#[error("Error constructing guest region collection: {0}")]
179+
Collection(#[from] GuestRegionCollectionError),
180+
/// Error while allocating raw mmap region
181+
#[error("Error setting up raw memory for guest region: {0}")]
182+
MmapRegion(#[from] MmapRegionError),
183+
/// A combination of region length and guest address would overflow.
184+
#[error("Combination of guest address and region length invalid (would overflow)")]
185+
InvalidGuestRegion,
186+
}
187+
174188
impl<B: NewBitmap> GuestMemoryMmap<B> {
175189
/// Creates a container and allocates anonymous memory for guest memory regions.
176190
///
177191
/// Valid memory regions are specified as a slice of (Address, Size) tuples sorted by Address.
178-
pub fn from_ranges(ranges: &[(GuestAddress, usize)]) -> result::Result<Self, Error> {
192+
pub fn from_ranges(ranges: &[(GuestAddress, usize)]) -> result::Result<Self, FromRangesError> {
179193
Self::from_ranges_with_files(ranges.iter().map(|r| (r.0, r.1, None)))
180194
}
181195

182196
/// Creates a container and allocates anonymous memory for guest memory regions.
183197
///
184198
/// Valid memory regions are specified as a sequence of (Address, Size, [`Option<FileOffset>`])
185199
/// tuples sorted by Address.
186-
pub fn from_ranges_with_files<A, T>(ranges: T) -> result::Result<Self, Error>
200+
pub fn from_ranges_with_files<A, T>(ranges: T) -> result::Result<Self, FromRangesError>
187201
where
188202
A: Borrow<(GuestAddress, usize, Option<FileOffset>)>,
189203
T: IntoIterator<Item = A>,
@@ -194,8 +208,9 @@ impl<B: NewBitmap> GuestMemoryMmap<B> {
194208
.map(|x| {
195209
GuestRegionMmap::from_range(x.borrow().0, x.borrow().1, x.borrow().2.clone())
196210
})
197-
.collect::<result::Result<Vec<_>, Error>>()?,
211+
.collect::<Result<Vec<_>, _>>()?,
198212
)
213+
.map_err(Into::into)
199214
}
200215
}
201216

src/region.rs

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -169,18 +169,9 @@ pub trait GuestMemoryRegion: Bytes<MemoryRegionAddress, E = GuestMemoryError> {
169169
}
170170
}
171171

172-
/// Errors that can occur when dealing with [`GuestRegion`]s, or collections thereof
172+
/// Errors that can occur when dealing with [`GuestRegionCollection`]s
173173
#[derive(Debug, thiserror::Error)]
174-
pub enum GuestRegionError {
175-
/// Adding the guest base address to the length of the underlying mapping resulted
176-
/// in an overflow.
177-
#[error("Adding the guest base address to the length of the underlying mapping resulted in an overflow")]
178-
#[cfg(feature = "backend-mmap")]
179-
InvalidGuestRegion,
180-
/// Error creating a `MmapRegion` object.
181-
#[error("{0}")]
182-
#[cfg(feature = "backend-mmap")]
183-
MmapRegion(crate::mmap::MmapRegionError),
174+
pub enum GuestRegionCollectionError {
184175
/// No memory region found.
185176
#[error("No memory region found")]
186177
NoMemoryRegion,
@@ -230,7 +221,9 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
230221
/// * `regions` - The vector of regions.
231222
/// The regions shouldn't overlap, and they should be sorted
232223
/// by the starting address.
233-
pub fn from_regions(mut regions: Vec<R>) -> std::result::Result<Self, GuestRegionError> {
224+
pub fn from_regions(
225+
mut regions: Vec<R>,
226+
) -> std::result::Result<Self, GuestRegionCollectionError> {
234227
Self::from_arc_regions(regions.drain(..).map(Arc::new).collect())
235228
}
236229

@@ -246,21 +239,23 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
246239
/// * `regions` - The vector of `Arc` regions.
247240
/// The regions shouldn't overlap and they should be sorted
248241
/// by the starting address.
249-
pub fn from_arc_regions(regions: Vec<Arc<R>>) -> std::result::Result<Self, GuestRegionError> {
242+
pub fn from_arc_regions(
243+
regions: Vec<Arc<R>>,
244+
) -> std::result::Result<Self, GuestRegionCollectionError> {
250245
if regions.is_empty() {
251-
return Err(GuestRegionError::NoMemoryRegion);
246+
return Err(GuestRegionCollectionError::NoMemoryRegion);
252247
}
253248

254249
for window in regions.windows(2) {
255250
let prev = &window[0];
256251
let next = &window[1];
257252

258253
if prev.start_addr() > next.start_addr() {
259-
return Err(GuestRegionError::UnsortedMemoryRegions);
254+
return Err(GuestRegionCollectionError::UnsortedMemoryRegions);
260255
}
261256

262257
if prev.last_addr() >= next.start_addr() {
263-
return Err(GuestRegionError::MemoryRegionOverlap);
258+
return Err(GuestRegionCollectionError::MemoryRegionOverlap);
264259
}
265260
}
266261

@@ -274,7 +269,7 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
274269
pub fn insert_region(
275270
&self,
276271
region: Arc<R>,
277-
) -> std::result::Result<GuestRegionCollection<R>, GuestRegionError> {
272+
) -> std::result::Result<GuestRegionCollection<R>, GuestRegionCollectionError> {
278273
let mut regions = self.regions.clone();
279274
regions.push(region);
280275
regions.sort_by_key(|x| x.start_addr());
@@ -292,7 +287,7 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
292287
&self,
293288
base: GuestAddress,
294289
size: GuestUsize,
295-
) -> std::result::Result<(GuestRegionCollection<R>, Arc<R>), GuestRegionError> {
290+
) -> std::result::Result<(GuestRegionCollection<R>, Arc<R>), GuestRegionCollectionError> {
296291
if let Ok(region_index) = self.regions.binary_search_by_key(&base, |x| x.start_addr()) {
297292
if self.regions.get(region_index).unwrap().len() == size {
298293
let mut regions = self.regions.clone();
@@ -301,7 +296,7 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
301296
}
302297
}
303298

304-
Err(GuestRegionError::NoMemoryRegion)
299+
Err(GuestRegionCollectionError::NoMemoryRegion)
305300
}
306301
}
307302

@@ -479,7 +474,7 @@ impl<R: GuestMemoryRegionBytes> Bytes<MemoryRegionAddress> for R {
479474

480475
#[cfg(test)]
481476
pub(crate) mod tests {
482-
use crate::region::{GuestMemoryRegionBytes, GuestRegionError};
477+
use crate::region::{GuestMemoryRegionBytes, GuestRegionCollectionError};
483478
use crate::{
484479
Address, GuestAddress, GuestMemory, GuestMemoryRegion, GuestRegionCollection, GuestUsize,
485480
};
@@ -510,7 +505,7 @@ pub(crate) mod tests {
510505
pub(crate) type Collection = GuestRegionCollection<MockRegion>;
511506

512507
fn check_guest_memory_mmap(
513-
maybe_guest_mem: Result<Collection, GuestRegionError>,
508+
maybe_guest_mem: Result<Collection, GuestRegionCollectionError>,
514509
expected_regions_summary: &[(GuestAddress, u64)],
515510
) {
516511
assert!(maybe_guest_mem.is_ok());
@@ -537,7 +532,7 @@ pub(crate) mod tests {
537532

538533
pub(crate) fn new_guest_memory_collection_from_regions(
539534
regions_summary: &[(GuestAddress, u64)],
540-
) -> Result<Collection, GuestRegionError> {
535+
) -> Result<Collection, GuestRegionCollectionError> {
541536
Collection::from_regions(
542537
regions_summary
543538
.iter()
@@ -548,7 +543,7 @@ pub(crate) mod tests {
548543

549544
fn new_guest_memory_collection_from_arc_regions(
550545
regions_summary: &[(GuestAddress, u64)],
551-
) -> Result<Collection, GuestRegionError> {
546+
) -> Result<Collection, GuestRegionCollectionError> {
552547
Collection::from_arc_regions(
553548
regions_summary
554549
.iter()
@@ -563,11 +558,11 @@ pub(crate) mod tests {
563558

564559
assert!(matches!(
565560
new_guest_memory_collection_from_regions(&regions_summary).unwrap_err(),
566-
GuestRegionError::NoMemoryRegion
561+
GuestRegionCollectionError::NoMemoryRegion
567562
));
568563
assert!(matches!(
569564
new_guest_memory_collection_from_arc_regions(&regions_summary).unwrap_err(),
570-
GuestRegionError::NoMemoryRegion
565+
GuestRegionCollectionError::NoMemoryRegion
571566
));
572567
}
573568

@@ -577,11 +572,11 @@ pub(crate) mod tests {
577572

578573
assert!(matches!(
579574
new_guest_memory_collection_from_regions(&regions_summary).unwrap_err(),
580-
GuestRegionError::MemoryRegionOverlap
575+
GuestRegionCollectionError::MemoryRegionOverlap
581576
));
582577
assert!(matches!(
583578
new_guest_memory_collection_from_arc_regions(&regions_summary).unwrap_err(),
584-
GuestRegionError::MemoryRegionOverlap
579+
GuestRegionCollectionError::MemoryRegionOverlap
585580
));
586581
}
587582

@@ -591,11 +586,11 @@ pub(crate) mod tests {
591586

592587
assert!(matches!(
593588
new_guest_memory_collection_from_regions(&regions_summary).unwrap_err(),
594-
GuestRegionError::UnsortedMemoryRegions
589+
GuestRegionCollectionError::UnsortedMemoryRegions
595590
));
596591
assert!(matches!(
597592
new_guest_memory_collection_from_arc_regions(&regions_summary).unwrap_err(),
598-
GuestRegionError::UnsortedMemoryRegions
593+
GuestRegionCollectionError::UnsortedMemoryRegions
599594
));
600595
}
601596

0 commit comments

Comments
 (0)