@@ -9,6 +9,7 @@ use std::fs::File;
99use std:: io:: { Read , Seek , SeekFrom } ;
1010use std:: mem:: ManuallyDrop ;
1111use std:: os:: fd:: AsRawFd ;
12+ use std:: ptr:: null_mut;
1213use std:: sync:: Arc ;
1314
1415use kvm_bindings:: { KVM_MEM_LOG_DIRTY_PAGES , kvm_userspace_memory_region2} ;
@@ -55,6 +56,8 @@ pub enum MemoryError {
5556 MemfdSetLen ( std:: io:: Error ) ,
5657 /// Total sum of memory regions exceeds largest possible file offset
5758 OffsetTooLarge ,
59+ /// Error calling mmap: {0}
60+ Mmap ( std:: io:: Error ) ,
5861}
5962
6063/// Newtype that implements [`ReadVolatile`] and [`WriteVolatile`] if `T` implements `Read` or
@@ -246,16 +249,40 @@ pub fn create(
246249 let mut builder = MmapRegionBuilder :: new_with_bitmap (
247250 size,
248251 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+ ) ;
252253
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 {
254257 let file_offset = FileOffset :: from_arc ( Arc :: clone ( file) , offset) ;
255258
256259 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 ( ) ) ) ;
257280 }
258281
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+
259286 offset = match offset. checked_add ( size as u64 ) {
260287 None => return Err ( MemoryError :: OffsetTooLarge ) ,
261288 Some ( new_off) if new_off >= i64:: MAX as u64 => {
0 commit comments