Skip to content

Commit 812ef24

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 <roypat@amazon.co.uk>
1 parent 7f2f4d2 commit 812ef24

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
@@ -51,7 +51,7 @@ pub use guest_memory::{
5151
};
5252

5353
pub mod region;
54-
pub use region::{GuestMemoryRegion, GuestRegionCollection, GuestRegionError as Error};
54+
pub use region::{GuestMemoryRegion, GuestRegionCollection, GuestRegionCollectionError};
5555

5656
pub mod io;
5757
pub use io::{ReadVolatile, WriteVolatile};

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
@@ -142,18 +142,9 @@ pub trait GuestMemoryRegion: Bytes<MemoryRegionAddress, E = GuestMemoryError> {
142142
}
143143
}
144144

145-
/// Errors that can occur when dealing with [`GuestRegion`]s, or collections thereof
145+
/// Errors that can occur when dealing with [`GuestRegionCollection`]s
146146
#[derive(Debug, thiserror::Error)]
147-
pub enum GuestRegionError {
148-
/// Adding the guest base address to the length of the underlying mapping resulted
149-
/// in an overflow.
150-
#[error("Adding the guest base address to the length of the underlying mapping resulted in an overflow")]
151-
#[cfg(feature = "backend-mmap")]
152-
InvalidGuestRegion,
153-
/// Error creating a `MmapRegion` object.
154-
#[error("{0}")]
155-
#[cfg(feature = "backend-mmap")]
156-
MmapRegion(crate::mmap::MmapRegionError),
147+
pub enum GuestRegionCollectionError {
157148
/// No memory region found.
158149
#[error("No memory region found")]
159150
NoMemoryRegion,
@@ -203,7 +194,9 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
203194
/// * `regions` - The vector of regions.
204195
/// The regions shouldn't overlap, and they should be sorted
205196
/// by the starting address.
206-
pub fn from_regions(mut regions: Vec<R>) -> std::result::Result<Self, GuestRegionError> {
197+
pub fn from_regions(
198+
mut regions: Vec<R>,
199+
) -> std::result::Result<Self, GuestRegionCollectionError> {
207200
Self::from_arc_regions(regions.drain(..).map(Arc::new).collect())
208201
}
209202

@@ -219,21 +212,23 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
219212
/// * `regions` - The vector of `Arc` regions.
220213
/// The regions shouldn't overlap and they should be sorted
221214
/// by the starting address.
222-
pub fn from_arc_regions(regions: Vec<Arc<R>>) -> std::result::Result<Self, GuestRegionError> {
215+
pub fn from_arc_regions(
216+
regions: Vec<Arc<R>>,
217+
) -> std::result::Result<Self, GuestRegionCollectionError> {
223218
if regions.is_empty() {
224-
return Err(GuestRegionError::NoMemoryRegion);
219+
return Err(GuestRegionCollectionError::NoMemoryRegion);
225220
}
226221

227222
for window in regions.windows(2) {
228223
let prev = &window[0];
229224
let next = &window[1];
230225

231226
if prev.start_addr() > next.start_addr() {
232-
return Err(GuestRegionError::UnsortedMemoryRegions);
227+
return Err(GuestRegionCollectionError::UnsortedMemoryRegions);
233228
}
234229

235230
if prev.last_addr() >= next.start_addr() {
236-
return Err(GuestRegionError::MemoryRegionOverlap);
231+
return Err(GuestRegionCollectionError::MemoryRegionOverlap);
237232
}
238233
}
239234

@@ -247,7 +242,7 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
247242
pub fn insert_region(
248243
&self,
249244
region: Arc<R>,
250-
) -> std::result::Result<GuestRegionCollection<R>, GuestRegionError> {
245+
) -> std::result::Result<GuestRegionCollection<R>, GuestRegionCollectionError> {
251246
let mut regions = self.regions.clone();
252247
regions.push(region);
253248
regions.sort_by_key(|x| x.start_addr());
@@ -265,7 +260,7 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
265260
&self,
266261
base: GuestAddress,
267262
size: GuestUsize,
268-
) -> std::result::Result<(GuestRegionCollection<R>, Arc<R>), GuestRegionError> {
263+
) -> std::result::Result<(GuestRegionCollection<R>, Arc<R>), GuestRegionCollectionError> {
269264
if let Ok(region_index) = self.regions.binary_search_by_key(&base, |x| x.start_addr()) {
270265
if self.regions.get(region_index).unwrap().len() == size {
271266
let mut regions = self.regions.clone();
@@ -274,7 +269,7 @@ impl<R: GuestMemoryRegion> GuestRegionCollection<R> {
274269
}
275270
}
276271

277-
Err(GuestRegionError::NoMemoryRegion)
272+
Err(GuestRegionCollectionError::NoMemoryRegion)
278273
}
279274
}
280275

@@ -452,7 +447,7 @@ impl<R: GuestMemoryRegionBytes> Bytes<MemoryRegionAddress> for R {
452447

453448
#[cfg(test)]
454449
pub(crate) mod tests {
455-
use crate::region::{GuestMemoryRegionBytes, GuestRegionError};
450+
use crate::region::{GuestMemoryRegionBytes, GuestRegionCollectionError};
456451
use crate::{
457452
Address, GuestAddress, GuestMemory, GuestMemoryRegion, GuestRegionCollection, GuestUsize,
458453
};
@@ -483,7 +478,7 @@ pub(crate) mod tests {
483478
pub(crate) type Collection = GuestRegionCollection<MockRegion>;
484479

485480
fn check_guest_memory_mmap(
486-
maybe_guest_mem: Result<Collection, GuestRegionError>,
481+
maybe_guest_mem: Result<Collection, GuestRegionCollectionError>,
487482
expected_regions_summary: &[(GuestAddress, u64)],
488483
) {
489484
assert!(maybe_guest_mem.is_ok());
@@ -510,7 +505,7 @@ pub(crate) mod tests {
510505

511506
pub(crate) fn new_guest_memory_collection_from_regions(
512507
regions_summary: &[(GuestAddress, u64)],
513-
) -> Result<Collection, GuestRegionError> {
508+
) -> Result<Collection, GuestRegionCollectionError> {
514509
Collection::from_regions(
515510
regions_summary
516511
.iter()
@@ -521,7 +516,7 @@ pub(crate) mod tests {
521516

522517
fn new_guest_memory_collection_from_arc_regions(
523518
regions_summary: &[(GuestAddress, u64)],
524-
) -> Result<Collection, GuestRegionError> {
519+
) -> Result<Collection, GuestRegionCollectionError> {
525520
Collection::from_arc_regions(
526521
regions_summary
527522
.iter()
@@ -536,11 +531,11 @@ pub(crate) mod tests {
536531

537532
assert!(matches!(
538533
new_guest_memory_collection_from_regions(&regions_summary).unwrap_err(),
539-
GuestRegionError::NoMemoryRegion
534+
GuestRegionCollectionError::NoMemoryRegion
540535
));
541536
assert!(matches!(
542537
new_guest_memory_collection_from_arc_regions(&regions_summary).unwrap_err(),
543-
GuestRegionError::NoMemoryRegion
538+
GuestRegionCollectionError::NoMemoryRegion
544539
));
545540
}
546541

@@ -550,11 +545,11 @@ pub(crate) mod tests {
550545

551546
assert!(matches!(
552547
new_guest_memory_collection_from_regions(&regions_summary).unwrap_err(),
553-
GuestRegionError::MemoryRegionOverlap
548+
GuestRegionCollectionError::MemoryRegionOverlap
554549
));
555550
assert!(matches!(
556551
new_guest_memory_collection_from_arc_regions(&regions_summary).unwrap_err(),
557-
GuestRegionError::MemoryRegionOverlap
552+
GuestRegionCollectionError::MemoryRegionOverlap
558553
));
559554
}
560555

@@ -564,11 +559,11 @@ pub(crate) mod tests {
564559

565560
assert!(matches!(
566561
new_guest_memory_collection_from_regions(&regions_summary).unwrap_err(),
567-
GuestRegionError::UnsortedMemoryRegions
562+
GuestRegionCollectionError::UnsortedMemoryRegions
568563
));
569564
assert!(matches!(
570565
new_guest_memory_collection_from_arc_regions(&regions_summary).unwrap_err(),
571-
GuestRegionError::UnsortedMemoryRegions
566+
GuestRegionCollectionError::UnsortedMemoryRegions
572567
));
573568
}
574569

0 commit comments

Comments
 (0)