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