Skip to content

Commit 1708bd0

Browse files
committed
Add mmap_nofd function
1 parent 996db47 commit 1708bd0

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

src/sys/mman.rs

Lines changed: 26 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,31 @@ pub unsafe fn mmap<F: AsFd>(
440439
}
441440
}
442441

442+
/// Variant of the [`mmap`] function, which uses `None` for the
443+
/// `f` argument and `0` for `offset`.
444+
///
445+
/// # Safety
446+
///
447+
/// See the [`mmap(2)`] man page for detailed requirements.
448+
///
449+
/// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
450+
pub unsafe fn mmap_nofd(
451+
addr: Option<NonZeroUsize>,
452+
length: NonZeroUsize,
453+
prot: ProtFlags,
454+
flags: MapFlags,
455+
) -> Result<*mut c_void> {
456+
let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void);
457+
458+
let ret = libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), -1, 0);
459+
460+
if ret == libc::MAP_FAILED {
461+
Err(Errno::last())
462+
} else {
463+
Ok(ret)
464+
}
465+
}
466+
443467
/// Expands (or shrinks) an existing memory mapping, potentially moving it at
444468
/// the same time.
445469
///

0 commit comments

Comments
 (0)