Compare commits
12 Commits
master
...
andre/mmap
Author | SHA1 | Date |
---|---|---|
André Silva | b6187890b0 | |
Sergey Pepyakin | 1d142ea8b0 | |
Sergey Pepyakin | 331b730bac | |
Sergey Pepyakin | 518da20b6b | |
Sergey Pepyakin | 9f4cc26c02 | |
Sergey Pepyakin | a0776876c1 | |
Sergey Pepyakin | 5b86cb5bca | |
Sergey Pepyakin | 9614eb9508 | |
Sergey Pepyakin | af2788a06d | |
Sergey Pepyakin | b1be3f46c2 | |
Sergey Pepyakin | 68925b62a1 | |
Sergey Pepyakin | a5d5368c78 |
|
@ -3,4 +3,3 @@
|
|||
**/*.rs.bk
|
||||
Cargo.lock
|
||||
spec/target
|
||||
.idea
|
||||
|
|
12
.travis.yml
12
.travis.yml
|
@ -40,17 +40,7 @@ after_success: |
|
|||
ghp-import -n target/doc &&
|
||||
git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
|
||||
|
||||
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
|
||||
cache: cargo
|
||||
before_cache:
|
||||
# Travis can't cache files that are not readable by "others"
|
||||
- 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
|
||||
|
|
16
Cargo.toml
16
Cargo.toml
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "wasmi"
|
||||
version = "0.5.1"
|
||||
version = "0.4.5"
|
||||
authors = ["Nikolay Volf <nikvolf@gmail.com>", "Svyatoslav Nikolsky <svyatonik@yandex.ru>", "Sergey Pepyakin <s.pepyakin@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
readme = "README.md"
|
||||
|
@ -11,17 +11,18 @@ keywords = ["wasm", "webassembly", "bytecode", "interpreter"]
|
|||
exclude = [ "/res/*", "/tests/*", "/fuzz/*", "/benches/*" ]
|
||||
|
||||
[dependencies]
|
||||
wasmi-validation = { version = "0.2", path = "validation", default-features = false }
|
||||
parity-wasm = { version = "0.40.1", default-features = false }
|
||||
wasmi-validation = { version = "0.1", path = "validation", default-features = false }
|
||||
parity-wasm = { version = "0.31", default-features = false }
|
||||
memory_units = "0.3.0"
|
||||
libm = { version = "0.1.2", optional = true }
|
||||
num-rational = { version = "0.2.2", default-features = false }
|
||||
num-traits = { version = "0.2.8", default-features = false }
|
||||
num-rational = "0.2.2"
|
||||
num-traits = "0.2.8"
|
||||
libc = "0.2.58"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_matches = "1.1"
|
||||
rand = "0.4.2"
|
||||
wabt = "0.9"
|
||||
wabt = "0.6"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
|
@ -30,13 +31,10 @@ std = [
|
|||
"parity-wasm/std",
|
||||
"wasmi-validation/std",
|
||||
"num-rational/std",
|
||||
"num-rational/bigint-std",
|
||||
"num-traits/std"
|
||||
]
|
||||
# Enable for no_std support
|
||||
core = [
|
||||
# `core` doesn't support vec_memory
|
||||
"vec_memory",
|
||||
"wasmi-validation/core",
|
||||
"libm"
|
||||
]
|
||||
|
|
|
@ -26,8 +26,8 @@ This crate supports `no_std` environments.
|
|||
Enable the `core` feature and disable default features:
|
||||
```toml
|
||||
[dependencies]
|
||||
wasmi = {
|
||||
version = "*",
|
||||
parity-wasm = {
|
||||
version = "0.31",
|
||||
default-features = false,
|
||||
features = "core"
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@ authors = ["Sergey Pepyakin <s.pepyakin@gmail.com>"]
|
|||
[dependencies]
|
||||
wasmi = { path = ".." }
|
||||
assert_matches = "1.2"
|
||||
wabt = "0.9"
|
||||
wabt = "0.6"
|
||||
|
||||
[profile.bench]
|
||||
debug = true
|
||||
|
|
|
@ -13,7 +13,7 @@ use wasmi::{ImportsBuilder, Module, ModuleInstance, NopExternals, RuntimeValue};
|
|||
use test::Bencher;
|
||||
|
||||
// Load a module from a file.
|
||||
fn load_from_file(filename: &str) -> Result<Module, Box<dyn error::Error>> {
|
||||
fn load_from_file(filename: &str) -> Result<Module, Box<error::Error>> {
|
||||
use std::io::prelude::*;
|
||||
let mut file = File::open(filename)?;
|
||||
let mut buf = Vec::new();
|
||||
|
|
|
@ -33,7 +33,7 @@ pub extern "C" fn prepare_tiny_keccak() -> *const TinyKeccakTestData {
|
|||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn bench_tiny_keccak(test_data: *mut TinyKeccakTestData) {
|
||||
pub extern "C" fn bench_tiny_keccak(test_data: *const TinyKeccakTestData) {
|
||||
unsafe {
|
||||
let mut keccak = Keccak::new_keccak256();
|
||||
keccak.update((*test_data).data);
|
||||
|
|
|
@ -10,7 +10,7 @@ cargo-fuzz = true
|
|||
|
||||
[dependencies]
|
||||
wasmi = { path = ".." }
|
||||
wabt = "0.9"
|
||||
wabt = "0.6.0"
|
||||
wasmparser = "0.14.1"
|
||||
tempdir = "0.3.6"
|
||||
|
||||
|
|
|
@ -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.
|
||||
wasmi = { path = ".." }
|
||||
tempdir = "0.3.6"
|
||||
wabt = "0.9"
|
||||
wabt = "0.6.0"
|
||||
|
|
17
src/func.rs
17
src/func.rs
|
@ -1,8 +1,6 @@
|
|||
use alloc::{
|
||||
borrow::Cow,
|
||||
rc::{Rc, Weak},
|
||||
vec::Vec,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use alloc::rc::{Rc, Weak};
|
||||
use core::fmt;
|
||||
use host::Externals;
|
||||
use isa;
|
||||
|
@ -196,13 +194,12 @@ impl FuncInstance {
|
|||
/// [`resume_execution`]: struct.FuncInvocation.html#method.resume_execution
|
||||
pub fn invoke_resumable<'args>(
|
||||
func: &FuncRef,
|
||||
args: impl Into<Cow<'args, [RuntimeValue]>>,
|
||||
args: &'args [RuntimeValue],
|
||||
) -> Result<FuncInvocation<'args>, Trap> {
|
||||
let args = args.into();
|
||||
check_function_args(func.signature(), &args)?;
|
||||
match *func.as_internal() {
|
||||
FuncInstanceInternal::Internal { .. } => {
|
||||
let interpreter = Interpreter::new(func, &*args, None)?;
|
||||
let interpreter = Interpreter::new(func, args, None)?;
|
||||
Ok(FuncInvocation {
|
||||
kind: FuncInvocationKind::Internal(interpreter),
|
||||
})
|
||||
|
@ -259,7 +256,7 @@ pub struct FuncInvocation<'args> {
|
|||
enum FuncInvocationKind<'args> {
|
||||
Internal(Interpreter),
|
||||
Host {
|
||||
args: Cow<'args, [RuntimeValue]>,
|
||||
args: &'args [RuntimeValue],
|
||||
host_func_index: usize,
|
||||
finished: bool,
|
||||
},
|
||||
|
@ -306,7 +303,7 @@ impl<'args> FuncInvocation<'args> {
|
|||
return Err(ResumableError::AlreadyStarted);
|
||||
}
|
||||
*finished = true;
|
||||
Ok(externals.invoke_index(*host_func_index, args.as_ref().into())?)
|
||||
Ok(externals.invoke_index(*host_func_index, args.clone().into())?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -114,11 +114,11 @@ pub trait HostError: 'static + ::core::fmt::Display + ::core::fmt::Debug + Send
|
|||
}
|
||||
}
|
||||
|
||||
impl dyn HostError {
|
||||
impl HostError {
|
||||
/// Attempt to downcast this `HostError` to a concrete type by reference.
|
||||
pub fn downcast_ref<T: HostError>(&self) -> Option<&T> {
|
||||
if self.__private_get_type_id__() == TypeId::of::<T>() {
|
||||
unsafe { Some(&*(self as *const dyn HostError as *const T)) }
|
||||
unsafe { Some(&*(self as *const HostError as *const T)) }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
@ -128,7 +128,7 @@ impl dyn HostError {
|
|||
/// reference.
|
||||
pub fn downcast_mut<T: HostError>(&mut self) -> Option<&mut T> {
|
||||
if self.__private_get_type_id__() == TypeId::of::<T>() {
|
||||
unsafe { Some(&mut *(self as *mut dyn HostError as *mut T)) }
|
||||
unsafe { Some(&mut *(self as *mut HostError as *mut T)) }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
@ -257,5 +257,5 @@ mod tests {
|
|||
}
|
||||
|
||||
// Tests that `HostError` trait is object safe.
|
||||
fn _host_error_is_object_safe(_: &dyn HostError) {}
|
||||
fn _host_error_is_object_safe(_: &HostError) {}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
use alloc::{collections::BTreeMap, string::String};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
use alloc::collections::BTreeMap;
|
||||
|
||||
use func::FuncRef;
|
||||
use global::GlobalRef;
|
||||
|
@ -100,7 +103,7 @@ pub trait ImportResolver {
|
|||
/// [`ImportResolver`]: trait.ImportResolver.html
|
||||
/// [`ModuleImportResolver`]: trait.ModuleImportResolver.html
|
||||
pub struct ImportsBuilder<'a> {
|
||||
modules: BTreeMap<String, &'a dyn ModuleImportResolver>,
|
||||
modules: BTreeMap<String, &'a ModuleImportResolver>,
|
||||
}
|
||||
|
||||
impl<'a> Default for ImportsBuilder<'a> {
|
||||
|
@ -121,7 +124,7 @@ impl<'a> ImportsBuilder<'a> {
|
|||
pub fn with_resolver<N: Into<String>>(
|
||||
mut self,
|
||||
name: N,
|
||||
resolver: &'a dyn ModuleImportResolver,
|
||||
resolver: &'a ModuleImportResolver,
|
||||
) -> Self {
|
||||
self.modules.insert(name.into(), resolver);
|
||||
self
|
||||
|
@ -130,15 +133,11 @@ impl<'a> ImportsBuilder<'a> {
|
|||
/// Register an resolver by a name.
|
||||
///
|
||||
/// Mutable borrowed version.
|
||||
pub fn push_resolver<N: Into<String>>(
|
||||
&mut self,
|
||||
name: N,
|
||||
resolver: &'a dyn ModuleImportResolver,
|
||||
) {
|
||||
pub fn push_resolver<N: Into<String>>(&mut self, name: N, resolver: &'a ModuleImportResolver) {
|
||||
self.modules.insert(name.into(), resolver);
|
||||
}
|
||||
|
||||
fn resolver(&self, name: &str) -> Option<&dyn ModuleImportResolver> {
|
||||
fn resolver(&self, name: &str) -> Option<&ModuleImportResolver> {
|
||||
self.modules.get(name).cloned()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -67,7 +67,8 @@
|
|||
//! - Reserved immediates are ignored for `call_indirect`, `current_memory`, `grow_memory`.
|
||||
//!
|
||||
|
||||
use alloc::vec::Vec;
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
/// Should we keep a value before "discarding" a stack frame?
|
||||
///
|
||||
|
|
15
src/lib.rs
15
src/lib.rs
|
@ -96,6 +96,8 @@
|
|||
|
||||
#![warn(missing_docs)]
|
||||
#![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"))]
|
||||
#[macro_use]
|
||||
|
@ -117,11 +119,8 @@ extern crate parity_wasm;
|
|||
|
||||
extern crate wasmi_validation as validation;
|
||||
|
||||
use alloc::{
|
||||
boxed::Box,
|
||||
string::{String, ToString},
|
||||
vec::Vec,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use core::fmt;
|
||||
#[cfg(feature = "std")]
|
||||
use std::error;
|
||||
|
@ -240,7 +239,7 @@ pub enum TrapKind {
|
|||
/// Typically returned from an implementation of [`Externals`].
|
||||
///
|
||||
/// [`Externals`]: trait.Externals.html
|
||||
Host(Box<dyn host::HostError>),
|
||||
Host(Box<host::HostError>),
|
||||
}
|
||||
|
||||
impl TrapKind {
|
||||
|
@ -274,7 +273,7 @@ pub enum Error {
|
|||
/// Trap.
|
||||
Trap(Trap),
|
||||
/// Custom embedder error.
|
||||
Host(Box<dyn host::HostError>),
|
||||
Host(Box<host::HostError>),
|
||||
}
|
||||
|
||||
impl Error {
|
||||
|
@ -286,7 +285,7 @@ impl Error {
|
|||
/// [`Host`]: enum.Error.html#variant.Host
|
||||
/// [`Trap`]: enum.Error.html#variant.Trap
|
||||
/// [`TrapKind::Host`]: enum.TrapKind.html#variant.Host
|
||||
pub fn as_host_error(&self) -> Option<&dyn host::HostError> {
|
||||
pub fn as_host_error(&self) -> Option<&host::HostError> {
|
||||
match *self {
|
||||
Error::Host(ref host_err) => Some(&**host_err),
|
||||
Error::Trap(ref trap) => match *trap.kind() {
|
||||
|
|
|
@ -27,7 +27,7 @@ impl Mmap {
|
|||
/// - `len` should be greater than 0.
|
||||
/// - `mmap` returns an error (almost certainly means out of memory).
|
||||
fn new(len: usize) -> Result<Self, &'static str> {
|
||||
if len > isize::max_value() as usize {
|
||||
if len >= isize::max_value() as usize {
|
||||
return Err("`len` should not exceed `isize::max_value()`");
|
||||
}
|
||||
if len == 0 {
|
||||
|
@ -49,7 +49,8 @@ impl Mmap {
|
|||
// `MAP_ANON` - mapping is not backed by any file and initial contents are
|
||||
// initialized to zero.
|
||||
// `MAP_PRIVATE` - the mapping is private to this process.
|
||||
libc::MAP_ANON | libc::MAP_PRIVATE,
|
||||
// `MAP_NORESERVE` - do not reserve swap space for this mapping.
|
||||
libc::MAP_ANON | libc::MAP_PRIVATE | libc::MAP_NORESERVE,
|
||||
// `fildes` - a file descriptor. Pass -1 as this is required for some platforms
|
||||
// when the `MAP_ANON` is passed.
|
||||
-1,
|
||||
|
@ -58,12 +59,19 @@ impl Mmap {
|
|||
)
|
||||
};
|
||||
|
||||
match ptr_or_err {
|
||||
match ptr_or_err as usize {
|
||||
// `mmap` returns -1 in case of an error.
|
||||
// `mmap` shouldn't return 0 since it has a special meaning for compilers.
|
||||
//
|
||||
// With the current parameters, the error can only be returned in case of insufficient
|
||||
// memory.
|
||||
libc::MAP_FAILED => Err("mmap returned an error"),
|
||||
x if x == 0 || x as isize == -1 => Err("mmap returned error"),
|
||||
_ => {
|
||||
let ptr = NonNull::new(ptr_or_err as *mut u8).ok_or("mmap returned 0")?;
|
||||
let ptr = unsafe {
|
||||
// Safety Proof:
|
||||
// the ptr cannot be null as checked within the enclosing match.
|
||||
NonNull::new_unchecked(ptr_or_err as *mut u8)
|
||||
};
|
||||
Ok(Self { ptr, len })
|
||||
}
|
||||
}
|
||||
|
@ -113,77 +121,73 @@ impl Drop for Mmap {
|
|||
|
||||
pub struct ByteBuf {
|
||||
mmap: Option<Mmap>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
// NOTE: we either make this an arbitrarily large value and use MAP_NORESERVE
|
||||
// (which means we can segfault when writing instead of the allocation
|
||||
// failing). or we need to figure out the maximum mem + swap available.
|
||||
const MMAP_SIZE: usize = 2 << 40;
|
||||
|
||||
impl ByteBuf {
|
||||
pub fn new(len: usize) -> Result<Self, &'static str> {
|
||||
let mmap = if len == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(Mmap::new(len)?)
|
||||
Some(Mmap::new(MMAP_SIZE)?)
|
||||
};
|
||||
Ok(Self { mmap })
|
||||
|
||||
Ok(Self { mmap, len })
|
||||
}
|
||||
|
||||
pub fn realloc(&mut self, new_len: usize) -> Result<(), &'static str> {
|
||||
let new_mmap = if new_len == 0 {
|
||||
None
|
||||
} else {
|
||||
let mut new_mmap = Mmap::new(new_len)?;
|
||||
if let Some(cur_mmap) = self.mmap.take() {
|
||||
let src = cur_mmap.as_slice();
|
||||
let dst = new_mmap.as_slice_mut();
|
||||
let amount = src.len().min(dst.len());
|
||||
dst[..amount].copy_from_slice(&src[..amount]);
|
||||
}
|
||||
Some(new_mmap)
|
||||
};
|
||||
if new_len == 0 {
|
||||
self.mmap = None
|
||||
} else if let None = self.mmap {
|
||||
self.mmap = Some(Mmap::new(MMAP_SIZE)?)
|
||||
}
|
||||
|
||||
self.len = new_len;
|
||||
|
||||
self.mmap = new_mmap;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.mmap.as_ref().map(|m| m.len).unwrap_or(0)
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
self.mmap.as_ref().map(|m| m.as_slice()).unwrap_or(&[])
|
||||
let len = self.len();
|
||||
self.mmap
|
||||
.as_ref()
|
||||
.map(|m| m.as_slice().split_at(len).0)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn as_slice_mut(&mut self) -> &mut [u8] {
|
||||
let len = self.len();
|
||||
self.mmap
|
||||
.as_mut()
|
||||
.map(|m| m.as_slice_mut())
|
||||
.map(|m| m.as_slice_mut().split_at_mut(len).0)
|
||||
.unwrap_or(&mut [])
|
||||
}
|
||||
|
||||
pub fn erase(&mut self) -> Result<(), &'static str> {
|
||||
let len = self.len();
|
||||
if len > 0 {
|
||||
// The order is important.
|
||||
//
|
||||
// 1. First we clear, and thus drop, the current mmap if any.
|
||||
// 2. And then we create a new one.
|
||||
//
|
||||
// Otherwise we double the peak memory consumption.
|
||||
self.mmap = None;
|
||||
self.mmap = Some(Mmap::new(len)?);
|
||||
}
|
||||
match self.mmap {
|
||||
// Nothing to do here...
|
||||
None => return Ok(()),
|
||||
Some(Mmap { len: cur_len, .. }) => cur_len,
|
||||
};
|
||||
|
||||
// The order is important.
|
||||
//
|
||||
// 1. First we clear, and thus drop, the current mmap if any.
|
||||
// 2. And then we create a new one.
|
||||
//
|
||||
// Otherwise we double the peak memory consumption.
|
||||
self.mmap = None;
|
||||
self.mmap = Some(Mmap::new(MMAP_SIZE)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ByteBuf;
|
||||
|
||||
const PAGE_SIZE: usize = 4096;
|
||||
|
||||
// This is not required since wasm memories can only grow but nice to have.
|
||||
#[test]
|
||||
fn byte_buf_shrink() {
|
||||
let mut byte_buf = ByteBuf::new(PAGE_SIZE * 3).unwrap();
|
||||
byte_buf.realloc(PAGE_SIZE * 2).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
use alloc::{rc::Rc, string::ToString, vec::Vec};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use alloc::rc::Rc;
|
||||
use core::{
|
||||
cell::{Cell, RefCell},
|
||||
cmp, fmt,
|
||||
|
@ -506,34 +508,6 @@ impl MemoryInstance {
|
|||
.erase()
|
||||
.map_err(|err| Error::Memory(err.to_string()))
|
||||
}
|
||||
|
||||
/// Provides direct access to the underlying memory buffer.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Any call that requires write access to memory (such as [`set`], [`clear`], etc) made within
|
||||
/// the closure will panic.
|
||||
///
|
||||
/// [`set`]: #method.get
|
||||
/// [`clear`]: #method.set
|
||||
pub fn with_direct_access<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
let buf = self.buffer.borrow();
|
||||
f(buf.as_slice())
|
||||
}
|
||||
|
||||
/// Provides direct mutable access to the underlying memory buffer.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Any calls that requires either read or write access to memory (such as [`get`], [`set`], [`copy`], etc) made
|
||||
/// within the closure will panic. Proceed with caution.
|
||||
///
|
||||
/// [`get`]: #method.get
|
||||
/// [`set`]: #method.set
|
||||
pub fn with_direct_access_mut<R, F: FnOnce(&mut [u8]) -> R>(&self, f: F) -> R {
|
||||
let mut buf = self.buffer.borrow_mut();
|
||||
f(buf.as_slice_mut())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -705,36 +679,4 @@ mod tests {
|
|||
|
||||
assert_eq!(data, [17, 129]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_copy() {
|
||||
let mem = MemoryInstance::alloc(Pages(1), None).unwrap();
|
||||
mem.set(100, &[0]).expect("memory set should not fail");
|
||||
mem.with_direct_access_mut(|buf| {
|
||||
assert_eq!(
|
||||
buf.len(),
|
||||
65536,
|
||||
"the buffer length is expected to be 1 page long"
|
||||
);
|
||||
buf[..10].copy_from_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
});
|
||||
mem.with_direct_access(|buf| {
|
||||
assert_eq!(
|
||||
buf.len(),
|
||||
65536,
|
||||
"the buffer length is expected to be 1 page long"
|
||||
);
|
||||
assert_eq!(&buf[..10], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
});
|
||||
}
|
||||
|
||||
#[should_panic]
|
||||
#[test]
|
||||
fn zero_copy_panics_on_nested_access() {
|
||||
let mem = MemoryInstance::alloc(Pages(1), None).unwrap();
|
||||
let mem_inner = mem.clone();
|
||||
mem.with_direct_access(move |_| {
|
||||
let _ = mem_inner.set(0, &[11, 12, 13]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
//! An implementation of `ByteBuf` based on a plain `Vec`.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
pub struct ByteBuf {
|
||||
buf: Vec<u8>,
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
use alloc::{
|
||||
borrow::ToOwned,
|
||||
rc::Rc,
|
||||
string::{String, ToString},
|
||||
vec::Vec,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use alloc::rc::Rc;
|
||||
use core::cell::RefCell;
|
||||
use core::fmt;
|
||||
use Trap;
|
||||
|
@ -421,11 +418,7 @@ impl ModuleInstance {
|
|||
.map(|es| es.entries())
|
||||
.unwrap_or(&[])
|
||||
{
|
||||
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) {
|
||||
let offset_val = match eval_init_expr(element_segment.offset(), &module_ref) {
|
||||
RuntimeValue::I32(v) => v as u32,
|
||||
_ => panic!("Due to validation elem segment offset should evaluate to i32"),
|
||||
};
|
||||
|
@ -454,11 +447,7 @@ impl ModuleInstance {
|
|||
}
|
||||
|
||||
for data_segment in module.data_section().map(|ds| ds.entries()).unwrap_or(&[]) {
|
||||
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) {
|
||||
let offset_val = match eval_init_expr(data_segment.offset(), &module_ref) {
|
||||
RuntimeValue::I32(v) => v as u32,
|
||||
_ => panic!("Due to validation data segment offset should evaluate to i32"),
|
||||
};
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
use alloc::{string::String, vec::Vec};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
use parity_wasm::elements::{BlockType, FuncBody, Instruction};
|
||||
|
||||
|
@ -251,14 +252,13 @@ impl Compiler {
|
|||
);
|
||||
self.sink.emit_br_nez(target);
|
||||
}
|
||||
BrTable(ref br_table_data) => {
|
||||
BrTable(ref table, default) => {
|
||||
// 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
|
||||
// popped off.
|
||||
let value_stack_height = context.value_stack.len().saturating_sub(1);
|
||||
|
||||
let targets = br_table_data
|
||||
.table
|
||||
let targets = table
|
||||
.iter()
|
||||
.map(|depth| {
|
||||
require_target(
|
||||
|
@ -270,7 +270,7 @@ impl Compiler {
|
|||
})
|
||||
.collect::<Result<Vec<_>, _>>();
|
||||
let default_target = require_target(
|
||||
br_table_data.default,
|
||||
default,
|
||||
value_stack_height,
|
||||
&context.frame_stack,
|
||||
&self.label_stack,
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
use alloc::vec::Vec;
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
use crate::{
|
||||
isa,
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
use alloc::{boxed::Box, vec::Vec};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use core::fmt;
|
||||
use core::ops;
|
||||
use core::{u32, usize};
|
||||
|
@ -1289,8 +1290,14 @@ impl FunctionContext {
|
|||
debug_assert!(!self.is_initialized);
|
||||
|
||||
let num_locals = locals.iter().map(|l| l.count() as usize).sum();
|
||||
let locals = vec![Default::default(); num_locals];
|
||||
|
||||
value_stack.extend(num_locals)?;
|
||||
// TODO: Replace with extend.
|
||||
for local in locals {
|
||||
value_stack
|
||||
.push(local)
|
||||
.map_err(|_| TrapKind::StackOverflow)?;
|
||||
}
|
||||
|
||||
self.is_initialized = true;
|
||||
Ok(())
|
||||
|
@ -1436,18 +1443,6 @@ impl ValueStack {
|
|||
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]
|
||||
fn len(&self) -> usize {
|
||||
self.sp
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
use alloc::{rc::Rc, vec::Vec};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use alloc::rc::Rc;
|
||||
use core::cell::RefCell;
|
||||
use core::fmt;
|
||||
use core::u32;
|
||||
|
|
|
@ -285,7 +285,7 @@ fn resume_call_host_func() {
|
|||
let export = instance.export_by_name("test").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);
|
||||
match result {
|
||||
Err(ResumableError::Trap(_)) => {}
|
||||
|
@ -330,7 +330,7 @@ fn resume_call_host_func_type_mismatch() {
|
|||
let export = instance.export_by_name("test").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);
|
||||
match result {
|
||||
Err(ResumableError::Trap(_)) => {}
|
||||
|
|
27
src/value.rs
27
src/value.rs
|
@ -368,7 +368,6 @@ impl WrapInto<F32> for F64 {
|
|||
macro_rules! impl_try_truncate_into {
|
||||
(@primitive $from: ident, $into: ident, $to_primitive:path) => {
|
||||
impl TryTruncateInto<$into, TrapKind> for $from {
|
||||
#[cfg(feature = "std")]
|
||||
fn try_truncate_into(self) -> Result<$into, TrapKind> {
|
||||
// Casting from a float to an integer will round the float towards zero
|
||||
num_rational::BigRational::from_float(self)
|
||||
|
@ -376,23 +375,6 @@ macro_rules! impl_try_truncate_into {
|
|||
.and_then(|val| $to_primitive(&val))
|
||||
.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) => {
|
||||
|
@ -837,6 +819,15 @@ impl_integer!(u32);
|
|||
impl_integer!(i64);
|
||||
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 {
|
||||
($op:ident, $e:expr, $fXX:ident, $FXXExt:ident) => {
|
||||
::libm::$FXXExt::$op($e)
|
||||
|
|
|
@ -18,7 +18,6 @@ fn spec_to_runtime_value(val: Value<u32, u64>) -> RuntimeValue {
|
|||
Value::I64(v) => RuntimeValue::I64(v),
|
||||
Value::F32(v) => RuntimeValue::F32(v.into()),
|
||||
Value::F64(v) => RuntimeValue::F64(v.into()),
|
||||
Value::V128(_) => panic!("v128 is not supported"),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "wasmi-validation"
|
||||
version = "0.2.0"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
license = "MIT/Apache-2.0"
|
||||
|
@ -8,7 +8,7 @@ repository = "https://github.com/paritytech/wasmi"
|
|||
description = "Wasm code validator"
|
||||
|
||||
[dependencies]
|
||||
parity-wasm = { version = "0.40.1", default-features = false }
|
||||
parity-wasm = { version = "0.31", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
assert_matches = "1.1"
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
use crate::Error;
|
||||
use alloc::vec::Vec;
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use parity_wasm::elements::{
|
||||
BlockType, FunctionType, GlobalType, MemoryType, TableType, ValueType,
|
||||
};
|
||||
|
|
|
@ -1,3 +1,6 @@
|
|||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
use crate::{
|
||||
context::ModuleContext, stack::StackWithLimit, util::Locals, Error, FuncValidator,
|
||||
DEFAULT_MEMORY_INDEX, DEFAULT_TABLE_INDEX,
|
||||
|
@ -266,8 +269,8 @@ impl<'a> FunctionValidationContext<'a> {
|
|||
BrIf(depth) => {
|
||||
self.validate_br_if(depth)?;
|
||||
}
|
||||
BrTable(ref br_table_data) => {
|
||||
self.validate_br_table(&*br_table_data.table, br_table_data.default)?;
|
||||
BrTable(ref table, default) => {
|
||||
self.validate_br_table(table, default)?;
|
||||
make_top_frame_polymorphic(&mut self.value_stack, &mut self.frame_stack);
|
||||
}
|
||||
Return => {
|
||||
|
|
|
@ -2,6 +2,8 @@
|
|||
// #![warn(missing_docs)]
|
||||
|
||||
#![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"))]
|
||||
#[macro_use]
|
||||
|
@ -19,7 +21,8 @@ pub const DEFAULT_TABLE_INDEX: u32 = 0;
|
|||
/// Maximal number of pages that a wasm instance supports.
|
||||
pub const LINEAR_MEMORY_MAX_PAGES: u32 = 65536;
|
||||
|
||||
use alloc::{string::String, vec::Vec};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use core::fmt;
|
||||
#[cfg(feature = "std")]
|
||||
use std::error;
|
||||
|
@ -319,11 +322,7 @@ pub fn validate_module<V: Validator>(module: &Module) -> Result<V::Output, Error
|
|||
if let Some(data_section) = module.data_section() {
|
||||
for data_segment in data_section.entries() {
|
||||
context.require_memory(data_segment.index())?;
|
||||
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())?;
|
||||
let init_ty = expr_const_type(data_segment.offset(), context.globals())?;
|
||||
if init_ty != ValueType::I32 {
|
||||
return Err(Error("segment offset should return I32".into()));
|
||||
}
|
||||
|
@ -334,11 +333,8 @@ pub fn validate_module<V: Validator>(module: &Module) -> Result<V::Output, Error
|
|||
if let Some(element_section) = module.elements_section() {
|
||||
for element_segment in element_section.entries() {
|
||||
context.require_table(element_segment.index())?;
|
||||
let offset = element_segment
|
||||
.offset()
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error("passive element segments are not supported".into()))?;
|
||||
let init_ty = expr_const_type(&offset, context.globals())?;
|
||||
|
||||
let init_ty = expr_const_type(element_segment.offset(), context.globals())?;
|
||||
if init_ty != ValueType::I32 {
|
||||
return Err(Error("segment offset should return I32".into()));
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
use alloc::{string::String, vec::Vec};
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
|
||||
use core::fmt;
|
||||
#[cfg(feature = "std")]
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
use crate::Error;
|
||||
use alloc::string::String;
|
||||
#[allow(unused_imports)]
|
||||
use alloc::prelude::v1::*;
|
||||
use parity_wasm::elements::{Local, ValueType};
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
Loading…
Reference in New Issue