Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove to_wasm_error #1963

Merged
merged 5 commits into from
Dec 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* [#1941](https://github.com/wasmerio/wasmer/pull/1941) Turn `get_remaining_points`/`set_remaining_points` of the `Metering` middleware into free functions to allow using them in an ahead-of-time compilation setup
* [#1955](https://github.com/wasmerio/wasmer/pull/1955) Set `jit` as a default feature of the `wasmer-wasm-c-api` crate
* [#1944](https://github.com/wasmerio/wasmer/pull/1944) Require `WasmerEnv` to be `Send + Sync` even in dynamic functions.
* [#1963](https://github.com/wasmerio/wasmer/pull/1963) Removed `to_wasm_error` in favour of `impl From<BinaryReaderError> for WasmError`

### Fixed

Expand Down
7 changes: 2 additions & 5 deletions lib/compiler-cranelift/src/translator/code_translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ use smallvec::SmallVec;
use std::vec::Vec;

use wasmer_compiler::wasmparser::{MemoryImmediate, Operator};
use wasmer_compiler::{to_wasm_error, WasmResult};
use wasmer_compiler::WasmResult;
use wasmer_compiler::{wasm_unsupported, ModuleTranslationState};
use wasmer_types::{FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, TableIndex};

Expand Down Expand Up @@ -383,10 +383,7 @@ pub fn translate_operator<FE: FuncEnvironment + ?Sized>(
}
Operator::BrIf { relative_depth } => translate_br_if(*relative_depth, builder, state),
Operator::BrTable { table } => {
let mut depths = table
.targets()
.collect::<Result<Vec<_>, _>>()
.map_err(to_wasm_error)?;
let mut depths = table.targets().collect::<Result<Vec<_>, _>>()?;
let default = depths.pop().unwrap().0;
let mut min_depth = default;
for (depth, _) in depths.iter() {
Expand Down
10 changes: 5 additions & 5 deletions lib/compiler-cranelift/src/translator/func_translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
use tracing::info;
use wasmer_compiler::wasmparser;
use wasmer_compiler::{
to_wasm_error, wasm_unsupported, MiddlewareBinaryReader, ModuleMiddlewareChain,
ModuleTranslationState, WasmResult,
wasm_unsupported, MiddlewareBinaryReader, ModuleMiddlewareChain, ModuleTranslationState,
WasmResult,
};
use wasmer_types::LocalFunctionIndex;

Expand Down Expand Up @@ -174,11 +174,11 @@ fn parse_local_decls<FE: FuncEnvironment + ?Sized>(
environ: &mut FE,
) -> WasmResult<()> {
let mut next_local = num_params;
let local_count = reader.read_local_count().map_err(to_wasm_error)?;
let local_count = reader.read_local_count()?;

for _ in 0..local_count {
builder.set_srcloc(cur_srcloc(reader));
let (count, ty) = reader.read_local_decl().map_err(to_wasm_error)?;
let (count, ty) = reader.read_local_decl()?;
declare_locals(builder, count, ty, &mut next_local, environ)?;
}

Expand Down Expand Up @@ -239,7 +239,7 @@ fn parse_function_body<FE: FuncEnvironment + ?Sized>(
// Keep going until the final `End` operator which pops the outermost block.
while !state.control_stack.is_empty() {
builder.set_srcloc(cur_srcloc(&reader));
let op = reader.read_operator().map_err(to_wasm_error)?;
let op = reader.read_operator()?;
environ.before_translate_operator(&op, builder, state)?;
translate_operator(module_translation_state, &op, builder, state, environ)?;
environ.after_translate_operator(&op, builder, state)?;
Expand Down
15 changes: 6 additions & 9 deletions lib/compiler-llvm/src/translator/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use crate::config::{CompiledKind, LLVM};
use crate::object_file::{load_object_file, CompiledFunction};
use wasmer_compiler::wasmparser::{MemoryImmediate, Operator};
use wasmer_compiler::{
to_wasm_error, wptype_to_type, CompileError, FunctionBodyData, MiddlewareBinaryReader,
ModuleMiddlewareChain, ModuleTranslationState, RelocationTarget, Symbol, SymbolRegistry,
wptype_to_type, CompileError, FunctionBodyData, MiddlewareBinaryReader, ModuleMiddlewareChain,
ModuleTranslationState, RelocationTarget, Symbol, SymbolRegistry,
};
use wasmer_types::entity::PrimaryMap;
use wasmer_types::{
Expand Down Expand Up @@ -182,9 +182,9 @@ impl FuncTranslator {
}

let mut locals = vec![];
let num_locals = reader.read_local_count().map_err(to_wasm_error)?;
let num_locals = reader.read_local_count()?;
for _ in 0..num_locals {
let (count, ty) = reader.read_local_decl().map_err(to_wasm_error)?;
let (count, ty) = reader.read_local_decl()?;
let ty = wptype_to_type(ty).map_err(to_compile_error)?;
let ty = type_to_llvm(&intrinsics, ty)?;
for _ in 0..count {
Expand Down Expand Up @@ -224,7 +224,7 @@ impl FuncTranslator {

while fcg.state.has_control_frames() {
let pos = reader.current_position() as u32;
let op = reader.read_operator().map_err(to_wasm_error)?;
let op = reader.read_operator()?;
fcg.translate_operator(op, pos)?;
}

Expand Down Expand Up @@ -1530,10 +1530,7 @@ impl<'ctx, 'a> LLVMFunctionCodeGenerator<'ctx, 'a> {
.get_insert_block()
.ok_or_else(|| CompileError::Codegen("not currently in a block".to_string()))?;

let mut label_depths = table
.targets()
.collect::<Result<Vec<_>, _>>()
.map_err(to_wasm_error)?;
let mut label_depths = table.targets().collect::<Result<Vec<_>, _>>()?;
let default_depth = label_depths.pop().unwrap().0;

let index = self.state.pop1()?;
Expand Down
8 changes: 7 additions & 1 deletion lib/compiler/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use thiserror::Error;
pub enum CompileError {
/// A Wasm translation error occured.
#[cfg_attr(feature = "std", error("WebAssembly translation error: {0}"))]
Wasm(#[cfg_attr(feature = "std", from)] WasmError),
Wasm(WasmError),

/// A compilation error occured.
#[cfg_attr(feature = "std", error("Compilation error: {0}"))]
Expand All @@ -42,6 +42,12 @@ pub enum CompileError {
Resource(String),
}

impl From<WasmError> for CompileError {
fn from(original: WasmError) -> Self {
Self::Wasm(original)
}
}

/// A WebAssembly translation error.
///
/// When a WebAssembly function can't be translated, one of these error codes will be returned
Expand Down
6 changes: 3 additions & 3 deletions lib/compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ pub use crate::target::{
};
#[cfg(feature = "translator")]
pub use crate::translator::{
to_wasm_error, translate_module, wptype_to_type, FunctionBodyData, FunctionMiddleware,
MiddlewareBinaryReader, MiddlewareReaderState, ModuleEnvironment, ModuleInfoTranslation,
ModuleMiddleware, ModuleMiddlewareChain, ModuleTranslationState,
translate_module, wptype_to_type, FunctionBodyData, FunctionMiddleware, MiddlewareBinaryReader,
MiddlewareReaderState, ModuleEnvironment, ModuleInfoTranslation, ModuleMiddleware,
ModuleMiddlewareChain, ModuleTranslationState,
};
pub use crate::trap::TrapInformation;
pub use crate::unwind::CompiledFunctionUnwindInfo;
Expand Down
53 changes: 47 additions & 6 deletions lib/compiler/src/translator/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::WasmError;
use crate::{CompileError, WasmError};
use wasmparser::BinaryReaderError;

/// Return an `Err(WasmError::Unsupported(msg))` where `msg` the string built by calling `format!`
Expand All @@ -8,10 +8,51 @@ macro_rules! wasm_unsupported {
($($arg:tt)*) => { $crate::WasmError::Unsupported(format!($($arg)*)) }
}

/// Converts a Wasm binary reading error to a runtime Wasm error
pub fn to_wasm_error(e: BinaryReaderError) -> WasmError {
WasmError::InvalidWebAssembly {
message: e.message().into(),
offset: e.offset(),
impl From<BinaryReaderError> for WasmError {
fn from(original: BinaryReaderError) -> Self {
Self::InvalidWebAssembly {
message: original.message().into(),
offset: original.offset(),
}
}
}

impl From<BinaryReaderError> for CompileError {
fn from(original: BinaryReaderError) -> Self {
// `From` does not seem to be transitive by default, so we convert
// BinaryReaderError -> WasmError -> CompileError
Self::from(WasmError::from(original))
}
}

#[cfg(test)]
mod tests {
use super::*;
use wasmparser::BinaryReader;

#[test]
fn can_convert_binary_reader_error_to_wasm_error() {
let mut reader = BinaryReader::new(b"\0\0\0\0");
let binary_reader_error = reader.read_bytes(10).unwrap_err();
match WasmError::from(binary_reader_error) {
WasmError::InvalidWebAssembly { message, offset } => {
assert_eq!(message, "Unexpected EOF");
assert_eq!(offset, 0);
}
err => panic!("Unexpected error: {:?}", err),
}
}

#[test]
fn can_convert_binary_reader_error_to_compile_error() {
let mut reader = BinaryReader::new(b"\0\0\0\0");
let binary_reader_error = reader.read_bytes(10).unwrap_err();
match CompileError::from(binary_reader_error) {
CompileError::Wasm(WasmError::InvalidWebAssembly { message, offset }) => {
assert_eq!(message, "Unexpected EOF");
assert_eq!(offset, 0);
}
err => panic!("Unexpected error: {:?}", err),
}
}
}
1 change: 0 additions & 1 deletion lib/compiler/src/translator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ mod error;
mod sections;

pub use self::environ::{FunctionBodyData, ModuleEnvironment, ModuleInfoTranslation};
pub use self::error::to_wasm_error;
pub use self::middleware::{
FunctionMiddleware, MiddlewareBinaryReader, MiddlewareReaderState, ModuleMiddleware,
ModuleMiddlewareChain,
Expand Down
10 changes: 3 additions & 7 deletions lib/compiler/src/translator/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//! Translation skeleton that traverses the whole WebAssembly module and call helper functions
//! to deal with each part of it.
use super::environ::ModuleEnvironment;
use super::error::to_wasm_error;
use super::sections::{
parse_data_section, parse_element_section, parse_export_section, parse_function_section,
parse_global_section, parse_import_section, parse_memory_section, parse_name_section,
Expand All @@ -23,7 +22,7 @@ pub fn translate_module<'data>(
let mut module_translation_state = ModuleTranslationState::new();

for payload in Parser::new(0).parse_all(data) {
match payload.map_err(to_wasm_error)? {
match payload? {
Payload::Version { .. } | Payload::End => {}

Payload::TypeSection(types) => {
Expand Down Expand Up @@ -69,7 +68,7 @@ pub fn translate_module<'data>(
let offset = code.original_position();
environ.define_function_body(
&module_translation_state,
code.read_bytes(size).map_err(to_wasm_error)?,
code.read_bytes(size)?,
offset,
)?;
}
Expand All @@ -94,10 +93,7 @@ pub fn translate_module<'data>(
name: "name",
data,
data_offset,
} => parse_name_section(
NameSectionReader::new(data, data_offset).map_err(to_wasm_error)?,
environ,
)?,
} => parse_name_section(NameSectionReader::new(data, data_offset)?, environ)?,

Payload::CustomSection { name, data, .. } => environ.custom_section(name, data)?,

Expand Down
Loading