Skip to content

Commit 362d0a9

Browse files
committed
Add mmap_anonymous function
1 parent 996db47 commit 362d0a9

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/sys/mman.rs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -426,8 +426,7 @@ pub unsafe fn mmap<F: AsFd>(
426426
f: Option<F>,
427427
offset: off_t,
428428
) -> Result<*mut c_void> {
429-
let ptr =
430-
addr.map_or(std::ptr::null_mut(), |a| usize::from(a) as *mut c_void);
429+
let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void);
431430

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

442+
/// Create an anonymous memory mapping.
443+
///
444+
/// This function is a wrapper around [`mmap`]:
445+
/// `mmap(ptr, len, prot, MAP_ANONYMOUS | flags, -1, 0)`.
446+
///
447+
/// # Safety
448+
///
449+
/// See the [`mmap(2)`] man page for detailed requirements.
450+
///
451+
/// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
452+
pub unsafe fn mmap_anonymous(
453+
addr: Option<NonZeroUsize>,
454+
length: NonZeroUsize,
455+
prot: ProtFlags,
456+
flags: MapFlags,
457+
) -> Result<*mut c_void> {
458+
let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void);
459+
460+
let flags = MapFlags::MAP_ANONYMOUS | flags;
461+
let ret = libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), -1, 0);
462+
463+
if ret == libc::MAP_FAILED {
464+
Err(Errno::last())
465+
} else {
466+
Ok(ret)
467+
}
468+
}
469+
443470
/// Expands (or shrinks) an existing memory mapping, potentially moving it at
444471
/// the same time.
445472
///

0 commit comments

Comments
 (0)