Merge pull request #14 from wasmerio/func

Func* to Function* for clarity
This commit is contained in:
Syrus Akbary
2020-05-04 14:15:22 -07:00
committed by GitHub
46 changed files with 350 additions and 342 deletions

View File

@@ -1,4 +1,4 @@
use crate::externals::{Extern, Func, Global, Memory, Table}; use crate::externals::{Extern, Function, Global, Memory, Table};
use crate::import_object::LikeNamespace; use crate::import_object::LikeNamespace;
use indexmap::IndexMap; use indexmap::IndexMap;
use std::iter::FromIterator; use std::iter::FromIterator;
@@ -103,7 +103,7 @@ impl Exports {
} }
/// Get an export as a `Func`. /// Get an export as a `Func`.
pub fn get_func(&self, name: &str) -> Result<&Func, ExportError> { pub fn get_function(&self, name: &str) -> Result<&Function, ExportError> {
self.get(name) self.get(name)
} }

View File

@@ -4,7 +4,7 @@ use crate::store::{Store, StoreObject};
use crate::types::{Val, ValAnyFunc}; use crate::types::{Val, ValAnyFunc};
use crate::Mutability; use crate::Mutability;
use crate::RuntimeError; use crate::RuntimeError;
use crate::{ExternType, FuncType, GlobalType, MemoryType, TableType, ValType}; use crate::{ExternType, FunctionType, GlobalType, MemoryType, TableType, ValType};
use std::cmp::max; use std::cmp::max;
use std::slice; use std::slice;
use wasm_common::{Bytes, HostFunction, Pages, ValueType, WasmTypeList, WithEnv, WithoutEnv}; use wasm_common::{Bytes, HostFunction, Pages, ValueType, WasmTypeList, WithEnv, WithoutEnv};
@@ -16,7 +16,7 @@ use wasmer_runtime::{
#[derive(Clone)] #[derive(Clone)]
pub enum Extern { pub enum Extern {
Func(Func), Function(Function),
Global(Global), Global(Global),
Table(Table), Table(Table),
Memory(Memory), Memory(Memory),
@@ -25,7 +25,7 @@ pub enum Extern {
impl Extern { impl Extern {
pub fn ty(&self) -> ExternType { pub fn ty(&self) -> ExternType {
match self { match self {
Extern::Func(ft) => ExternType::Func(ft.ty().clone()), Extern::Function(ft) => ExternType::Function(ft.ty().clone()),
Extern::Memory(ft) => ExternType::Memory(ft.ty().clone()), Extern::Memory(ft) => ExternType::Memory(ft.ty().clone()),
Extern::Table(tt) => ExternType::Table(tt.ty().clone()), Extern::Table(tt) => ExternType::Table(tt.ty().clone()),
Extern::Global(gt) => ExternType::Global(gt.ty().clone()), Extern::Global(gt) => ExternType::Global(gt.ty().clone()),
@@ -34,7 +34,7 @@ impl Extern {
pub(crate) fn from_export(store: &Store, export: Export) -> Extern { pub(crate) fn from_export(store: &Store, export: Export) -> Extern {
match export { match export {
Export::Function(f) => Extern::Func(Func::from_export(store, f)), Export::Function(f) => Extern::Function(Function::from_export(store, f)),
Export::Memory(m) => Extern::Memory(Memory::from_export(store, m)), Export::Memory(m) => Extern::Memory(Memory::from_export(store, m)),
Export::Global(g) => Extern::Global(Global::from_export(store, g)), Export::Global(g) => Extern::Global(Global::from_export(store, g)),
Export::Table(t) => Extern::Table(Table::from_export(store, t)), Export::Table(t) => Extern::Table(Table::from_export(store, t)),
@@ -45,7 +45,7 @@ impl Extern {
impl<'a> Exportable<'a> for Extern { impl<'a> Exportable<'a> for Extern {
fn to_export(&self) -> Export { fn to_export(&self) -> Export {
match self { match self {
Extern::Func(f) => f.to_export(), Extern::Function(f) => f.to_export(),
Extern::Global(g) => g.to_export(), Extern::Global(g) => g.to_export(),
Extern::Memory(m) => m.to_export(), Extern::Memory(m) => m.to_export(),
Extern::Table(t) => t.to_export(), Extern::Table(t) => t.to_export(),
@@ -61,7 +61,7 @@ impl<'a> Exportable<'a> for Extern {
impl StoreObject for Extern { impl StoreObject for Extern {
fn comes_from_same_store(&self, store: &Store) -> bool { fn comes_from_same_store(&self, store: &Store) -> bool {
let my_store = match self { let my_store = match self {
Extern::Func(f) => f.store(), Extern::Function(f) => f.store(),
Extern::Global(g) => g.store(), Extern::Global(g) => g.store(),
Extern::Memory(m) => m.store(), Extern::Memory(m) => m.store(),
Extern::Table(t) => t.store(), Extern::Table(t) => t.store(),
@@ -70,9 +70,9 @@ impl StoreObject for Extern {
} }
} }
impl From<Func> for Extern { impl From<Function> for Extern {
fn from(r: Func) -> Self { fn from(r: Function) -> Self {
Extern::Func(r) Extern::Function(r)
} }
} }
@@ -492,7 +492,7 @@ pub enum InnerFunc {
/// A WebAssembly `function`. /// A WebAssembly `function`.
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct Func { pub struct Function {
store: Store, store: Store,
// If the Function is owned by the Store, not the instance // If the Function is owned by the Store, not the instance
inner: InnerFunc, inner: InnerFunc,
@@ -500,12 +500,12 @@ pub struct Func {
exported: ExportFunction, exported: ExportFunction,
} }
impl Func { impl Function {
/// Creates a new `Func` with the given parameters. /// Creates a new `Func` with the given parameters.
/// ///
/// * `store` - a global cache to store information in /// * `store` - a global cache to store information in
/// * `func` - the function. /// * `func` - the function.
pub fn new<F, Args, Rets, Env>(store: &Store, func: F) -> Func pub fn new<F, Args, Rets, Env>(store: &Store, func: F) -> Self
where where
F: HostFunction<Args, Rets, WithoutEnv, Env>, F: HostFunction<Args, Rets, WithoutEnv, Env>,
Args: WasmTypeList, Args: WasmTypeList,
@@ -517,7 +517,7 @@ impl Func {
let vmctx = (func.env().unwrap_or(std::ptr::null_mut()) as *mut _) as *mut VMContext; let vmctx = (func.env().unwrap_or(std::ptr::null_mut()) as *mut _) as *mut VMContext;
let func_type = func.ty(); let func_type = func.ty();
let signature = store.engine().register_signature(&func_type); let signature = store.engine().register_signature(&func_type);
Func { Self {
store: store.clone(), store: store.clone(),
owned_by_store: true, owned_by_store: true,
inner: InnerFunc::Host(HostFunc { inner: InnerFunc::Host(HostFunc {
@@ -536,7 +536,7 @@ impl Func {
/// * `store` - a global cache to store information in. /// * `store` - a global cache to store information in.
/// * `env` - the function environment. /// * `env` - the function environment.
/// * `func` - the function. /// * `func` - the function.
pub fn new_env<F, Args, Rets, Env>(store: &Store, env: &mut Env, func: F) -> Func pub fn new_env<F, Args, Rets, Env>(store: &Store, env: &mut Env, func: F) -> Self
where where
F: HostFunction<Args, Rets, WithEnv, Env>, F: HostFunction<Args, Rets, WithEnv, Env>,
Args: WasmTypeList, Args: WasmTypeList,
@@ -548,7 +548,7 @@ impl Func {
let vmctx = (func.env().unwrap_or(std::ptr::null_mut()) as *mut _) as *mut VMContext; let vmctx = (func.env().unwrap_or(std::ptr::null_mut()) as *mut _) as *mut VMContext;
let func_type = func.ty(); let func_type = func.ty();
let signature = store.engine().register_signature(&func_type); let signature = store.engine().register_signature(&func_type);
Func { Self {
store: store.clone(), store: store.clone(),
owned_by_store: true, owned_by_store: true,
inner: InnerFunc::Host(HostFunc { inner: InnerFunc::Host(HostFunc {
@@ -563,7 +563,7 @@ impl Func {
} }
/// Returns the underlying type of this function. /// Returns the underlying type of this function.
pub fn ty(&self) -> FuncType { pub fn ty(&self) -> FunctionType {
self.store self.store
.engine() .engine()
.lookup_signature(self.exported.signature) .lookup_signature(self.exported.signature)
@@ -662,9 +662,9 @@ impl Func {
Ok(results.into_boxed_slice()) Ok(results.into_boxed_slice())
} }
pub(crate) fn from_export(store: &Store, wasmer_export: ExportFunction) -> Func { pub(crate) fn from_export(store: &Store, wasmer_export: ExportFunction) -> Self {
let trampoline = store.engine().trampoline(wasmer_export.signature).unwrap(); let trampoline = store.engine().trampoline(wasmer_export.signature).unwrap();
Func { Self {
store: store.clone(), store: store.clone(),
owned_by_store: false, owned_by_store: false,
inner: InnerFunc::Wasm(WasmFunc { trampoline }), inner: InnerFunc::Wasm(WasmFunc { trampoline }),
@@ -681,19 +681,19 @@ impl Func {
} }
} }
impl<'a> Exportable<'a> for Func { impl<'a> Exportable<'a> for Function {
fn to_export(&self) -> Export { fn to_export(&self) -> Export {
self.exported.clone().into() self.exported.clone().into()
} }
fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> {
match _extern { match _extern {
Extern::Func(func) => Ok(func), Extern::Function(func) => Ok(func),
_ => Err(ExportError::IncompatibleType), _ => Err(ExportError::IncompatibleType),
} }
} }
} }
impl std::fmt::Debug for Func { impl std::fmt::Debug for Function {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(()) Ok(())
} }

View File

@@ -201,7 +201,7 @@ impl Extend<((String, String), Export)> for ImportObject {
/// ///
/// let import_object = imports! { /// let import_object = imports! {
/// "env" => { /// "env" => {
/// "foo" => Func::new(&store, foo) /// "foo" => Function::new(&store, foo)
/// } /// }
/// }; /// };
/// ///

View File

@@ -13,7 +13,7 @@ mod tunables;
mod types; mod types;
pub use crate::exports::{ExportError, Exportable, Exports}; pub use crate::exports::{ExportError, Exportable, Exports};
pub use crate::externals::{Extern, Func, Global, Memory, Table}; pub use crate::externals::{Extern, Function, Global, Memory, Table};
pub use crate::import_object::{ImportObject, ImportObjectIterator, LikeNamespace}; pub use crate::import_object::{ImportObject, ImportObjectIterator, LikeNamespace};
pub use crate::instance::Instance; pub use crate::instance::Instance;
pub use crate::memory_view::MemoryView; pub use crate::memory_view::MemoryView;
@@ -22,7 +22,7 @@ pub use crate::ptr::{Array, Item, WasmPtr};
pub use crate::store::{Engine, Store, StoreObject}; pub use crate::store::{Engine, Store, StoreObject};
pub use crate::tunables::Tunables; pub use crate::tunables::Tunables;
pub use crate::types::{ pub use crate::types::{
AnyRef, ExportType, ExternType, FuncType, GlobalType, HostInfo, HostRef, ImportType, AnyRef, ExportType, ExternType, FunctionType, GlobalType, HostInfo, HostRef, ImportType,
MemoryType, Mutability, TableType, Val, ValType, MemoryType, Mutability, TableType, Val, ValType,
}; };

View File

@@ -1,14 +1,14 @@
use crate::externals::Func; use crate::externals::Function;
use crate::store::{Store, StoreObject}; use crate::store::{Store, StoreObject};
use crate::RuntimeError; use crate::RuntimeError;
use std::ptr; use std::ptr;
use wasm_common::Value; use wasm_common::Value;
pub use wasm_common::{ pub use wasm_common::{
AnyRef, ExportType, ExternType, FuncType, GlobalType, HostInfo, HostRef, ImportType, AnyRef, ExportType, ExternType, FunctionType, GlobalType, HostInfo, HostRef, ImportType,
MemoryType, Mutability, TableType, Type as ValType, MemoryType, Mutability, TableType, Type as ValType,
}; };
pub type Val = Value<Func>; pub type Val = Value<Function>;
impl StoreObject for Val { impl StoreObject for Val {
fn comes_from_same_store(&self, store: &Store) -> bool { fn comes_from_same_store(&self, store: &Store) -> bool {
@@ -21,8 +21,8 @@ impl StoreObject for Val {
} }
} }
impl From<Func> for Val { impl From<Function> for Val {
fn from(val: Func) -> Val { fn from(val: Function) -> Val {
Val::FuncRef(val) Val::FuncRef(val)
} }
} }
@@ -66,7 +66,7 @@ impl ValAnyFunc for Val {
signature: item.type_index, signature: item.type_index,
vmctx: item.vmctx, vmctx: item.vmctx,
}; };
let f = Func::from_export(store, export); let f = Function::from_export(store, export);
Val::FuncRef(f) Val::FuncRef(f)
} }
} }

View File

@@ -14,7 +14,8 @@ use cranelift_codegen::{binemit, isa, Context};
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use wasm_common::entity::{EntityRef, PrimaryMap, SecondaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap, SecondaryMap};
use wasm_common::{ use wasm_common::{
Features, FuncIndex, FuncType, LocalFuncIndex, MemoryIndex, SignatureIndex, TableIndex, Features, FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, SignatureIndex,
TableIndex,
}; };
use wasmer_compiler::CompileError; use wasmer_compiler::CompileError;
use wasmer_compiler::{ use wasmer_compiler::{
@@ -31,7 +32,7 @@ pub struct RelocSink<'a> {
module: &'a Module, module: &'a Module,
/// Current function index. /// Current function index.
local_func_index: LocalFuncIndex, local_func_index: LocalFunctionIndex,
/// Relocations recorded for the function. /// Relocations recorded for the function.
pub func_relocs: Vec<Relocation>, pub func_relocs: Vec<Relocation>,
@@ -58,7 +59,7 @@ impl<'a> binemit::RelocSink for RelocSink<'a> {
debug_assert_eq!(namespace, 0); debug_assert_eq!(namespace, 0);
RelocationTarget::LocalFunc( RelocationTarget::LocalFunc(
self.module self.module
.local_func_index(FuncIndex::from_u32(index)) .local_func_index(FunctionIndex::from_u32(index))
.expect("The provided function should be local"), .expect("The provided function should be local"),
) )
} else if let ExternalName::LibCall(libcall) = *name { } else if let ExternalName::LibCall(libcall) = *name {
@@ -99,7 +100,7 @@ impl<'a> binemit::RelocSink for RelocSink<'a> {
impl<'a> RelocSink<'a> { impl<'a> RelocSink<'a> {
/// Return a new `RelocSink` instance. /// Return a new `RelocSink` instance.
pub fn new(module: &'a Module, func_index: FuncIndex) -> Self { pub fn new(module: &'a Module, func_index: FunctionIndex) -> Self {
let local_func_index = module let local_func_index = module
.local_func_index(func_index) .local_func_index(func_index)
.expect("The provided function should be local"); .expect("The provided function should be local");
@@ -200,7 +201,7 @@ impl Compiler for CraneliftCompiler {
&self, &self,
module: &Module, module: &Module,
module_translation: &ModuleTranslationState, module_translation: &ModuleTranslationState,
function_body_inputs: PrimaryMap<LocalFuncIndex, FunctionBodyData<'_>>, function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'_>>,
memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>,
table_plans: PrimaryMap<TableIndex, TablePlan>, table_plans: PrimaryMap<TableIndex, TablePlan>,
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
@@ -214,7 +215,7 @@ impl Compiler for CraneliftCompiler {
let functions = function_body_inputs let functions = function_body_inputs
.into_iter() .into_iter()
.collect::<Vec<(LocalFuncIndex, &FunctionBodyData<'_>)>>() .collect::<Vec<(LocalFunctionIndex, &FunctionBodyData<'_>)>>()
.par_iter() .par_iter()
.map_init(FuncTranslator::new, |func_translator, (i, input)| { .map_init(FuncTranslator::new, |func_translator, (i, input)| {
let func_index = module.func_index(*i); let func_index = module.func_index(*i);
@@ -279,7 +280,7 @@ impl Compiler for CraneliftCompiler {
}) })
.collect::<Result<Vec<_>, CompileError>>()? .collect::<Result<Vec<_>, CompileError>>()?
.into_iter() .into_iter()
.collect::<PrimaryMap<LocalFuncIndex, _>>(); .collect::<PrimaryMap<LocalFunctionIndex, _>>();
let custom_sections = PrimaryMap::new(); let custom_sections = PrimaryMap::new();
@@ -288,7 +289,7 @@ impl Compiler for CraneliftCompiler {
fn compile_wasm_trampolines( fn compile_wasm_trampolines(
&self, &self,
signatures: &[FuncType], signatures: &[FunctionType],
) -> Result<Vec<FunctionBody>, CompileError> { ) -> Result<Vec<FunctionBody>, CompileError> {
signatures signatures
.par_iter() .par_iter()

View File

@@ -3,13 +3,13 @@
use cranelift_codegen::ir; use cranelift_codegen::ir;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::LocalFuncIndex; use wasm_common::LocalFunctionIndex;
/// Value ranges for functions. /// Value ranges for functions.
pub type ValueLabelsRanges = PrimaryMap<LocalFuncIndex, cranelift_codegen::ValueLabelsRanges>; pub type ValueLabelsRanges = PrimaryMap<LocalFunctionIndex, cranelift_codegen::ValueLabelsRanges>;
/// Stack slots for functions. /// Stack slots for functions.
pub type StackSlots = PrimaryMap<LocalFuncIndex, ir::StackSlots>; pub type StackSlots = PrimaryMap<LocalFunctionIndex, ir::StackSlots>;
/// Memory definition offset in the VMContext structure. /// Memory definition offset in the VMContext structure.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View File

@@ -1,7 +1,7 @@
use cranelift_codegen::isa::CallConv; use cranelift_codegen::isa::CallConv;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::LocalFuncIndex; use wasm_common::LocalFunctionIndex;
pub use cranelift_codegen::ir::FrameLayoutChange; pub use cranelift_codegen::ir::FrameLayoutChange;
@@ -18,4 +18,4 @@ pub struct FrameLayout {
} }
/// Functions frame layouts. /// Functions frame layouts.
pub type FrameLayouts = PrimaryMap<LocalFuncIndex, FrameLayout>; pub type FrameLayouts = PrimaryMap<LocalFunctionIndex, FrameLayout>;

View File

@@ -11,14 +11,14 @@ use cranelift_codegen::isa::TargetFrontendConfig;
use std::convert::TryFrom; use std::convert::TryFrom;
use wasm_common::entity::EntityRef; use wasm_common::entity::EntityRef;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{FuncIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex}; use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};
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, Module, TablePlan, TableStyle}; use wasmer_runtime::{MemoryPlan, MemoryStyle, Module, TablePlan, 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: FuncIndex) -> ir::ExternalName { pub fn get_func_name(func_index: FunctionIndex) -> ir::ExternalName {
ir::ExternalName::user(0, func_index.as_u32()) ir::ExternalName::user(0, func_index.as_u32())
} }
@@ -731,7 +731,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
fn make_direct_func( fn make_direct_func(
&mut self, &mut self,
func: &mut ir::Function, func: &mut ir::Function,
index: FuncIndex, index: FunctionIndex,
) -> WasmResult<ir::FuncRef> { ) -> WasmResult<ir::FuncRef> {
let sigidx = self.module.functions[index]; let sigidx = self.module.functions[index];
let signature = func.import_signature(self.signatures[sigidx].clone()); let signature = func.import_signature(self.signatures[sigidx].clone());
@@ -823,7 +823,7 @@ impl<'module_environment> BaseFuncEnvironment for FuncEnvironment<'module_enviro
fn translate_call( fn translate_call(
&mut self, &mut self,
mut pos: FuncCursor<'_>, mut pos: FuncCursor<'_>,
callee_index: FuncIndex, callee_index: FunctionIndex,
callee: ir::FuncRef, callee: ir::FuncRef,
call_args: &[ir::Value], call_args: &[ir::Value],
) -> WasmResult<ir::Inst> { ) -> WasmResult<ir::Inst> {

View File

@@ -14,14 +14,14 @@ use cranelift_codegen::print_errors::pretty_error;
use cranelift_codegen::Context; use cranelift_codegen::Context;
use cranelift_codegen::{binemit, ir}; use cranelift_codegen::{binemit, ir};
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
use wasm_common::FuncType; use wasm_common::FunctionType;
use wasmer_compiler::{CompileError, CompiledFunction, CompiledFunctionFrameInfo, FunctionBody}; use wasmer_compiler::{CompileError, CompiledFunction, CompiledFunctionFrameInfo, FunctionBody};
/// Create a trampoline for invoking a WebAssembly function. /// Create a trampoline for invoking a WebAssembly function.
pub fn make_wasm_trampoline( pub fn make_wasm_trampoline(
isa: &dyn TargetIsa, isa: &dyn TargetIsa,
fn_builder_ctx: &mut FunctionBuilderContext, fn_builder_ctx: &mut FunctionBuilderContext,
func_type: &FuncType, func_type: &FunctionType,
value_size: usize, value_size: usize,
) -> Result<FunctionBody, CompileError> { ) -> Result<FunctionBody, CompileError> {
let pointer_type = isa.pointer_type(); let pointer_type = isa.pointer_type();

View File

@@ -37,7 +37,7 @@ use cranelift_codegen::ir::{
use cranelift_codegen::packed_option::ReservedValue; use cranelift_codegen::packed_option::ReservedValue;
use cranelift_frontend::{FunctionBuilder, Variable}; use cranelift_frontend::{FunctionBuilder, Variable};
use std::vec::Vec; use std::vec::Vec;
use wasm_common::{FuncIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex}; use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};
use wasmer_compiler::wasmparser::{MemoryImmediate, Operator}; use wasmer_compiler::wasmparser::{MemoryImmediate, Operator};
use wasmer_compiler::{to_wasm_error, WasmResult}; use wasmer_compiler::{to_wasm_error, WasmResult};
use wasmer_compiler::{wasm_unsupported, ModuleTranslationState}; use wasmer_compiler::{wasm_unsupported, ModuleTranslationState};
@@ -508,7 +508,7 @@ pub fn translate_operator<FE: FuncEnvironment + ?Sized>(
let call = environ.translate_call( let call = environ.translate_call(
builder.cursor(), builder.cursor(),
FuncIndex::from_u32(*function_index), FunctionIndex::from_u32(*function_index),
fref, fref,
args, args,
)?; )?;

View File

@@ -9,7 +9,7 @@ use cranelift_codegen::ir::immediates::Offset32;
use cranelift_codegen::ir::{self, InstBuilder}; use cranelift_codegen::ir::{self, InstBuilder};
use cranelift_codegen::isa::TargetFrontendConfig; use cranelift_codegen::isa::TargetFrontendConfig;
use cranelift_frontend::FunctionBuilder; use cranelift_frontend::FunctionBuilder;
use wasm_common::{FuncIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex}; use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};
use wasmer_compiler::wasmparser::Operator; use wasmer_compiler::wasmparser::Operator;
use wasmer_compiler::WasmResult; use wasmer_compiler::WasmResult;
@@ -146,7 +146,7 @@ pub trait FuncEnvironment: TargetEnvironment {
fn make_direct_func( fn make_direct_func(
&mut self, &mut self,
func: &mut ir::Function, func: &mut ir::Function,
index: FuncIndex, index: FunctionIndex,
) -> WasmResult<ir::FuncRef>; ) -> WasmResult<ir::FuncRef>;
/// Translate a `call_indirect` WebAssembly instruction at `pos`. /// Translate a `call_indirect` WebAssembly instruction at `pos`.
@@ -180,7 +180,7 @@ pub trait FuncEnvironment: TargetEnvironment {
fn translate_call( fn translate_call(
&mut self, &mut self,
mut pos: FuncCursor, mut pos: FuncCursor,
_callee_index: FuncIndex, _callee_index: FunctionIndex,
callee: ir::FuncRef, callee: ir::FuncRef,
call_args: &[ir::Value], call_args: &[ir::Value],
) -> WasmResult<ir::Inst> { ) -> WasmResult<ir::Inst> {

View File

@@ -10,7 +10,7 @@ use super::func_environ::{FuncEnvironment, GlobalVariable};
use crate::{HashMap, Occupied, Vacant}; use crate::{HashMap, Occupied, Vacant};
use cranelift_codegen::ir::{self, Block, Inst, Value}; use cranelift_codegen::ir::{self, Block, Inst, Value};
use std::vec::Vec; use std::vec::Vec;
use wasm_common::{FuncIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex}; use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};
use wasmer_compiler::WasmResult; use wasmer_compiler::WasmResult;
/// Information about the presence of an associated `else` for an `if`, or the /// Information about the presence of an associated `else` for an `if`, or the
@@ -213,7 +213,7 @@ pub struct FuncTranslationState {
// Imported and local functions that have been created by // Imported and local functions that have been created by
// `FuncEnvironment::make_direct_func()`. // `FuncEnvironment::make_direct_func()`.
// Stores both the function reference and the number of WebAssembly arguments // Stores both the function reference and the number of WebAssembly arguments
functions: HashMap<FuncIndex, (ir::FuncRef, usize)>, functions: HashMap<FunctionIndex, (ir::FuncRef, usize)>,
} }
// Public methods that are exposed to non-`wasmer_compiler` API consumers. // Public methods that are exposed to non-`wasmer_compiler` API consumers.
@@ -490,7 +490,7 @@ impl FuncTranslationState {
index: u32, index: u32,
environ: &mut FE, environ: &mut FE,
) -> WasmResult<(ir::FuncRef, usize)> { ) -> WasmResult<(ir::FuncRef, usize)> {
let index = FuncIndex::from_u32(index); let index = FunctionIndex::from_u32(index);
match self.functions.entry(index) { match self.functions.entry(index) {
Occupied(entry) => Ok(*entry.get()), Occupied(entry) => Ok(*entry.get()),
Vacant(entry) => { Vacant(entry) => {

View File

@@ -7,7 +7,7 @@ use cranelift_codegen::binemit::Reloc;
use cranelift_codegen::ir::{self, AbiParam}; use cranelift_codegen::ir::{self, AbiParam};
use cranelift_codegen::isa::TargetFrontendConfig; use cranelift_codegen::isa::TargetFrontendConfig;
use cranelift_frontend::FunctionBuilder; use cranelift_frontend::FunctionBuilder;
use wasm_common::{FuncType, Type}; use wasm_common::{FunctionType, Type};
use wasmer_compiler::wasm_unsupported; use wasmer_compiler::wasm_unsupported;
use wasmer_compiler::wasmparser; use wasmer_compiler::wasmparser;
use wasmer_compiler::RelocationKind; use wasmer_compiler::RelocationKind;
@@ -16,7 +16,7 @@ use wasmer_runtime::libcalls::LibCall;
/// Helper function translate a Funciton signature into Cranelift Ir /// Helper function translate a Funciton signature into Cranelift Ir
pub fn signature_to_cranelift_ir( pub fn signature_to_cranelift_ir(
signature: &FuncType, signature: &FunctionType,
target_config: &TargetFrontendConfig, target_config: &TargetFrontendConfig,
) -> ir::Signature { ) -> ir::Signature {
let mut sig = ir::Signature::new(target_config.default_call_conv); let mut sig = ir::Signature::new(target_config.default_call_conv);

View File

@@ -8,7 +8,7 @@ use crate::translator::FuncTranslator;
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use wasm_common::entity::{EntityRef, PrimaryMap, SecondaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap, SecondaryMap};
use wasm_common::Features; use wasm_common::Features;
use wasm_common::{FuncIndex, FuncType, LocalFuncIndex, MemoryIndex, TableIndex}; use wasm_common::{FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, TableIndex};
use wasmer_compiler::{ use wasmer_compiler::{
Compilation, CompileError, CompiledFunction, Compiler, CompilerConfig, CustomSection, Compilation, CompileError, CompiledFunction, Compiler, CompilerConfig, CustomSection,
CustomSectionProtection, FunctionBody, FunctionBodyData, ModuleTranslationState, Relocation, CustomSectionProtection, FunctionBody, FunctionBodyData, ModuleTranslationState, Relocation,
@@ -58,7 +58,7 @@ impl Compiler for LLVMCompiler {
&self, &self,
module: &'module Module, module: &'module Module,
_module_translation: &ModuleTranslationState, _module_translation: &ModuleTranslationState,
function_body_inputs: PrimaryMap<LocalFuncIndex, FunctionBodyData<'data>>, function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'data>>,
memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>,
table_plans: PrimaryMap<TableIndex, TablePlan>, table_plans: PrimaryMap<TableIndex, TablePlan>,
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
@@ -83,7 +83,7 @@ impl Compiler for LLVMCompiler {
} }
let mut functions = function_body_inputs let mut functions = function_body_inputs
.into_iter() .into_iter()
.collect::<Vec<(LocalFuncIndex, &FunctionBodyData<'_>)>>() .collect::<Vec<(LocalFunctionIndex, &FunctionBodyData<'_>)>>()
.par_iter() .par_iter()
.map_init(FuncTranslator::new, |func_translator, (i, input)| { .map_init(FuncTranslator::new, |func_translator, (i, input)| {
// TODO: remove (to serialize) // TODO: remove (to serialize)
@@ -130,7 +130,7 @@ impl Compiler for LLVMCompiler {
}) })
.collect::<Result<Vec<_>, CompileError>>()? .collect::<Result<Vec<_>, CompileError>>()?
.into_iter() .into_iter()
.collect::<PrimaryMap<LocalFuncIndex, _>>(); .collect::<PrimaryMap<LocalFunctionIndex, _>>();
let mut custom_sections = PrimaryMap::new(); let mut custom_sections = PrimaryMap::new();
if used_readonly_section { if used_readonly_section {
@@ -141,7 +141,7 @@ impl Compiler for LLVMCompiler {
fn compile_wasm_trampolines( fn compile_wasm_trampolines(
&self, &self,
signatures: &[FuncType], signatures: &[FunctionType],
) -> Result<Vec<FunctionBody>, CompileError> { ) -> Result<Vec<FunctionBody>, CompileError> {
signatures signatures
.par_iter() .par_iter()

View File

@@ -4,7 +4,7 @@ use inkwell::{
context::Context, module::Linkage, passes::PassManager, targets::FileType, types::BasicType, context::Context, module::Linkage, passes::PassManager, targets::FileType, types::BasicType,
values::FunctionValue, AddressSpace, values::FunctionValue, AddressSpace,
}; };
use wasm_common::{FuncType, Type}; use wasm_common::{FunctionType, Type};
use wasmer_compiler::{CompileError, CompiledFunctionUnwindInfo, FunctionBody}; use wasmer_compiler::{CompileError, CompiledFunctionUnwindInfo, FunctionBody};
pub struct FuncTrampoline { pub struct FuncTrampoline {
@@ -20,7 +20,7 @@ impl FuncTrampoline {
pub fn trampoline( pub fn trampoline(
&mut self, &mut self,
ty: &FuncType, ty: &FunctionType,
config: &LLVMConfig, config: &LLVMConfig,
) -> Result<FunctionBody, CompileError> { ) -> Result<FunctionBody, CompileError> {
let mut module = self.ctx.create_module(""); let mut module = self.ctx.create_module("");
@@ -104,7 +104,7 @@ impl FuncTrampoline {
fn generate_trampoline<'ctx>( fn generate_trampoline<'ctx>(
trampoline_func: FunctionValue, trampoline_func: FunctionValue,
func_sig: &FuncType, func_sig: &FunctionType,
context: &'ctx Context, context: &'ctx Context,
intrinsics: &Intrinsics<'ctx>, intrinsics: &Intrinsics<'ctx>,
) -> Result<(), CompileError> { ) -> Result<(), CompileError> {

View File

@@ -33,7 +33,8 @@ use std::collections::HashMap;
use crate::config::LLVMConfig; use crate::config::LLVMConfig;
use wasm_common::entity::{EntityRef, PrimaryMap, SecondaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap, SecondaryMap};
use wasm_common::{ use wasm_common::{
FuncIndex, FuncType, GlobalIndex, LocalFuncIndex, MemoryIndex, SignatureIndex, TableIndex, Type, FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, MemoryIndex, SignatureIndex,
TableIndex, Type,
}; };
use wasmer_compiler::wasmparser::{self, BinaryReader, MemoryImmediate, Operator}; use wasmer_compiler::wasmparser::{self, BinaryReader, MemoryImmediate, Operator};
use wasmer_compiler::{ use wasmer_compiler::{
@@ -101,12 +102,12 @@ impl FuncTranslator {
pub fn translate( pub fn translate(
&mut self, &mut self,
wasm_module: &WasmerCompilerModule, wasm_module: &WasmerCompilerModule,
func_index: &LocalFuncIndex, func_index: &LocalFunctionIndex,
function_body: &FunctionBodyData, function_body: &FunctionBodyData,
config: &LLVMConfig, config: &LLVMConfig,
memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>, memory_plans: &PrimaryMap<MemoryIndex, MemoryPlan>,
table_plans: &PrimaryMap<TableIndex, TablePlan>, table_plans: &PrimaryMap<TableIndex, TablePlan>,
func_names: &SecondaryMap<FuncIndex, String>, func_names: &SecondaryMap<FunctionIndex, String>,
) -> Result<(CompiledFunction, Vec<LocalRelocation>, Vec<CustomSection>), CompileError> { ) -> Result<(CompiledFunction, Vec<LocalRelocation>, Vec<CustomSection>), CompileError> {
let func_index = wasm_module.func_index(*func_index); let func_index = wasm_module.func_index(*func_index);
let func_name = func_names.get(func_index).unwrap(); let func_name = func_names.get(func_index).unwrap();
@@ -1307,8 +1308,8 @@ pub struct LLVMModuleCodeGenerator<'ctx> {
intrinsics: Option<Intrinsics<'ctx>>, intrinsics: Option<Intrinsics<'ctx>>,
functions: Vec<LLVMFunctionCodeGenerator<'ctx>>, functions: Vec<LLVMFunctionCodeGenerator<'ctx>>,
signatures: Map<SignatureIndex, FunctionType<'ctx>>, signatures: Map<SignatureIndex, FunctionType<'ctx>>,
function_signatures: Option<Arc<Map<FuncIndex, SignatureIndex>>>, function_signatures: Option<Arc<Map<FunctionIndex, SignatureIndex>>>,
llvm_functions: Rc<RefCell<HashMap<FuncIndex, FunctionValue<'ctx>>>>, llvm_functions: Rc<RefCell<HashMap<FunctionIndex, FunctionValue<'ctx>>>>,
func_import_count: usize, func_import_count: usize,
personality_func: ManuallyDrop<FunctionValue<'ctx>>, personality_func: ManuallyDrop<FunctionValue<'ctx>>,
module: ManuallyDrop<Rc<RefCell<Module<'ctx>>>>, module: ManuallyDrop<Rc<RefCell<Module<'ctx>>>>,
@@ -2146,7 +2147,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
state.push1_extra(res, info); state.push1_extra(res, info);
} }
Operator::Call { function_index } => { Operator::Call { function_index } => {
let func_index = FuncIndex::from_u32(function_index); let func_index = FunctionIndex::from_u32(function_index);
let sigindex = module.functions.get(func_index).unwrap(); let sigindex = module.functions.get(func_index).unwrap();
let func_type = module.signatures.get(*sigindex).unwrap(); let func_type = module.signatures.get(*sigindex).unwrap();
let func_name = module.func_names.get(&func_index).unwrap(); let func_name = module.func_names.get(&func_index).unwrap();
@@ -9081,7 +9082,7 @@ impl<'ctx> ModuleCodeGenerator<LLVMFunctionCodeGenerator<'ctx>, LLVMBackend, Com
), ),
}; };
let func_index = FuncIndex::new(self.func_import_count + self.functions.len()); let func_index = FunctionIndex::new(self.func_import_count + self.functions.len());
let sig_id = self.function_signatures.as_ref().unwrap()[func_index]; let sig_id = self.function_signatures.as_ref().unwrap()[func_index];
let func_sig = module_info.read().unwrap().signatures[sig_id].clone(); let func_sig = module_info.read().unwrap().signatures[sig_id].clone();
@@ -9290,7 +9291,7 @@ impl<'ctx> ModuleCodeGenerator<LLVMFunctionCodeGenerator<'ctx>, LLVMBackend, Com
fn feed_function_signatures( fn feed_function_signatures(
&mut self, &mut self,
assoc: Map<FuncIndex, SignatureIndex>, assoc: Map<FunctionIndex, SignatureIndex>,
) -> Result<(), CompileError> { ) -> Result<(), CompileError> {
for (index, sig_id) in &assoc { for (index, sig_id) in &assoc {
if index.index() >= self.func_import_count { if index.index() >= self.func_import_count {

View File

@@ -26,7 +26,7 @@ use wasmer_runtime_core::{
module::ModuleInfo, module::ModuleInfo,
structures::TypedIndex, structures::TypedIndex,
types::{ types::{
GlobalIndex, ImportedFuncIndex, LocalOrImport, MemoryIndex, SignatureIndex, TableIndex, Type, GlobalIndex, ImportedFunctionIndex, LocalOrImport, MemoryIndex, SignatureIndex, TableIndex, Type,
}, },
units::Pages, units::Pages,
vm::{Ctx, INTERNALS_SIZE}, vm::{Ctx, INTERNALS_SIZE},
@@ -34,8 +34,8 @@ use wasmer_runtime_core::{
*/ */
use wasm_common::entity::{EntityRef, PrimaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap};
use wasm_common::{ use wasm_common::{
FuncIndex, FuncType, GlobalIndex, MemoryIndex, Mutability, Pages, SignatureIndex, TableIndex, FunctionIndex, FunctionType as FuncType, GlobalIndex, MemoryIndex, Mutability, Pages,
Type, SignatureIndex, TableIndex, Type,
}; };
use wasmer_runtime::Module as WasmerCompilerModule; use wasmer_runtime::Module as WasmerCompilerModule;
use wasmer_runtime::{MemoryPlan, MemoryStyle, VMOffsets}; use wasmer_runtime::{MemoryPlan, MemoryStyle, VMOffsets};
@@ -637,7 +637,7 @@ pub struct CtxType<'ctx, 'a> {
cached_tables: HashMap<TableIndex, TableCache<'ctx>>, cached_tables: HashMap<TableIndex, TableCache<'ctx>>,
cached_sigindices: HashMap<SignatureIndex, IntValue<'ctx>>, cached_sigindices: HashMap<SignatureIndex, IntValue<'ctx>>,
cached_globals: HashMap<GlobalIndex, GlobalCache<'ctx>>, cached_globals: HashMap<GlobalIndex, GlobalCache<'ctx>>,
cached_imported_functions: HashMap<FuncIndex, ImportedFuncCache<'ctx>>, cached_imported_functions: HashMap<FunctionIndex, ImportedFuncCache<'ctx>>,
offsets: VMOffsets, offsets: VMOffsets,
} }
@@ -1114,7 +1114,7 @@ impl<'ctx, 'a> CtxType<'ctx, 'a> {
pub fn imported_func( pub fn imported_func(
&mut self, &mut self,
index: FuncIndex, index: FunctionIndex,
intrinsics: &Intrinsics<'ctx>, intrinsics: &Intrinsics<'ctx>,
module: &Module<'ctx>, module: &Module<'ctx>,
) -> (PointerValue<'ctx>, PointerValue<'ctx>) { ) -> (PointerValue<'ctx>, PointerValue<'ctx>) {

View File

@@ -6,7 +6,7 @@ use crate::config::SinglepassConfig;
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use wasm_common::entity::{EntityRef, PrimaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap};
use wasm_common::Features; use wasm_common::Features;
use wasm_common::{FuncIndex, FuncType, LocalFuncIndex, MemoryIndex, TableIndex}; use wasm_common::{FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, TableIndex};
use wasmer_compiler::FunctionBodyData; use wasmer_compiler::FunctionBodyData;
use wasmer_compiler::TrapInformation; use wasmer_compiler::TrapInformation;
use wasmer_compiler::{Compilation, CompileError, Compiler, FunctionBody}; use wasmer_compiler::{Compilation, CompileError, Compiler, FunctionBody};
@@ -52,7 +52,7 @@ impl Compiler for SinglepassCompiler {
&self, &self,
_module: &Module, _module: &Module,
_module_translation: &ModuleTranslationState, _module_translation: &ModuleTranslationState,
_function_body_inputs: PrimaryMap<LocalFuncIndex, FunctionBodyData<'_>>, _function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'_>>,
_memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, _memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>,
_table_plans: PrimaryMap<TableIndex, TablePlan>, _table_plans: PrimaryMap<TableIndex, TablePlan>,
) -> Result<Compilation, CompileError> { ) -> Result<Compilation, CompileError> {
@@ -67,7 +67,7 @@ impl Compiler for SinglepassCompiler {
fn compile_wasm_trampolines( fn compile_wasm_trampolines(
&self, &self,
_signatures: &[FuncType], _signatures: &[FunctionType],
) -> Result<Vec<FunctionBody>, CompileError> { ) -> Result<Vec<FunctionBody>, CompileError> {
// Note: do not implement this yet // Note: do not implement this yet
Err(CompileError::Codegen( Err(CompileError::Codegen(

View File

@@ -9,7 +9,7 @@ use crate::target::Target;
use crate::FunctionBodyData; use crate::FunctionBodyData;
use crate::ModuleTranslationState; use crate::ModuleTranslationState;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{Features, FuncType, LocalFuncIndex, MemoryIndex, TableIndex}; use wasm_common::{Features, FunctionType, LocalFunctionIndex, MemoryIndex, TableIndex};
use wasmer_runtime::Module; use wasmer_runtime::Module;
use wasmer_runtime::{MemoryPlan, TablePlan}; use wasmer_runtime::{MemoryPlan, TablePlan};
use wasmparser::{validate, OperatorValidatorConfig, ValidatingParserConfig}; use wasmparser::{validate, OperatorValidatorConfig, ValidatingParserConfig};
@@ -64,7 +64,7 @@ pub trait Compiler {
module: &'module Module, module: &'module Module,
module_translation: &ModuleTranslationState, module_translation: &ModuleTranslationState,
// The list of function bodies // The list of function bodies
function_body_inputs: PrimaryMap<LocalFuncIndex, FunctionBodyData<'data>>, function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'data>>,
// The plans for the module memories (imported and local) // The plans for the module memories (imported and local)
memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>, memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>,
// The plans for the module tables (imported and local) // The plans for the module tables (imported and local)
@@ -82,6 +82,6 @@ pub trait Compiler {
/// ``` /// ```
fn compile_wasm_trampolines( fn compile_wasm_trampolines(
&self, &self,
signatures: &[FuncType], signatures: &[FunctionType],
) -> Result<Vec<FunctionBody>, CompileError>; ) -> Result<Vec<FunctionBody>, CompileError>;
} }

View File

@@ -12,7 +12,7 @@ use crate::{CompiledFunctionUnwindInfo, FunctionAddressMap, JumpTableOffsets, Re
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::LocalFuncIndex; use wasm_common::LocalFunctionIndex;
/// The frame info for a Compiled function. /// The frame info for a Compiled function.
/// ///
@@ -59,7 +59,7 @@ pub struct CompiledFunction {
} }
/// The compiled functions map (index in the Wasm -> function) /// The compiled functions map (index in the Wasm -> function)
pub type Functions = PrimaryMap<LocalFuncIndex, CompiledFunction>; pub type Functions = PrimaryMap<LocalFunctionIndex, CompiledFunction>;
/// The custom sections for a Compilation. /// The custom sections for a Compilation.
pub type CustomSections = PrimaryMap<SectionIndex, CustomSection>; pub type CustomSections = PrimaryMap<SectionIndex, CustomSection>;
@@ -85,7 +85,7 @@ impl Compilation {
} }
/// Gets the bytes of a single function /// Gets the bytes of a single function
pub fn get(&self, func: LocalFuncIndex) -> &CompiledFunction { pub fn get(&self, func: LocalFunctionIndex) -> &CompiledFunction {
&self.functions[func] &self.functions[func]
} }
@@ -100,35 +100,35 @@ impl Compilation {
} }
/// Gets functions jump table offsets. /// Gets functions jump table offsets.
pub fn get_relocations(&self) -> PrimaryMap<LocalFuncIndex, Vec<Relocation>> { pub fn get_relocations(&self) -> PrimaryMap<LocalFunctionIndex, Vec<Relocation>> {
self.functions self.functions
.iter() .iter()
.map(|(_, func)| func.relocations.clone()) .map(|(_, func)| func.relocations.clone())
.collect::<PrimaryMap<LocalFuncIndex, _>>() .collect::<PrimaryMap<LocalFunctionIndex, _>>()
} }
/// Gets functions jump table offsets. /// Gets functions jump table offsets.
pub fn get_function_bodies(&self) -> PrimaryMap<LocalFuncIndex, FunctionBody> { pub fn get_function_bodies(&self) -> PrimaryMap<LocalFunctionIndex, FunctionBody> {
self.functions self.functions
.iter() .iter()
.map(|(_, func)| func.body.clone()) .map(|(_, func)| func.body.clone())
.collect::<PrimaryMap<LocalFuncIndex, _>>() .collect::<PrimaryMap<LocalFunctionIndex, _>>()
} }
/// Gets functions jump table offsets. /// Gets functions jump table offsets.
pub fn get_jt_offsets(&self) -> PrimaryMap<LocalFuncIndex, JumpTableOffsets> { pub fn get_jt_offsets(&self) -> PrimaryMap<LocalFunctionIndex, JumpTableOffsets> {
self.functions self.functions
.iter() .iter()
.map(|(_, func)| func.jt_offsets.clone()) .map(|(_, func)| func.jt_offsets.clone())
.collect::<PrimaryMap<LocalFuncIndex, _>>() .collect::<PrimaryMap<LocalFunctionIndex, _>>()
} }
/// Gets functions jump table offsets. /// Gets functions jump table offsets.
pub fn get_frame_info(&self) -> PrimaryMap<LocalFuncIndex, CompiledFunctionFrameInfo> { pub fn get_frame_info(&self) -> PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo> {
self.functions self.functions
.iter() .iter()
.map(|(_, func)| func.frame_info.clone()) .map(|(_, func)| func.frame_info.clone())
.collect::<PrimaryMap<LocalFuncIndex, _>>() .collect::<PrimaryMap<LocalFunctionIndex, _>>()
} }
/// Gets custom section data. /// Gets custom section data.

View File

@@ -15,7 +15,7 @@ use crate::{Addend, CodeOffset, JumpTable};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{FuncIndex, LocalFuncIndex}; use wasm_common::{FunctionIndex, LocalFunctionIndex};
use wasmer_runtime::libcalls::LibCall; use wasmer_runtime::libcalls::LibCall;
/// Relocation kinds for every ISA. /// Relocation kinds for every ISA.
@@ -90,14 +90,14 @@ pub struct Relocation {
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)] #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)]
pub enum RelocationTarget { pub enum RelocationTarget {
/// A relocation to a function defined locally in the wasm (not an imported one). /// A relocation to a function defined locally in the wasm (not an imported one).
LocalFunc(LocalFuncIndex), LocalFunc(LocalFunctionIndex),
/// A compiler-generated libcall. /// A compiler-generated libcall.
LibCall(LibCall), LibCall(LibCall),
/// Jump table index. /// Jump table index.
JumpTable(LocalFuncIndex, JumpTable), JumpTable(LocalFunctionIndex, JumpTable),
/// Custom sections generated by the compiler /// Custom sections generated by the compiler
CustomSection(SectionIndex), CustomSection(SectionIndex),
} }
/// Relocations to apply to function bodies. /// Relocations to apply to function bodies.
pub type Relocations = PrimaryMap<LocalFuncIndex, Vec<Relocation>>; pub type Relocations = PrimaryMap<LocalFunctionIndex, Vec<Relocation>>;

View File

@@ -7,10 +7,10 @@ use crate::{WasmError, WasmResult};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::sync::Arc; use std::sync::Arc;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::FuncType; use wasm_common::FunctionType;
use wasm_common::{ use wasm_common::{
DataIndex, DataInitializer, DataInitializerLocation, ElemIndex, ExportIndex, FuncIndex, DataIndex, DataInitializer, DataInitializerLocation, ElemIndex, ExportIndex, FunctionIndex,
GlobalIndex, GlobalInit, GlobalType, ImportIndex, LocalFuncIndex, MemoryIndex, MemoryType, GlobalIndex, GlobalInit, GlobalType, ImportIndex, LocalFunctionIndex, MemoryIndex, MemoryType,
SignatureIndex, TableIndex, TableType, SignatureIndex, TableIndex, TableType,
}; };
use wasmer_runtime::{Module, TableElements}; use wasmer_runtime::{Module, TableElements};
@@ -34,7 +34,7 @@ pub struct ModuleTranslation<'data> {
pub module: Module, pub module: Module,
/// References to the function bodies. /// References to the function bodies.
pub function_body_inputs: PrimaryMap<LocalFuncIndex, FunctionBodyData<'data>>, pub function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'data>>,
/// References to the data initializers. /// References to the data initializers.
pub data_initializers: Vec<DataInitializer<'data>>, pub data_initializers: Vec<DataInitializer<'data>>,
@@ -102,7 +102,7 @@ impl<'data> ModuleEnvironment<'data> {
Ok(()) Ok(())
} }
pub(crate) fn declare_signature(&mut self, sig: FuncType) -> WasmResult<()> { pub(crate) fn declare_signature(&mut self, sig: FunctionType) -> WasmResult<()> {
// TODO: Deduplicate signatures. // TODO: Deduplicate signatures.
self.result.module.signatures.push(sig); self.result.module.signatures.push(sig);
Ok(()) Ok(())
@@ -120,7 +120,7 @@ impl<'data> ModuleEnvironment<'data> {
"Imported functions must be declared first" "Imported functions must be declared first"
); );
self.declare_import( self.declare_import(
ImportIndex::Function(FuncIndex::from_u32( ImportIndex::Function(FunctionIndex::from_u32(
self.result.module.num_imported_funcs as _, self.result.module.num_imported_funcs as _,
)), )),
module, module,
@@ -283,7 +283,7 @@ impl<'data> ModuleEnvironment<'data> {
pub(crate) fn declare_func_export( pub(crate) fn declare_func_export(
&mut self, &mut self,
func_index: FuncIndex, func_index: FunctionIndex,
name: &str, name: &str,
) -> WasmResult<()> { ) -> WasmResult<()> {
self.declare_export(ExportIndex::Function(func_index), name) self.declare_export(ExportIndex::Function(func_index), name)
@@ -313,7 +313,7 @@ impl<'data> ModuleEnvironment<'data> {
self.declare_export(ExportIndex::Global(global_index), name) self.declare_export(ExportIndex::Global(global_index), name)
} }
pub(crate) fn declare_start_func(&mut self, func_index: FuncIndex) -> WasmResult<()> { pub(crate) fn declare_start_func(&mut self, func_index: FunctionIndex) -> WasmResult<()> {
debug_assert!(self.result.module.start_func.is_none()); debug_assert!(self.result.module.start_func.is_none());
self.result.module.start_func = Some(func_index); self.result.module.start_func = Some(func_index);
Ok(()) Ok(())
@@ -332,7 +332,7 @@ impl<'data> ModuleEnvironment<'data> {
table_index: TableIndex, table_index: TableIndex,
base: Option<GlobalIndex>, base: Option<GlobalIndex>,
offset: usize, offset: usize,
elements: Box<[FuncIndex]>, elements: Box<[FunctionIndex]>,
) -> WasmResult<()> { ) -> WasmResult<()> {
self.result.module.table_elements.push(TableElements { self.result.module.table_elements.push(TableElements {
table_index, table_index,
@@ -346,7 +346,7 @@ impl<'data> ModuleEnvironment<'data> {
pub(crate) fn declare_passive_element( pub(crate) fn declare_passive_element(
&mut self, &mut self,
elem_index: ElemIndex, elem_index: ElemIndex,
segments: Box<[FuncIndex]>, segments: Box<[FunctionIndex]>,
) -> WasmResult<()> { ) -> WasmResult<()> {
let old = self let old = self
.result .result
@@ -428,7 +428,7 @@ impl<'data> ModuleEnvironment<'data> {
pub(crate) fn declare_func_name( pub(crate) fn declare_func_name(
&mut self, &mut self,
func_index: FuncIndex, func_index: FunctionIndex,
name: &'data str, name: &'data str,
) -> WasmResult<()> { ) -> WasmResult<()> {
self.result self.result

View File

@@ -18,15 +18,16 @@ use std::vec::Vec;
use wasm_common::entity::packed_option::ReservedValue; use wasm_common::entity::packed_option::ReservedValue;
use wasm_common::entity::EntityRef; use wasm_common::entity::EntityRef;
use wasm_common::{ use wasm_common::{
DataIndex, ElemIndex, FuncIndex, FuncType, GlobalIndex, GlobalInit, GlobalType, MemoryIndex, DataIndex, ElemIndex, FunctionIndex, FunctionType, GlobalIndex, GlobalInit, GlobalType,
MemoryType, Pages, SignatureIndex, TableIndex, TableType, Type, V128, MemoryIndex, MemoryType, Pages, SignatureIndex, TableIndex, TableType, Type, V128,
}; };
use wasmparser::{ use wasmparser::{
self, CodeSectionReader, Data, DataKind, DataSectionReader, Element, ElementItem, ElementItems, self, CodeSectionReader, Data, DataKind, DataSectionReader, Element, ElementItem, ElementItems,
ElementKind, ElementSectionReader, Export, ExportSectionReader, ExternalKind, ElementKind, ElementSectionReader, Export, ExportSectionReader, ExternalKind,
FuncType as WPFuncType, FunctionSectionReader, GlobalSectionReader, GlobalType as WPGlobalType, FuncType as WPFunctionType, FunctionSectionReader, GlobalSectionReader,
ImportSectionEntryType, ImportSectionReader, MemorySectionReader, MemoryType as WPMemoryType, GlobalType as WPGlobalType, ImportSectionEntryType, ImportSectionReader, MemorySectionReader,
NameSectionReader, Naming, NamingReader, Operator, TableSectionReader, TypeSectionReader, MemoryType as WPMemoryType, NameSectionReader, Naming, NamingReader, Operator,
TableSectionReader, TypeSectionReader,
}; };
/// Helper function translating wasmparser types to Wasm Type. /// Helper function translating wasmparser types to Wasm Type.
@@ -57,7 +58,7 @@ pub fn parse_type_section(
for entry in types { for entry in types {
match entry.map_err(to_wasm_error)? { match entry.map_err(to_wasm_error)? {
WPFuncType { WPFunctionType {
form: wasmparser::Type::Func, form: wasmparser::Type::Func,
params, params,
returns, returns,
@@ -76,7 +77,7 @@ pub fn parse_type_section(
.expect("only numeric types are supported in function signatures") .expect("only numeric types are supported in function signatures")
}) })
.collect(); .collect();
let sig = FuncType::new(sig_params, sig_returns); let sig = FunctionType::new(sig_params, sig_returns);
environ.declare_signature(sig)?; environ.declare_signature(sig)?;
module_translation_state.wasm_types.push((params, returns)); module_translation_state.wasm_types.push((params, returns));
} }
@@ -238,7 +239,7 @@ pub fn parse_global_section(
} }
Operator::RefNull => GlobalInit::RefNullConst, Operator::RefNull => GlobalInit::RefNullConst,
Operator::RefFunc { function_index } => { Operator::RefFunc { function_index } => {
GlobalInit::RefFunc(FuncIndex::from_u32(function_index)) GlobalInit::RefFunc(FunctionIndex::from_u32(function_index))
} }
Operator::GlobalGet { global_index } => { Operator::GlobalGet { global_index } => {
GlobalInit::GetGlobal(GlobalIndex::from_u32(global_index)) GlobalInit::GetGlobal(GlobalIndex::from_u32(global_index))
@@ -279,7 +280,9 @@ pub fn parse_export_section<'data>(
// becomes a concern here. // becomes a concern here.
let index = index as usize; let index = index as usize;
match *kind { match *kind {
ExternalKind::Function => environ.declare_func_export(FuncIndex::new(index), field)?, ExternalKind::Function => {
environ.declare_func_export(FunctionIndex::new(index), field)?
}
ExternalKind::Table => environ.declare_table_export(TableIndex::new(index), field)?, ExternalKind::Table => environ.declare_table_export(TableIndex::new(index), field)?,
ExternalKind::Memory => { ExternalKind::Memory => {
environ.declare_memory_export(MemoryIndex::new(index), field)? environ.declare_memory_export(MemoryIndex::new(index), field)?
@@ -296,17 +299,17 @@ pub fn parse_export_section<'data>(
/// Parses the Start section of the wasm module. /// Parses the Start section of the wasm module.
pub fn parse_start_section(index: u32, environ: &mut ModuleEnvironment) -> WasmResult<()> { pub fn parse_start_section(index: u32, environ: &mut ModuleEnvironment) -> WasmResult<()> {
environ.declare_start_func(FuncIndex::from_u32(index))?; environ.declare_start_func(FunctionIndex::from_u32(index))?;
Ok(()) Ok(())
} }
fn read_elems(items: &ElementItems) -> WasmResult<Box<[FuncIndex]>> { fn read_elems(items: &ElementItems) -> WasmResult<Box<[FunctionIndex]>> {
let items_reader = items.get_items_reader().map_err(to_wasm_error)?; let items_reader = items.get_items_reader().map_err(to_wasm_error)?;
let mut elems = Vec::with_capacity(usize::try_from(items_reader.get_count()).unwrap()); let mut elems = Vec::with_capacity(usize::try_from(items_reader.get_count()).unwrap());
for item in items_reader { for item in items_reader {
let elem = match item.map_err(to_wasm_error)? { let elem = match item.map_err(to_wasm_error)? {
ElementItem::Null => FuncIndex::reserved_value(), ElementItem::Null => FunctionIndex::reserved_value(),
ElementItem::Func(index) => FuncIndex::from_u32(index), ElementItem::Func(index) => FunctionIndex::from_u32(index),
}; };
elems.push(elem); elems.push(elem);
} }
@@ -460,7 +463,7 @@ pub fn parse_name_section<'data>(
fn parse_function_name_subsection( fn parse_function_name_subsection(
mut naming_reader: NamingReader<'_>, mut naming_reader: NamingReader<'_>,
) -> Option<HashMap<FuncIndex, &str>> { ) -> Option<HashMap<FunctionIndex, &str>> {
let mut function_names = HashMap::new(); let mut function_names = HashMap::new();
for _ in 0..naming_reader.get_count() { for _ in 0..naming_reader.get_count() {
let Naming { index, name } = naming_reader.read().ok()?; let Naming { index, name } = naming_reader.read().ok()?;
@@ -470,7 +473,7 @@ fn parse_function_name_subsection(
} }
if function_names if function_names
.insert(FuncIndex::from_u32(index), name) .insert(FunctionIndex::from_u32(index), name)
.is_some() .is_some()
{ {
// If the function index has been previously seen, then we // If the function index has been previously seen, then we

View File

@@ -4,7 +4,7 @@ use region;
use std::mem::ManuallyDrop; use std::mem::ManuallyDrop;
use std::{cmp, mem}; use std::{cmp, mem};
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::LocalFuncIndex; use wasm_common::LocalFunctionIndex;
use wasmer_compiler::FunctionBody; use wasmer_compiler::FunctionBody;
use wasmer_runtime::{Mmap, VMFunctionBody}; use wasmer_runtime::{Mmap, VMFunctionBody};
@@ -60,8 +60,8 @@ impl CodeMemory {
/// Allocate a continuous memory blocks for a single compiled function. /// Allocate a continuous memory blocks for a single compiled function.
pub fn allocate_functions( pub fn allocate_functions(
&mut self, &mut self,
functions: &PrimaryMap<LocalFuncIndex, FunctionBody>, functions: &PrimaryMap<LocalFunctionIndex, FunctionBody>,
) -> Result<PrimaryMap<LocalFuncIndex, *mut [VMFunctionBody]>, String> { ) -> Result<PrimaryMap<LocalFunctionIndex, *mut [VMFunctionBody]>, String> {
let fat_ptrs = self.allocate_for_compilation(functions)?; let fat_ptrs = self.allocate_for_compilation(functions)?;
// Second, create a PrimaryMap from result vector of pointers. // Second, create a PrimaryMap from result vector of pointers.
@@ -94,7 +94,7 @@ impl CodeMemory {
/// Allocates memory for both the function bodies as well as function unwind data. /// Allocates memory for both the function bodies as well as function unwind data.
pub fn allocate_for_compilation( pub fn allocate_for_compilation(
&mut self, &mut self,
compilation: &PrimaryMap<LocalFuncIndex, FunctionBody>, compilation: &PrimaryMap<LocalFunctionIndex, FunctionBody>,
) -> Result<Box<[&mut [VMFunctionBody]]>, String> { ) -> Result<Box<[&mut [VMFunctionBody]]>, String> {
let total_len = compilation let total_len = compilation
.values() .values()

View File

@@ -9,7 +9,7 @@ use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{FuncType, LocalFuncIndex, MemoryIndex, SignatureIndex, TableIndex}; use wasm_common::{FunctionType, LocalFunctionIndex, MemoryIndex, SignatureIndex, TableIndex};
use wasmer_compiler::{Compilation, CompileError, FunctionBody, Target}; use wasmer_compiler::{Compilation, CompileError, FunctionBody, Target};
#[cfg(feature = "compiler")] #[cfg(feature = "compiler")]
use wasmer_compiler::{Compiler, CompilerConfig}; use wasmer_compiler::{Compiler, CompilerConfig};
@@ -92,13 +92,13 @@ impl JITEngine {
} }
/// Register a signature /// Register a signature
pub fn register_signature(&self, func_type: &FuncType) -> VMSharedSignatureIndex { pub fn register_signature(&self, func_type: &FunctionType) -> VMSharedSignatureIndex {
let compiler = self.compiler(); let compiler = self.compiler();
compiler.signatures().register(func_type) compiler.signatures().register(func_type)
} }
/// Lookup a signature /// Lookup a signature
pub fn lookup_signature(&self, sig: VMSharedSignatureIndex) -> Option<FuncType> { pub fn lookup_signature(&self, sig: VMSharedSignatureIndex) -> Option<FunctionType> {
let compiler = self.compiler(); let compiler = self.compiler();
compiler.signatures().lookup(sig) compiler.signatures().lookup(sig)
} }
@@ -192,9 +192,9 @@ impl JITEngineInner {
pub(crate) fn allocate<'data>( pub(crate) fn allocate<'data>(
&mut self, &mut self,
module: &Module, module: &Module,
functions: &PrimaryMap<LocalFuncIndex, FunctionBody>, functions: &PrimaryMap<LocalFunctionIndex, FunctionBody>,
trampolines: &PrimaryMap<SignatureIndex, FunctionBody>, trampolines: &PrimaryMap<SignatureIndex, FunctionBody>,
) -> Result<PrimaryMap<LocalFuncIndex, *mut [VMFunctionBody]>, CompileError> { ) -> Result<PrimaryMap<LocalFunctionIndex, *mut [VMFunctionBody]>, CompileError> {
// Allocate all of the compiled functions into executable memory, // Allocate all of the compiled functions into executable memory,
// copying over their contents. // copying over their contents.
let allocated_functions = let allocated_functions =

View File

@@ -2,7 +2,7 @@
use std::ptr::write_unaligned; use std::ptr::write_unaligned;
use wasm_common::entity::{EntityRef, PrimaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap};
use wasm_common::LocalFuncIndex; use wasm_common::LocalFunctionIndex;
use wasmer_compiler::{ use wasmer_compiler::{
JumpTable, JumpTableOffsets, RelocationKind, RelocationTarget, Relocations, SectionBody, JumpTable, JumpTableOffsets, RelocationKind, RelocationTarget, Relocations, SectionBody,
SectionIndex, SectionIndex,
@@ -15,8 +15,8 @@ use wasmer_runtime::VMFunctionBody;
/// Performs all required relocations inside the function code, provided the necessary metadata. /// Performs all required relocations inside the function code, provided the necessary metadata.
pub fn link_module( pub fn link_module(
module: &Module, module: &Module,
allocated_functions: &PrimaryMap<LocalFuncIndex, *mut [VMFunctionBody]>, allocated_functions: &PrimaryMap<LocalFunctionIndex, *mut [VMFunctionBody]>,
jt_offsets: &PrimaryMap<LocalFuncIndex, JumpTableOffsets>, jt_offsets: &PrimaryMap<LocalFunctionIndex, JumpTableOffsets>,
relocations: Relocations, relocations: Relocations,
allocated_sections: &PrimaryMap<SectionIndex, SectionBody>, allocated_sections: &PrimaryMap<SectionIndex, SectionBody>,
) { ) {

View File

@@ -18,7 +18,7 @@ use std::any::Any;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasm_common::{ use wasm_common::{
DataInitializer, LocalFuncIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, DataInitializer, LocalFunctionIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex,
MemoryIndex, OwnedDataInitializer, SignatureIndex, TableIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, TableIndex,
}; };
use wasmer_compiler::CompileError; use wasmer_compiler::CompileError;
@@ -35,7 +35,7 @@ use wasmer_runtime::{MemoryPlan, TablePlan};
pub struct CompiledModule { pub struct CompiledModule {
serializable: SerializableModule, serializable: SerializableModule,
finished_functions: BoxedSlice<LocalFuncIndex, *mut [VMFunctionBody]>, finished_functions: BoxedSlice<LocalFunctionIndex, *mut [VMFunctionBody]>,
signatures: BoxedSlice<SignatureIndex, VMSharedSignatureIndex>, signatures: BoxedSlice<SignatureIndex, VMSharedSignatureIndex>,
frame_info_registration: Mutex<Option<Option<GlobalFrameInfoRegistration>>>, frame_info_registration: Mutex<Option<Option<GlobalFrameInfoRegistration>>>,
} }
@@ -99,7 +99,7 @@ impl CompiledModule {
.get_frame_info() .get_frame_info()
.values() .values()
.map(|frame_info| SerializableFunctionFrameInfo::Processed(frame_info.clone())) .map(|frame_info| SerializableFunctionFrameInfo::Processed(frame_info.clone()))
.collect::<PrimaryMap<LocalFuncIndex, _>>(); .collect::<PrimaryMap<LocalFunctionIndex, _>>();
let serializable_compilation = SerializableCompilation { let serializable_compilation = SerializableCompilation {
function_bodies: compilation.get_function_bodies(), function_bodies: compilation.get_function_bodies(),

View File

@@ -40,7 +40,7 @@ fn get_extern_from_import(module: &Module, import_index: &ImportIndex) -> Extern
match import_index { match import_index {
ImportIndex::Function(index) => { ImportIndex::Function(index) => {
let func = module.signatures[module.functions[*index]].clone(); let func = module.signatures[module.functions[*index]].clone();
ExternType::Func(func) ExternType::Function(func)
} }
ImportIndex::Table(index) => { ImportIndex::Table(index) => {
let table = module.tables[*index].clone(); let table = module.tables[*index].clone();
@@ -66,7 +66,7 @@ fn get_extern_from_export(
match export { match export {
Export::Function(ref f) => { Export::Function(ref f) => {
let func = signatures.lookup(f.signature).unwrap().clone(); let func = signatures.lookup(f.signature).unwrap().clone();
ExternType::Func(func) ExternType::Function(func)
} }
Export::Table(ref t) => { Export::Table(ref t) => {
let table = t.plan().table.clone(); let table = t.plan().table.clone();

View File

@@ -11,20 +11,20 @@ use wasmer_runtime::Module;
use wasm_common::entity::PrimaryMap; use wasm_common::entity::PrimaryMap;
use wasm_common::{ use wasm_common::{
Features, LocalFuncIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, TableIndex, Features, LocalFunctionIndex, MemoryIndex, OwnedDataInitializer, SignatureIndex, TableIndex,
}; };
use wasmer_runtime::{MemoryPlan, TablePlan}; use wasmer_runtime::{MemoryPlan, TablePlan};
/// The compilation related data for a serialized modules /// The compilation related data for a serialized modules
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct SerializableCompilation { pub struct SerializableCompilation {
pub function_bodies: PrimaryMap<LocalFuncIndex, FunctionBody>, pub function_bodies: PrimaryMap<LocalFunctionIndex, FunctionBody>,
pub function_relocations: PrimaryMap<LocalFuncIndex, Vec<Relocation>>, pub function_relocations: PrimaryMap<LocalFunctionIndex, Vec<Relocation>>,
pub function_jt_offsets: PrimaryMap<LocalFuncIndex, JumpTableOffsets>, pub function_jt_offsets: PrimaryMap<LocalFunctionIndex, JumpTableOffsets>,
// This is `SerializableFunctionFrameInfo` instead of `CompiledFunctionFrameInfo`, // This is `SerializableFunctionFrameInfo` instead of `CompiledFunctionFrameInfo`,
// to allow lazy frame_info deserialization, we convert it to it's lazy binary // to allow lazy frame_info deserialization, we convert it to it's lazy binary
// format upon serialization. // format upon serialization.
pub function_frame_info: PrimaryMap<LocalFuncIndex, SerializableFunctionFrameInfo>, pub function_frame_info: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>,
pub trampolines: PrimaryMap<SignatureIndex, FunctionBody>, pub trampolines: PrimaryMap<SignatureIndex, FunctionBody>,
pub custom_sections: PrimaryMap<SectionIndex, SectionBody>, pub custom_sections: PrimaryMap<SectionIndex, SectionBody>,
} }

View File

@@ -15,7 +15,7 @@ use std::cmp;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasm_common::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasm_common::LocalFuncIndex; use wasm_common::LocalFunctionIndex;
use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation};
use wasmer_runtime::{Module, VMFunctionBody}; use wasmer_runtime::{Module, VMFunctionBody};
@@ -54,15 +54,18 @@ struct ModuleFrameInfo {
start: usize, start: usize,
functions: BTreeMap<usize, FunctionInfo>, functions: BTreeMap<usize, FunctionInfo>,
module: Arc<Module>, module: Arc<Module>,
frame_infos: PrimaryMap<LocalFuncIndex, SerializableFunctionFrameInfo>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>,
} }
impl ModuleFrameInfo { impl ModuleFrameInfo {
fn function_debug_info(&self, local_index: LocalFuncIndex) -> &SerializableFunctionFrameInfo { fn function_debug_info(
&self,
local_index: LocalFunctionIndex,
) -> &SerializableFunctionFrameInfo {
&self.frame_infos.get(local_index).unwrap() &self.frame_infos.get(local_index).unwrap()
} }
fn process_function_debug_info(&mut self, local_index: LocalFuncIndex) { fn process_function_debug_info(&mut self, local_index: LocalFunctionIndex) {
let mut func = self.frame_infos.get_mut(local_index).unwrap(); let mut func = self.frame_infos.get_mut(local_index).unwrap();
let processed: CompiledFunctionFrameInfo = match func { let processed: CompiledFunctionFrameInfo = match func {
SerializableFunctionFrameInfo::Processed(_) => { SerializableFunctionFrameInfo::Processed(_) => {
@@ -76,7 +79,7 @@ impl ModuleFrameInfo {
fn processed_function_frame_info( fn processed_function_frame_info(
&self, &self,
local_index: LocalFuncIndex, local_index: LocalFunctionIndex,
) -> &CompiledFunctionFrameInfo { ) -> &CompiledFunctionFrameInfo {
match self.function_debug_info(local_index) { match self.function_debug_info(local_index) {
SerializableFunctionFrameInfo::Processed(di) => &di, SerializableFunctionFrameInfo::Processed(di) => &di,
@@ -96,7 +99,7 @@ impl ModuleFrameInfo {
struct FunctionInfo { struct FunctionInfo {
start: usize, start: usize,
local_index: LocalFuncIndex, local_index: LocalFunctionIndex,
} }
impl GlobalFrameInfo { impl GlobalFrameInfo {
@@ -223,8 +226,8 @@ impl Drop for GlobalFrameInfoRegistration {
/// dropped, will be used to unregister all name information from this map. /// dropped, will be used to unregister all name information from this map.
pub fn register( pub fn register(
module: &Arc<Module>, module: &Arc<Module>,
finished_functions: &BoxedSlice<LocalFuncIndex, *mut [VMFunctionBody]>, finished_functions: &BoxedSlice<LocalFunctionIndex, *mut [VMFunctionBody]>,
frame_infos: PrimaryMap<LocalFuncIndex, SerializableFunctionFrameInfo>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>,
) -> Option<GlobalFrameInfoRegistration> { ) -> Option<GlobalFrameInfoRegistration> {
let mut min = usize::max_value(); let mut min = usize::max_value();
let mut max = 0; let mut max = 0;

View File

@@ -1,13 +1,13 @@
use crate::vmcontext::{VMFunctionImport, VMGlobalImport, VMMemoryImport, VMTableImport}; use crate::vmcontext::{VMFunctionImport, VMGlobalImport, VMMemoryImport, VMTableImport};
use std::collections::HashSet; use std::collections::HashSet;
use wasm_common::entity::{BoxedSlice, PrimaryMap}; use wasm_common::entity::{BoxedSlice, PrimaryMap};
use wasm_common::{FuncIndex, GlobalIndex, MemoryIndex, TableIndex}; use wasm_common::{FunctionIndex, GlobalIndex, MemoryIndex, TableIndex};
/// Resolved import pointers. /// Resolved import pointers.
#[derive(Clone)] #[derive(Clone)]
pub struct Imports { pub struct Imports {
/// Resolved addresses for imported functions. /// Resolved addresses for imported functions.
pub functions: BoxedSlice<FuncIndex, VMFunctionImport>, pub functions: BoxedSlice<FunctionIndex, VMFunctionImport>,
/// Resolved addresses for imported tables. /// Resolved addresses for imported tables.
pub tables: BoxedSlice<TableIndex, VMTableImport>, pub tables: BoxedSlice<TableIndex, VMTableImport>,
@@ -22,7 +22,7 @@ pub struct Imports {
impl Imports { impl Imports {
/// Construct a new `Imports` instance. /// Construct a new `Imports` instance.
pub fn new( pub fn new(
function_imports: PrimaryMap<FuncIndex, VMFunctionImport>, function_imports: PrimaryMap<FunctionIndex, VMFunctionImport>,
table_imports: PrimaryMap<TableIndex, VMTableImport>, table_imports: PrimaryMap<TableIndex, VMTableImport>,
memory_imports: PrimaryMap<MemoryIndex, VMMemoryImport>, memory_imports: PrimaryMap<MemoryIndex, VMMemoryImport>,
global_imports: PrimaryMap<GlobalIndex, VMGlobalImport>, global_imports: PrimaryMap<GlobalIndex, VMGlobalImport>,

View File

@@ -24,8 +24,8 @@ use std::sync::Arc;
use std::{mem, ptr, slice}; use std::{mem, ptr, slice};
use wasm_common::entity::{packed_option::ReservedValue, BoxedSlice, EntityRef, PrimaryMap}; use wasm_common::entity::{packed_option::ReservedValue, BoxedSlice, EntityRef, PrimaryMap};
use wasm_common::{ use wasm_common::{
DataIndex, DataInitializer, ElemIndex, ExportIndex, FuncIndex, GlobalIndex, GlobalInit, DataIndex, DataInitializer, ElemIndex, ExportIndex, FunctionIndex, GlobalIndex, GlobalInit,
LocalFuncIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, Pages, LocalFunctionIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, Pages,
SignatureIndex, TableIndex, SignatureIndex, TableIndex,
}; };
@@ -84,7 +84,7 @@ pub(crate) struct Instance {
passive_data: RefCell<HashMap<DataIndex, Arc<[u8]>>>, passive_data: RefCell<HashMap<DataIndex, Arc<[u8]>>>,
/// Pointers to functions in executable memory. /// Pointers to functions in executable memory.
finished_functions: BoxedSlice<LocalFuncIndex, *mut [VMFunctionBody]>, finished_functions: BoxedSlice<LocalFunctionIndex, *mut [VMFunctionBody]>,
/// Hosts can store arbitrary per-instance information here. /// Hosts can store arbitrary per-instance information here.
host_state: Box<dyn Any>, host_state: Box<dyn Any>,
@@ -128,7 +128,7 @@ impl Instance {
} }
/// Return the indexed `VMFunctionImport`. /// Return the indexed `VMFunctionImport`.
fn imported_function(&self, index: FuncIndex) -> &VMFunctionImport { fn imported_function(&self, index: FunctionIndex) -> &VMFunctionImport {
let index = usize::try_from(index.as_u32()).unwrap(); let index = usize::try_from(index.as_u32()).unwrap();
unsafe { &*self.imported_functions_ptr().add(index) } unsafe { &*self.imported_functions_ptr().add(index) }
} }
@@ -536,9 +536,9 @@ impl Instance {
Layout::from_size_align(size, align).unwrap() Layout::from_size_align(size, align).unwrap()
} }
/// Get a `VMCallerCheckedAnyfunc` for the given `FuncIndex`. /// Get a `VMCallerCheckedAnyfunc` for the given `FunctionIndex`.
fn get_caller_checked_anyfunc(&self, index: FuncIndex) -> VMCallerCheckedAnyfunc { fn get_caller_checked_anyfunc(&self, index: FunctionIndex) -> VMCallerCheckedAnyfunc {
if index == FuncIndex::reserved_value() { if index == FunctionIndex::reserved_value() {
return VMCallerCheckedAnyfunc::default(); return VMCallerCheckedAnyfunc::default();
} }
@@ -775,7 +775,7 @@ impl InstanceHandle {
/// safety. /// safety.
pub unsafe fn new( pub unsafe fn new(
module: Arc<Module>, module: Arc<Module>,
finished_functions: BoxedSlice<LocalFuncIndex, *mut [VMFunctionBody]>, finished_functions: BoxedSlice<LocalFunctionIndex, *mut [VMFunctionBody]>,
finished_memories: BoxedSlice<LocalMemoryIndex, LinearMemory>, finished_memories: BoxedSlice<LocalMemoryIndex, LinearMemory>,
finished_tables: BoxedSlice<LocalTableIndex, Table>, finished_tables: BoxedSlice<LocalTableIndex, Table>,
finished_globals: BoxedSlice<LocalGlobalIndex, VMGlobalDefinition>, finished_globals: BoxedSlice<LocalGlobalIndex, VMGlobalDefinition>,
@@ -1173,7 +1173,7 @@ fn initialize_tables(instance: &Instance) -> Result<(), Trap> {
} }
/// Initialize the `Instance::passive_elements` map by resolving the /// Initialize the `Instance::passive_elements` map by resolving the
/// `Module::passive_elements`'s `FuncIndex`s into `VMCallerCheckedAnyfunc`s for /// `Module::passive_elements`'s `FunctionIndex`s into `VMCallerCheckedAnyfunc`s for
/// this instance. /// this instance.
fn initialize_passive_elements(instance: &Instance) { fn initialize_passive_elements(instance: &Instance) {
let mut passive_elements = instance.passive_elements.borrow_mut(); let mut passive_elements = instance.passive_elements.borrow_mut();

View File

@@ -9,10 +9,10 @@ use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::Arc; use std::sync::Arc;
use wasm_common::entity::{EntityRef, PrimaryMap}; use wasm_common::entity::{EntityRef, PrimaryMap};
use wasm_common::{ use wasm_common::{
DataIndex, ElemIndex, ExportIndex, ExportType, ExternType, FuncIndex, FuncType, GlobalIndex, DataIndex, ElemIndex, ExportIndex, ExportType, ExternType, FunctionIndex, FunctionType,
GlobalInit, GlobalType, ImportIndex, ImportType, LocalFuncIndex, LocalGlobalIndex, GlobalIndex, GlobalInit, GlobalType, ImportIndex, ImportType, LocalFunctionIndex,
LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, Pages, SignatureIndex, TableIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, MemoryType, Pages,
TableType, SignatureIndex, TableIndex, TableType,
}; };
/// A WebAssembly table initializer. /// A WebAssembly table initializer.
@@ -25,7 +25,7 @@ pub struct TableElements {
/// The offset to add to the base. /// The offset to add to the base.
pub offset: usize, pub offset: usize,
/// The values to write into the table elements. /// The values to write into the table elements.
pub elements: Box<[FuncIndex]>, pub elements: Box<[FunctionIndex]>,
} }
/// Implemenation styles for WebAssembly linear memory. /// Implemenation styles for WebAssembly linear memory.
@@ -114,13 +114,13 @@ pub struct Module {
pub exports: IndexMap<String, ExportIndex>, pub exports: IndexMap<String, ExportIndex>,
/// The module "start" function, if present. /// The module "start" function, if present.
pub start_func: Option<FuncIndex>, pub start_func: Option<FunctionIndex>,
/// WebAssembly table initializers. /// WebAssembly table initializers.
pub table_elements: Vec<TableElements>, pub table_elements: Vec<TableElements>,
/// WebAssembly passive elements. /// WebAssembly passive elements.
pub passive_elements: HashMap<ElemIndex, Box<[FuncIndex]>>, pub passive_elements: HashMap<ElemIndex, Box<[FunctionIndex]>>,
/// WebAssembly passive data segments. /// WebAssembly passive data segments.
pub passive_data: HashMap<DataIndex, Arc<[u8]>>, pub passive_data: HashMap<DataIndex, Arc<[u8]>>,
@@ -129,13 +129,13 @@ pub struct Module {
pub global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>, pub global_initializers: PrimaryMap<LocalGlobalIndex, GlobalInit>,
/// WebAssembly function names. /// WebAssembly function names.
pub func_names: HashMap<FuncIndex, String>, pub func_names: HashMap<FunctionIndex, String>,
/// WebAssembly function signatures. /// WebAssembly function signatures.
pub signatures: PrimaryMap<SignatureIndex, FuncType>, pub signatures: PrimaryMap<SignatureIndex, FunctionType>,
/// Types of functions (imported and local). /// Types of functions (imported and local).
pub functions: PrimaryMap<FuncIndex, SignatureIndex>, pub functions: PrimaryMap<FunctionIndex, SignatureIndex>,
/// WebAssembly tables (imported and local). /// WebAssembly tables (imported and local).
pub tables: PrimaryMap<TableIndex, TableType>, pub tables: PrimaryMap<TableIndex, TableType>,
@@ -186,12 +186,12 @@ impl Module {
} }
/// Get the given passive element, if it exists. /// Get the given passive element, if it exists.
pub fn get_passive_element(&self, index: ElemIndex) -> Option<&[FuncIndex]> { pub fn get_passive_element(&self, index: ElemIndex) -> Option<&[FunctionIndex]> {
self.passive_elements.get(&index).map(|es| &**es) self.passive_elements.get(&index).map(|es| &**es)
} }
/// Get the exported signatures of the module /// Get the exported signatures of the module
pub fn exported_signatures(&self) -> Vec<FuncType> { pub fn exported_signatures(&self) -> Vec<FunctionType> {
self.exports self.exports
.iter() .iter()
.filter_map(|(_name, export_index)| match export_index { .filter_map(|(_name, export_index)| match export_index {
@@ -202,7 +202,7 @@ impl Module {
} }
_ => None, _ => None,
}) })
.collect::<Vec<FuncType>>() .collect::<Vec<FunctionType>>()
} }
/// Get the export types of the module /// Get the export types of the module
@@ -212,7 +212,7 @@ impl Module {
ExportIndex::Function(i) => { ExportIndex::Function(i) => {
let signature = self.functions.get(i.clone()).unwrap(); let signature = self.functions.get(i.clone()).unwrap();
let func_type = self.signatures.get(signature.clone()).unwrap(); let func_type = self.signatures.get(signature.clone()).unwrap();
ExternType::Func(func_type.clone()) ExternType::Function(func_type.clone())
} }
ExportIndex::Table(i) => { ExportIndex::Table(i) => {
let table_type = self.tables.get(i.clone()).unwrap(); let table_type = self.tables.get(i.clone()).unwrap();
@@ -240,7 +240,7 @@ impl Module {
ImportIndex::Function(i) => { ImportIndex::Function(i) => {
let signature = self.functions.get(i.clone()).unwrap(); let signature = self.functions.get(i.clone()).unwrap();
let func_type = self.signatures.get(signature.clone()).unwrap(); let func_type = self.signatures.get(signature.clone()).unwrap();
ExternType::Func(func_type.clone()) ExternType::Function(func_type.clone())
} }
ImportIndex::Table(i) => { ImportIndex::Table(i) => {
let table_type = self.tables.get(i.clone()).unwrap(); let table_type = self.tables.get(i.clone()).unwrap();
@@ -259,21 +259,21 @@ impl Module {
}) })
} }
/// Convert a `LocalFuncIndex` into a `FuncIndex`. /// Convert a `LocalFunctionIndex` into a `FunctionIndex`.
pub fn func_index(&self, local_func: LocalFuncIndex) -> FuncIndex { pub fn func_index(&self, local_func: LocalFunctionIndex) -> FunctionIndex {
FuncIndex::new(self.num_imported_funcs + local_func.index()) FunctionIndex::new(self.num_imported_funcs + local_func.index())
} }
/// Convert a `FuncIndex` into a `LocalFuncIndex`. Returns None if the /// Convert a `FunctionIndex` into a `LocalFunctionIndex`. Returns None if the
/// index is an imported function. /// index is an imported function.
pub fn local_func_index(&self, func: FuncIndex) -> Option<LocalFuncIndex> { pub fn local_func_index(&self, func: FunctionIndex) -> Option<LocalFunctionIndex> {
func.index() func.index()
.checked_sub(self.num_imported_funcs) .checked_sub(self.num_imported_funcs)
.map(LocalFuncIndex::new) .map(LocalFunctionIndex::new)
} }
/// Test whether the given function index is for an imported function. /// Test whether the given function index is for an imported function.
pub fn is_imported_function(&self, index: FuncIndex) -> bool { pub fn is_imported_function(&self, index: FunctionIndex) -> bool {
index.index() < self.num_imported_funcs index.index() < self.num_imported_funcs
} }

View File

@@ -6,7 +6,7 @@ use more_asserts::{assert_lt, debug_assert_lt};
use std::collections::{hash_map, HashMap}; use std::collections::{hash_map, HashMap};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::sync::RwLock; use std::sync::RwLock;
use wasm_common::FuncType; use wasm_common::FunctionType;
/// WebAssembly requires that the caller and callee signatures in an indirect /// WebAssembly requires that the caller and callee signatures in an indirect
/// call must match. To implement this efficiently, keep a registry of all /// call must match. To implement this efficiently, keep a registry of all
@@ -24,8 +24,8 @@ pub struct SignatureRegistry {
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct Inner { struct Inner {
signature2index: HashMap<FuncType, VMSharedSignatureIndex>, signature2index: HashMap<FunctionType, VMSharedSignatureIndex>,
index2signature: HashMap<VMSharedSignatureIndex, FuncType>, index2signature: HashMap<VMSharedSignatureIndex, FunctionType>,
} }
impl SignatureRegistry { impl SignatureRegistry {
@@ -37,7 +37,7 @@ impl SignatureRegistry {
} }
/// Register a signature and return its unique index. /// Register a signature and return its unique index.
pub fn register(&self, sig: &FuncType) -> VMSharedSignatureIndex { pub fn register(&self, sig: &FunctionType) -> VMSharedSignatureIndex {
let mut inner = self.inner.write().unwrap(); let mut inner = self.inner.write().unwrap();
let len = inner.signature2index.len(); let len = inner.signature2index.len();
match inner.signature2index.entry(sig.clone()) { match inner.signature2index.entry(sig.clone()) {
@@ -62,7 +62,7 @@ impl SignatureRegistry {
/// ///
/// Note that for this operation to be semantically correct the `idx` must /// Note that for this operation to be semantically correct the `idx` must
/// have previously come from a call to `register` of this same object. /// have previously come from a call to `register` of this same object.
pub fn lookup(&self, idx: VMSharedSignatureIndex) -> Option<FuncType> { pub fn lookup(&self, idx: VMSharedSignatureIndex) -> Option<FunctionType> {
self.inner self.inner
.read() .read()
.unwrap() .unwrap()

View File

@@ -6,7 +6,7 @@ use crate::VMBuiltinFunctionIndex;
use more_asserts::assert_lt; use more_asserts::assert_lt;
use std::convert::TryFrom; use std::convert::TryFrom;
use wasm_common::{ use wasm_common::{
FuncIndex, GlobalIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, FunctionIndex, GlobalIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex,
SignatureIndex, TableIndex, SignatureIndex, TableIndex,
}; };
@@ -364,7 +364,7 @@ impl VMOffsets {
} }
/// Return the offset to `VMFunctionImport` index `index`. /// Return the offset to `VMFunctionImport` index `index`.
pub fn vmctx_vmfunction_import(&self, index: FuncIndex) -> u32 { pub fn vmctx_vmfunction_import(&self, index: FunctionIndex) -> u32 {
assert_lt!(index.as_u32(), self.num_imported_functions); assert_lt!(index.as_u32(), self.num_imported_functions);
self.vmctx_imported_functions_begin() self.vmctx_imported_functions_begin()
.checked_add( .checked_add(
@@ -455,14 +455,14 @@ impl VMOffsets {
} }
/// Return the offset to the `body` field in `*const VMFunctionBody` index `index`. /// Return the offset to the `body` field in `*const VMFunctionBody` index `index`.
pub fn vmctx_vmfunction_import_body(&self, index: FuncIndex) -> u32 { pub fn vmctx_vmfunction_import_body(&self, index: FunctionIndex) -> u32 {
self.vmctx_vmfunction_import(index) self.vmctx_vmfunction_import(index)
.checked_add(u32::from(self.vmfunction_import_body())) .checked_add(u32::from(self.vmfunction_import_body()))
.unwrap() .unwrap()
} }
/// Return the offset to the `vmctx` field in `*const VMFunctionBody` index `index`. /// Return the offset to the `vmctx` field in `*const VMFunctionBody` index `index`.
pub fn vmctx_vmfunction_import_vmctx(&self, index: FuncIndex) -> u32 { pub fn vmctx_vmfunction_import_vmctx(&self, index: FunctionIndex) -> u32 {
self.vmctx_vmfunction_import(index) self.vmctx_vmfunction_import(index)
.checked_add(u32::from(self.vmfunction_import_vmctx())) .checked_add(u32::from(self.vmfunction_import_vmctx()))
.unwrap() .unwrap()

View File

@@ -26,7 +26,7 @@ pub use crate::syscalls::types;
pub use crate::utils::{get_wasi_version, is_wasi_module, WasiVersion}; pub use crate::utils::{get_wasi_version, is_wasi_module, WasiVersion};
use thiserror::Error; use thiserror::Error;
use wasmer::{imports, Func, ImportObject, Memory, Store}; use wasmer::{imports, Function, ImportObject, Memory, Store};
/// This is returned in `RuntimeError`. /// This is returned in `RuntimeError`.
/// Use `downcast` or `downcast_ref` to retrieve the `ExitCode`. /// Use `downcast` or `downcast_ref` to retrieve the `ExitCode`.
@@ -100,51 +100,51 @@ pub fn generate_import_object_from_env(
fn generate_import_object_snapshot0(store: &Store, env: &mut WasiEnv) -> ImportObject { fn generate_import_object_snapshot0(store: &Store, env: &mut WasiEnv) -> ImportObject {
imports! { imports! {
"wasi_unstable" => { "wasi_unstable" => {
"args_get" => Func::new_env(store, env, args_get), "args_get" => Function::new_env(store, env, args_get),
"args_sizes_get" => Func::new_env(store, env, args_sizes_get), "args_sizes_get" => Function::new_env(store, env, args_sizes_get),
"clock_res_get" => Func::new_env(store, env, clock_res_get), "clock_res_get" => Function::new_env(store, env, clock_res_get),
"clock_time_get" => Func::new_env(store, env, clock_time_get), "clock_time_get" => Function::new_env(store, env, clock_time_get),
"environ_get" => Func::new_env(store, env, environ_get), "environ_get" => Function::new_env(store, env, environ_get),
"environ_sizes_get" => Func::new_env(store, env, environ_sizes_get), "environ_sizes_get" => Function::new_env(store, env, environ_sizes_get),
"fd_advise" => Func::new_env(store, env, fd_advise), "fd_advise" => Function::new_env(store, env, fd_advise),
"fd_allocate" => Func::new_env(store, env, fd_allocate), "fd_allocate" => Function::new_env(store, env, fd_allocate),
"fd_close" => Func::new_env(store, env, fd_close), "fd_close" => Function::new_env(store, env, fd_close),
"fd_datasync" => Func::new_env(store, env, fd_datasync), "fd_datasync" => Function::new_env(store, env, fd_datasync),
"fd_fdstat_get" => Func::new_env(store, env, fd_fdstat_get), "fd_fdstat_get" => Function::new_env(store, env, fd_fdstat_get),
"fd_fdstat_set_flags" => Func::new_env(store, env, fd_fdstat_set_flags), "fd_fdstat_set_flags" => Function::new_env(store, env, fd_fdstat_set_flags),
"fd_fdstat_set_rights" => Func::new_env(store, env, fd_fdstat_set_rights), "fd_fdstat_set_rights" => Function::new_env(store, env, fd_fdstat_set_rights),
"fd_filestat_get" => Func::new_env(store, env, legacy::snapshot0::fd_filestat_get), "fd_filestat_get" => Function::new_env(store, env, legacy::snapshot0::fd_filestat_get),
"fd_filestat_set_size" => Func::new_env(store, env, fd_filestat_set_size), "fd_filestat_set_size" => Function::new_env(store, env, fd_filestat_set_size),
"fd_filestat_set_times" => Func::new_env(store, env, fd_filestat_set_times), "fd_filestat_set_times" => Function::new_env(store, env, fd_filestat_set_times),
"fd_pread" => Func::new_env(store, env, fd_pread), "fd_pread" => Function::new_env(store, env, fd_pread),
"fd_prestat_get" => Func::new_env(store, env, fd_prestat_get), "fd_prestat_get" => Function::new_env(store, env, fd_prestat_get),
"fd_prestat_dir_name" => Func::new_env(store, env, fd_prestat_dir_name), "fd_prestat_dir_name" => Function::new_env(store, env, fd_prestat_dir_name),
"fd_pwrite" => Func::new_env(store, env, fd_pwrite), "fd_pwrite" => Function::new_env(store, env, fd_pwrite),
"fd_read" => Func::new_env(store, env, fd_read), "fd_read" => Function::new_env(store, env, fd_read),
"fd_readdir" => Func::new_env(store, env, fd_readdir), "fd_readdir" => Function::new_env(store, env, fd_readdir),
"fd_renumber" => Func::new_env(store, env, fd_renumber), "fd_renumber" => Function::new_env(store, env, fd_renumber),
"fd_seek" => Func::new_env(store, env, legacy::snapshot0::fd_seek), "fd_seek" => Function::new_env(store, env, legacy::snapshot0::fd_seek),
"fd_sync" => Func::new_env(store, env, fd_sync), "fd_sync" => Function::new_env(store, env, fd_sync),
"fd_tell" => Func::new_env(store, env, fd_tell), "fd_tell" => Function::new_env(store, env, fd_tell),
"fd_write" => Func::new_env(store, env, fd_write), "fd_write" => Function::new_env(store, env, fd_write),
"path_create_directory" => Func::new_env(store, env, path_create_directory), "path_create_directory" => Function::new_env(store, env, path_create_directory),
"path_filestat_get" => Func::new_env(store, env, legacy::snapshot0::path_filestat_get), "path_filestat_get" => Function::new_env(store, env, legacy::snapshot0::path_filestat_get),
"path_filestat_set_times" => Func::new_env(store, env, path_filestat_set_times), "path_filestat_set_times" => Function::new_env(store, env, path_filestat_set_times),
"path_link" => Func::new_env(store, env, path_link), "path_link" => Function::new_env(store, env, path_link),
"path_open" => Func::new_env(store, env, path_open), "path_open" => Function::new_env(store, env, path_open),
"path_readlink" => Func::new_env(store, env, path_readlink), "path_readlink" => Function::new_env(store, env, path_readlink),
"path_remove_directory" => Func::new_env(store, env, path_remove_directory), "path_remove_directory" => Function::new_env(store, env, path_remove_directory),
"path_rename" => Func::new_env(store, env, path_rename), "path_rename" => Function::new_env(store, env, path_rename),
"path_symlink" => Func::new_env(store, env, path_symlink), "path_symlink" => Function::new_env(store, env, path_symlink),
"path_unlink_file" => Func::new_env(store, env, path_unlink_file), "path_unlink_file" => Function::new_env(store, env, path_unlink_file),
"poll_oneoff" => Func::new_env(store, env, legacy::snapshot0::poll_oneoff), "poll_oneoff" => Function::new_env(store, env, legacy::snapshot0::poll_oneoff),
"proc_exit" => Func::new_env(store, env, proc_exit), "proc_exit" => Function::new_env(store, env, proc_exit),
"proc_raise" => Func::new_env(store, env, proc_raise), "proc_raise" => Function::new_env(store, env, proc_raise),
"random_get" => Func::new_env(store, env, random_get), "random_get" => Function::new_env(store, env, random_get),
"sched_yield" => Func::new_env(store, env, sched_yield), "sched_yield" => Function::new_env(store, env, sched_yield),
"sock_recv" => Func::new_env(store, env, sock_recv), "sock_recv" => Function::new_env(store, env, sock_recv),
"sock_send" => Func::new_env(store, env, sock_send), "sock_send" => Function::new_env(store, env, sock_send),
"sock_shutdown" => Func::new_env(store, env, sock_shutdown), "sock_shutdown" => Function::new_env(store, env, sock_shutdown),
}, },
} }
} }
@@ -153,51 +153,51 @@ fn generate_import_object_snapshot0(store: &Store, env: &mut WasiEnv) -> ImportO
fn generate_import_object_snapshot1(store: &Store, env: &mut WasiEnv) -> ImportObject { fn generate_import_object_snapshot1(store: &Store, env: &mut WasiEnv) -> ImportObject {
imports! { imports! {
"wasi_snapshot_preview1" => { "wasi_snapshot_preview1" => {
"args_get" => Func::new_env(store, env, args_get), "args_get" => Function::new_env(store, env, args_get),
"args_sizes_get" => Func::new_env(store, env, args_sizes_get), "args_sizes_get" => Function::new_env(store, env, args_sizes_get),
"clock_res_get" => Func::new_env(store, env, clock_res_get), "clock_res_get" => Function::new_env(store, env, clock_res_get),
"clock_time_get" => Func::new_env(store, env, clock_time_get), "clock_time_get" => Function::new_env(store, env, clock_time_get),
"environ_get" => Func::new_env(store, env, environ_get), "environ_get" => Function::new_env(store, env, environ_get),
"environ_sizes_get" => Func::new_env(store, env, environ_sizes_get), "environ_sizes_get" => Function::new_env(store, env, environ_sizes_get),
"fd_advise" => Func::new_env(store, env, fd_advise), "fd_advise" => Function::new_env(store, env, fd_advise),
"fd_allocate" => Func::new_env(store, env, fd_allocate), "fd_allocate" => Function::new_env(store, env, fd_allocate),
"fd_close" => Func::new_env(store, env, fd_close), "fd_close" => Function::new_env(store, env, fd_close),
"fd_datasync" => Func::new_env(store, env, fd_datasync), "fd_datasync" => Function::new_env(store, env, fd_datasync),
"fd_fdstat_get" => Func::new_env(store, env, fd_fdstat_get), "fd_fdstat_get" => Function::new_env(store, env, fd_fdstat_get),
"fd_fdstat_set_flags" => Func::new_env(store, env, fd_fdstat_set_flags), "fd_fdstat_set_flags" => Function::new_env(store, env, fd_fdstat_set_flags),
"fd_fdstat_set_rights" => Func::new_env(store, env, fd_fdstat_set_rights), "fd_fdstat_set_rights" => Function::new_env(store, env, fd_fdstat_set_rights),
"fd_filestat_get" => Func::new_env(store, env, fd_filestat_get), "fd_filestat_get" => Function::new_env(store, env, fd_filestat_get),
"fd_filestat_set_size" => Func::new_env(store, env, fd_filestat_set_size), "fd_filestat_set_size" => Function::new_env(store, env, fd_filestat_set_size),
"fd_filestat_set_times" => Func::new_env(store, env, fd_filestat_set_times), "fd_filestat_set_times" => Function::new_env(store, env, fd_filestat_set_times),
"fd_pread" => Func::new_env(store, env, fd_pread), "fd_pread" => Function::new_env(store, env, fd_pread),
"fd_prestat_get" => Func::new_env(store, env, fd_prestat_get), "fd_prestat_get" => Function::new_env(store, env, fd_prestat_get),
"fd_prestat_dir_name" => Func::new_env(store, env, fd_prestat_dir_name), "fd_prestat_dir_name" => Function::new_env(store, env, fd_prestat_dir_name),
"fd_pwrite" => Func::new_env(store, env, fd_pwrite), "fd_pwrite" => Function::new_env(store, env, fd_pwrite),
"fd_read" => Func::new_env(store, env, fd_read), "fd_read" => Function::new_env(store, env, fd_read),
"fd_readdir" => Func::new_env(store, env, fd_readdir), "fd_readdir" => Function::new_env(store, env, fd_readdir),
"fd_renumber" => Func::new_env(store, env, fd_renumber), "fd_renumber" => Function::new_env(store, env, fd_renumber),
"fd_seek" => Func::new_env(store, env, fd_seek), "fd_seek" => Function::new_env(store, env, fd_seek),
"fd_sync" => Func::new_env(store, env, fd_sync), "fd_sync" => Function::new_env(store, env, fd_sync),
"fd_tell" => Func::new_env(store, env, fd_tell), "fd_tell" => Function::new_env(store, env, fd_tell),
"fd_write" => Func::new_env(store, env, fd_write), "fd_write" => Function::new_env(store, env, fd_write),
"path_create_directory" => Func::new_env(store, env, path_create_directory), "path_create_directory" => Function::new_env(store, env, path_create_directory),
"path_filestat_get" => Func::new_env(store, env, path_filestat_get), "path_filestat_get" => Function::new_env(store, env, path_filestat_get),
"path_filestat_set_times" => Func::new_env(store, env, path_filestat_set_times), "path_filestat_set_times" => Function::new_env(store, env, path_filestat_set_times),
"path_link" => Func::new_env(store, env, path_link), "path_link" => Function::new_env(store, env, path_link),
"path_open" => Func::new_env(store, env, path_open), "path_open" => Function::new_env(store, env, path_open),
"path_readlink" => Func::new_env(store, env, path_readlink), "path_readlink" => Function::new_env(store, env, path_readlink),
"path_remove_directory" => Func::new_env(store, env, path_remove_directory), "path_remove_directory" => Function::new_env(store, env, path_remove_directory),
"path_rename" => Func::new_env(store, env, path_rename), "path_rename" => Function::new_env(store, env, path_rename),
"path_symlink" => Func::new_env(store, env, path_symlink), "path_symlink" => Function::new_env(store, env, path_symlink),
"path_unlink_file" => Func::new_env(store, env, path_unlink_file), "path_unlink_file" => Function::new_env(store, env, path_unlink_file),
"poll_oneoff" => Func::new_env(store, env, poll_oneoff), "poll_oneoff" => Function::new_env(store, env, poll_oneoff),
"proc_exit" => Func::new_env(store, env, proc_exit), "proc_exit" => Function::new_env(store, env, proc_exit),
"proc_raise" => Func::new_env(store, env, proc_raise), "proc_raise" => Function::new_env(store, env, proc_raise),
"random_get" => Func::new_env(store, env, random_get), "random_get" => Function::new_env(store, env, random_get),
"sched_yield" => Func::new_env(store, env, sched_yield), "sched_yield" => Function::new_env(store, env, sched_yield),
"sock_recv" => Func::new_env(store, env, sock_recv), "sock_recv" => Function::new_env(store, env, sock_recv),
"sock_send" => Func::new_env(store, env, sock_send), "sock_send" => Function::new_env(store, env, sock_send),
"sock_shutdown" => Func::new_env(store, env, sock_shutdown), "sock_shutdown" => Function::new_env(store, env, sock_shutdown),
} }
} }
} }

View File

@@ -44,7 +44,7 @@ const SNAPSHOT1_NAMESPACE: &str = "wasi_snapshot_preview1";
/// detection is faster than the non-strict one. /// detection is faster than the non-strict one.
pub fn get_wasi_version(module: &Module, strict: bool) -> Option<WasiVersion> { pub fn get_wasi_version(module: &Module, strict: bool) -> Option<WasiVersion> {
let mut imports = module.imports().filter_map(|extern_| match extern_.ty() { let mut imports = module.imports().filter_map(|extern_| match extern_.ty() {
ExternType::Func(_f) => Some(extern_.module().to_owned()), ExternType::Function(_f) => Some(extern_.module().to_owned()),
_ => None, _ => None,
}); });

View File

@@ -7,8 +7,8 @@ use serde::{Deserialize, Serialize};
/// Index type of a function defined locally inside the WebAssembly module. /// Index type of a function defined locally inside the WebAssembly module.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct LocalFuncIndex(u32); pub struct LocalFunctionIndex(u32);
entity_impl!(LocalFuncIndex); entity_impl!(LocalFunctionIndex);
/// Index type of a table defined locally inside the WebAssembly module. /// Index type of a table defined locally inside the WebAssembly module.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
@@ -31,8 +31,8 @@ entity_impl!(LocalGlobalIndex);
/// Index type of a function (imported or local) inside the WebAssembly module. /// Index type of a function (imported or local) inside the WebAssembly module.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct FuncIndex(u32); pub struct FunctionIndex(u32);
entity_impl!(FuncIndex); entity_impl!(FunctionIndex);
/// Index type of a table (imported or local) inside the WebAssembly module. /// Index type of a table (imported or local) inside the WebAssembly module.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
@@ -75,7 +75,7 @@ entity_impl!(ElemIndex);
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub enum ExportIndex { pub enum ExportIndex {
/// Function export. /// Function export.
Function(FuncIndex), Function(FunctionIndex),
/// Table export. /// Table export.
Table(TableIndex), Table(TableIndex),
/// Memory export. /// Memory export.
@@ -89,7 +89,7 @@ pub enum ExportIndex {
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub enum ImportIndex { pub enum ImportIndex {
/// Function import. /// Function import.
Function(FuncIndex), Function(FunctionIndex),
/// Table import. /// Table import.
Table(TableIndex), Table(TableIndex),
/// Memory import. /// Memory import.

View File

@@ -40,7 +40,7 @@ pub mod entity {
pub use crate::data_initializer::{DataInitializer, DataInitializerLocation, OwnedDataInitializer}; pub use crate::data_initializer::{DataInitializer, DataInitializerLocation, OwnedDataInitializer};
pub use crate::features::Features; pub use crate::features::Features;
pub use crate::indexes::{ pub use crate::indexes::{
DataIndex, ElemIndex, ExportIndex, FuncIndex, GlobalIndex, ImportIndex, LocalFuncIndex, DataIndex, ElemIndex, ExportIndex, FunctionIndex, GlobalIndex, ImportIndex, LocalFunctionIndex,
LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, SignatureIndex, TableIndex, LocalGlobalIndex, LocalMemoryIndex, LocalTableIndex, MemoryIndex, SignatureIndex, TableIndex,
}; };
pub use crate::native::{ pub use crate::native::{
@@ -51,8 +51,8 @@ pub use crate::r#ref::{AnyRef, HostInfo, HostRef};
pub use crate::units::{Bytes, Pages}; pub use crate::units::{Bytes, Pages};
pub use crate::values::Value; pub use crate::values::Value;
pub use types::{ pub use types::{
ExportType, ExternType, FuncType, GlobalInit, GlobalType, ImportType, MemoryType, Mutability, ExportType, ExternType, FunctionType, GlobalInit, GlobalType, ImportType, MemoryType,
TableType, Type, V128, Mutability, TableType, Type, V128,
}; };
/// Version number of this crate. /// Version number of this crate.

View File

@@ -1,7 +1,7 @@
//! This module permits to create native functions //! This module permits to create native functions
//! easily in Rust, thanks to it's advanced typing system. //! easily in Rust, thanks to it's advanced typing system.
use crate::types::{FuncType, Type}; use crate::types::{FunctionType, Type};
use std::convert::Infallible; use std::convert::Infallible;
use std::marker::PhantomData; use std::marker::PhantomData;
@@ -300,8 +300,8 @@ where
} }
/// Get the type of the Func /// Get the type of the Func
pub fn ty(&self) -> FuncType { pub fn ty(&self) -> FunctionType {
FuncType::new(Args::wasm_types(), Rets::wasm_types()) FunctionType::new(Args::wasm_types(), Rets::wasm_types())
} }
/// Get the type of the Func /// Get the type of the Func
@@ -633,36 +633,36 @@ mod test_func {
#[test] #[test]
fn test_function_types() { fn test_function_types() {
assert_eq!(Func::new(func).ty(), FuncType::new(vec![], vec![])); assert_eq!(Function::new(func).ty(), FunctionType::new(vec![], vec![]));
assert_eq!( assert_eq!(
Func::new(func__i32).ty(), Function::new(func__i32).ty(),
FuncType::new(vec![], vec![Type::I32]) FunctionType::new(vec![], vec![Type::I32])
); );
assert_eq!( assert_eq!(
Func::new(func_i32).ty(), Function::new(func_i32).ty(),
FuncType::new(vec![Type::I32], vec![]) FunctionType::new(vec![Type::I32], vec![])
); );
assert_eq!( assert_eq!(
Func::new(func_i32__i32).ty(), Function::new(func_i32__i32).ty(),
FuncType::new(vec![Type::I32], vec![Type::I32]) FunctionType::new(vec![Type::I32], vec![Type::I32])
); );
assert_eq!( assert_eq!(
Func::new(func_i32_i32__i32).ty(), Function::new(func_i32_i32__i32).ty(),
FuncType::new(vec![Type::I32, Type::I32], vec![Type::I32]) FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32])
); );
assert_eq!( assert_eq!(
Func::new(func_i32_i32__i32_i32).ty(), Function::new(func_i32_i32__i32_i32).ty(),
FuncType::new(vec![Type::I32, Type::I32], vec![Type::I32, Type::I32]) FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32, Type::I32])
); );
assert_eq!( assert_eq!(
Func::new(func_f32_i32__i32_f32).ty(), Function::new(func_f32_i32__i32_f32).ty(),
FuncType::new(vec![Type::F32, Type::I32], vec![Type::I32, Type::F32]) FunctionType::new(vec![Type::F32, Type::I32], vec![Type::I32, Type::F32])
); );
} }
#[test] #[test]
fn test_function_pointer() { fn test_function_pointer() {
let f = Func::new(func_i32__i32); let f = Function::new(func_i32__i32);
let function = unsafe { let function = unsafe {
std::mem::transmute::<*const FunctionBody, fn(i32, i32, i32) -> i32>(f.address) std::mem::transmute::<*const FunctionBody, fn(i32, i32, i32) -> i32>(f.address)
}; };
@@ -680,7 +680,7 @@ mod test_func {
pub num: i32, pub num: i32,
}; };
let mut my_env = Env { num: 2 }; let mut my_env = Env { num: 2 };
let f = Func::new_env(&mut my_env, func_i32__i32_env); let f = Function::new_env(&mut my_env, func_i32__i32_env);
let function = unsafe { let function = unsafe {
std::mem::transmute::<*const FunctionBody, fn(&mut Env, i32, i32) -> i32>(f.address) std::mem::transmute::<*const FunctionBody, fn(&mut Env, i32, i32) -> i32>(f.address)
}; };
@@ -690,7 +690,7 @@ mod test_func {
#[test] #[test]
fn test_function_call() { fn test_function_call() {
let f = Func::new(func_i32__i32); let f = Function::new(func_i32__i32);
let x = |args: <(i32, i32) as WasmTypeList>::Array, let x = |args: <(i32, i32) as WasmTypeList>::Array,
rets: &mut <(i32, i32) as WasmTypeList>::Array| { rets: &mut <(i32, i32) as WasmTypeList>::Array| {
let result = func_i32_i32__i32_i32(args[0] as _, args[1] as _); let result = func_i32_i32__i32_i32(args[0] as _, args[1] as _);

View File

@@ -1,4 +1,4 @@
use crate::indexes::{FuncIndex, GlobalIndex}; use crate::indexes::{FunctionIndex, GlobalIndex};
use crate::units::Pages; use crate::units::Pages;
use crate::values::Value; use crate::values::Value;
@@ -100,7 +100,7 @@ impl From<&[u8]> for V128 {
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub enum ExternType { pub enum ExternType {
/// This external type is the type of a WebAssembly function. /// This external type is the type of a WebAssembly function.
Func(FuncType), Function(FunctionType),
/// This external type is the type of a WebAssembly global. /// This external type is the type of a WebAssembly global.
Global(GlobalType), Global(GlobalType),
/// This external type is the type of a WebAssembly table. /// This external type is the type of a WebAssembly table.
@@ -192,7 +192,7 @@ macro_rules! accessors {
impl ExternType { impl ExternType {
accessors! { accessors! {
(Func(FuncType) func unwrap_func) (Function(FunctionType) func unwrap_func)
(Global(GlobalType) global unwrap_global) (Global(GlobalType) global unwrap_global)
(Table(TableType) table unwrap_table) (Table(TableType) table unwrap_table)
(Memory(MemoryType) memory unwrap_memory) (Memory(MemoryType) memory unwrap_memory)
@@ -200,7 +200,7 @@ impl ExternType {
/// Check if two externs are compatible /// Check if two externs are compatible
pub fn is_compatible_with(&self, other: &Self) -> bool { pub fn is_compatible_with(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
(ExternType::Func(a), ExternType::Func(b)) => a == b, (ExternType::Function(a), ExternType::Function(b)) => a == b,
(ExternType::Global(a), ExternType::Global(b)) => is_global_compatible(a, b), (ExternType::Global(a), ExternType::Global(b)) => is_global_compatible(a, b),
(ExternType::Table(a), ExternType::Table(b)) => is_table_compatible(a, b), (ExternType::Table(a), ExternType::Table(b)) => is_table_compatible(a, b),
(ExternType::Memory(a), ExternType::Memory(b)) => is_memory_compatible(a, b), (ExternType::Memory(a), ExternType::Memory(b)) => is_memory_compatible(a, b),
@@ -216,14 +216,14 @@ impl ExternType {
/// WebAssembly functions can have 0 or more parameters and results. /// WebAssembly functions can have 0 or more parameters and results.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct FuncType { pub struct FunctionType {
/// The parameters of the function /// The parameters of the function
params: Vec<Type>, params: Vec<Type>,
/// The return values of the function /// The return values of the function
results: Vec<Type>, results: Vec<Type>,
} }
impl FuncType { impl FunctionType {
/// Creates a new Function Type with the given parameter and return types. /// Creates a new Function Type with the given parameter and return types.
pub fn new<Params, Returns>(params: Params, returns: Returns) -> Self pub fn new<Params, Returns>(params: Params, returns: Returns) -> Self
where where
@@ -257,7 +257,7 @@ impl FuncType {
// } // }
} }
impl std::fmt::Display for FuncType { impl std::fmt::Display for FunctionType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let params = self let params = self
.params .params
@@ -358,7 +358,7 @@ pub enum GlobalInit {
/// A `ref.null`. /// A `ref.null`.
RefNullConst, RefNullConst,
/// A `ref.func <index>`. /// A `ref.func <index>`.
RefFunc(FuncIndex), RefFunc(FunctionIndex),
} }
impl GlobalInit { impl GlobalInit {

View File

@@ -121,7 +121,7 @@ impl Run {
// Try to instantiate the wasm file, with no provided imports // Try to instantiate the wasm file, with no provided imports
let imports = imports! {}; let imports = imports! {};
let instance = Instance::new(&module, &imports)?; let instance = Instance::new(&module, &imports)?;
let start: &Func = instance.exports.get("_start")?; let start: &Function = instance.exports.get("_start")?;
start.call(&[])?; start.call(&[])?;
Ok(()) Ok(())
@@ -185,7 +185,7 @@ impl Run {
invoke: &str, invoke: &str,
args: &Vec<String>, args: &Vec<String>,
) -> Result<Box<[Val]>> { ) -> Result<Box<[Val]>> {
let func: &Func = instance.exports.get(&invoke)?; let func: &Function = instance.exports.get(&invoke)?;
let func_ty = func.ty(); let func_ty = func.ty();
let required_arguments = func_ty.params().len(); let required_arguments = func_ty.params().len();
let provided_arguments = args.len(); let provided_arguments = args.len();

View File

@@ -1,7 +1,7 @@
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use std::path::PathBuf; use std::path::PathBuf;
use wasmer::{Func, Instance, Memory, Module}; use wasmer::{Function, Instance, Memory, Module};
use wasmer_wasi::{ use wasmer_wasi::{
generate_import_object_from_env, get_wasi_version, WasiEnv, WasiState, WasiVersion, generate_import_object_from_env, get_wasi_version, WasiEnv, WasiState, WasiVersion,
}; };
@@ -114,7 +114,7 @@ impl Wasi {
let memory: &Memory = instance.exports.get("memory")?; let memory: &Memory = instance.exports.get("memory")?;
wasi_env.set_memory(memory); wasi_env.set_memory(memory);
let start: &Func = instance.exports.get("_start")?; let start: &Function = instance.exports.get("_start")?;
start.call(&[])?; start.call(&[])?;

View File

@@ -3,16 +3,16 @@ use wasmer::*;
/// Return an instance implementing the "spectest" interface used in the /// Return an instance implementing the "spectest" interface used in the
/// spec testsuite. /// spec testsuite.
pub fn spectest_importobject(store: &Store) -> ImportObject { pub fn spectest_importobject(store: &Store) -> ImportObject {
let print = Func::new(store, || {}); let print = Function::new(store, || {});
let print_i32 = Func::new(store, |val: i32| println!("{}: i32", val)); let print_i32 = Function::new(store, |val: i32| println!("{}: i32", val));
let print_i64 = Func::new(store, |val: i64| println!("{}: i64", val)); let print_i64 = Function::new(store, |val: i64| println!("{}: i64", val));
let print_f32 = Func::new(store, |val: f32| println!("{}: f32", val)); let print_f32 = Function::new(store, |val: f32| println!("{}: f32", val));
let print_f64 = Func::new(store, |val: f64| println!("{}: f64", val)); let print_f64 = Function::new(store, |val: f64| println!("{}: f64", val));
let print_i32_f32 = Func::new(store, |i: i32, f: f32| { let print_i32_f32 = Function::new(store, |i: i32, f: f32| {
println!("{}: i32", i); println!("{}: i32", i);
println!("{}: f32", f); println!("{}: f32", f);
}); });
let print_f64_f64 = Func::new(store, |f1: f64, f2: f64| { let print_f64_f64 = Function::new(store, |f1: f64, f2: f64| {
println!("{}: f64", f1); println!("{}: f64", f1);
println!("{}: f64", f2); println!("{}: f64", f2);
}); });

View File

@@ -306,7 +306,7 @@ impl Wast {
args: &[Val], args: &[Val],
) -> Result<Vec<Val>> { ) -> Result<Vec<Val>> {
let instance = self.get_instance(instance_name.as_ref().map(|x| &**x))?; let instance = self.get_instance(instance_name.as_ref().map(|x| &**x))?;
let func: &Func = instance.exports.get(field)?; let func: &Function = instance.exports.get(field)?;
match func.call(args) { match func.call(args) {
Ok(result) => Ok(result.into()), Ok(result) => Ok(result.into()),
Err(e) => Err(e.into()), Err(e) => Err(e.into()),