Add special error types for compile, linking, and runtime errors. (#99)

* Add error types and convert most results to wasmer-runtime results

* Fix spectests

* Fix umbrella project to work with new error types
This commit is contained in:
Lachlan Sneff
2019-01-18 10:54:16 -08:00
committed by GitHub
parent 9c0d78ae46
commit 8a9f5fa61a
18 changed files with 394 additions and 179 deletions

View File

@ -1,4 +1,4 @@
use crate::{module::ModuleInner, types::LocalFuncIndex, vm};
use crate::{error::CompileResult, module::ModuleInner, types::LocalFuncIndex, vm};
use std::ptr::NonNull;
pub use crate::mmap::{Mmap, Protect};
@ -6,7 +6,7 @@ pub use crate::sig_registry::SigRegistry;
pub trait Compiler {
/// Compiles a `Module` from WebAssembly binary format
fn compile(&self, wasm: &[u8]) -> Result<ModuleInner, String>;
fn compile(&self, wasm: &[u8]) -> CompileResult<ModuleInner>;
}
pub trait FuncResolver {

View File

@ -1,4 +1,5 @@
use crate::{
error::{LinkError, LinkResult},
export::{Context, Export},
import::Imports,
memory::LinearMemory,
@ -102,7 +103,6 @@ impl LocalBacking {
LocalOrImport::Local(local_memory_index) => {
let memory_desc = &module.memories[local_memory_index];
let data_top = init_base + init.data.len();
println!("data_top: {}", data_top);
assert!((memory_desc.min * LinearMemory::PAGE_SIZE) as usize >= data_top);
let mem: &mut LinearMemory = &mut memories[local_memory_index];
@ -306,7 +306,7 @@ impl ImportBacking {
module: &ModuleInner,
imports: &mut Imports,
vmctx: *mut vm::Ctx,
) -> Result<Self, String> {
) -> LinkResult<Self> {
Ok(ImportBacking {
functions: import_functions(module, imports, vmctx)?,
memories: import_memories(module, imports, vmctx)?,
@ -324,7 +324,7 @@ fn import_functions(
module: &ModuleInner,
imports: &mut Imports,
vmctx: *mut vm::Ctx,
) -> Result<BoxedMap<ImportedFuncIndex, vm::ImportedFunc>, String> {
) -> LinkResult<BoxedMap<ImportedFuncIndex, vm::ImportedFunc>> {
let mut functions = Map::with_capacity(module.imported_functions.len());
for (index, ImportName { namespace, name }) in &module.imported_functions {
let sig_index = module.func_assoc[index.convert_up(module)];
@ -347,18 +347,33 @@ fn import_functions(
},
});
} else {
return Err(format!(
"unexpected signature for {:?}:{:?}",
namespace, name
));
Err(LinkError::IncorrectImportSignature {
namespace: namespace.clone(),
name: name.clone(),
expected: expected_sig.clone(),
found: signature.clone(),
})?
}
}
Some(_) => {
return Err(format!("incorrect import type for {}:{}", namespace, name));
}
None => {
return Err(format!("import not found: {}:{}", namespace, name));
Some(export_type) => {
let export_type_name = match export_type {
Export::Function { .. } => "function",
Export::Memory { .. } => "memory",
Export::Table { .. } => "table",
Export::Global { .. } => "global",
}
.to_string();
Err(LinkError::IncorrectImportType {
namespace: namespace.clone(),
name: name.clone(),
expected: "function".to_string(),
found: export_type_name,
})?
}
None => Err(LinkError::ImportNotFound {
namespace: namespace.clone(),
name: name.clone(),
})?,
}
}
Ok(functions.into_boxed_map())
@ -368,7 +383,7 @@ fn import_memories(
module: &ModuleInner,
imports: &mut Imports,
vmctx: *mut vm::Ctx,
) -> Result<BoxedMap<ImportedMemoryIndex, vm::ImportedMemory>, String> {
) -> LinkResult<BoxedMap<ImportedMemoryIndex, vm::ImportedMemory>> {
let mut memories = Map::with_capacity(module.imported_memories.len());
for (_index, (ImportName { namespace, name }, expected_memory_desc)) in
&module.imported_memories
@ -391,18 +406,33 @@ fn import_memories(
},
});
} else {
return Err(format!(
"incorrect memory description for {}:{}",
namespace, name,
));
Err(LinkError::IncorrectMemoryDescription {
namespace: namespace.clone(),
name: name.clone(),
expected: expected_memory_desc.clone(),
found: memory_desc.clone(),
})?
}
}
Some(_) => {
return Err(format!("incorrect import type for {}:{}", namespace, name));
}
None => {
return Err(format!("import not found: {}:{}", namespace, name));
Some(export_type) => {
let export_type_name = match export_type {
Export::Function { .. } => "function",
Export::Memory { .. } => "memory",
Export::Table { .. } => "table",
Export::Global { .. } => "global",
}
.to_string();
Err(LinkError::IncorrectImportType {
namespace: namespace.clone(),
name: name.clone(),
expected: "memory".to_string(),
found: export_type_name,
})?
}
None => Err(LinkError::ImportNotFound {
namespace: namespace.clone(),
name: name.clone(),
})?,
}
}
Ok(memories.into_boxed_map())
@ -412,7 +442,7 @@ fn import_tables(
module: &ModuleInner,
imports: &mut Imports,
vmctx: *mut vm::Ctx,
) -> Result<BoxedMap<ImportedTableIndex, vm::ImportedTable>, String> {
) -> LinkResult<BoxedMap<ImportedTableIndex, vm::ImportedTable>> {
let mut tables = Map::with_capacity(module.imported_tables.len());
for (_index, (ImportName { namespace, name }, expected_table_desc)) in &module.imported_tables {
let table_import = imports
@ -433,18 +463,33 @@ fn import_tables(
},
});
} else {
return Err(format!(
"incorrect table description for {}:{}",
namespace, name,
));
Err(LinkError::IncorrectTableDescription {
namespace: namespace.clone(),
name: name.clone(),
expected: expected_table_desc.clone(),
found: table_desc.clone(),
})?
}
}
Some(_) => {
return Err(format!("incorrect import type for {}:{}", namespace, name));
}
None => {
return Err(format!("import not found: {}:{}", namespace, name));
Some(export_type) => {
let export_type_name = match export_type {
Export::Function { .. } => "function",
Export::Memory { .. } => "memory",
Export::Table { .. } => "table",
Export::Global { .. } => "global",
}
.to_string();
Err(LinkError::IncorrectImportType {
namespace: namespace.clone(),
name: name.clone(),
expected: "table".to_string(),
found: export_type_name,
})?
}
None => Err(LinkError::ImportNotFound {
namespace: namespace.clone(),
name: name.clone(),
})?,
}
}
Ok(tables.into_boxed_map())
@ -453,7 +498,7 @@ fn import_tables(
fn import_globals(
module: &ModuleInner,
imports: &mut Imports,
) -> Result<BoxedMap<ImportedGlobalIndex, vm::ImportedGlobal>, String> {
) -> LinkResult<BoxedMap<ImportedGlobalIndex, vm::ImportedGlobal>> {
let mut globals = Map::with_capacity(module.imported_globals.len());
for (_, (ImportName { namespace, name }, imported_global_desc)) in &module.imported_globals {
let import = imports
@ -466,18 +511,33 @@ fn import_globals(
global: local.inner(),
});
} else {
return Err(format!(
"unexpected global description for {:?}:{:?}",
namespace, name
));
Err(LinkError::IncorrectGlobalDescription {
namespace: namespace.clone(),
name: name.clone(),
expected: imported_global_desc.clone(),
found: global.clone(),
})?
}
}
Some(_) => {
return Err(format!("incorrect import type for {}:{}", namespace, name));
}
None => {
return Err(format!("import not found: {}:{}", namespace, name));
Some(export_type) => {
let export_type_name = match export_type {
Export::Function { .. } => "function",
Export::Memory { .. } => "memory",
Export::Table { .. } => "table",
Export::Global { .. } => "global",
}
.to_string();
Err(LinkError::IncorrectImportType {
namespace: namespace.clone(),
name: name.clone(),
expected: "global".to_string(),
found: export_type_name,
})?
}
None => Err(LinkError::ImportNotFound {
namespace: namespace.clone(),
name: name.clone(),
})?,
}
}
Ok(globals.into_boxed_map())

162
lib/runtime/src/error.rs Normal file
View File

@ -0,0 +1,162 @@
use crate::types::{FuncSig, GlobalDesc, Memory, MemoryIndex, Table, TableIndex, Type};
pub type Result<T> = std::result::Result<T, Box<Error>>;
pub type CompileResult<T> = std::result::Result<T, Box<CompileError>>;
pub type LinkResult<T> = std::result::Result<T, Box<LinkError>>;
pub type RuntimeResult<T> = std::result::Result<T, Box<RuntimeError>>;
pub type CallResult<T> = std::result::Result<T, Box<CallError>>;
/// This is returned when the chosen compiler is unable to
/// successfully compile the provided webassembly module into
/// a `Module`.
///
/// Comparing two `CompileError`s always evaluates to false.
#[derive(Debug, Clone)]
pub enum CompileError {
ValidationError { msg: String },
InternalError { msg: String },
}
impl PartialEq for CompileError {
fn eq(&self, _other: &CompileError) -> bool {
false
}
}
/// This is returned when the runtime is unable to
/// correctly link the module with the provided imports.
///
/// Comparing two `LinkError`s always evaluates to false.
#[derive(Debug, Clone)]
pub enum LinkError {
IncorrectImportType {
namespace: String,
name: String,
expected: String,
found: String,
},
IncorrectImportSignature {
namespace: String,
name: String,
expected: FuncSig,
found: FuncSig,
},
ImportNotFound {
namespace: String,
name: String,
},
IncorrectMemoryDescription {
namespace: String,
name: String,
expected: Memory,
found: Memory,
},
IncorrectTableDescription {
namespace: String,
name: String,
expected: Table,
found: Table,
},
IncorrectGlobalDescription {
namespace: String,
name: String,
expected: GlobalDesc,
found: GlobalDesc,
},
}
impl PartialEq for LinkError {
fn eq(&self, _other: &LinkError) -> bool {
false
}
}
/// This is the error type returned when calling
/// a webassembly function.
///
/// The main way to do this is `Instance.call`.
///
/// Comparing two `RuntimeError`s always evaluates to false.
#[derive(Debug, Clone)]
pub enum RuntimeError {
OutOfBoundsAccess { memory: MemoryIndex, addr: u32 },
IndirectCallSignature { table: TableIndex },
IndirectCallToNull { table: TableIndex },
Unknown { msg: String },
}
impl PartialEq for RuntimeError {
fn eq(&self, _other: &RuntimeError) -> bool {
false
}
}
/// This error type is produced by calling a wasm function
/// exported from a module.
///
/// If the module traps in some way while running, this will
/// be the `CallError::Runtime(RuntimeError)` variant.
///
/// Comparing two `CallError`s always evaluates to false.
#[derive(Debug, Clone)]
pub enum CallError {
Signature { expected: FuncSig, found: Vec<Type> },
NoSuchExport { name: String },
ExportNotFunc { name: String },
Runtime(RuntimeError),
}
impl PartialEq for CallError {
fn eq(&self, _other: &CallError) -> bool {
false
}
}
/// The amalgamation of all errors that can occur
/// during the compilation, instantiation, or execution
/// of a webassembly module.
///
/// Comparing two `Error`s always evaluates to false.
#[derive(Debug, Clone)]
pub enum Error {
CompileError(CompileError),
LinkError(LinkError),
RuntimeError(RuntimeError),
CallError(CallError),
}
impl PartialEq for Error {
fn eq(&self, _other: &Error) -> bool {
false
}
}
impl From<Box<CompileError>> for Box<Error> {
fn from(compile_err: Box<CompileError>) -> Self {
Box::new(Error::CompileError(*compile_err))
}
}
impl From<Box<LinkError>> for Box<Error> {
fn from(link_err: Box<LinkError>) -> Self {
Box::new(Error::LinkError(*link_err))
}
}
impl From<Box<RuntimeError>> for Box<Error> {
fn from(runtime_err: Box<RuntimeError>) -> Self {
Box::new(Error::RuntimeError(*runtime_err))
}
}
impl From<Box<CallError>> for Box<Error> {
fn from(call_err: Box<CallError>) -> Self {
Box::new(Error::CallError(*call_err))
}
}
impl From<Box<RuntimeError>> for Box<CallError> {
fn from(runtime_err: Box<RuntimeError>) -> Self {
Box::new(CallError::Runtime(*runtime_err))
}
}

View File

@ -1,6 +1,7 @@
use crate::recovery::call_protected;
use crate::{
backing::{ImportBacking, LocalBacking},
error::{CallError, CallResult, Result},
export::{
Context, Export, ExportIter, FuncPointer, GlobalPointer, MemoryPointer, TablePointer,
},
@ -31,10 +32,7 @@ pub struct Instance {
}
impl Instance {
pub(crate) fn new(
module: Rc<ModuleInner>,
mut imports: Box<Imports>,
) -> Result<Instance, String> {
pub(crate) fn new(module: Rc<ModuleInner>, mut imports: Box<Imports>) -> Result<Instance> {
// We need the backing and import_backing to create a vm::Ctx, but we need
// a vm::Ctx to create a backing and an import_backing. The solution is to create an
// uninitialized vm::Ctx and then initialize it in-place.
@ -73,17 +71,22 @@ impl Instance {
///
/// This will eventually return `Result<Option<Vec<Value>>, String>` in
/// order to support multi-value returns.
pub fn call(&mut self, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
let export_index = self
.module
.exports
.get(name)
.ok_or_else(|| format!("there is no export with that name: {}", name))?;
pub fn call(&mut self, name: &str, args: &[Value]) -> CallResult<Option<Value>> {
let export_index =
self.module
.exports
.get(name)
.ok_or_else(|| CallError::NoSuchExport {
name: name.to_string(),
})?;
let func_index = if let ExportIndex::Func(func_index) = export_index {
*func_index
} else {
return Err("that export is not a function".to_string());
return Err(CallError::ExportNotFunc {
name: name.to_string(),
}
.into());
};
self.call_with_index(func_index, args)
@ -103,7 +106,7 @@ impl Instance {
&mut self,
func_index: FuncIndex,
args: &[Value],
) -> Result<Option<Value>, String> {
) -> CallResult<Option<Value>> {
let (func_ref, ctx, signature) = self.inner.get_func_from_index(&self.module, func_index);
let func_ptr = CodePtr::from_ptr(func_ref.inner() as _);
@ -118,7 +121,10 @@ impl Instance {
);
if !signature.check_sig(args) {
return Err("incorrect signature".to_string());
Err(CallError::Signature {
expected: signature.clone(),
found: args.iter().map(|val| val.ty()).collect(),
})?
}
let libffi_args: Vec<_> = args
@ -132,7 +138,7 @@ impl Instance {
.chain(iter::once(libffi_arg(&vmctx_ptr)))
.collect();
call_protected(|| {
Ok(call_protected(|| {
signature
.returns
.first()
@ -149,7 +155,7 @@ impl Instance {
}
None
})
})
})?)
}
}

View File

@ -7,6 +7,7 @@ pub mod macros;
#[doc(hidden)]
pub mod backend;
mod backing;
pub mod error;
pub mod export;
pub mod import;
pub mod instance;
@ -23,14 +24,15 @@ pub mod vm;
#[doc(hidden)]
pub mod vmcalls;
pub use self::import::Imports;
use self::error::CompileResult;
pub use self::instance::Instance;
#[doc(inline)]
pub use self::module::Module;
pub use self::error::Result;
use std::rc::Rc;
/// Compile a webassembly module using the provided compiler.
pub fn compile(wasm: &[u8], compiler: &dyn backend::Compiler) -> Result<module::Module, String> {
pub fn compile(wasm: &[u8], compiler: &dyn backend::Compiler) -> CompileResult<module::Module> {
compiler
.compile(wasm)
.map(|inner| module::Module::new(Rc::new(inner)))

View File

@ -1,5 +1,6 @@
use crate::{
backend::FuncResolver,
error::Result,
import::Imports,
sig_registry::SigRegistry,
structures::Map,
@ -47,7 +48,7 @@ impl Module {
}
/// Instantiate a webassembly module with the provided imports.
pub fn instantiate(&self, imports: Imports) -> Result<Instance, String> {
pub fn instantiate(&self, imports: Imports) -> Result<Instance> {
Instance::new(Rc::clone(&self.0), Box::new(imports))
}
}

View File

@ -4,7 +4,10 @@
//! are very special, the async signal unsafety of Rust's TLS implementation generally does not affect the correctness here
//! unless you have memory unsafety elsewhere in your code.
use crate::sighandler::install_sighandler;
use crate::{
error::{RuntimeError, RuntimeResult},
sighandler::install_sighandler,
};
use nix::libc::siginfo_t;
use nix::sys::signal::{Signal, SIGBUS, SIGFPE, SIGILL, SIGSEGV};
use std::cell::{Cell, UnsafeCell};
@ -23,7 +26,7 @@ thread_local! {
pub static CAUGHT_ADDRESS: Cell<usize> = Cell::new(0);
}
pub fn call_protected<T>(f: impl FnOnce() -> T) -> Result<T, String> {
pub fn call_protected<T>(f: impl FnOnce() -> T) -> RuntimeResult<T> {
unsafe {
let jmp_buf = SETJMP_BUFFER.with(|buf| buf.get());
let prev_jmp_buf = *jmp_buf;
@ -45,7 +48,11 @@ pub fn call_protected<T>(f: impl FnOnce() -> T) -> Result<T, String> {
Err(_) => "error while getting the Signal",
_ => "unkown trapped signal",
};
Err(format!("trap at {:#x} - {}", addr, signal))
// When the trap-handler is fully implemented, this will return more information.
Err(RuntimeError::Unknown {
msg: format!("trap at {:#x} - {}", addr, signal),
}
.into())
} else {
let ret = f(); // TODO: Switch stack?
*jmp_buf = prev_jmp_buf;