wasmtime/runtime/vm/mmap_vec.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
use crate::prelude::*;
#[cfg(not(has_virtual_memory))]
use crate::runtime::vm::send_sync_ptr::SendSyncPtr;
#[cfg(has_virtual_memory)]
use crate::runtime::vm::{mmap::UnalignedLength, Mmap};
#[cfg(not(has_virtual_memory))]
use alloc::alloc::Layout;
use alloc::sync::Arc;
use core::ops::{Deref, Range};
#[cfg(not(has_virtual_memory))]
use core::ptr::NonNull;
#[cfg(feature = "std")]
use std::fs::File;
/// A type which prefers to store backing memory in an OS-backed memory mapping
/// but can fall back to the regular memory allocator as well.
///
/// This type is used to store code in Wasmtime and manage read-only and
/// executable permissions of compiled images. This is created from either an
/// in-memory compilation or by deserializing an artifact from disk. Methods
/// are provided for managing VM permissions when the `signals-based-traps`
/// Cargo feature is enabled.
///
/// The length of an `MmapVec` is not guaranteed to be page-aligned. That means
/// that if the contents are not themselves page-aligned, which compiled images
/// are typically not, then the remaining bytes in the final page for
/// mmap-backed instances are unused.
///
/// Note that when `signals-based-traps` is disabled then this type is
/// backed by the regular memory allocator via `alloc` APIs. In such a
/// scenario this type does not support read-only or executable bits
/// and the methods are not available. However, the `CustomCodeMemory`
/// mechanism may be used by the embedder to set up and tear down
/// executable permissions on parts of this storage.
pub enum MmapVec {
#[doc(hidden)]
#[cfg(not(has_virtual_memory))]
Alloc {
base: SendSyncPtr<u8>,
layout: Layout,
},
#[doc(hidden)]
#[cfg(has_virtual_memory)]
Mmap {
mmap: Mmap<UnalignedLength>,
len: usize,
},
}
impl MmapVec {
/// Consumes an existing `mmap` and wraps it up into an `MmapVec`.
///
/// The returned `MmapVec` will have the `size` specified, which can be
/// smaller than the region mapped by the `Mmap`. The returned `MmapVec`
/// will only have at most `size` bytes accessible.
#[cfg(has_virtual_memory)]
fn new_mmap<M>(mmap: M, len: usize) -> MmapVec
where
M: Into<Mmap<UnalignedLength>>,
{
let mmap = mmap.into();
assert!(len <= mmap.len());
MmapVec::Mmap { mmap, len }
}
#[cfg(not(has_virtual_memory))]
fn new_alloc(len: usize, alignment: usize) -> MmapVec {
let layout = Layout::from_size_align(len, alignment)
.expect("Invalid size or alignment for MmapVec allocation");
let base = SendSyncPtr::new(
NonNull::new(unsafe { alloc::alloc::alloc_zeroed(layout.clone()) })
.expect("Allocation of MmapVec storage failed"),
);
MmapVec::Alloc { base, layout }
}
/// Creates a new zero-initialized `MmapVec` with the given `size`
/// and `alignment`.
///
/// This commit will return a new `MmapVec` suitably sized to hold `size`
/// bytes. All bytes will be initialized to zero since this is a fresh OS
/// page allocation.
pub fn with_capacity_and_alignment(size: usize, alignment: usize) -> Result<MmapVec> {
#[cfg(has_virtual_memory)]
{
assert!(alignment <= crate::runtime::vm::host_page_size());
return Ok(MmapVec::new_mmap(Mmap::with_at_least(size)?, size));
}
#[cfg(not(has_virtual_memory))]
{
return Ok(MmapVec::new_alloc(size, alignment));
}
}
/// Creates a new `MmapVec` from the contents of an existing `slice`.
///
/// A new `MmapVec` is allocated to hold the contents of `slice` and then
/// `slice` is copied into the new mmap. It's recommended to avoid this
/// method if possible to avoid the need to copy data around.
pub fn from_slice(slice: &[u8]) -> Result<MmapVec> {
MmapVec::from_slice_with_alignment(slice, 1)
}
/// Creates a new `MmapVec` from the contents of an existing
/// `slice`, with a minimum alignment.
///
/// `align` must be a power of two. This is useful when page
/// alignment is required when the system otherwise does not use
/// virtual memory but has a custom code publish handler.
///
/// A new `MmapVec` is allocated to hold the contents of `slice` and then
/// `slice` is copied into the new mmap. It's recommended to avoid this
/// method if possible to avoid the need to copy data around. pub
pub fn from_slice_with_alignment(slice: &[u8], align: usize) -> Result<MmapVec> {
let mut result = MmapVec::with_capacity_and_alignment(slice.len(), align)?;
// SAFETY: The mmap hasn't been made readonly yet so this should be
// safe to call.
unsafe {
result.as_mut_slice().copy_from_slice(slice);
}
Ok(result)
}
/// Creates a new `MmapVec` which is the given `File` mmap'd into memory.
///
/// This function will determine the file's size and map the full contents
/// into memory. This will return an error if the file is too large to be
/// fully mapped into memory.
///
/// The file is mapped into memory with a "private mapping" meaning that
/// changes are not persisted back to the file itself and are only visible
/// within this process.
#[cfg(feature = "std")]
pub fn from_file(file: File) -> Result<MmapVec> {
let file = Arc::new(file);
let mmap = Mmap::from_file(Arc::clone(&file))
.with_context(move || format!("failed to create mmap for file {file:?}"))?;
let len = mmap.len();
Ok(MmapVec::new_mmap(mmap, len))
}
/// Makes the specified `range` within this `mmap` to be read/execute.
#[cfg(has_virtual_memory)]
pub unsafe fn make_executable(
&self,
range: Range<usize>,
enable_branch_protection: bool,
) -> Result<()> {
let (mmap, len) = match self {
MmapVec::Mmap { mmap, len } => (mmap, *len),
};
assert!(range.start <= range.end);
assert!(range.end <= len);
mmap.make_executable(range.start..range.end, enable_branch_protection)
}
/// Makes the specified `range` within this `mmap` to be read-only.
#[cfg(has_virtual_memory)]
pub unsafe fn make_readonly(&self, range: Range<usize>) -> Result<()> {
let (mmap, len) = match self {
MmapVec::Mmap { mmap, len } => (mmap, *len),
};
assert!(range.start <= range.end);
assert!(range.end <= len);
mmap.make_readonly(range.start..range.end)
}
/// Returns the underlying file that this mmap is mapping, if present.
#[cfg(feature = "std")]
pub fn original_file(&self) -> Option<&Arc<File>> {
match self {
#[cfg(not(has_virtual_memory))]
MmapVec::Alloc { .. } => None,
#[cfg(has_virtual_memory)]
MmapVec::Mmap { mmap, .. } => mmap.original_file(),
}
}
/// Returns the bounds, in host memory, of where this mmap
/// image resides.
pub fn image_range(&self) -> Range<*const u8> {
let base = self.as_ptr();
let len = self.len();
base..base.wrapping_add(len)
}
/// Views this region of memory as a mutable slice.
///
/// # Unsafety
///
/// This method is only safe if `make_readonly` hasn't been called yet to
/// ensure that the memory is indeed writable
pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] {
match self {
#[cfg(not(has_virtual_memory))]
MmapVec::Alloc { base, layout } => {
core::slice::from_raw_parts_mut(base.as_mut(), layout.size())
}
#[cfg(has_virtual_memory)]
MmapVec::Mmap { mmap, len } => mmap.slice_mut(0..*len),
}
}
}
impl Deref for MmapVec {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
match self {
#[cfg(not(has_virtual_memory))]
MmapVec::Alloc { base, layout } => unsafe {
core::slice::from_raw_parts(base.as_ptr(), layout.size())
},
#[cfg(has_virtual_memory)]
MmapVec::Mmap { mmap, len } => {
// SAFETY: all bytes for this mmap, which is owned by
// `MmapVec`, are always at least readable.
unsafe { mmap.slice(0..*len) }
}
}
}
}
impl Drop for MmapVec {
fn drop(&mut self) {
match self {
#[cfg(not(has_virtual_memory))]
MmapVec::Alloc { base, layout, .. } => unsafe {
alloc::alloc::dealloc(base.as_mut(), layout.clone());
},
#[cfg(has_virtual_memory)]
MmapVec::Mmap { .. } => {
// Drop impl on the `mmap` takes care of this case.
}
}
}
}
#[cfg(test)]
mod tests {
use super::MmapVec;
#[test]
fn smoke() {
let mut mmap = MmapVec::with_capacity_and_alignment(10, 1).unwrap();
assert_eq!(mmap.len(), 10);
assert_eq!(&mmap[..], &[0; 10]);
unsafe {
mmap.as_mut_slice()[0] = 1;
mmap.as_mut_slice()[2] = 3;
}
assert!(mmap.get(10).is_none());
assert_eq!(mmap[0], 1);
assert_eq!(mmap[2], 3);
}
#[test]
fn alignment() {
let mmap = MmapVec::with_capacity_and_alignment(10, 4096).unwrap();
let raw_ptr = &mmap[0] as *const _ as usize;
assert_eq!(raw_ptr & (4096 - 1), 0);
}
}