Removed Memory plans in favor of direct styles

This commit is contained in:
Syrus
2020-07-07 16:50:08 -07:00
parent d94bf1c022
commit b57a28edc7
22 changed files with 116 additions and 135 deletions

View File

@@ -21,9 +21,8 @@ pub struct Memory {
impl Memory { impl Memory {
pub fn new(store: &Store, ty: MemoryType) -> Result<Memory, MemoryError> { pub fn new(store: &Store, ty: MemoryType) -> Result<Memory, MemoryError> {
let tunables = store.tunables(); let tunables = store.tunables();
let memory_plan = tunables.memory_plan(ty); let style = tunables.memory_style(&ty);
let memory = tunables.create_memory(memory_plan)?; let memory = tunables.create_memory(&ty, &style)?;
let definition = memory.vmmemory(); let definition = memory.vmmemory();
Ok(Memory { Ok(Memory {

View File

@@ -6,9 +6,7 @@ use target_lexicon::{OperatingSystem, PointerWidth};
use wasmer_compiler::Target; use wasmer_compiler::Target;
use wasmer_engine::Tunables as BaseTunables; use wasmer_engine::Tunables as BaseTunables;
use wasmer_runtime::MemoryError; use wasmer_runtime::MemoryError;
use wasmer_runtime::{ use wasmer_runtime::{LinearMemory, LinearTable, Memory, MemoryStyle, Table, TableStyle};
LinearMemory, LinearTable, Memory, MemoryPlan, MemoryStyle, Table, TableStyle,
};
/// Tunable parameters for WebAssembly compilation. /// Tunable parameters for WebAssembly compilation.
#[derive(Clone)] #[derive(Clone)]
@@ -61,8 +59,8 @@ impl Tunables {
} }
impl BaseTunables for Tunables { impl BaseTunables for Tunables {
/// Get a `MemoryPlan` for the provided `MemoryType` /// Get a `MemoryStyle` for the provided `MemoryType`
fn memory_plan(&self, memory: MemoryType) -> MemoryPlan { fn memory_style(&self, memory: &MemoryType) -> MemoryStyle {
// A heap with a maximum that doesn't exceed the static memory bound specified by the // A heap with a maximum that doesn't exceed the static memory bound specified by the
// tunables make it static. // tunables make it static.
// //
@@ -70,19 +68,13 @@ impl BaseTunables for Tunables {
let maximum = memory.maximum.unwrap_or_else(Pages::max_value); let maximum = memory.maximum.unwrap_or_else(Pages::max_value);
if maximum <= self.static_memory_bound { if maximum <= self.static_memory_bound {
assert_ge!(self.static_memory_bound, memory.minimum); assert_ge!(self.static_memory_bound, memory.minimum);
MemoryPlan { MemoryStyle::Static {
memory,
style: MemoryStyle::Static {
bound: self.static_memory_bound, bound: self.static_memory_bound,
offset_guard_size: self.static_memory_offset_guard_size, offset_guard_size: self.static_memory_offset_guard_size,
},
} }
} else { } else {
MemoryPlan { MemoryStyle::Dynamic {
memory,
style: MemoryStyle::Dynamic {
offset_guard_size: self.dynamic_memory_offset_guard_size, offset_guard_size: self.dynamic_memory_offset_guard_size,
},
} }
} }
} }
@@ -93,8 +85,12 @@ impl BaseTunables for Tunables {
} }
/// Create a memory given a [`MemoryType`] and a [`MemoryStyle`]. /// Create a memory given a [`MemoryType`] and a [`MemoryStyle`].
fn create_memory(&self, plan: MemoryPlan) -> Result<Arc<dyn Memory>, MemoryError> { fn create_memory(
Ok(Arc::new(LinearMemory::new(&plan.memory, &plan.style)?)) &self,
ty: &MemoryType,
style: &MemoryStyle,
) -> Result<Arc<dyn Memory>, MemoryError> {
Ok(Arc::new(LinearMemory::new(&ty, &style)?))
} }
/// Create a table given a [`TableType`] and a [`TableStyle`]. /// Create a table given a [`TableType`] and a [`TableStyle`].

View File

@@ -175,16 +175,14 @@ fn memory_grow() -> Result<()> {
// due to stack overflow with a modern nightly, we can't update CI to use a version of nightly which will make this work // due to stack overflow with a modern nightly, we can't update CI to use a version of nightly which will make this work
/*assert!(matches!( /*assert!(matches!(
bad_result, bad_result,
Err(MemoryError::InvalidMemoryPlan { .. }) Err(MemoryError::InvalidMemory { .. })
));*/ ));*/
assert!( assert!(if let Err(MemoryError::InvalidMemory { .. }) = bad_result {
if let Err(MemoryError::InvalidMemoryPlan { .. }) = bad_result {
true true
} else { } else {
false false
} });
);
Ok(()) Ok(())
} }

View File

@@ -58,7 +58,7 @@ int main()
char *error_str2 = malloc(error_len2); char *error_str2 = malloc(error_len2);
wasmer_last_error_message(error_str2, error_len2); wasmer_last_error_message(error_str2, error_len2);
printf("Error str 2: `%s`\n", error_str2); printf("Error str 2: `%s`\n", error_str2);
assert(0 == strcmp(error_str2, "The memory plan is invalid because the maximum (10 pages) is less than the minimum (15 pages)")); assert(0 == strcmp(error_str2, "The memory is invalid because the maximum (10 pages) is less than the minimum (15 pages)"));
free(error_str2); free(error_str2);
printf("Destroy memory\n"); printf("Destroy memory\n");

View File

@@ -60,7 +60,7 @@ impl Compiler for CraneliftCompiler {
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
let isa = self.config().isa(target); let isa = self.config().isa(target);
let frontend_config = isa.frontend_config(); let frontend_config = isa.frontend_config();
let memory_plans = &compile_info.memory_plans; let memory_styles = &compile_info.memory_styles;
let table_styles = &compile_info.table_styles; let table_styles = &compile_info.table_styles;
let module = &compile_info.module; let module = &compile_info.module;
let signatures = module let signatures = module
@@ -100,7 +100,7 @@ impl Compiler for CraneliftCompiler {
isa.frontend_config(), isa.frontend_config(),
module, module,
&signatures, &signatures,
&memory_plans, &memory_styles,
&table_styles, &table_styles,
); );
context.func.name = get_func_name(func_index); context.func.name = get_func_name(func_index);

View File

@@ -18,7 +18,7 @@ use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, Table
use wasmer_compiler::{WasmError, WasmResult}; use wasmer_compiler::{WasmError, WasmResult};
use wasmer_runtime::VMBuiltinFunctionIndex; use wasmer_runtime::VMBuiltinFunctionIndex;
use wasmer_runtime::VMOffsets; use wasmer_runtime::VMOffsets;
use wasmer_runtime::{MemoryPlan, MemoryStyle, ModuleInfo, TableStyle}; use wasmer_runtime::{MemoryStyle, ModuleInfo, TableStyle};
/// Compute an `ir::ExternalName` for a given wasm function index. /// Compute an `ir::ExternalName` for a given wasm function index.
pub fn get_func_name(func_index: FunctionIndex) -> ir::ExternalName { pub fn get_func_name(func_index: FunctionIndex) -> ir::ExternalName {
@@ -84,10 +84,10 @@ pub struct FuncEnvironment<'module_environment> {
/// Offsets to struct fields accessed by JIT code. /// Offsets to struct fields accessed by JIT code.
offsets: VMOffsets, offsets: VMOffsets,
/// The memory plans /// The memory styles
memory_plans: &'module_environment PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'module_environment PrimaryMap<MemoryIndex, MemoryStyle>,
/// The table plans /// The table styles
table_styles: &'module_environment PrimaryMap<TableIndex, TableStyle>, table_styles: &'module_environment PrimaryMap<TableIndex, TableStyle>,
} }
@@ -96,7 +96,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
target_config: TargetFrontendConfig, target_config: TargetFrontendConfig,
module: &'module_environment ModuleInfo, module: &'module_environment ModuleInfo,
signatures: &'module_environment PrimaryMap<SignatureIndex, ir::Signature>, signatures: &'module_environment PrimaryMap<SignatureIndex, ir::Signature>,
memory_plans: &'module_environment PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'module_environment PrimaryMap<MemoryIndex, MemoryStyle>,
table_styles: &'module_environment PrimaryMap<TableIndex, TableStyle>, table_styles: &'module_environment PrimaryMap<TableIndex, TableStyle>,
) -> Self { ) -> Self {
Self { Self {
@@ -114,7 +114,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
memory_init_sig: None, memory_init_sig: None,
data_drop_sig: None, data_drop_sig: None,
offsets: VMOffsets::new(target_config.pointer_bytes(), module), offsets: VMOffsets::new(target_config.pointer_bytes(), module),
memory_plans, memory_styles,
table_styles, table_styles,
} }
} }
@@ -642,13 +642,8 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
// If we have a declared maximum, we can make this a "static" heap, which is // If we have a declared maximum, we can make this a "static" heap, which is
// allocated up front and never moved. // allocated up front and never moved.
let (offset_guard_size, heap_style, readonly_base) = match self.memory_plans[index] { let (offset_guard_size, heap_style, readonly_base) = match self.memory_styles[index] {
MemoryPlan { MemoryStyle::Dynamic { offset_guard_size } => {
style: MemoryStyle::Dynamic {
offset_guard_size
},
memory: _,
} => {
let heap_bound = func.create_global_value(ir::GlobalValueData::Load { let heap_bound = func.create_global_value(ir::GlobalValueData::Load {
base: ptr, base: ptr,
offset: Offset32::new(current_length_offset), offset: Offset32::new(current_length_offset),
@@ -663,9 +658,9 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
false, false,
) )
} }
MemoryPlan { MemoryStyle::Static {
style: MemoryStyle::Static { bound, offset_guard_size }, bound,
memory: _, offset_guard_size,
} => ( } => (
Uimm64::new(offset_guard_size), Uimm64::new(offset_guard_size),
ir::HeapStyle::Static { ir::HeapStyle::Static {

View File

@@ -44,7 +44,7 @@ impl Compiler for LLVMCompiler {
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
//let data = Arc::new(Mutex::new(0)); //let data = Arc::new(Mutex::new(0));
let mut func_names = SecondaryMap::new(); let mut func_names = SecondaryMap::new();
let memory_plans = &compile_info.memory_plans; let memory_styles = &compile_info.memory_styles;
let table_styles = &compile_info.table_styles; let table_styles = &compile_info.table_styles;
let module = &compile_info.module; let module = &compile_info.module;
@@ -78,7 +78,7 @@ impl Compiler for LLVMCompiler {
i, i,
input, input,
self.config(), self.config(),
&memory_plans, memory_styles,
&table_styles, &table_styles,
&func_names, &func_names,
) )

View File

@@ -34,7 +34,7 @@ use wasmer_compiler::{
to_wasm_error, wptype_to_type, CompileError, FunctionBodyData, GenerateMiddlewareChain, to_wasm_error, wptype_to_type, CompileError, FunctionBodyData, GenerateMiddlewareChain,
MiddlewareBinaryReader, ModuleTranslationState, RelocationTarget, MiddlewareBinaryReader, ModuleTranslationState, RelocationTarget,
}; };
use wasmer_runtime::{MemoryPlan, ModuleInfo, TableStyle}; use wasmer_runtime::{MemoryStyle, ModuleInfo, TableStyle};
fn to_compile_error(err: impl std::error::Error) -> CompileError { fn to_compile_error(err: impl std::error::Error) -> CompileError {
CompileError::Codegen(format!("{}", err)) CompileError::Codegen(format!("{}", err))
@@ -72,7 +72,7 @@ impl FuncTranslator {
local_func_index: &LocalFunctionIndex, local_func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData, function_body: &FunctionBodyData,
config: &LLVM, config: &LLVM,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &PrimaryMap<TableIndex, TableStyle>, _table_styles: &PrimaryMap<TableIndex, TableStyle>,
func_names: &SecondaryMap<FunctionIndex, String>, func_names: &SecondaryMap<FunctionIndex, String>,
) -> Result<CompiledFunction, CompileError> { ) -> Result<CompiledFunction, CompileError> {
@@ -198,7 +198,7 @@ impl FuncTranslator {
locals: params_locals, locals: params_locals,
ctx: CtxType::new(wasm_module, &func, &cache_builder), ctx: CtxType::new(wasm_module, &func, &cache_builder),
unreachable_depth: 0, unreachable_depth: 0,
memory_plans, memory_styles,
_table_styles, _table_styles,
module: &module, module: &module,
module_translation, module_translation,
@@ -908,7 +908,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
memory_index, memory_index,
self.intrinsics, self.intrinsics,
self.module, self.module,
self.memory_plans, self.memory_styles,
) { ) {
// The best we've got is `volatile`. // The best we've got is `volatile`.
// TODO: convert unwrap fail to CompileError // TODO: convert unwrap fail to CompileError
@@ -962,14 +962,14 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
let base_ptr = let base_ptr =
match self match self
.ctx .ctx
.memory(memory_index, intrinsics, self.module, self.memory_plans) .memory(memory_index, intrinsics, self.module, self.memory_styles)
{ {
MemoryCache::Dynamic { MemoryCache::Dynamic {
ptr_to_base_ptr, ptr_to_base_ptr,
current_length_ptr, current_length_ptr,
} => { } => {
// Bounds check it. // Bounds check it.
let minimum = self.memory_plans[memory_index].memory.minimum; let minimum = self.wasm_module.memories[memory_index].minimum;
let value_size_v = intrinsics.i64_ty.const_int(value_size as u64, false); let value_size_v = intrinsics.i64_ty.const_int(value_size as u64, false);
let ptr_in_bounds = if offset.is_const() { let ptr_in_bounds = if offset.is_const() {
// When the offset is constant, if it's below the minimum // When the offset is constant, if it's below the minimum
@@ -1264,7 +1264,7 @@ pub struct LLVMFunctionCodeGenerator<'ctx, 'a> {
locals: Vec<PointerValue<'ctx>>, // Contains params and locals locals: Vec<PointerValue<'ctx>>, // Contains params and locals
ctx: CtxType<'ctx, 'a>, ctx: CtxType<'ctx, 'a>,
unreachable_depth: usize, unreachable_depth: usize,
memory_plans: &'a PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &'a PrimaryMap<TableIndex, TableStyle>, _table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
// This is support for stackmaps: // This is support for stackmaps:

View File

@@ -27,7 +27,7 @@ use wasm_common::{
}; };
use wasmer_compiler::CompileError; use wasmer_compiler::CompileError;
use wasmer_runtime::ModuleInfo as WasmerCompilerModule; use wasmer_runtime::ModuleInfo as WasmerCompilerModule;
use wasmer_runtime::{MemoryPlan, MemoryStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets}; use wasmer_runtime::{MemoryStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets};
pub fn type_to_llvm_ptr<'ctx>( pub fn type_to_llvm_ptr<'ctx>(
intrinsics: &Intrinsics<'ctx>, intrinsics: &Intrinsics<'ctx>,
@@ -569,7 +569,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
index: MemoryIndex, index: MemoryIndex,
intrinsics: &Intrinsics<'ctx>, intrinsics: &Intrinsics<'ctx>,
module: &Module<'ctx>, module: &Module<'ctx>,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
) -> MemoryCache<'ctx> { ) -> MemoryCache<'ctx> {
let (cached_memories, wasm_module, ctx_ptr_value, cache_builder, offsets) = ( let (cached_memories, wasm_module, ctx_ptr_value, cache_builder, offsets) = (
&mut self.cached_memories, &mut self.cached_memories,
@@ -578,7 +578,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
&self.cache_builder, &self.cache_builder,
&self.offsets, &self.offsets,
); );
let memory_plan = &memory_plans[index]; let memory_style = &memory_styles[index];
*cached_memories.entry(index).or_insert_with(|| { *cached_memories.entry(index).or_insert_with(|| {
let memory_definition_ptr = let memory_definition_ptr =
if let Some(local_memory_index) = wasm_module.local_memory_index(index) { if let Some(local_memory_index) = wasm_module.local_memory_index(index) {
@@ -622,7 +622,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
"", "",
) )
.unwrap(); .unwrap();
if matches!(memory_plan.style, MemoryStyle::Dynamic { .. }) { if matches!(memory_style, MemoryStyle::Dynamic { .. }) {
let current_length_ptr = cache_builder let current_length_ptr = cache_builder
.build_struct_gep( .build_struct_gep(
memory_definition_ptr, memory_definition_ptr,

View File

@@ -20,7 +20,7 @@ use wasmer_compiler::{
TrapInformation, TrapInformation,
}; };
use wasmer_runtime::{ use wasmer_runtime::{
MemoryPlan, MemoryStyle, ModuleInfo, TableStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets, MemoryStyle, MemoryStyle, ModuleInfo, TableStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets,
}; };
/// The singlepass per-function code generator. /// The singlepass per-function code generator.
@@ -36,7 +36,7 @@ pub struct FuncGen<'a> {
vmoffsets: &'a VMOffsets, vmoffsets: &'a VMOffsets,
// // Memory plans. // // Memory plans.
memory_plans: &'a PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
// // Table plans. // // Table plans.
// table_styles: &'a PrimaryMap<TableIndex, TableStyle>, // table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
@@ -1226,7 +1226,7 @@ impl<'a> FuncGen<'a> {
value_size: usize, value_size: usize,
cb: F, cb: F,
) -> Result<(), CodegenError> { ) -> Result<(), CodegenError> {
let need_check = match self.memory_plans[MemoryIndex::new(0)].style { let need_check = match self.memory_styles[MemoryIndex::new(0)] {
MemoryStyle::Static { .. } => false, MemoryStyle::Static { .. } => false,
MemoryStyle::Dynamic => true, MemoryStyle::Dynamic => true,
}; };
@@ -1778,7 +1778,7 @@ impl<'a> FuncGen<'a> {
module: &'a ModuleInfo, module: &'a ModuleInfo,
config: &'a Singlepass, config: &'a Singlepass,
vmoffsets: &'a VMOffsets, vmoffsets: &'a VMOffsets,
memory_plans: &'a PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &'a PrimaryMap<TableIndex, TableStyle>, _table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
local_func_index: LocalFunctionIndex, local_func_index: LocalFunctionIndex,
local_types_excluding_arguments: &[WpType], local_types_excluding_arguments: &[WpType],
@@ -1816,7 +1816,7 @@ impl<'a> FuncGen<'a> {
module, module,
config, config,
vmoffsets, vmoffsets,
memory_plans, memory_styles,
// table_styles, // table_styles,
signature, signature,
assembler, assembler,

View File

@@ -55,7 +55,7 @@ impl Compiler for SinglepassCompiler {
return Err(CompileError::UnsupportedFeature("multivalue".to_string())); return Err(CompileError::UnsupportedFeature("multivalue".to_string()));
} }
let vmoffsets = VMOffsets::new(8, &compile_info.module); let vmoffsets = VMOffsets::new(8, &compile_info.module);
let memory_plans = &compile_info.memory_plans; let memory_styles = &compile_info.memory_styles;
let table_styles = &compile_info.table_styles; let table_styles = &compile_info.table_styles;
let module = &compile_info.module; let module = &compile_info.module;
let import_trampolines: PrimaryMap<SectionIndex, _> = (0..module.num_imported_funcs) let import_trampolines: PrimaryMap<SectionIndex, _> = (0..module.num_imported_funcs)
@@ -95,7 +95,7 @@ impl Compiler for SinglepassCompiler {
module, module,
&self.config, &self.config,
&vmoffsets, &vmoffsets,
&memory_plans, &memory_styles,
&table_styles, &table_styles,
*i, *i,
&locals, &locals,

View File

@@ -3,13 +3,13 @@ use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{Features, MemoryIndex, TableIndex}; use wasm_common::{Features, MemoryIndex, TableIndex};
use wasmer_runtime::{MemoryPlan, ModuleInfo, TableStyle}; use wasmer_runtime::{MemoryStyle, ModuleInfo, TableStyle};
/// The required info for compiling a module. /// The required info for compiling a module.
/// ///
/// This differs from [`ModuleInfo`] because it have extra info only /// This differs from [`ModuleInfo`] because it have extra info only
/// possible after translation (such as the features used for compiling, /// possible after translation (such as the features used for compiling,
/// or the `MemoryPlan` and `TableStyle`). /// or the `MemoryStyle` and `TableStyle`).
#[derive(Debug)] #[derive(Debug)]
#[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))] #[cfg_attr(feature = "enable-serde", derive(Deserialize, Serialize))]
pub struct CompileModuleInfo { pub struct CompileModuleInfo {
@@ -17,11 +17,11 @@ pub struct CompileModuleInfo {
pub features: Features, pub features: Features,
/// The module information /// The module information
pub module: Arc<ModuleInfo>, pub module: Arc<ModuleInfo>,
/// The memory plans used for compiling. /// The memory styles used for compiling.
/// ///
/// The compiler will emit the most optimal code based /// The compiler will emit the most optimal code based
/// on the memory style (static or dynamic) chosen. /// on the memory style (static or dynamic) chosen.
pub memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, pub memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>,
/// The table plans used for compiling. /// The table plans used for compiling.
pub table_styles: PrimaryMap<TableIndex, TableStyle>, pub table_styles: PrimaryMap<TableIndex, TableStyle>,
} }

View File

@@ -22,7 +22,7 @@ use wasmer_engine::{
}; };
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
use wasmer_engine::{Engine, SerializableFunctionFrameInfo}; use wasmer_engine::{Engine, SerializableFunctionFrameInfo};
use wasmer_runtime::{MemoryPlan, ModuleInfo, TableStyle, VMFunctionBody, VMSharedSignatureIndex}; use wasmer_runtime::{MemoryStyle, ModuleInfo, TableStyle, VMFunctionBody, VMSharedSignatureIndex};
/// A compiled wasm module, ready to be instantiated. /// A compiled wasm module, ready to be instantiated.
pub struct JITArtifact { pub struct JITArtifact {
@@ -55,11 +55,11 @@ impl JITArtifact {
let translation = environ.translate(data).map_err(CompileError::Wasm)?; let translation = environ.translate(data).map_err(CompileError::Wasm)?;
let memory_plans: PrimaryMap<MemoryIndex, MemoryPlan> = translation let memory_styles: PrimaryMap<MemoryIndex, MemoryStyle> = translation
.module .module
.memories .memories
.values() .values()
.map(|memory_type| tunables.memory_plan(*memory_type)) .map(|memory_type| tunables.memory_style(memory_type))
.collect(); .collect();
let table_styles: PrimaryMap<TableIndex, TableStyle> = translation let table_styles: PrimaryMap<TableIndex, TableStyle> = translation
.module .module
@@ -71,7 +71,7 @@ impl JITArtifact {
let compile_info = CompileModuleInfo { let compile_info = CompileModuleInfo {
module: Arc::new(translation.module), module: Arc::new(translation.module),
features: features.clone(), features: features.clone(),
memory_plans, memory_styles,
table_styles, table_styles,
}; };
@@ -271,8 +271,8 @@ impl Artifact for JITArtifact {
&*self.serializable.data_initializers &*self.serializable.data_initializers
} }
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan> { fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.serializable.compile_info.memory_plans &self.serializable.compile_info.memory_styles
} }
fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> { fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {

View File

@@ -32,7 +32,7 @@ use wasmer_engine::{
}; };
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
use wasmer_object::{emit_compilation, emit_data, get_object_for_target, CompilationNamer}; use wasmer_object::{emit_compilation, emit_data, get_object_for_target, CompilationNamer};
use wasmer_runtime::{MemoryPlan, TableStyle}; use wasmer_runtime::{MemoryStyle, TableStyle};
use wasmer_runtime::{ModuleInfo, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline}; use wasmer_runtime::{ModuleInfo, VMFunctionBody, VMSharedSignatureIndex, VMTrampoline};
/// A compiled wasm module, ready to be instantiated. /// A compiled wasm module, ready to be instantiated.
@@ -101,11 +101,11 @@ impl NativeArtifact {
) -> Result<(CompileModuleInfo, Compilation, Vec<DataInitializer<'data>>), CompileError> { ) -> Result<(CompileModuleInfo, Compilation, Vec<DataInitializer<'data>>), CompileError> {
let environ = ModuleEnvironment::new(); let environ = ModuleEnvironment::new();
let translation = environ.translate(data).map_err(CompileError::Wasm)?; let translation = environ.translate(data).map_err(CompileError::Wasm)?;
let memory_plans: PrimaryMap<MemoryIndex, MemoryPlan> = translation let memory_styles: PrimaryMap<MemoryIndex, MemoryStyle> = translation
.module .module
.memories .memories
.values() .values()
.map(|memory_type| tunables.memory_plan(*memory_type)) .map(|memory_type| tunables.memory_style(memory_type))
.collect(); .collect();
let table_styles: PrimaryMap<TableIndex, TableStyle> = translation let table_styles: PrimaryMap<TableIndex, TableStyle> = translation
.module .module
@@ -117,7 +117,7 @@ impl NativeArtifact {
let compile_info = CompileModuleInfo { let compile_info = CompileModuleInfo {
module: Arc::new(translation.module), module: Arc::new(translation.module),
features: features.clone(), features: features.clone(),
memory_plans, memory_styles,
table_styles, table_styles,
}; };
@@ -522,8 +522,8 @@ impl Artifact for NativeArtifact {
&*self.metadata.data_initializers &*self.metadata.data_initializers
} }
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan> { fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.metadata.compile_info.memory_plans &self.metadata.compile_info.memory_styles
} }
fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> { fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {

View File

@@ -12,7 +12,7 @@ use wasm_common::{
}; };
use wasmer_compiler::Features; use wasmer_compiler::Features;
use wasmer_runtime::{ use wasmer_runtime::{
InstanceHandle, MemoryPlan, ModuleInfo, TableStyle, VMFunctionBody, VMSharedSignatureIndex, InstanceHandle, MemoryStyle, ModuleInfo, TableStyle, VMFunctionBody, VMSharedSignatureIndex,
}; };
/// An `Artifact` is the product that the `Engine` /// An `Artifact` is the product that the `Engine`
@@ -41,8 +41,8 @@ pub trait Artifact {
/// Returns the features for this Artifact /// Returns the features for this Artifact
fn features(&self) -> &Features; fn features(&self) -> &Features;
/// Returns the memory plans associated with this `Artifact`. /// Returns the memory styles associated with this `Artifact`.
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan>; fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle>;
/// Returns the table plans associated with this `Artifact`. /// Returns the table plans associated with this `Artifact`.
fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle>; fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle>;
@@ -96,12 +96,12 @@ pub trait Artifact {
&module, &module,
resolver, resolver,
&self.finished_dynamic_function_trampolines(), &self.finished_dynamic_function_trampolines(),
self.memory_plans(), self.memory_styles(),
self.table_styles(), self.table_styles(),
) )
.map_err(InstantiationError::Link)?; .map_err(InstantiationError::Link)?;
let finished_memories = tunables let finished_memories = tunables
.create_memories(&module, self.memory_plans()) .create_memories(&module, self.memory_styles())
.map_err(InstantiationError::Link)? .map_err(InstantiationError::Link)?
.into_boxed_slice(); .into_boxed_slice();
let finished_tables = tunables let finished_tables = tunables

View File

@@ -6,13 +6,10 @@ use more_asserts::assert_ge;
use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasm_common::{ExternType, FunctionIndex, ImportIndex, MemoryIndex, TableIndex}; use wasm_common::{ExternType, FunctionIndex, ImportIndex, MemoryIndex, TableIndex};
use wasmer_runtime::{ use wasmer_runtime::{
Export, Imports, VMFunctionBody, VMFunctionImport, VMFunctionKind, VMGlobalImport, Export, Imports, MemoryStyle, ModuleInfo, TableStyle, VMFunctionBody, VMFunctionImport,
VMMemoryImport, VMTableImport, VMFunctionKind, VMGlobalImport, VMMemoryImport, VMTableImport,
}; };
use wasmer_runtime::{MemoryPlan, TableStyle};
use wasmer_runtime::{MemoryStyle, ModuleInfo};
/// Import resolver connects imports with available exported values. /// Import resolver connects imports with available exported values.
pub trait Resolver { pub trait Resolver {
/// Resolves an import a WebAssembly module to an export it's hooked up to. /// Resolves an import a WebAssembly module to an export it's hooked up to.
@@ -120,7 +117,7 @@ pub fn resolve_imports(
module: &ModuleInfo, module: &ModuleInfo,
resolver: &dyn Resolver, resolver: &dyn Resolver,
finished_dynamic_function_trampolines: &BoxedSlice<FunctionIndex, *mut [VMFunctionBody]>, finished_dynamic_function_trampolines: &BoxedSlice<FunctionIndex, *mut [VMFunctionBody]>,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &PrimaryMap<TableIndex, TableStyle>, _table_styles: &PrimaryMap<TableIndex, TableStyle>,
) -> Result<Imports, LinkError> { ) -> Result<Imports, LinkError> {
let mut function_imports = PrimaryMap::with_capacity(module.num_imported_funcs); let mut function_imports = PrimaryMap::with_capacity(module.num_imported_funcs);
@@ -181,20 +178,20 @@ pub fn resolve_imports(
// Sanity-check: Ensure that the imported memory has at least // Sanity-check: Ensure that the imported memory has at least
// guard-page protections the importing module expects it to have. // guard-page protections the importing module expects it to have.
let export_memory_style = m.style(); let export_memory_style = m.style();
let import_memory_plan = &memory_plans[*index]; let import_memory_style = &memory_styles[*index];
if let ( if let (
MemoryStyle::Static { bound, .. }, MemoryStyle::Static { bound, .. },
MemoryStyle::Static { MemoryStyle::Static {
bound: import_bound, bound: import_bound,
.. ..
}, },
) = (export_memory_style.clone(), &import_memory_plan.style) ) = (export_memory_style.clone(), &import_memory_style)
{ {
assert_ge!(bound, *import_bound); assert_ge!(bound, *import_bound);
} }
assert_ge!( assert_ge!(
export_memory_style.offset_guard_size(), export_memory_style.offset_guard_size(),
import_memory_plan.style.offset_guard_size() import_memory_style.offset_guard_size()
); );
} }
_ => { _ => {

View File

@@ -7,18 +7,22 @@ use wasm_common::{
}; };
use wasmer_runtime::MemoryError; use wasmer_runtime::MemoryError;
use wasmer_runtime::{Memory, ModuleInfo, Table, VMGlobalDefinition}; use wasmer_runtime::{Memory, ModuleInfo, Table, VMGlobalDefinition};
use wasmer_runtime::{MemoryPlan, TableStyle}; use wasmer_runtime::{MemoryStyle, TableStyle};
/// Tunables for an engine /// Tunables for an engine
pub trait Tunables { pub trait Tunables {
/// Construct a `MemoryPlan` for the provided `MemoryType` /// Construct a `MemoryStyle` for the provided `MemoryType`
fn memory_plan(&self, memory: MemoryType) -> MemoryPlan; fn memory_style(&self, memory: &MemoryType) -> MemoryStyle;
/// Construct a `TableStyle` for the provided `TableType` /// Construct a `TableStyle` for the provided `TableType`
fn table_style(&self, table: &TableType) -> TableStyle; fn table_style(&self, table: &TableType) -> TableStyle;
/// Create a memory given a memory type /// Create a memory given a memory type
fn create_memory(&self, memory_type: MemoryPlan) -> Result<Arc<dyn Memory>, MemoryError>; fn create_memory(
&self,
ty: &MemoryType,
style: &MemoryStyle,
) -> Result<Arc<dyn Memory>, MemoryError>;
/// Create a memory given a memory type /// Create a memory given a memory type
fn create_table(&self, ty: &TableType, style: &TableStyle) -> Result<Arc<dyn Table>, String>; fn create_table(&self, ty: &TableType, style: &TableStyle) -> Result<Arc<dyn Table>, String>;
@@ -27,15 +31,17 @@ pub trait Tunables {
fn create_memories( fn create_memories(
&self, &self,
module: &ModuleInfo, module: &ModuleInfo,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_styles: &PrimaryMap<MemoryIndex, MemoryStyle>,
) -> Result<PrimaryMap<LocalMemoryIndex, Arc<dyn Memory>>, LinkError> { ) -> Result<PrimaryMap<LocalMemoryIndex, Arc<dyn Memory>>, LinkError> {
let num_imports = module.num_imported_memories; let num_imports = module.num_imported_memories;
let mut memories: PrimaryMap<LocalMemoryIndex, _> = let mut memories: PrimaryMap<LocalMemoryIndex, _> =
PrimaryMap::with_capacity(module.memories.len() - num_imports); PrimaryMap::with_capacity(module.memories.len() - num_imports);
for index in num_imports..module.memories.len() { for index in num_imports..module.memories.len() {
let plan = memory_plans[MemoryIndex::new(index)].clone(); let mi = MemoryIndex::new(index);
let ty = &module.memories[mi];
let style = &memory_styles[mi];
memories.push( memories.push(
self.create_memory(plan) self.create_memory(ty, style)
.map_err(|e| LinkError::Resource(format!("Failed to create memory: {}", e)))?, .map_err(|e| LinkError::Resource(format!("Failed to create memory: {}", e)))?,
); );
} }

View File

@@ -9,7 +9,7 @@ use crate::vmcontext::{
}; };
use std::ptr::NonNull; use std::ptr::NonNull;
use std::sync::Arc; use std::sync::Arc;
use wasm_common::{FunctionType, GlobalType, TableType, MemoryType}; use wasm_common::{FunctionType, GlobalType, MemoryType, TableType};
/// The value of an export passed from one instance to another. /// The value of an export passed from one instance to another.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View File

@@ -39,7 +39,7 @@ pub mod libcalls;
pub use crate::export::*; pub use crate::export::*;
pub use crate::imports::Imports; pub use crate::imports::Imports;
pub use crate::instance::InstanceHandle; pub use crate::instance::InstanceHandle;
pub use crate::memory::{LinearMemory, Memory, MemoryError, MemoryPlan, MemoryStyle}; pub use crate::memory::{LinearMemory, Memory, MemoryError, MemoryStyle};
pub use crate::mmap::Mmap; pub use crate::mmap::Mmap;
pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo}; pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo};
pub use crate::probestack::PROBESTACK; pub use crate::probestack::PROBESTACK;

View File

@@ -33,9 +33,9 @@ pub enum MemoryError {
attempted_delta: Pages, attempted_delta: Pages,
}, },
/// The operation would cause the size of the memory size exceed the maximum. /// The operation would cause the size of the memory size exceed the maximum.
#[error("The memory plan is invalid because {}", reason)] #[error("The memory is invalid because {}", reason)]
InvalidMemoryPlan { InvalidMemory {
/// The reason why the memory plan is invalid. /// The reason why the memory style is invalid.
reason: String, reason: String,
}, },
/// A user defined error value, used for error cases not listed above. /// A user defined error value, used for error cases not listed above.
@@ -65,21 +65,13 @@ impl MemoryStyle {
pub fn offset_guard_size(&self) -> u64 { pub fn offset_guard_size(&self) -> u64 {
match self { match self {
Self::Dynamic { offset_guard_size } => *offset_guard_size, Self::Dynamic { offset_guard_size } => *offset_guard_size,
Self::Static { offset_guard_size, .. } => *offset_guard_size, Self::Static {
offset_guard_size, ..
} => *offset_guard_size,
} }
} }
} }
/// A WebAssembly linear memory description along with our chosen style for
/// implementing it.
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct MemoryPlan {
/// The WebAssembly linear memory description.
pub memory: MemoryType,
/// Our chosen implementation style.
pub style: MemoryStyle,
}
/// Trait for implementing Wasm Memory used by Wasmer. /// Trait for implementing Wasm Memory used by Wasmer.
pub trait Memory: fmt::Debug + Send + Sync { pub trait Memory: fmt::Debug + Send + Sync {
/// Returns the memory type for this memory. /// Returns the memory type for this memory.
@@ -143,12 +135,10 @@ impl LinearMemory {
pub fn new(memory: &MemoryType, style: &MemoryStyle) -> Result<Self, MemoryError> { pub fn new(memory: &MemoryType, style: &MemoryStyle) -> Result<Self, MemoryError> {
// `maximum` cannot be set to more than `65536` pages. // `maximum` cannot be set to more than `65536` pages.
assert_le!(memory.minimum, Pages::max_value()); assert_le!(memory.minimum, Pages::max_value());
assert!( assert!(memory.maximum.is_none() || memory.maximum.unwrap() <= Pages::max_value());
memory.maximum.is_none() || memory.maximum.unwrap() <= Pages::max_value()
);
if memory.maximum.is_some() && memory.maximum.unwrap() < memory.minimum { if memory.maximum.is_some() && memory.maximum.unwrap() < memory.minimum {
return Err(MemoryError::InvalidMemoryPlan { return Err(MemoryError::InvalidMemory {
reason: format!( reason: format!(
"the maximum ({} pages) is less than the minimum ({} pages)", "the maximum ({} pages) is less than the minimum ({} pages)",
memory.maximum.unwrap().0, memory.maximum.unwrap().0,
@@ -203,12 +193,12 @@ impl LinearMemory {
} }
impl Memory for LinearMemory { impl Memory for LinearMemory {
/// Returns the memory plan for this memory. /// Returns the type for this memory.
fn ty(&self) -> &MemoryType { fn ty(&self) -> &MemoryType {
&self.memory &self.memory
} }
/// Returns the memory plan for this memory. /// Returns the memory style for this memory.
fn style(&self) -> &MemoryStyle { fn style(&self) -> &MemoryStyle {
&self.style &self.style
} }

View File

@@ -91,7 +91,7 @@ pub struct ModuleInfo {
/// WebAssembly tables (imported and local). /// WebAssembly tables (imported and local).
pub tables: PrimaryMap<TableIndex, TableType>, pub tables: PrimaryMap<TableIndex, TableType>,
/// WebAssembly linear memory plans (imported and local). /// WebAssembly linear memories (imported and local).
pub memories: PrimaryMap<MemoryIndex, MemoryType>, pub memories: PrimaryMap<MemoryIndex, MemoryType>,
/// WebAssembly global variables (imported and local). /// WebAssembly global variables (imported and local).

View File

@@ -15,7 +15,7 @@ use wasmer_compiler::CompileError;
use wasmer_compiler::ModuleEnvironment; use wasmer_compiler::ModuleEnvironment;
use wasmer_engine::{Artifact, DeserializeError, Engine as _, SerializeError, Tunables}; use wasmer_engine::{Artifact, DeserializeError, Engine as _, SerializeError, Tunables};
use wasmer_runtime::{ use wasmer_runtime::{
MemoryPlan, ModuleInfo, TableStyle, VMContext, VMFunctionBody, VMSharedSignatureIndex, MemoryStyle, ModuleInfo, TableStyle, VMContext, VMFunctionBody, VMSharedSignatureIndex,
}; };
/// Serializable struct for the artifact /// Serializable struct for the artifact
@@ -25,7 +25,7 @@ pub struct DummyArtifactMetadata {
pub features: Features, pub features: Features,
pub data_initializers: Box<[OwnedDataInitializer]>, pub data_initializers: Box<[OwnedDataInitializer]>,
// Plans for that module // Plans for that module
pub memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, pub memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>,
pub table_styles: PrimaryMap<TableIndex, TableStyle>, pub table_styles: PrimaryMap<TableIndex, TableStyle>,
} }
@@ -64,11 +64,11 @@ impl DummyArtifact {
let translation = environ.translate(data).map_err(CompileError::Wasm)?; let translation = environ.translate(data).map_err(CompileError::Wasm)?;
let memory_plans: PrimaryMap<MemoryIndex, MemoryPlan> = translation let memory_styles: PrimaryMap<MemoryIndex, MemoryStyle> = translation
.module .module
.memories .memories
.values() .values()
.map(|memory_type| tunables.memory_plan(*memory_type)) .map(|memory_type| tunables.memory_style(memory_type))
.collect(); .collect();
let table_styles: PrimaryMap<TableIndex, TableStyle> = translation let table_styles: PrimaryMap<TableIndex, TableStyle> = translation
.module .module
@@ -88,7 +88,7 @@ impl DummyArtifact {
module: Arc::new(translation.module), module: Arc::new(translation.module),
features: Features::default(), features: Features::default(),
data_initializers, data_initializers,
memory_plans, memory_styles,
table_styles, table_styles,
}; };
Self::from_parts(&engine, metadata) Self::from_parts(&engine, metadata)
@@ -199,8 +199,8 @@ impl Artifact for DummyArtifact {
&*self.metadata.data_initializers &*self.metadata.data_initializers
} }
fn memory_plans(&self) -> &PrimaryMap<MemoryIndex, MemoryPlan> { fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.metadata.memory_plans &self.metadata.memory_styles
} }
fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> { fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {