Skip to content

Commit

Permalink
Add mmap_anonymous function
Browse files Browse the repository at this point in the history
  • Loading branch information
newpavlov committed Oct 2, 2023
1 parent 996db47 commit 362d0a9
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions src/sys/mman.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,7 @@ pub unsafe fn mmap<F: AsFd>(
f: Option<F>,
offset: off_t,
) -> Result<*mut c_void> {
let ptr =
addr.map_or(std::ptr::null_mut(), |a| usize::from(a) as *mut c_void);
let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void);

let fd = f.map(|f| f.as_fd().as_raw_fd()).unwrap_or(-1);
let ret =
Expand All @@ -440,6 +439,34 @@ pub unsafe fn mmap<F: AsFd>(
}
}

/// Create an anonymous memory mapping.
///
/// This function is a wrapper around [`mmap`]:
/// `mmap(ptr, len, prot, MAP_ANONYMOUS | flags, -1, 0)`.
///
/// # Safety
///
/// See the [`mmap(2)`] man page for detailed requirements.
///
/// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
pub unsafe fn mmap_anonymous(
addr: Option<NonZeroUsize>,
length: NonZeroUsize,
prot: ProtFlags,
flags: MapFlags,
) -> Result<*mut c_void> {
let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void);

let flags = MapFlags::MAP_ANONYMOUS | flags;
let ret = libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), -1, 0);

if ret == libc::MAP_FAILED {
Err(Errno::last())
} else {
Ok(ret)
}
}

/// Expands (or shrinks) an existing memory mapping, potentially moving it at
/// the same time.
///
Expand Down

0 comments on commit 362d0a9

Please sign in to comment.