* Implement the memory64 proposal in Wasmtime This commit implements the WebAssembly [memory64 proposal][proposal] in both Wasmtime and Cranelift. In terms of work done Cranelift ended up needing very little work here since most of it was already prepared for 64-bit memories at one point or another. Most of the work in Wasmtime is largely refactoring, changing a bunch of `u32` values to something else. A number of internal and public interfaces are changing as a result of this commit, for example: * Acessors on `wasmtime::Memory` that work with pages now all return `u64` unconditionally rather than `u32`. This makes it possible to accommodate 64-bit memories with this API, but we may also want to consider `usize` here at some point since the host can't grow past `usize`-limited pages anyway. * The `wasmtime::Limits` structure is removed in favor of minimum/maximum methods on table/memory types. * Many libcall intrinsics called by jit code now unconditionally take `u64` arguments instead of `u32`. Return values are `usize`, however, since the return value, if successful, is always bounded by host memory while arguments can come from any guest. * The `heap_addr` clif instruction now takes a 64-bit offset argument instead of a 32-bit one. It turns out that the legalization of `heap_addr` already worked with 64-bit offsets, so this change was fairly trivial to make. * The runtime implementation of mmap-based linear memories has changed to largely work in `usize` quantities in its API and in bytes instead of pages. This simplifies various aspects and reflects that mmap-memories are always bound by `usize` since that's what the host is using to address things, and additionally most calculations care about bytes rather than pages except for the very edge where we're going to/from wasm. Overall I've tried to minimize the amount of `as` casts as possible, using checked `try_from` and checked arithemtic with either error handling or explicit `unwrap()` calls to tell us about bugs in the future. Most locations have relatively obvious things to do with various implications on various hosts, and I think they should all be roughly of the right shape but time will tell. I mostly relied on the compiler complaining that various types weren't aligned to figure out type-casting, and I manually audited some of the more obvious locations. I suspect we have a number of hidden locations that will panic on 32-bit hosts if 64-bit modules try to run there, but otherwise I think we should be generally ok (famous last words). In any case I wouldn't want to enable this by default naturally until we've fuzzed it for some time. In terms of the actual underlying implementation, no one should expect memory64 to be all that fast. Right now it's implemented with "dynamic" heaps which have a few consequences: * All memory accesses are bounds-checked. I'm not sure how aggressively Cranelift tries to optimize out bounds checks, but I suspect not a ton since we haven't stressed this much historically. * Heaps are always precisely sized. This means that every call to `memory.grow` will incur a `memcpy` of memory from the old heap to the new. We probably want to at least look into `mremap` on Linux and otherwise try to implement schemes where dynamic heaps have some reserved pages to grow into to help amortize the cost of `memory.grow`. The memory64 spec test suite is scheduled to now run on CI, but as with all the other spec test suites it's really not all that comprehensive. I've tried adding more tests for basic things as I've had to implement guards for them, but I wouldn't really consider the testing adequate from just this PR itself. I did try to take care in one test to actually allocate a 4gb+ heap and then avoid running that in the pooling allocator or in emulation because otherwise that may fail or take excessively long. [proposal]: https://github.com/WebAssembly/memory64/blob/master/proposals/memory64/Overview.md * Fix some tests * More test fixes * Fix wasmtime tests * Fix doctests * Revert to 32-bit immediate offsets in `heap_addr` This commit updates the generation of addresses in wasm code to always use 32-bit offsets for `heap_addr`, and if the calculated offset is bigger than 32-bits we emit a manual add with an overflow check. * Disable memory64 for spectest fuzzing * Fix wrong offset being added to heap addr * More comments! * Clarify bytes/pages
304 lines
9.8 KiB
Rust
304 lines
9.8 KiB
Rust
//! Low-level abstraction for allocating and managing zero-filled pages
|
|
//! of memory.
|
|
|
|
use anyhow::{bail, Result};
|
|
use more_asserts::assert_le;
|
|
use std::io;
|
|
use std::ptr;
|
|
use std::slice;
|
|
|
|
/// Round `size` up to the nearest multiple of `page_size`.
|
|
fn round_up_to_page_size(size: usize, page_size: usize) -> usize {
|
|
(size + (page_size - 1)) & !(page_size - 1)
|
|
}
|
|
|
|
/// A simple struct consisting of a page-aligned pointer to page-aligned
|
|
/// and initially-zeroed memory and a length.
|
|
#[derive(Debug)]
|
|
pub struct Mmap {
|
|
// Note that this is stored as a `usize` instead of a `*const` or `*mut`
|
|
// pointer to allow this structure to be natively `Send` and `Sync` without
|
|
// `unsafe impl`. This type is sendable across threads and shareable since
|
|
// the coordination all happens at the OS layer.
|
|
ptr: usize,
|
|
len: usize,
|
|
}
|
|
|
|
impl Mmap {
|
|
/// Construct a new empty instance of `Mmap`.
|
|
pub fn new() -> Self {
|
|
// Rust's slices require non-null pointers, even when empty. `Vec`
|
|
// contains code to create a non-null dangling pointer value when
|
|
// constructed empty, so we reuse that here.
|
|
let empty = Vec::<u8>::new();
|
|
Self {
|
|
ptr: empty.as_ptr() as usize,
|
|
len: 0,
|
|
}
|
|
}
|
|
|
|
/// Create a new `Mmap` pointing to at least `size` bytes of page-aligned accessible memory.
|
|
pub fn with_at_least(size: usize) -> Result<Self> {
|
|
let page_size = region::page::size();
|
|
let rounded_size = round_up_to_page_size(size, page_size);
|
|
Self::accessible_reserved(rounded_size, rounded_size)
|
|
}
|
|
|
|
/// Create a new `Mmap` pointing to `accessible_size` bytes of page-aligned accessible memory,
|
|
/// within a reserved mapping of `mapping_size` bytes. `accessible_size` and `mapping_size`
|
|
/// must be native page-size multiples.
|
|
#[cfg(not(target_os = "windows"))]
|
|
pub fn accessible_reserved(accessible_size: usize, mapping_size: usize) -> Result<Self> {
|
|
let page_size = region::page::size();
|
|
assert_le!(accessible_size, mapping_size);
|
|
assert_eq!(mapping_size & (page_size - 1), 0);
|
|
assert_eq!(accessible_size & (page_size - 1), 0);
|
|
|
|
// Mmap may return EINVAL if the size is zero, so just
|
|
// special-case that.
|
|
if mapping_size == 0 {
|
|
return Ok(Self::new());
|
|
}
|
|
|
|
Ok(if accessible_size == mapping_size {
|
|
// Allocate a single read-write region at once.
|
|
let ptr = unsafe {
|
|
libc::mmap(
|
|
ptr::null_mut(),
|
|
mapping_size,
|
|
libc::PROT_READ | libc::PROT_WRITE,
|
|
libc::MAP_PRIVATE | libc::MAP_ANON,
|
|
-1,
|
|
0,
|
|
)
|
|
};
|
|
if ptr as isize == -1_isize {
|
|
bail!(
|
|
"mmap failed to allocate {:#x} bytes: {}",
|
|
mapping_size,
|
|
io::Error::last_os_error()
|
|
);
|
|
}
|
|
|
|
Self {
|
|
ptr: ptr as usize,
|
|
len: mapping_size,
|
|
}
|
|
} else {
|
|
// Reserve the mapping size.
|
|
let ptr = unsafe {
|
|
libc::mmap(
|
|
ptr::null_mut(),
|
|
mapping_size,
|
|
libc::PROT_NONE,
|
|
libc::MAP_PRIVATE | libc::MAP_ANON,
|
|
-1,
|
|
0,
|
|
)
|
|
};
|
|
if ptr as isize == -1_isize {
|
|
bail!(
|
|
"mmap failed to allocate {:#x} bytes: {}",
|
|
mapping_size,
|
|
io::Error::last_os_error()
|
|
);
|
|
}
|
|
|
|
let mut result = Self {
|
|
ptr: ptr as usize,
|
|
len: mapping_size,
|
|
};
|
|
|
|
if accessible_size != 0 {
|
|
// Commit the accessible size.
|
|
result.make_accessible(0, accessible_size)?;
|
|
}
|
|
|
|
result
|
|
})
|
|
}
|
|
|
|
/// Create a new `Mmap` pointing to `accessible_size` bytes of page-aligned accessible memory,
|
|
/// within a reserved mapping of `mapping_size` bytes. `accessible_size` and `mapping_size`
|
|
/// must be native page-size multiples.
|
|
#[cfg(target_os = "windows")]
|
|
pub fn accessible_reserved(accessible_size: usize, mapping_size: usize) -> Result<Self> {
|
|
use winapi::um::memoryapi::VirtualAlloc;
|
|
use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE};
|
|
|
|
if mapping_size == 0 {
|
|
return Ok(Self::new());
|
|
}
|
|
|
|
let page_size = region::page::size();
|
|
assert_le!(accessible_size, mapping_size);
|
|
assert_eq!(mapping_size & (page_size - 1), 0);
|
|
assert_eq!(accessible_size & (page_size - 1), 0);
|
|
|
|
Ok(if accessible_size == mapping_size {
|
|
// Allocate a single read-write region at once.
|
|
let ptr = unsafe {
|
|
VirtualAlloc(
|
|
ptr::null_mut(),
|
|
mapping_size,
|
|
MEM_RESERVE | MEM_COMMIT,
|
|
PAGE_READWRITE,
|
|
)
|
|
};
|
|
if ptr.is_null() {
|
|
bail!("VirtualAlloc failed: {}", io::Error::last_os_error());
|
|
}
|
|
|
|
Self {
|
|
ptr: ptr as usize,
|
|
len: mapping_size,
|
|
}
|
|
} else {
|
|
// Reserve the mapping size.
|
|
let ptr =
|
|
unsafe { VirtualAlloc(ptr::null_mut(), mapping_size, MEM_RESERVE, PAGE_NOACCESS) };
|
|
if ptr.is_null() {
|
|
bail!("VirtualAlloc failed: {}", io::Error::last_os_error());
|
|
}
|
|
|
|
let mut result = Self {
|
|
ptr: ptr as usize,
|
|
len: mapping_size,
|
|
};
|
|
|
|
if accessible_size != 0 {
|
|
// Commit the accessible size.
|
|
result.make_accessible(0, accessible_size)?;
|
|
}
|
|
|
|
result
|
|
})
|
|
}
|
|
|
|
/// Make the memory starting at `start` and extending for `len` bytes accessible.
|
|
/// `start` and `len` must be native page-size multiples and describe a range within
|
|
/// `self`'s reserved memory.
|
|
#[cfg(not(target_os = "windows"))]
|
|
pub fn make_accessible(&mut self, start: usize, len: usize) -> Result<()> {
|
|
let page_size = region::page::size();
|
|
assert_eq!(start & (page_size - 1), 0);
|
|
assert_eq!(len & (page_size - 1), 0);
|
|
assert_le!(len, self.len);
|
|
assert_le!(start, self.len - len);
|
|
|
|
// Commit the accessible size.
|
|
let ptr = self.ptr as *const u8;
|
|
unsafe {
|
|
region::protect(ptr.add(start), len, region::Protection::READ_WRITE)?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Make the memory starting at `start` and extending for `len` bytes accessible.
|
|
/// `start` and `len` must be native page-size multiples and describe a range within
|
|
/// `self`'s reserved memory.
|
|
#[cfg(target_os = "windows")]
|
|
pub fn make_accessible(&mut self, start: usize, len: usize) -> Result<()> {
|
|
use winapi::ctypes::c_void;
|
|
use winapi::um::memoryapi::VirtualAlloc;
|
|
use winapi::um::winnt::{MEM_COMMIT, PAGE_READWRITE};
|
|
let page_size = region::page::size();
|
|
assert_eq!(start & (page_size - 1), 0);
|
|
assert_eq!(len & (page_size - 1), 0);
|
|
assert_le!(len, self.len);
|
|
assert_le!(start, self.len - len);
|
|
|
|
// Commit the accessible size.
|
|
let ptr = self.ptr as *const u8;
|
|
if unsafe {
|
|
VirtualAlloc(
|
|
ptr.add(start) as *mut c_void,
|
|
len,
|
|
MEM_COMMIT,
|
|
PAGE_READWRITE,
|
|
)
|
|
}
|
|
.is_null()
|
|
{
|
|
bail!("VirtualAlloc failed: {}", io::Error::last_os_error());
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Return the allocated memory as a slice of u8.
|
|
pub fn as_slice(&self) -> &[u8] {
|
|
unsafe { slice::from_raw_parts(self.ptr as *const u8, self.len) }
|
|
}
|
|
|
|
/// Return the allocated memory as a mutable slice of u8.
|
|
pub fn as_mut_slice(&mut self) -> &mut [u8] {
|
|
unsafe { slice::from_raw_parts_mut(self.ptr as *mut u8, self.len) }
|
|
}
|
|
|
|
/// Return the allocated memory as a pointer to u8.
|
|
pub fn as_ptr(&self) -> *const u8 {
|
|
self.ptr as *const u8
|
|
}
|
|
|
|
/// Return the allocated memory as a mutable pointer to u8.
|
|
pub fn as_mut_ptr(&self) -> *mut u8 {
|
|
self.ptr as *mut u8
|
|
}
|
|
|
|
/// Return the length of the allocated memory.
|
|
pub fn len(&self) -> usize {
|
|
self.len
|
|
}
|
|
|
|
/// Return whether any memory has been allocated.
|
|
pub fn is_empty(&self) -> bool {
|
|
self.len() == 0
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub(crate) unsafe fn from_raw(ptr: usize, len: usize) -> Self {
|
|
Self { ptr, len }
|
|
}
|
|
}
|
|
|
|
impl Drop for Mmap {
|
|
#[cfg(not(target_os = "windows"))]
|
|
fn drop(&mut self) {
|
|
if self.len != 0 {
|
|
let r = unsafe { libc::munmap(self.ptr as *mut libc::c_void, self.len) };
|
|
assert_eq!(r, 0, "munmap failed: {}", io::Error::last_os_error());
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "windows")]
|
|
fn drop(&mut self) {
|
|
if self.len != 0 {
|
|
use winapi::ctypes::c_void;
|
|
use winapi::um::memoryapi::VirtualFree;
|
|
use winapi::um::winnt::MEM_RELEASE;
|
|
let r = unsafe { VirtualFree(self.ptr as *mut c_void, 0, MEM_RELEASE) };
|
|
assert_ne!(r, 0);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn _assert() {
|
|
fn _assert_send_sync<T: Send + Sync>() {}
|
|
_assert_send_sync::<Mmap>();
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_round_up_to_page_size() {
|
|
assert_eq!(round_up_to_page_size(0, 4096), 0);
|
|
assert_eq!(round_up_to_page_size(1, 4096), 4096);
|
|
assert_eq!(round_up_to_page_size(4096, 4096), 4096);
|
|
assert_eq!(round_up_to_page_size(4097, 4096), 8192);
|
|
}
|
|
}
|