use crate::prelude::*;
use crate::runtime::vm::{HostAlignedByteCount, Mmap, mmap::AlignedLength};
use crate::{LinearMemory, MemoryImage};
use alloc::sync::Arc;
use wasmtime_environ::MemoryTunables;
#[derive(Debug)]
pub struct MmapMemory {
mmap: Arc<Mmap<AlignedLength>>,
len: usize,
maximum: Option<usize>,
extra_to_reserve_on_growth: HostAlignedByteCount,
pre_guard_size: HostAlignedByteCount,
offset_guard_size: HostAlignedByteCount,
}
impl MmapMemory {
pub fn new(
ty: &wasmtime_environ::Memory,
memory_tunables: &MemoryTunables<'_>,
minimum: usize,
maximum: Option<usize>,
) -> Result<Self> {
let offset_guard_bytes =
HostAlignedByteCount::new_rounded_up_u64(memory_tunables.guard_size())
.context("tunable.memory_guard_size overflows")?;
let pre_guard_bytes = if memory_tunables.tunables().guard_before_linear_memory {
offset_guard_bytes
} else {
HostAlignedByteCount::ZERO
};
let mut alloc_bytes = memory_tunables.reservation();
let mut extra_to_reserve_on_growth = memory_tunables.reservation_for_growth();
let minimum_u64 = u64::try_from(minimum).unwrap();
if minimum_u64 <= alloc_bytes {
if let Ok(max) = ty.maximum_byte_size() {
if max <= alloc_bytes {
extra_to_reserve_on_growth = 0;
}
}
} else {
alloc_bytes = minimum_u64.saturating_add(extra_to_reserve_on_growth);
}
let alloc_bytes = HostAlignedByteCount::new_rounded_up_u64(alloc_bytes)
.context("tunables.memory_reservation overflows")?;
let extra_to_reserve_on_growth =
HostAlignedByteCount::new_rounded_up_u64(extra_to_reserve_on_growth)
.context("tunables.memory_reservation_for_growth overflows")?;
let request_bytes = pre_guard_bytes
.checked_add(alloc_bytes)
.and_then(|i| i.checked_add(offset_guard_bytes))
.with_context(|| format!("cannot allocate {minimum} with guard regions"))?;
let mmap = Mmap::accessible_reserved(HostAlignedByteCount::ZERO, request_bytes)?;
if minimum > 0 {
let accessible = HostAlignedByteCount::new_rounded_up(minimum)?;
unsafe {
mmap.make_accessible(pre_guard_bytes, accessible)?;
}
}
Ok(Self {
mmap: try_new::<Arc<_>>(mmap)?,
len: minimum,
maximum,
pre_guard_size: pre_guard_bytes,
offset_guard_size: offset_guard_bytes,
extra_to_reserve_on_growth,
})
}
fn accessible(&self) -> HostAlignedByteCount {
let accessible = HostAlignedByteCount::new_rounded_up(self.len)
.expect("accessible region always fits in usize");
debug_assert!(accessible <= self.current_capacity());
accessible
}
fn current_capacity(&self) -> HostAlignedByteCount {
let mmap_len = self.mmap.len_aligned();
mmap_len
.checked_sub(self.offset_guard_size)
.and_then(|i| i.checked_sub(self.pre_guard_size))
.expect("guard regions fit in mmap.len")
}
}
unsafe impl LinearMemory for MmapMemory {
fn byte_size(&self) -> usize {
self.len
}
fn byte_capacity(&self) -> usize {
self.current_capacity().byte_count()
}
fn grow_to(&mut self, new_size: usize) -> Result<()> {
let new_accessible = HostAlignedByteCount::new_rounded_up(new_size)?;
let current_capacity = self.current_capacity();
if new_accessible > current_capacity {
let request_bytes = self
.pre_guard_size
.checked_add(new_accessible)
.and_then(|s| s.checked_add(self.extra_to_reserve_on_growth))
.and_then(|s| s.checked_add(self.offset_guard_size))
.context("overflow calculating size of memory allocation")?;
let mut new_mmap =
Mmap::accessible_reserved(HostAlignedByteCount::ZERO, request_bytes)?;
unsafe {
new_mmap.make_accessible(self.pre_guard_size, new_accessible)?;
}
unsafe {
let range =
self.pre_guard_size.byte_count()..(self.pre_guard_size.byte_count() + self.len);
let src = self.mmap.slice(range.clone());
let dst = new_mmap.slice_mut(range);
dst.copy_from_slice(src);
}
self.mmap = try_new::<Arc<_>>(new_mmap)?;
} else {
assert!(new_size <= current_capacity.byte_count());
assert!(self.maximum.map_or(true, |max| new_size <= max));
if let Ok(difference) = new_accessible.checked_sub(self.accessible()) {
unsafe {
self.mmap.make_accessible(
self.pre_guard_size
.checked_add(self.accessible())
.context("overflow calculating new accessible region")?,
difference,
)?;
}
}
}
self.len = new_size;
Ok(())
}
fn as_ptr(&self) -> *mut u8 {
unsafe {
self.mmap
.as_non_null()
.byte_add(self.pre_guard_size.byte_count())
.as_ptr()
}
}
fn init_from_image(&mut self, image: &MemoryImage) -> Result<bool> {
let image_end = image.linear_memory_offset().checked_add(image.len());
assert!(
image_end.is_some_and(|end| end <= self.len),
"MemoryImage does not fit into the MmapMemory"
);
let base = self.mmap.offset(self.pre_guard_size)?;
unsafe {
image.vm().map_at(&base)?;
}
Ok(true)
}
}