Compare commits

...

12 Commits

Author SHA1 Message Date
Cadey Ratio 0b6dd64219 fix no_std building 2019-10-24 10:29:04 -04:00
adam-rhebo d2ea44e37c Avoid temporary allocations during function context initialization (#217)
* Avoid temporary allocation when push locals during function invocation.

* Extend value stack for all locals at once.
2019-10-22 17:23:25 +02:00
Sergei Pepyakin f19e1c27fc
Fix tiny_keccak (#215) 2019-09-28 19:05:17 +02:00
Sergei Pepyakin 59ab1c8d78
Don't use `cache: cargo` in Travis CI's config (#213) 2019-09-26 14:13:29 +02:00
Sergei Pepyakin e6bdaf76f6
Bump wabt up to 0.9. (#212) 2019-09-26 13:18:57 +02:00
Pierre Krieger 390f4b2c4a Use a Cow for the resumable parameters (#210)
* Use a Cow for the resumable parameters

* Try fixing tests
2019-09-09 12:34:49 +02:00
Sergei Pepyakin 08c09adbf2
Bump wasmi-validation (#209) 2019-09-05 23:49:30 +02:00
Sergei Pepyakin 990e6698cb
Bump wasmi (#208) 2019-09-05 23:26:48 +02:00
DemiMarie-parity 7b1e5820c3 Update parity-wasm (#207) 2019-09-05 22:59:10 +02:00
thiolliere 9d998c7289 Update README.md (#205) 2019-08-27 22:20:17 +02:00
Sergei Pepyakin b1ea069c4a
Update parity-wasm (#198) 2019-07-17 14:24:36 +03:00
Sergei Pepyakin b67af25899
Apply cargo-fix on wasmi (#191)
* cargo-fix wasmi

* fmt

* Remove allow_failures

* Add dyn in benches

* Fix nightly
2019-07-10 17:45:06 +03:00
29 changed files with 137 additions and 104 deletions

View File

@ -11,8 +11,6 @@ matrix:
- rust: stable - rust: stable
- rust: stable - rust: stable
env: TARGET=armv7-unknown-linux-gnueabihf env: TARGET=armv7-unknown-linux-gnueabihf
allow_failures:
- rust: nightly
install: install:
- if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then rustup target add wasm32-unknown-unknown; fi - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then rustup target add wasm32-unknown-unknown; fi
@ -42,7 +40,17 @@ after_success: |
ghp-import -n target/doc && ghp-import -n target/doc &&
git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
cache: cargo cache:
# Don't use `cache: cargo` since it adds the `target` directory and that can be huge.
# Saving and loading this directory dwarfes actual compilation and test times. But what is more
# important, is that travis timeouts the build since the job doesn't produce any output for more
# than 10 minutes.
#
# So we just cache ~/.cargo directory
directories:
- /home/travis/.cargo
before_cache: before_cache:
# Travis can't cache files that are not readable by "others" # Travis can't cache files that are not readable by "others"
- chmod -R a+r $HOME/.cargo - chmod -R a+r $HOME/.cargo
# According to the Travis CI docs for building Rust project this is done by,
- rm -rf /home/travis/.cargo/registry

View File

@ -1,6 +1,6 @@
[package] [package]
name = "wasmi" name = "wasmi"
version = "0.5.0" version = "0.5.1"
authors = ["Nikolay Volf <nikvolf@gmail.com>", "Svyatoslav Nikolsky <svyatonik@yandex.ru>", "Sergey Pepyakin <s.pepyakin@gmail.com>"] authors = ["Nikolay Volf <nikvolf@gmail.com>", "Svyatoslav Nikolsky <svyatonik@yandex.ru>", "Sergey Pepyakin <s.pepyakin@gmail.com>"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
readme = "README.md" readme = "README.md"
@ -11,18 +11,17 @@ keywords = ["wasm", "webassembly", "bytecode", "interpreter"]
exclude = [ "/res/*", "/tests/*", "/fuzz/*", "/benches/*" ] exclude = [ "/res/*", "/tests/*", "/fuzz/*", "/benches/*" ]
[dependencies] [dependencies]
wasmi-validation = { version = "0.1", path = "validation", default-features = false } wasmi-validation = { version = "0.2", path = "validation", default-features = false }
parity-wasm = { version = "0.31", default-features = false } parity-wasm = { version = "0.40.1", default-features = false }
memory_units = "0.3.0" memory_units = "0.3.0"
libm = { version = "0.1.2", optional = true } libm = { version = "0.1.2", optional = true }
num-rational = "0.2.2" num-rational = { version = "0.2.2", default-features = false }
num-traits = "0.2.8" num-traits = { version = "0.2.8", default-features = false }
libc = "0.2.58"
[dev-dependencies] [dev-dependencies]
assert_matches = "1.1" assert_matches = "1.1"
rand = "0.4.2" rand = "0.4.2"
wabt = "0.6" wabt = "0.9"
[features] [features]
default = ["std"] default = ["std"]
@ -31,10 +30,13 @@ std = [
"parity-wasm/std", "parity-wasm/std",
"wasmi-validation/std", "wasmi-validation/std",
"num-rational/std", "num-rational/std",
"num-rational/bigint-std",
"num-traits/std" "num-traits/std"
] ]
# Enable for no_std support # Enable for no_std support
core = [ core = [
# `core` doesn't support vec_memory
"vec_memory",
"wasmi-validation/core", "wasmi-validation/core",
"libm" "libm"
] ]

View File

@ -26,8 +26,8 @@ This crate supports `no_std` environments.
Enable the `core` feature and disable default features: Enable the `core` feature and disable default features:
```toml ```toml
[dependencies] [dependencies]
parity-wasm = { wasmi = {
version = "0.31", version = "*",
default-features = false, default-features = false,
features = "core" features = "core"
} }

View File

@ -6,7 +6,7 @@ authors = ["Sergey Pepyakin <s.pepyakin@gmail.com>"]
[dependencies] [dependencies]
wasmi = { path = ".." } wasmi = { path = ".." }
assert_matches = "1.2" assert_matches = "1.2"
wabt = "0.6" wabt = "0.9"
[profile.bench] [profile.bench]
debug = true debug = true

View File

@ -13,7 +13,7 @@ use wasmi::{ImportsBuilder, Module, ModuleInstance, NopExternals, RuntimeValue};
use test::Bencher; use test::Bencher;
// Load a module from a file. // Load a module from a file.
fn load_from_file(filename: &str) -> Result<Module, Box<error::Error>> { fn load_from_file(filename: &str) -> Result<Module, Box<dyn error::Error>> {
use std::io::prelude::*; use std::io::prelude::*;
let mut file = File::open(filename)?; let mut file = File::open(filename)?;
let mut buf = Vec::new(); let mut buf = Vec::new();

View File

@ -33,7 +33,7 @@ pub extern "C" fn prepare_tiny_keccak() -> *const TinyKeccakTestData {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn bench_tiny_keccak(test_data: *const TinyKeccakTestData) { pub extern "C" fn bench_tiny_keccak(test_data: *mut TinyKeccakTestData) {
unsafe { unsafe {
let mut keccak = Keccak::new_keccak256(); let mut keccak = Keccak::new_keccak256();
keccak.update((*test_data).data); keccak.update((*test_data).data);

View File

@ -10,7 +10,7 @@ cargo-fuzz = true
[dependencies] [dependencies]
wasmi = { path = ".." } wasmi = { path = ".." }
wabt = "0.6.0" wabt = "0.9"
wasmparser = "0.14.1" wasmparser = "0.14.1"
tempdir = "0.3.6" tempdir = "0.3.6"

View File

@ -7,4 +7,4 @@ authors = ["Sergey Pepyakin <s.pepyakin@gmail.com>"]
honggfuzz = "=0.5.9" # Strict equal since hfuzz requires dep and cmd versions to match. honggfuzz = "=0.5.9" # Strict equal since hfuzz requires dep and cmd versions to match.
wasmi = { path = ".." } wasmi = { path = ".." }
tempdir = "0.3.6" tempdir = "0.3.6"
wabt = "0.6.0" wabt = "0.9"

View File

@ -1,6 +1,8 @@
#[allow(unused_imports)] use alloc::{
use alloc::prelude::v1::*; borrow::Cow,
use alloc::rc::{Rc, Weak}; rc::{Rc, Weak},
vec::Vec,
};
use core::fmt; use core::fmt;
use host::Externals; use host::Externals;
use isa; use isa;
@ -194,12 +196,13 @@ impl FuncInstance {
/// [`resume_execution`]: struct.FuncInvocation.html#method.resume_execution /// [`resume_execution`]: struct.FuncInvocation.html#method.resume_execution
pub fn invoke_resumable<'args>( pub fn invoke_resumable<'args>(
func: &FuncRef, func: &FuncRef,
args: &'args [RuntimeValue], args: impl Into<Cow<'args, [RuntimeValue]>>,
) -> Result<FuncInvocation<'args>, Trap> { ) -> Result<FuncInvocation<'args>, Trap> {
let args = args.into();
check_function_args(func.signature(), &args)?; check_function_args(func.signature(), &args)?;
match *func.as_internal() { match *func.as_internal() {
FuncInstanceInternal::Internal { .. } => { FuncInstanceInternal::Internal { .. } => {
let interpreter = Interpreter::new(func, args, None)?; let interpreter = Interpreter::new(func, &*args, None)?;
Ok(FuncInvocation { Ok(FuncInvocation {
kind: FuncInvocationKind::Internal(interpreter), kind: FuncInvocationKind::Internal(interpreter),
}) })
@ -256,7 +259,7 @@ pub struct FuncInvocation<'args> {
enum FuncInvocationKind<'args> { enum FuncInvocationKind<'args> {
Internal(Interpreter), Internal(Interpreter),
Host { Host {
args: &'args [RuntimeValue], args: Cow<'args, [RuntimeValue]>,
host_func_index: usize, host_func_index: usize,
finished: bool, finished: bool,
}, },
@ -303,7 +306,7 @@ impl<'args> FuncInvocation<'args> {
return Err(ResumableError::AlreadyStarted); return Err(ResumableError::AlreadyStarted);
} }
*finished = true; *finished = true;
Ok(externals.invoke_index(*host_func_index, args.clone().into())?) Ok(externals.invoke_index(*host_func_index, args.as_ref().into())?)
} }
} }
} }

View File

@ -114,11 +114,11 @@ pub trait HostError: 'static + ::core::fmt::Display + ::core::fmt::Debug + Send
} }
} }
impl HostError { impl dyn HostError {
/// Attempt to downcast this `HostError` to a concrete type by reference. /// Attempt to downcast this `HostError` to a concrete type by reference.
pub fn downcast_ref<T: HostError>(&self) -> Option<&T> { pub fn downcast_ref<T: HostError>(&self) -> Option<&T> {
if self.__private_get_type_id__() == TypeId::of::<T>() { if self.__private_get_type_id__() == TypeId::of::<T>() {
unsafe { Some(&*(self as *const HostError as *const T)) } unsafe { Some(&*(self as *const dyn HostError as *const T)) }
} else { } else {
None None
} }
@ -128,7 +128,7 @@ impl HostError {
/// reference. /// reference.
pub fn downcast_mut<T: HostError>(&mut self) -> Option<&mut T> { pub fn downcast_mut<T: HostError>(&mut self) -> Option<&mut T> {
if self.__private_get_type_id__() == TypeId::of::<T>() { if self.__private_get_type_id__() == TypeId::of::<T>() {
unsafe { Some(&mut *(self as *mut HostError as *mut T)) } unsafe { Some(&mut *(self as *mut dyn HostError as *mut T)) }
} else { } else {
None None
} }
@ -257,5 +257,5 @@ mod tests {
} }
// Tests that `HostError` trait is object safe. // Tests that `HostError` trait is object safe.
fn _host_error_is_object_safe(_: &HostError) {} fn _host_error_is_object_safe(_: &dyn HostError) {}
} }

View File

@ -1,7 +1,4 @@
#[allow(unused_imports)] use alloc::{collections::BTreeMap, string::String};
use alloc::prelude::v1::*;
use alloc::collections::BTreeMap;
use func::FuncRef; use func::FuncRef;
use global::GlobalRef; use global::GlobalRef;
@ -103,7 +100,7 @@ pub trait ImportResolver {
/// [`ImportResolver`]: trait.ImportResolver.html /// [`ImportResolver`]: trait.ImportResolver.html
/// [`ModuleImportResolver`]: trait.ModuleImportResolver.html /// [`ModuleImportResolver`]: trait.ModuleImportResolver.html
pub struct ImportsBuilder<'a> { pub struct ImportsBuilder<'a> {
modules: BTreeMap<String, &'a ModuleImportResolver>, modules: BTreeMap<String, &'a dyn ModuleImportResolver>,
} }
impl<'a> Default for ImportsBuilder<'a> { impl<'a> Default for ImportsBuilder<'a> {
@ -124,7 +121,7 @@ impl<'a> ImportsBuilder<'a> {
pub fn with_resolver<N: Into<String>>( pub fn with_resolver<N: Into<String>>(
mut self, mut self,
name: N, name: N,
resolver: &'a ModuleImportResolver, resolver: &'a dyn ModuleImportResolver,
) -> Self { ) -> Self {
self.modules.insert(name.into(), resolver); self.modules.insert(name.into(), resolver);
self self
@ -133,11 +130,15 @@ impl<'a> ImportsBuilder<'a> {
/// Register an resolver by a name. /// Register an resolver by a name.
/// ///
/// Mutable borrowed version. /// Mutable borrowed version.
pub fn push_resolver<N: Into<String>>(&mut self, name: N, resolver: &'a ModuleImportResolver) { pub fn push_resolver<N: Into<String>>(
&mut self,
name: N,
resolver: &'a dyn ModuleImportResolver,
) {
self.modules.insert(name.into(), resolver); self.modules.insert(name.into(), resolver);
} }
fn resolver(&self, name: &str) -> Option<&ModuleImportResolver> { fn resolver(&self, name: &str) -> Option<&dyn ModuleImportResolver> {
self.modules.get(name).cloned() self.modules.get(name).cloned()
} }
} }

View File

@ -67,8 +67,7 @@
//! - Reserved immediates are ignored for `call_indirect`, `current_memory`, `grow_memory`. //! - Reserved immediates are ignored for `call_indirect`, `current_memory`, `grow_memory`.
//! //!
#[allow(unused_imports)] use alloc::vec::Vec;
use alloc::prelude::v1::*;
/// Should we keep a value before "discarding" a stack frame? /// Should we keep a value before "discarding" a stack frame?
/// ///

View File

@ -96,8 +96,6 @@
#![warn(missing_docs)] #![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
//// alloc is required in no_std
#![cfg_attr(not(feature = "std"), feature(alloc, alloc_prelude))]
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
#[macro_use] #[macro_use]
@ -119,8 +117,11 @@ extern crate parity_wasm;
extern crate wasmi_validation as validation; extern crate wasmi_validation as validation;
#[allow(unused_imports)] use alloc::{
use alloc::prelude::v1::*; boxed::Box,
string::{String, ToString},
vec::Vec,
};
use core::fmt; use core::fmt;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::error; use std::error;
@ -239,7 +240,7 @@ pub enum TrapKind {
/// Typically returned from an implementation of [`Externals`]. /// Typically returned from an implementation of [`Externals`].
/// ///
/// [`Externals`]: trait.Externals.html /// [`Externals`]: trait.Externals.html
Host(Box<host::HostError>), Host(Box<dyn host::HostError>),
} }
impl TrapKind { impl TrapKind {
@ -273,7 +274,7 @@ pub enum Error {
/// Trap. /// Trap.
Trap(Trap), Trap(Trap),
/// Custom embedder error. /// Custom embedder error.
Host(Box<host::HostError>), Host(Box<dyn host::HostError>),
} }
impl Error { impl Error {
@ -285,7 +286,7 @@ impl Error {
/// [`Host`]: enum.Error.html#variant.Host /// [`Host`]: enum.Error.html#variant.Host
/// [`Trap`]: enum.Error.html#variant.Trap /// [`Trap`]: enum.Error.html#variant.Trap
/// [`TrapKind::Host`]: enum.TrapKind.html#variant.Host /// [`TrapKind::Host`]: enum.TrapKind.html#variant.Host
pub fn as_host_error(&self) -> Option<&host::HostError> { pub fn as_host_error(&self) -> Option<&dyn host::HostError> {
match *self { match *self {
Error::Host(ref host_err) => Some(&**host_err), Error::Host(ref host_err) => Some(&**host_err),
Error::Trap(ref trap) => match *trap.kind() { Error::Trap(ref trap) => match *trap.kind() {

View File

@ -1,6 +1,4 @@
#[allow(unused_imports)] use alloc::{rc::Rc, string::ToString, vec::Vec};
use alloc::prelude::v1::*;
use alloc::rc::Rc;
use core::{ use core::{
cell::{Cell, RefCell}, cell::{Cell, RefCell},
cmp, fmt, cmp, fmt,

View File

@ -1,6 +1,6 @@
//! An implementation of `ByteBuf` based on a plain `Vec`. //! An implementation of `ByteBuf` based on a plain `Vec`.
use alloc::prelude::v1::*; use alloc::vec::Vec;
pub struct ByteBuf { pub struct ByteBuf {
buf: Vec<u8>, buf: Vec<u8>,

View File

@ -1,6 +1,9 @@
#[allow(unused_imports)] use alloc::{
use alloc::prelude::v1::*; borrow::ToOwned,
use alloc::rc::Rc; rc::Rc,
string::{String, ToString},
vec::Vec,
};
use core::cell::RefCell; use core::cell::RefCell;
use core::fmt; use core::fmt;
use Trap; use Trap;
@ -418,7 +421,11 @@ impl ModuleInstance {
.map(|es| es.entries()) .map(|es| es.entries())
.unwrap_or(&[]) .unwrap_or(&[])
{ {
let offset_val = match eval_init_expr(element_segment.offset(), &module_ref) { let offset = element_segment
.offset()
.as_ref()
.expect("passive segments are rejected due to validation");
let offset_val = match eval_init_expr(offset, &module_ref) {
RuntimeValue::I32(v) => v as u32, RuntimeValue::I32(v) => v as u32,
_ => panic!("Due to validation elem segment offset should evaluate to i32"), _ => panic!("Due to validation elem segment offset should evaluate to i32"),
}; };
@ -447,7 +454,11 @@ impl ModuleInstance {
} }
for data_segment in module.data_section().map(|ds| ds.entries()).unwrap_or(&[]) { for data_segment in module.data_section().map(|ds| ds.entries()).unwrap_or(&[]) {
let offset_val = match eval_init_expr(data_segment.offset(), &module_ref) { let offset = data_segment
.offset()
.as_ref()
.expect("passive segments are rejected due to validation");
let offset_val = match eval_init_expr(offset, &module_ref) {
RuntimeValue::I32(v) => v as u32, RuntimeValue::I32(v) => v as u32,
_ => panic!("Due to validation data segment offset should evaluate to i32"), _ => panic!("Due to validation data segment offset should evaluate to i32"),
}; };

View File

@ -1,5 +1,4 @@
#[allow(unused_imports)] use alloc::{string::String, vec::Vec};
use alloc::prelude::v1::*;
use parity_wasm::elements::{BlockType, FuncBody, Instruction}; use parity_wasm::elements::{BlockType, FuncBody, Instruction};
@ -252,13 +251,14 @@ impl Compiler {
); );
self.sink.emit_br_nez(target); self.sink.emit_br_nez(target);
} }
BrTable(ref table, default) => { BrTable(ref br_table_data) => {
// At this point, the condition value is at the top of the stack. // At this point, the condition value is at the top of the stack.
// But at the point of actual jump the condition will already be // But at the point of actual jump the condition will already be
// popped off. // popped off.
let value_stack_height = context.value_stack.len().saturating_sub(1); let value_stack_height = context.value_stack.len().saturating_sub(1);
let targets = table let targets = br_table_data
.table
.iter() .iter()
.map(|depth| { .map(|depth| {
require_target( require_target(
@ -270,7 +270,7 @@ impl Compiler {
}) })
.collect::<Result<Vec<_>, _>>(); .collect::<Result<Vec<_>, _>>();
let default_target = require_target( let default_target = require_target(
default, br_table_data.default,
value_stack_height, value_stack_height,
&context.frame_stack, &context.frame_stack,
&self.label_stack, &self.label_stack,

View File

@ -1,5 +1,4 @@
#[allow(unused_imports)] use alloc::vec::Vec;
use alloc::prelude::v1::*;
use crate::{ use crate::{
isa, isa,

View File

@ -1,5 +1,4 @@
#[allow(unused_imports)] use alloc::{boxed::Box, vec::Vec};
use alloc::prelude::v1::*;
use core::fmt; use core::fmt;
use core::ops; use core::ops;
use core::{u32, usize}; use core::{u32, usize};
@ -1290,14 +1289,8 @@ impl FunctionContext {
debug_assert!(!self.is_initialized); debug_assert!(!self.is_initialized);
let num_locals = locals.iter().map(|l| l.count() as usize).sum(); let num_locals = locals.iter().map(|l| l.count() as usize).sum();
let locals = vec![Default::default(); num_locals];
// TODO: Replace with extend. value_stack.extend(num_locals)?;
for local in locals {
value_stack
.push(local)
.map_err(|_| TrapKind::StackOverflow)?;
}
self.is_initialized = true; self.is_initialized = true;
Ok(()) Ok(())
@ -1443,6 +1436,18 @@ impl ValueStack {
Ok(()) Ok(())
} }
fn extend(&mut self, len: usize) -> Result<(), TrapKind> {
let cells = self
.buf
.get_mut(self.sp..self.sp + len)
.ok_or_else(|| TrapKind::StackOverflow)?;
for cell in cells {
*cell = Default::default();
}
self.sp += len;
Ok(())
}
#[inline] #[inline]
fn len(&self) -> usize { fn len(&self) -> usize {
self.sp self.sp

View File

@ -1,6 +1,4 @@
#[allow(unused_imports)] use alloc::{rc::Rc, vec::Vec};
use alloc::prelude::v1::*;
use alloc::rc::Rc;
use core::cell::RefCell; use core::cell::RefCell;
use core::fmt; use core::fmt;
use core::u32; use core::u32;

View File

@ -285,7 +285,7 @@ fn resume_call_host_func() {
let export = instance.export_by_name("test").unwrap(); let export = instance.export_by_name("test").unwrap();
let func_instance = export.as_func().unwrap(); let func_instance = export.as_func().unwrap();
let mut invocation = FuncInstance::invoke_resumable(&func_instance, &[]).unwrap(); let mut invocation = FuncInstance::invoke_resumable(&func_instance, &[][..]).unwrap();
let result = invocation.start_execution(&mut env); let result = invocation.start_execution(&mut env);
match result { match result {
Err(ResumableError::Trap(_)) => {} Err(ResumableError::Trap(_)) => {}
@ -330,7 +330,7 @@ fn resume_call_host_func_type_mismatch() {
let export = instance.export_by_name("test").unwrap(); let export = instance.export_by_name("test").unwrap();
let func_instance = export.as_func().unwrap(); let func_instance = export.as_func().unwrap();
let mut invocation = FuncInstance::invoke_resumable(&func_instance, &[]).unwrap(); let mut invocation = FuncInstance::invoke_resumable(&func_instance, &[][..]).unwrap();
let result = invocation.start_execution(&mut env); let result = invocation.start_execution(&mut env);
match result { match result {
Err(ResumableError::Trap(_)) => {} Err(ResumableError::Trap(_)) => {}

View File

@ -368,6 +368,7 @@ impl WrapInto<F32> for F64 {
macro_rules! impl_try_truncate_into { macro_rules! impl_try_truncate_into {
(@primitive $from: ident, $into: ident, $to_primitive:path) => { (@primitive $from: ident, $into: ident, $to_primitive:path) => {
impl TryTruncateInto<$into, TrapKind> for $from { impl TryTruncateInto<$into, TrapKind> for $from {
#[cfg(feature = "std")]
fn try_truncate_into(self) -> Result<$into, TrapKind> { fn try_truncate_into(self) -> Result<$into, TrapKind> {
// Casting from a float to an integer will round the float towards zero // Casting from a float to an integer will round the float towards zero
num_rational::BigRational::from_float(self) num_rational::BigRational::from_float(self)
@ -375,6 +376,23 @@ macro_rules! impl_try_truncate_into {
.and_then(|val| $to_primitive(&val)) .and_then(|val| $to_primitive(&val))
.ok_or(TrapKind::InvalidConversionToInt) .ok_or(TrapKind::InvalidConversionToInt)
} }
#[cfg(not(feature = "std"))]
fn try_truncate_into(self) -> Result<$into, TrapKind> {
// Casting from a float to an integer will round the float towards zero
// NOTE: currently this will cause Undefined Behavior if the rounded value cannot be represented by the
// target integer type. This includes Inf and NaN. This is a bug and will be fixed.
if self.is_nan() || self.is_infinite() {
return Err(TrapKind::InvalidConversionToInt);
}
// range check
let result = self as $into;
if result as $from != self.trunc() {
return Err(TrapKind::InvalidConversionToInt);
}
Ok(self as $into)
}
} }
}; };
(@wrapped $from:ident, $intermediate:ident, $into:ident) => { (@wrapped $from:ident, $intermediate:ident, $into:ident) => {
@ -819,15 +837,6 @@ impl_integer!(u32);
impl_integer!(i64); impl_integer!(i64);
impl_integer!(u64); impl_integer!(u64);
// Use std float functions in std environment.
// And libm's implementation in no_std
#[cfg(feature = "std")]
macro_rules! call_math {
($op:ident, $e:expr, $fXX:ident, $FXXExt:ident) => {
$fXX::$op($e)
};
}
#[cfg(not(feature = "std"))]
macro_rules! call_math { macro_rules! call_math {
($op:ident, $e:expr, $fXX:ident, $FXXExt:ident) => { ($op:ident, $e:expr, $fXX:ident, $FXXExt:ident) => {
::libm::$FXXExt::$op($e) ::libm::$FXXExt::$op($e)

View File

@ -18,6 +18,7 @@ fn spec_to_runtime_value(val: Value<u32, u64>) -> RuntimeValue {
Value::I64(v) => RuntimeValue::I64(v), Value::I64(v) => RuntimeValue::I64(v),
Value::F32(v) => RuntimeValue::F32(v.into()), Value::F32(v) => RuntimeValue::F32(v.into()),
Value::F64(v) => RuntimeValue::F64(v.into()), Value::F64(v) => RuntimeValue::F64(v.into()),
Value::V128(_) => panic!("v128 is not supported"),
} }
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "wasmi-validation" name = "wasmi-validation"
version = "0.1.0" version = "0.2.0"
authors = ["Parity Technologies <admin@parity.io>"] authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018" edition = "2018"
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
@ -8,7 +8,7 @@ repository = "https://github.com/paritytech/wasmi"
description = "Wasm code validator" description = "Wasm code validator"
[dependencies] [dependencies]
parity-wasm = { version = "0.31", default-features = false } parity-wasm = { version = "0.40.1", default-features = false }
[dev-dependencies] [dev-dependencies]
assert_matches = "1.1" assert_matches = "1.1"

View File

@ -1,6 +1,5 @@
use crate::Error; use crate::Error;
#[allow(unused_imports)] use alloc::vec::Vec;
use alloc::prelude::v1::*;
use parity_wasm::elements::{ use parity_wasm::elements::{
BlockType, FunctionType, GlobalType, MemoryType, TableType, ValueType, BlockType, FunctionType, GlobalType, MemoryType, TableType, ValueType,
}; };

View File

@ -1,6 +1,3 @@
#[allow(unused_imports)]
use alloc::prelude::v1::*;
use crate::{ use crate::{
context::ModuleContext, stack::StackWithLimit, util::Locals, Error, FuncValidator, context::ModuleContext, stack::StackWithLimit, util::Locals, Error, FuncValidator,
DEFAULT_MEMORY_INDEX, DEFAULT_TABLE_INDEX, DEFAULT_MEMORY_INDEX, DEFAULT_TABLE_INDEX,
@ -269,8 +266,8 @@ impl<'a> FunctionValidationContext<'a> {
BrIf(depth) => { BrIf(depth) => {
self.validate_br_if(depth)?; self.validate_br_if(depth)?;
} }
BrTable(ref table, default) => { BrTable(ref br_table_data) => {
self.validate_br_table(table, default)?; self.validate_br_table(&*br_table_data.table, br_table_data.default)?;
make_top_frame_polymorphic(&mut self.value_stack, &mut self.frame_stack); make_top_frame_polymorphic(&mut self.value_stack, &mut self.frame_stack);
} }
Return => { Return => {

View File

@ -2,8 +2,6 @@
// #![warn(missing_docs)] // #![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
//// alloc is required in no_std
#![cfg_attr(not(feature = "std"), feature(alloc, alloc_prelude))]
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
#[macro_use] #[macro_use]
@ -21,8 +19,7 @@ pub const DEFAULT_TABLE_INDEX: u32 = 0;
/// Maximal number of pages that a wasm instance supports. /// Maximal number of pages that a wasm instance supports.
pub const LINEAR_MEMORY_MAX_PAGES: u32 = 65536; pub const LINEAR_MEMORY_MAX_PAGES: u32 = 65536;
#[allow(unused_imports)] use alloc::{string::String, vec::Vec};
use alloc::prelude::v1::*;
use core::fmt; use core::fmt;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::error; use std::error;
@ -322,7 +319,11 @@ pub fn validate_module<V: Validator>(module: &Module) -> Result<V::Output, Error
if let Some(data_section) = module.data_section() { if let Some(data_section) = module.data_section() {
for data_segment in data_section.entries() { for data_segment in data_section.entries() {
context.require_memory(data_segment.index())?; context.require_memory(data_segment.index())?;
let init_ty = expr_const_type(data_segment.offset(), context.globals())?; let offset = data_segment
.offset()
.as_ref()
.ok_or_else(|| Error("passive memory segments are not supported".into()))?;
let init_ty = expr_const_type(&offset, context.globals())?;
if init_ty != ValueType::I32 { if init_ty != ValueType::I32 {
return Err(Error("segment offset should return I32".into())); return Err(Error("segment offset should return I32".into()));
} }
@ -333,8 +334,11 @@ pub fn validate_module<V: Validator>(module: &Module) -> Result<V::Output, Error
if let Some(element_section) = module.elements_section() { if let Some(element_section) = module.elements_section() {
for element_segment in element_section.entries() { for element_segment in element_section.entries() {
context.require_table(element_segment.index())?; context.require_table(element_segment.index())?;
let offset = element_segment
let init_ty = expr_const_type(element_segment.offset(), context.globals())?; .offset()
.as_ref()
.ok_or_else(|| Error("passive element segments are not supported".into()))?;
let init_ty = expr_const_type(&offset, context.globals())?;
if init_ty != ValueType::I32 { if init_ty != ValueType::I32 {
return Err(Error("segment offset should return I32".into())); return Err(Error("segment offset should return I32".into()));
} }

View File

@ -1,5 +1,4 @@
#[allow(unused_imports)] use alloc::{string::String, vec::Vec};
use alloc::prelude::v1::*;
use core::fmt; use core::fmt;
#[cfg(feature = "std")] #[cfg(feature = "std")]

View File

@ -1,6 +1,5 @@
use crate::Error; use crate::Error;
#[allow(unused_imports)] use alloc::string::String;
use alloc::prelude::v1::*;
use parity_wasm::elements::{Local, ValueType}; use parity_wasm::elements::{Local, ValueType};
#[cfg(test)] #[cfg(test)]