@@ -9,6 +9,7 @@ use std::fs::File;
9
9
use std:: io:: { Read , Seek , SeekFrom } ;
10
10
use std:: mem:: ManuallyDrop ;
11
11
use std:: os:: fd:: AsRawFd ;
12
+ use std:: ptr:: null_mut;
12
13
use std:: sync:: Arc ;
13
14
14
15
use kvm_bindings:: { KVM_MEM_LOG_DIRTY_PAGES , kvm_userspace_memory_region2} ;
@@ -56,6 +57,8 @@ pub enum MemoryError {
56
57
MemfdSetLen ( std:: io:: Error ) ,
57
58
/// Total sum of memory regions exceeds largest possible file offset
58
59
OffsetTooLarge ,
60
+ /// Error calling mmap: {0}
61
+ Mmap ( std:: io:: Error ) ,
59
62
}
60
63
61
64
/// Newtype that implements [`ReadVolatile`] and [`WriteVolatile`] if `T` implements `Read` or
@@ -249,16 +252,40 @@ pub fn create(
249
252
let mut builder = MmapRegionBuilder :: new_with_bitmap (
250
253
size,
251
254
track_dirty_pages. then ( || AtomicBitmap :: with_len ( size) ) ,
252
- )
253
- . with_mmap_prot ( libc:: PROT_READ | libc:: PROT_WRITE )
254
- . with_mmap_flags ( libc:: MAP_NORESERVE | mmap_flags) ;
255
+ ) ;
255
256
256
- if let Some ( ref file) = file {
257
+ // when computing offset below we ensure it fits into i64
258
+ #[ allow( clippy:: cast_possible_wrap) ]
259
+ let ( fd, fd_off) = if let Some ( ref file) = file {
257
260
let file_offset = FileOffset :: from_arc ( Arc :: clone ( file) , offset) ;
258
261
259
262
builder = builder. with_file_offset ( file_offset) ;
263
+
264
+ ( file. as_raw_fd ( ) , offset as libc:: off_t )
265
+ } else {
266
+ ( -1 , 0 )
267
+ } ;
268
+
269
+ // SAFETY: the arguments to mmap cannot cause any memory unsafety in the rust sense
270
+ let ptr = unsafe {
271
+ libc:: mmap (
272
+ null_mut ( ) ,
273
+ size,
274
+ libc:: PROT_READ | libc:: PROT_WRITE ,
275
+ libc:: MAP_NORESERVE | mmap_flags,
276
+ fd,
277
+ fd_off,
278
+ )
279
+ } ;
280
+
281
+ if ptr == libc:: MAP_FAILED {
282
+ return Err ( MemoryError :: Mmap ( std:: io:: Error :: last_os_error ( ) ) ) ;
260
283
}
261
284
285
+ // SAFETY: we check above that mmap succeeded, and the size we passed to builder is the
286
+ // same as the size of the mmap area.
287
+ let builder = unsafe { builder. with_raw_mmap_pointer ( ptr. cast ( ) ) } ;
288
+
262
289
offset = match offset. checked_add ( size as u64 ) {
263
290
None => return Err ( MemoryError :: OffsetTooLarge ) ,
264
291
Some ( new_off) if new_off >= i64:: MAX as u64 => {
0 commit comments