#![deny(clippy::all, clippy::pedantic)]
#![deny(unsafe_op_in_unsafe_fn)]
#![allow(
// pedantic exceptions
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss,
clippy::doc_markdown,
clippy::explicit_deref_methods,
clippy::missing_errors_doc,
clippy::module_name_repetitions,
clippy::must_use_candidate,
clippy::needless_pass_by_value,
clippy::return_self_not_must_use,
clippy::unreadable_literal,
clippy::upper_case_acronyms,
)]
#![allow(clippy::len_without_is_empty, clippy::missing_safety_doc)]
#[cfg_attr(unix, path = "unix.rs")]
#[cfg_attr(windows, path = "windows.rs")]
#[cfg_attr(not(any(unix, windows)), path = "stub.rs")]
mod os;
use crate::os::{file_len, MmapInner};
#[cfg(unix)]
mod advice;
#[cfg(unix)]
pub use crate::advice::{Advice, UncheckedAdvice};
use std::fmt;
#[cfg(not(any(unix, windows)))]
use std::fs::File;
use std::io::{Error, ErrorKind};
use std::ops::{Deref, DerefMut};
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawHandle, RawHandle};
use std::slice;
#[cfg(not(any(unix, windows)))]
pub struct MmapRawDescriptor<'a>(&'a File);
#[cfg(unix)]
pub struct MmapRawDescriptor(RawFd);
#[cfg(windows)]
pub struct MmapRawDescriptor(RawHandle);
pub trait MmapAsRawDesc {
fn as_raw_desc(&self) -> MmapRawDescriptor;
}
#[cfg(not(any(unix, windows)))]
impl MmapAsRawDesc for &File {
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(self)
}
}
#[cfg(unix)]
impl MmapAsRawDesc for RawFd {
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(*self)
}
}
#[cfg(unix)]
impl<T> MmapAsRawDesc for &T
where
T: AsRawFd,
{
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(self.as_raw_fd())
}
}
#[cfg(windows)]
impl MmapAsRawDesc for RawHandle {
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(*self)
}
}
#[cfg(windows)]
impl<T> MmapAsRawDesc for &T
where
T: AsRawHandle,
{
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(self.as_raw_handle())
}
}
pub struct MapIfSafeError {
inner: MapIfSafeErrorInner,
}
#[derive(Debug)]
#[allow(dead_code)] enum MapIfSafeErrorInner {
NotSupported,
NotSafe(std::io::Error),
MapFailed(std::io::Error),
}
impl MapIfSafeError {
#[allow(dead_code)] fn new_not_supported() -> Self {
let inner = MapIfSafeErrorInner::NotSupported;
Self { inner }
}
#[allow(dead_code)] fn new_not_safe(reason: std::io::Error) -> Self {
let inner = MapIfSafeErrorInner::NotSafe(reason);
Self { inner }
}
#[allow(dead_code)] fn new_map_failed(reason: std::io::Error) -> Self {
let inner = MapIfSafeErrorInner::MapFailed(reason);
Self { inner }
}
pub fn not_supported(&self) -> bool {
matches!(self.inner, MapIfSafeErrorInner::NotSupported)
}
pub fn not_safe(&self) -> bool {
matches!(self.inner, MapIfSafeErrorInner::NotSafe(_))
}
pub fn map_failed(&self) -> bool {
matches!(self.inner, MapIfSafeErrorInner::MapFailed(_))
}
}
impl std::error::Error for MapIfSafeError {}
impl fmt::Display for MapIfSafeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[allow(clippy::match_same_arms)]
match &self.inner {
MapIfSafeErrorInner::NotSupported => {
fmt::Display::fmt(&Error::from(ErrorKind::Unsupported), f)
}
MapIfSafeErrorInner::NotSafe(e) => fmt::Display::fmt(e, f),
MapIfSafeErrorInner::MapFailed(e) => fmt::Display::fmt(e, f),
}
}
}
impl fmt::Debug for MapIfSafeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.inner, f)
}
}
impl From<MapIfSafeError> for std::io::Error {
fn from(value: MapIfSafeError) -> Self {
#[allow(clippy::match_same_arms)]
match value.inner {
MapIfSafeErrorInner::NotSupported => std::io::ErrorKind::Unsupported.into(),
MapIfSafeErrorInner::NotSafe(e) => e,
MapIfSafeErrorInner::MapFailed(e) => e,
}
}
}
#[derive(Clone, Debug, Default)]
#[allow(clippy::struct_excessive_bools)]
pub struct MmapOptions {
offset: u64,
len: Option<usize>,
huge: Option<u8>,
stack: bool,
populate: bool,
no_reserve_swap: bool,
no_probe_handle: bool,
}
impl MmapOptions {
pub fn new() -> MmapOptions {
MmapOptions::default()
}
pub fn offset(&mut self, offset: u64) -> &mut Self {
self.offset = offset;
self
}
pub fn len(&mut self, len: usize) -> &mut Self {
self.len = Some(len);
self
}
fn validate_len(len: u64) -> std::io::Result<usize> {
if isize::try_from(len).is_err() {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map length overflows isize",
));
}
Ok(len as usize)
}
fn get_len<T: MmapAsRawDesc>(&self, file: &T) -> std::io::Result<usize> {
let len = if let Some(len) = self.len {
len as u64
} else {
let desc = file.as_raw_desc();
let file_len = file_len(desc.0)?;
if file_len < self.offset {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map offset is larger than length",
));
}
file_len - self.offset
};
Self::validate_len(len)
}
pub fn stack(&mut self) -> &mut Self {
self.stack = true;
self
}
pub fn huge(&mut self, page_bits: Option<u8>) -> &mut Self {
self.huge = Some(page_bits.unwrap_or(0));
self
}
pub fn populate(&mut self) -> &mut Self {
self.populate = true;
self
}
pub fn no_reserve_swap(&mut self) -> &mut Self {
self.no_reserve_swap = true;
self
}
pub fn no_probe_handle(&mut self) -> &mut Self {
self.no_probe_handle = true;
self
}
pub unsafe fn map<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<Mmap> {
let desc = file.as_raw_desc();
MmapInner::map(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| Mmap { inner })
}
pub unsafe fn map_exec<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<Mmap> {
let desc = file.as_raw_desc();
MmapInner::map_exec(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| Mmap { inner })
}
pub unsafe fn map_mut<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<MmapMut> {
let desc = file.as_raw_desc();
MmapInner::map_mut(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| MmapMut { inner })
}
pub unsafe fn map_copy<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<MmapMut> {
let desc = file.as_raw_desc();
MmapInner::map_copy(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| MmapMut { inner })
}
pub unsafe fn map_copy_read_only<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<Mmap> {
let desc = file.as_raw_desc();
MmapInner::map_copy_read_only(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| Mmap { inner })
}
pub fn map_if_safe<T: MmapAsRawDesc>(&self, file: T) -> Result<Mmap, MapIfSafeError> {
let desc = file.as_raw_desc();
let len = self
.get_len(&file)
.map_err(MapIfSafeError::new_map_failed)?;
MmapInner::check_safe_to_map(desc.0, self.offset, len)?;
MmapInner::map(
len,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map_err(MapIfSafeError::new_map_failed)
.map(|inner| Mmap { inner })
}
pub fn map_anon(&self) -> std::io::Result<MmapMut> {
let len = self.len.unwrap_or(0);
let len = Self::validate_len(len as u64)?;
MmapInner::map_anon(
len,
self.stack,
self.populate,
self.huge,
self.no_reserve_swap,
)
.map(|inner| MmapMut { inner })
}
pub fn map_raw<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<MmapRaw> {
let desc = file.as_raw_desc();
MmapInner::map_mut(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| MmapRaw { inner })
}
pub fn map_raw_read_only<T: MmapAsRawDesc>(&self, file: T) -> std::io::Result<MmapRaw> {
let desc = file.as_raw_desc();
MmapInner::map(
self.get_len(&file)?,
desc.0,
self.offset,
self.populate,
self.no_reserve_swap,
!self.no_probe_handle,
)
.map(|inner| MmapRaw { inner })
}
}
pub struct Mmap {
inner: MmapInner,
}
impl Mmap {
pub unsafe fn map<T: MmapAsRawDesc>(file: T) -> std::io::Result<Mmap> {
unsafe { MmapOptions::new().map(file) }
}
pub fn map_if_safe<T: MmapAsRawDesc>(file: T) -> Result<Mmap, MapIfSafeError> {
MmapOptions::new().map_if_safe(file)
}
pub fn make_mut(mut self) -> std::io::Result<MmapMut> {
self.inner.make_mut()?;
Ok(MmapMut { inner: self.inner })
}
#[cfg(unix)]
pub fn advise(&self, advice: Advice) -> std::io::Result<()> {
unsafe {
self.inner
.advise(advice as libc::c_int, 0, self.inner.len())
}
}
#[cfg(unix)]
pub unsafe fn unchecked_advise(&self, advice: UncheckedAdvice) -> std::io::Result<()> {
unsafe {
self.inner
.advise(advice as libc::c_int, 0, self.inner.len())
}
}
#[cfg(unix)]
pub fn advise_range(&self, advice: Advice, offset: usize, len: usize) -> std::io::Result<()> {
unsafe { self.inner.advise(advice as libc::c_int, offset, len) }
}
#[cfg(unix)]
pub unsafe fn unchecked_advise_range(
&self,
advice: UncheckedAdvice,
offset: usize,
len: usize,
) -> std::io::Result<()> {
unsafe { self.inner.advise(advice as libc::c_int, offset, len) }
}
#[cfg(unix)]
pub fn lock(&self) -> std::io::Result<()> {
self.inner.lock()
}
#[cfg(unix)]
pub fn unlock(&self) -> std::io::Result<()> {
self.inner.unlock()
}
#[cfg(target_os = "linux")]
pub unsafe fn remap(&mut self, new_len: usize, options: RemapOptions) -> std::io::Result<()> {
self.inner.remap(new_len, options)
}
}
#[cfg(feature = "stable_deref_trait")]
unsafe impl stable_deref_trait::StableDeref for Mmap {}
impl Deref for Mmap {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.inner.ptr(), self.inner.len()) }
}
}
impl AsRef<[u8]> for Mmap {
#[inline]
fn as_ref(&self) -> &[u8] {
self.deref()
}
}
impl fmt::Debug for Mmap {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Mmap")
.field("ptr", &self.as_ptr())
.field("len", &self.len())
.finish()
}
}
pub struct MmapRaw {
inner: MmapInner,
}
impl MmapRaw {
pub fn map_raw<T: MmapAsRawDesc>(file: T) -> std::io::Result<MmapRaw> {
MmapOptions::new().map_raw(file)
}
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.inner.ptr()
}
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
self.inner.ptr().cast_mut()
}
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn flush(&self) -> std::io::Result<()> {
let len = self.len();
self.inner.flush(0, len)
}
pub fn flush_async(&self) -> std::io::Result<()> {
let len = self.len();
self.inner.flush_async(0, len)
}
pub fn flush_range(&self, offset: usize, len: usize) -> std::io::Result<()> {
self.inner.flush(offset, len)
}
pub fn flush_async_range(&self, offset: usize, len: usize) -> std::io::Result<()> {
self.inner.flush_async(offset, len)
}
#[cfg(unix)]
pub fn advise(&self, advice: Advice) -> std::io::Result<()> {
unsafe {
self.inner
.advise(advice as libc::c_int, 0, self.inner.len())
}
}
#[cfg(unix)]
pub unsafe fn unchecked_advise(&self, advice: UncheckedAdvice) -> std::io::Result<()> {
unsafe {
self.inner
.advise(advice as libc::c_int, 0, self.inner.len())
}
}
#[cfg(unix)]
pub fn advise_range(&self, advice: Advice, offset: usize, len: usize) -> std::io::Result<()> {
unsafe { self.inner.advise(advice as libc::c_int, offset, len) }
}
#[cfg(unix)]
pub unsafe fn unchecked_advise_range(
&self,
advice: UncheckedAdvice,
offset: usize,
len: usize,
) -> std::io::Result<()> {
unsafe { self.inner.advise(advice as libc::c_int, offset, len) }
}
#[cfg(unix)]
pub fn lock(&self) -> std::io::Result<()> {
self.inner.lock()
}
#[cfg(unix)]
pub fn unlock(&self) -> std::io::Result<()> {
self.inner.unlock()
}
#[cfg(target_os = "linux")]
pub unsafe fn remap(&mut self, new_len: usize, options: RemapOptions) -> std::io::Result<()> {
self.inner.remap(new_len, options)
}
}
impl fmt::Debug for MmapRaw {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("MmapRaw")
.field("ptr", &self.as_ptr())
.field("len", &self.len())
.finish()
}
}
impl From<Mmap> for MmapRaw {
fn from(value: Mmap) -> Self {
Self { inner: value.inner }
}
}
impl From<MmapMut> for MmapRaw {
fn from(value: MmapMut) -> Self {
Self { inner: value.inner }
}
}
pub struct MmapMut {
inner: MmapInner,
}
impl MmapMut {
pub unsafe fn map_mut<T: MmapAsRawDesc>(file: T) -> std::io::Result<MmapMut> {
unsafe { MmapOptions::new().map_mut(file) }
}
pub fn map_anon(length: usize) -> std::io::Result<MmapMut> {
MmapOptions::new().len(length).map_anon()
}
pub fn flush(&self) -> std::io::Result<()> {
let len = self.len();
self.inner.flush(0, len)
}
pub fn flush_async(&self) -> std::io::Result<()> {
let len = self.len();
self.inner.flush_async(0, len)
}
pub fn flush_range(&self, offset: usize, len: usize) -> std::io::Result<()> {
self.inner.flush(offset, len)
}
pub fn flush_async_range(&self, offset: usize, len: usize) -> std::io::Result<()> {
self.inner.flush_async(offset, len)
}
pub fn make_read_only(mut self) -> std::io::Result<Mmap> {
self.inner.make_read_only()?;
Ok(Mmap { inner: self.inner })
}
pub fn make_exec(mut self) -> std::io::Result<Mmap> {
self.inner.make_exec()?;
Ok(Mmap { inner: self.inner })
}
#[cfg(unix)]
pub fn advise(&self, advice: Advice) -> std::io::Result<()> {
unsafe {
self.inner
.advise(advice as libc::c_int, 0, self.inner.len())
}
}
#[cfg(unix)]
pub unsafe fn unchecked_advise(&self, advice: UncheckedAdvice) -> std::io::Result<()> {
unsafe {
self.inner
.advise(advice as libc::c_int, 0, self.inner.len())
}
}
#[cfg(unix)]
pub fn advise_range(&self, advice: Advice, offset: usize, len: usize) -> std::io::Result<()> {
unsafe { self.inner.advise(advice as libc::c_int, offset, len) }
}
#[cfg(unix)]
pub unsafe fn unchecked_advise_range(
&self,
advice: UncheckedAdvice,
offset: usize,
len: usize,
) -> std::io::Result<()> {
unsafe { self.inner.advise(advice as libc::c_int, offset, len) }
}
#[cfg(unix)]
pub fn lock(&self) -> std::io::Result<()> {
self.inner.lock()
}
#[cfg(unix)]
pub fn unlock(&self) -> std::io::Result<()> {
self.inner.unlock()
}
#[cfg(target_os = "linux")]
pub unsafe fn remap(&mut self, new_len: usize, options: RemapOptions) -> std::io::Result<()> {
self.inner.remap(new_len, options)
}
}
#[cfg(feature = "stable_deref_trait")]
unsafe impl stable_deref_trait::StableDeref for MmapMut {}
impl Deref for MmapMut {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.inner.ptr(), self.inner.len()) }
}
}
impl DerefMut for MmapMut {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.inner.mut_ptr(), self.inner.len()) }
}
}
impl AsRef<[u8]> for MmapMut {
#[inline]
fn as_ref(&self) -> &[u8] {
self.deref()
}
}
impl AsMut<[u8]> for MmapMut {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
self.deref_mut()
}
}
impl fmt::Debug for MmapMut {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("MmapMut")
.field("ptr", &self.as_ptr())
.field("len", &self.len())
.finish()
}
}
#[derive(Copy, Clone, Default, Debug)]
#[cfg(target_os = "linux")]
pub struct RemapOptions {
may_move: bool,
}
#[cfg(target_os = "linux")]
impl RemapOptions {
pub fn new() -> Self {
Self::default()
}
pub fn may_move(mut self, may_move: bool) -> Self {
self.may_move = may_move;
self
}
pub(crate) fn into_flags(self) -> libc::c_int {
if self.may_move {
libc::MREMAP_MAYMOVE
} else {
0
}
}
}