Skip to content

Commit

Permalink
Add mmap_nofd function
Browse files Browse the repository at this point in the history
  • Loading branch information
newpavlov committed Sep 8, 2023
1 parent 996db47 commit 1708bd0
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 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,31 @@ pub unsafe fn mmap<F: AsFd>(
}
}

/// Variant of the [`mmap`] function, which uses `None` for the
/// `f` argument and `0` for `offset`.
///
/// # 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_nofd(
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 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 1708bd0

Please sign in to comment.