Skip to content

Commit

Permalink
Option for host managed memory (#1400)
Browse files Browse the repository at this point in the history
* Option for host managed memory

* Rename Allocator to MemoryCreator

* Create LinearMemory and MemoryCreator traits in api

* Leave only one as_ptr function in LinearMemory trait

* Memory creator test

* Update comments/docs for LinearMemory and MemoryCreator traits

* Add guard page to the custom memory example

* Remove mut from LinearMemory trait as_ptr

* Host_memory_grow test
  • Loading branch information
Maciej Kot authored Apr 6, 2020
1 parent c2cb4ea commit 78c548d
Show file tree
Hide file tree
Showing 11 changed files with 356 additions and 17 deletions.
43 changes: 43 additions & 0 deletions crates/api/src/externals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -853,3 +853,46 @@ impl Memory {
}
}
}

/// A linear memory. This trait provides an interface for raw memory buffers which are used
/// by wasmtime, e.g. inside ['Memory']. Such buffers are in principle not thread safe.
/// By implementing this trait together with MemoryCreator,
/// one can supply wasmtime with custom allocated host managed memory.
///
/// # Safety
/// The memory should be page aligned and a multiple of page size.
/// To prevent possible silent overflows, the memory should be protected by a guard page.
/// Additionally the safety concerns explained in ['Memory'], for accessing the memory
/// apply here as well.
///
/// Note that this is a relatively new and experimental feature and it is recommended
/// to be familiar with wasmtime runtime code to use it.
pub unsafe trait LinearMemory {
/// Returns the number of allocated wasm pages.
fn size(&self) -> u32;

/// Grow memory by the specified amount of wasm pages.
///
/// Returns `None` if memory can't be grown by the specified amount
/// of wasm pages.
fn grow(&self, delta: u32) -> Option<u32>;

/// Return the allocated memory as a mutable pointer to u8.
fn as_ptr(&self) -> *mut u8;
}

/// A memory creator. Can be used to provide a memory creator
/// to wasmtime which supplies host managed memory.
///
/// # Safety
/// This trait is unsafe, as the memory safety depends on proper implementation of
/// memory management. Memories created by the MemoryCreator should always be treated
/// as owned by wasmtime instance, and any modification of them outside of wasmtime
/// invoked routines is unsafe and may lead to corruption.
///
/// Note that this is a relatively new and experimental feature and it is recommended
/// to be familiar with wasmtime runtime code to use it.
pub unsafe trait MemoryCreator: Send + Sync {
/// Create new LinearMemory
fn new_memory(&self, ty: MemoryType) -> Result<Box<dyn LinearMemory>, String>;
}
1 change: 1 addition & 0 deletions crates/api/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ fn instantiate(
config.validating_config.operator_config.enable_bulk_memory,
&mut resolver,
sig_registry,
config.memory_creator.as_ref().map(|a| a as _),
)
.map_err(|e| -> Error {
match e {
Expand Down
16 changes: 16 additions & 0 deletions crates/api/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::externals::MemoryCreator;
use crate::trampoline::MemoryCreatorProxy;
use anyhow::Result;
use std::cell::RefCell;
use std::fmt;
Expand All @@ -9,6 +11,7 @@ use wasmtime_environ::settings::{self, Configurable};
use wasmtime_environ::CacheConfig;
use wasmtime_jit::{native, CompilationStrategy, Compiler};
use wasmtime_profiling::{JitDumpAgent, NullProfilerAgent, ProfilingAgent, VTuneAgent};
use wasmtime_runtime::RuntimeMemoryCreator;

// Runtime Environment

Expand All @@ -27,6 +30,7 @@ pub struct Config {
pub(crate) strategy: CompilationStrategy,
pub(crate) cache_config: CacheConfig,
pub(crate) profiler: Arc<dyn ProfilingAgent>,
pub(crate) memory_creator: Option<MemoryCreatorProxy>,
}

impl Config {
Expand Down Expand Up @@ -66,6 +70,7 @@ impl Config {
strategy: CompilationStrategy::Auto,
cache_config: CacheConfig::new_cache_disabled(),
profiler: Arc::new(NullProfilerAgent),
memory_creator: None,
}
}

Expand Down Expand Up @@ -326,6 +331,12 @@ impl Config {
self.cache_config = wasmtime_environ::CacheConfig::from_file(None)?;
Ok(self)
}

/// Sets a custom memory creator
pub fn with_host_memory(&mut self, mem_creator: Arc<dyn MemoryCreator>) -> &mut Self {
self.memory_creator = Some(MemoryCreatorProxy { mem_creator });
self
}
}

impl Default for Config {
Expand Down Expand Up @@ -506,6 +517,11 @@ impl Store {
&self.inner.engine
}

/// Returns an optional reference to a ['RuntimeMemoryCreator']
pub(crate) fn memory_creator(&self) -> Option<&dyn RuntimeMemoryCreator> {
self.engine().config.memory_creator.as_ref().map(|x| x as _)
}

pub(crate) fn compiler(&self) -> std::cell::Ref<'_, Compiler> {
self.inner.compiler.borrow()
}
Expand Down
1 change: 1 addition & 0 deletions crates/api/src/trampoline/create_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub(crate) fn create_handle(
finished_functions.into_boxed_slice(),
trampolines,
imports,
store.memory_creator(),
&data_initializers,
signatures.into_boxed_slice(),
None,
Expand Down
46 changes: 43 additions & 3 deletions crates/api/src/trampoline/memory.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use super::create_handle::create_handle;
use crate::MemoryType;
use crate::externals::{LinearMemory, MemoryCreator};
use crate::Store;
use crate::{Limits, MemoryType};
use anyhow::Result;
use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::{wasm, Module};
use wasmtime_runtime::InstanceHandle;
use wasmtime_environ::{wasm, MemoryPlan, Module, WASM_PAGE_SIZE};
use wasmtime_runtime::{
InstanceHandle, RuntimeLinearMemory, RuntimeMemoryCreator, VMMemoryDefinition,
};

use std::sync::Arc;

pub fn create_handle_with_memory(store: &Store, memory: &MemoryType) -> Result<InstanceHandle> {
let mut module = Module::new();
Expand All @@ -31,3 +36,38 @@ pub fn create_handle_with_memory(store: &Store, memory: &MemoryType) -> Result<I
Box::new(()),
)
}

struct LinearMemoryProxy {
mem: Box<dyn LinearMemory>,
}

impl RuntimeLinearMemory for LinearMemoryProxy {
fn size(&self) -> u32 {
self.mem.size()
}

fn grow(&self, delta: u32) -> Option<u32> {
self.mem.grow(delta)
}

fn vmmemory(&self) -> VMMemoryDefinition {
VMMemoryDefinition {
base: self.mem.as_ptr(),
current_length: self.mem.size() as usize * WASM_PAGE_SIZE as usize,
}
}
}

#[derive(Clone)]
pub(crate) struct MemoryCreatorProxy {
pub(crate) mem_creator: Arc<dyn MemoryCreator>,
}

impl RuntimeMemoryCreator for MemoryCreatorProxy {
fn new_memory(&self, plan: &MemoryPlan) -> Result<Box<dyn RuntimeLinearMemory>, String> {
let ty = MemoryType::new(Limits::new(plan.memory.minimum, plan.memory.maximum));
self.mem_creator
.new_memory(ty)
.map(|mem| Box::new(LinearMemoryProxy { mem }) as Box<dyn RuntimeLinearMemory>)
}
}
2 changes: 2 additions & 0 deletions crates/api/src/trampoline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ mod global;
mod memory;
mod table;

pub(crate) use memory::MemoryCreatorProxy;

use self::func::create_handle_with_function;
use self::global::create_global;
use self::memory::create_handle_with_memory;
Expand Down
192 changes: 192 additions & 0 deletions crates/api/tests/memory_creator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
#[cfg(not(target_os = "windows"))]
mod not_for_windows {
use wasmtime::*;
use wasmtime_environ::{WASM_MAX_PAGES, WASM_PAGE_SIZE};

use libc::c_void;
use libc::MAP_FAILED;
use libc::{mmap, mprotect, munmap};
use libc::{sysconf, _SC_PAGESIZE};
use libc::{MAP_ANON, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};

use std::cell::RefCell;
use std::io::Error;
use std::ptr::null_mut;
use std::sync::{Arc, Mutex};

struct CustomMemory {
mem: *mut c_void,
size: usize,
used_wasm_pages: RefCell<u32>,
glob_page_counter: Arc<Mutex<u64>>,
}

impl CustomMemory {
unsafe fn new(
num_wasm_pages: u32,
max_wasm_pages: u32,
glob_counter: Arc<Mutex<u64>>,
) -> Self {
let page_size = sysconf(_SC_PAGESIZE) as usize;
let guard_size = page_size;
let size = max_wasm_pages as usize * WASM_PAGE_SIZE as usize + guard_size;
let used_size = num_wasm_pages as usize * WASM_PAGE_SIZE as usize;
assert_eq!(size % page_size, 0); // we rely on WASM_PAGE_SIZE being multiple of host page size

let mem = mmap(null_mut(), size, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
assert_ne!(mem, MAP_FAILED, "mmap failed: {}", Error::last_os_error());

let r = mprotect(mem, used_size, PROT_READ | PROT_WRITE);
assert_eq!(r, 0, "mprotect failed: {}", Error::last_os_error());
*glob_counter.lock().unwrap() += num_wasm_pages as u64;

Self {
mem,
size,
used_wasm_pages: RefCell::new(num_wasm_pages),
glob_page_counter: glob_counter,
}
}
}

impl Drop for CustomMemory {
fn drop(&mut self) {
let n = *self.used_wasm_pages.borrow() as u64;
*self.glob_page_counter.lock().unwrap() -= n;
let r = unsafe { munmap(self.mem, self.size) };
assert_eq!(r, 0, "munmap failed: {}", Error::last_os_error());
}
}

unsafe impl LinearMemory for CustomMemory {
fn size(&self) -> u32 {
*self.used_wasm_pages.borrow()
}

fn grow(&self, delta: u32) -> Option<u32> {
let delta_size = (delta as usize).checked_mul(WASM_PAGE_SIZE as usize)?;

let prev_pages = *self.used_wasm_pages.borrow();
let prev_size = (prev_pages as usize).checked_mul(WASM_PAGE_SIZE as usize)?;

let new_pages = prev_pages.checked_add(delta)?;
let new_size = (new_pages as usize).checked_mul(WASM_PAGE_SIZE as usize)?;

let guard_size = unsafe { sysconf(_SC_PAGESIZE) as usize };

if new_size > self.size - guard_size {
return None;
}
unsafe {
let start = (self.mem as *mut u8).add(prev_size) as _;
let r = mprotect(start, delta_size, PROT_READ | PROT_WRITE);
assert_eq!(r, 0, "mprotect failed: {}", Error::last_os_error());
}

*self.glob_page_counter.lock().unwrap() += delta as u64;
*self.used_wasm_pages.borrow_mut() = new_pages;
Some(prev_pages)
}

fn as_ptr(&self) -> *mut u8 {
self.mem as *mut u8
}
}

struct CustomMemoryCreator {
pub num_created_memories: Mutex<usize>,
pub num_total_pages: Arc<Mutex<u64>>,
}

impl CustomMemoryCreator {
pub fn new() -> Self {
Self {
num_created_memories: Mutex::new(0),
num_total_pages: Arc::new(Mutex::new(0)),
}
}
}

unsafe impl MemoryCreator for CustomMemoryCreator {
fn new_memory(&self, ty: MemoryType) -> Result<Box<dyn LinearMemory>, String> {
let max = ty.limits().max().unwrap_or(WASM_MAX_PAGES);
unsafe {
let mem = Box::new(CustomMemory::new(
ty.limits().min(),
max,
self.num_total_pages.clone(),
));
*self.num_created_memories.lock().unwrap() += 1;
Ok(mem)
}
}
}

#[test]
fn host_memory() -> anyhow::Result<()> {
let mem_creator = Arc::new(CustomMemoryCreator::new());
let mut config = Config::default();
config.with_host_memory(mem_creator.clone());
let engine = Engine::new(&config);
let store = Store::new(&engine);

let module = Module::new(
&store,
r#"
(module
(memory (export "memory") 1)
)
"#,
)?;
Instance::new(&module, &[])?;

assert_eq!(*mem_creator.num_created_memories.lock().unwrap(), 1);

Ok(())
}

#[test]
fn host_memory_grow() -> anyhow::Result<()> {
let mem_creator = Arc::new(CustomMemoryCreator::new());
let mut config = Config::default();
config.with_host_memory(mem_creator.clone());
let engine = Engine::new(&config);
let store = Store::new(&engine);

let module = Module::new(
&store,
r#"
(module
(func $f (drop (memory.grow (i32.const 1))))
(memory (export "memory") 1 2)
(start $f)
)
"#,
)?;

let instance1 = Instance::new(&module, &[])?;
let instance2 = Instance::new(&module, &[])?;

assert_eq!(*mem_creator.num_created_memories.lock().unwrap(), 2);

assert_eq!(
instance2
.get_export("memory")
.unwrap()
.memory()
.unwrap()
.size(),
2
);

// we take the lock outside the assert, so it won't get poisoned on assert failure
let tot_pages = *mem_creator.num_total_pages.lock().unwrap();
assert_eq!(tot_pages, 4);

drop(instance1);
let tot_pages = *mem_creator.num_total_pages.lock().unwrap();
assert_eq!(tot_pages, 2);

Ok(())
}
}
Loading

0 comments on commit 78c548d

Please sign in to comment.