core and alloc all the things

This commit is contained in:
Julius Rakow 2018-08-25 01:09:02 +02:00
parent 33a0e6ec4c
commit d38d268740
No known key found for this signature in database
GPG Key ID: 9AABD9B859435A93
19 changed files with 96 additions and 54 deletions

View File

@ -1,7 +1,9 @@
#[allow(unused_imports)]
use alloc::prelude::*;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::error; use std::error;
use std::fmt; use core::fmt;
#[derive(Debug)] #[derive(Debug)]
pub struct Error(String); pub struct Error(String);

View File

@ -1,5 +1,7 @@
use std::rc::{Rc, Weak}; #[allow(unused_imports)]
use std::fmt; use alloc::prelude::*;
use alloc::rc::{Rc, Weak};
use core::fmt;
use parity_wasm::elements::Local; use parity_wasm::elements::Local;
use {Trap, TrapKind, Signature}; use {Trap, TrapKind, Signature};
use host::Externals; use host::Externals;
@ -17,7 +19,7 @@ use isa;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FuncRef(Rc<FuncInstance>); pub struct FuncRef(Rc<FuncInstance>);
impl ::std::ops::Deref for FuncRef { impl ::core::ops::Deref for FuncRef {
type Target = FuncInstance; type Target = FuncInstance;
fn deref(&self) -> &FuncInstance { fn deref(&self) -> &FuncInstance {
&self.0 &self.0

View File

@ -1,5 +1,5 @@
use std::rc::Rc; use alloc::rc::Rc;
use std::cell::Cell; use core::cell::Cell;
use value::RuntimeValue; use value::RuntimeValue;
use Error; use Error;
use types::ValueType; use types::ValueType;
@ -13,7 +13,7 @@ use parity_wasm::elements::{ValueType as EValueType};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct GlobalRef(Rc<GlobalInstance>); pub struct GlobalRef(Rc<GlobalInstance>);
impl ::std::ops::Deref for GlobalRef { impl ::core::ops::Deref for GlobalRef {
type Target = GlobalInstance; type Target = GlobalInstance;
fn deref(&self) -> &GlobalInstance { fn deref(&self) -> &GlobalInstance {
&self.0 &self.0

View File

@ -1,4 +1,4 @@
use std::any::TypeId; use core::any::TypeId;
use value::{RuntimeValue, FromRuntimeValue}; use value::{RuntimeValue, FromRuntimeValue};
use {TrapKind, Trap}; use {TrapKind, Trap};
@ -98,7 +98,7 @@ impl<'a> RuntimeArgs<'a> {
/// _ => panic!(), /// _ => panic!(),
/// } /// }
/// ``` /// ```
pub trait HostError: 'static + ::std::fmt::Display + ::std::fmt::Debug + Send + Sync { pub trait HostError: 'static + ::core::fmt::Display + ::core::fmt::Debug + Send + Sync {
#[doc(hidden)] #[doc(hidden)]
fn __private_get_type_id__(&self) -> TypeId { fn __private_get_type_id__(&self) -> TypeId {
TypeId::of::<Self>() TypeId::of::<Self>()

View File

@ -1,3 +1,5 @@
#[allow(unused_imports)]
use alloc::prelude::*;
use hashmap_core::HashMap; use hashmap_core::HashMap;
use global::GlobalRef; use global::GlobalRef;
use memory::MemoryRef; use memory::MemoryRef;

View File

@ -67,6 +67,9 @@
//! - 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::prelude::*;
/// Should we keep a value before "discarding" a stack frame? /// Should we keep a value before "discarding" a stack frame?
/// ///
/// Note that this is a `enum` since Wasm doesn't support multiple return /// Note that this is a `enum` since Wasm doesn't support multiple return

View File

@ -96,6 +96,21 @@
#![warn(missing_docs)] #![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
//// alloc is required in no_std
#![cfg_attr(not(feature = "std"), feature(alloc))]
#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std as alloc;
#[cfg(feature = "std")]
#[macro_use]
extern crate core;
#[cfg(test)] #[cfg(test)]
extern crate wabt; extern crate wabt;
#[cfg(test)] #[cfg(test)]
@ -109,7 +124,9 @@ extern crate memory_units as memory_units_crate;
pub extern crate nan_preserving_float; pub extern crate nan_preserving_float;
use std::fmt; #[allow(unused_imports)]
use alloc::prelude::*;
use core::fmt;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::error; use std::error;

View File

@ -1,9 +1,11 @@
use std::u32; #[allow(unused_imports)]
use std::ops::Range; use alloc::prelude::*;
use std::cmp; use alloc::rc::Rc;
use std::fmt; use core::u32;
use std::rc::Rc; use core::ops::Range;
use std::cell::{Cell, RefCell}; use core::cmp;
use core::fmt;
use core::cell::{Cell, RefCell};
use parity_wasm::elements::ResizableLimits; use parity_wasm::elements::ResizableLimits;
use Error; use Error;
use memory_units::{RoundUpTo, Pages, Bytes}; use memory_units::{RoundUpTo, Pages, Bytes};
@ -28,7 +30,7 @@ const LINEAR_MEMORY_MAX_PAGES: Pages = Pages(65536);
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct MemoryRef(Rc<MemoryInstance>); pub struct MemoryRef(Rc<MemoryInstance>);
impl ::std::ops::Deref for MemoryRef { impl ::core::ops::Deref for MemoryRef {
type Target = MemoryInstance; type Target = MemoryInstance;
fn deref(&self) -> &MemoryInstance { fn deref(&self) -> &MemoryInstance {
&self.0 &self.0
@ -172,7 +174,7 @@ impl MemoryInstance {
/// Get value from memory at given offset. /// Get value from memory at given offset.
pub fn get_value<T: LittleEndianConvert>(&self, offset: u32) -> Result<T, Error> { pub fn get_value<T: LittleEndianConvert>(&self, offset: u32) -> Result<T, Error> {
let mut buffer = self.buffer.borrow_mut(); let mut buffer = self.buffer.borrow_mut();
let region = self.checked_region(&mut buffer, offset as usize, ::std::mem::size_of::<T>())?; let region = self.checked_region(&mut buffer, offset as usize, ::core::mem::size_of::<T>())?;
Ok(T::from_little_endian(&buffer[region.range()]).expect("Slice size is checked")) Ok(T::from_little_endian(&buffer[region.range()]).expect("Slice size is checked"))
} }
@ -216,7 +218,7 @@ impl MemoryInstance {
/// Copy value in the memory at given offset. /// Copy value in the memory at given offset.
pub fn set_value<T: LittleEndianConvert>(&self, offset: u32, value: T) -> Result<(), Error> { pub fn set_value<T: LittleEndianConvert>(&self, offset: u32, value: T) -> Result<(), Error> {
let mut buffer = self.buffer.borrow_mut(); let mut buffer = self.buffer.borrow_mut();
let range = self.checked_region(&mut buffer, offset as usize, ::std::mem::size_of::<T>())?.range(); let range = self.checked_region(&mut buffer, offset as usize, ::core::mem::size_of::<T>())?.range();
value.into_little_endian(&mut buffer[range]); value.into_little_endian(&mut buffer[range]);
Ok(()) Ok(())
} }
@ -254,7 +256,7 @@ impl MemoryInstance {
} }
fn checked_region<B>(&self, buffer: &mut B, offset: usize, size: usize) -> Result<CheckedRegion, Error> fn checked_region<B>(&self, buffer: &mut B, offset: usize, size: usize) -> Result<CheckedRegion, Error>
where B: ::std::ops::DerefMut<Target=Vec<u8>> where B: ::core::ops::DerefMut<Target=Vec<u8>>
{ {
let end = offset.checked_add(size) let end = offset.checked_add(size)
.ok_or_else(|| Error::Memory(format!("trying to access memory block of size {} from offset {}", size, offset)))?; .ok_or_else(|| Error::Memory(format!("trying to access memory block of size {} from offset {}", size, offset)))?;
@ -275,7 +277,7 @@ impl MemoryInstance {
fn checked_region_pair<B>(&self, buffer: &mut B, offset1: usize, size1: usize, offset2: usize, size2: usize) fn checked_region_pair<B>(&self, buffer: &mut B, offset1: usize, size1: usize, offset2: usize, size2: usize)
-> Result<(CheckedRegion, CheckedRegion), Error> -> Result<(CheckedRegion, CheckedRegion), Error>
where B: ::std::ops::DerefMut<Target=Vec<u8>> where B: ::core::ops::DerefMut<Target=Vec<u8>>
{ {
let end1 = offset1.checked_add(size1) let end1 = offset1.checked_add(size1)
.ok_or_else(|| Error::Memory(format!("trying to access memory block of size {} from offset {}", size1, offset1)))?; .ok_or_else(|| Error::Memory(format!("trying to access memory block of size {} from offset {}", size1, offset1)))?;
@ -314,7 +316,7 @@ impl MemoryInstance {
let (read_region, write_region) = self.checked_region_pair(&mut buffer, src_offset, len, dst_offset, len)?; let (read_region, write_region) = self.checked_region_pair(&mut buffer, src_offset, len, dst_offset, len)?;
unsafe { ::std::ptr::copy( unsafe { ::core::ptr::copy(
buffer[read_region.range()].as_ptr(), buffer[read_region.range()].as_ptr(),
buffer[write_region.range()].as_ptr() as *mut _, buffer[write_region.range()].as_ptr() as *mut _,
len, len,
@ -343,7 +345,7 @@ impl MemoryInstance {
return Err(Error::Memory(format!("non-overlapping copy is used for overlapping regions"))) return Err(Error::Memory(format!("non-overlapping copy is used for overlapping regions")))
} }
unsafe { ::std::ptr::copy_nonoverlapping( unsafe { ::core::ptr::copy_nonoverlapping(
buffer[read_region.range()].as_ptr(), buffer[read_region.range()].as_ptr(),
buffer[write_region.range()].as_ptr() as *mut _, buffer[write_region.range()].as_ptr() as *mut _,
len, len,

View File

@ -1,8 +1,10 @@
#[allow(unused_imports)]
use alloc::prelude::*;
use alloc::rc::Rc;
use runner::check_function_args; use runner::check_function_args;
use Trap; use Trap;
use std::rc::Rc; use core::cell::RefCell;
use std::cell::RefCell; use core::fmt;
use std::fmt;
use hashmap_core::HashMap; use hashmap_core::HashMap;
use parity_wasm::elements::{External, InitExpr, Internal, Instruction, ResizableLimits, Type}; use parity_wasm::elements::{External, InitExpr, Internal, Instruction, ResizableLimits, Type};
use {Module, Error, Signature, MemoryInstance, RuntimeValue, TableInstance}; use {Module, Error, Signature, MemoryInstance, RuntimeValue, TableInstance};
@ -32,7 +34,7 @@ use memory_units::Pages;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ModuleRef(pub(crate) Rc<ModuleInstance>); pub struct ModuleRef(pub(crate) Rc<ModuleInstance>);
impl ::std::ops::Deref for ModuleRef { impl ::core::ops::Deref for ModuleRef {
type Target = ModuleInstance; type Target = ModuleInstance;
fn deref(&self) -> &ModuleInstance { fn deref(&self) -> &ModuleInstance {
&self.0 &self.0

View File

@ -1,7 +1,9 @@
use std::ops; #[allow(unused_imports)]
use std::{u32, usize}; use alloc::prelude::*;
use std::fmt; use core::ops;
use std::iter::repeat; use core::{u32, usize};
use core::fmt;
use core::iter::repeat;
use parity_wasm::elements::Local; use parity_wasm::elements::Local;
use {Error, Trap, TrapKind, Signature}; use {Error, Trap, TrapKind, Signature};
use module::ModuleRef; use module::ModuleRef;
@ -19,7 +21,7 @@ use nan_preserving_float::{F32, F64};
use isa; use isa;
/// Maximum number of entries in value stack. /// Maximum number of entries in value stack.
pub const DEFAULT_VALUE_STACK_LIMIT: usize = (1024 * 1024) / ::std::mem::size_of::<RuntimeValue>(); pub const DEFAULT_VALUE_STACK_LIMIT: usize = (1024 * 1024) / ::core::mem::size_of::<RuntimeValue>();
// TODO: Make these parameters changeble. // TODO: Make these parameters changeble.
pub const DEFAULT_CALL_STACK_LIMIT: usize = 64 * 1024; pub const DEFAULT_CALL_STACK_LIMIT: usize = 64 * 1024;
@ -122,7 +124,7 @@ impl Interpreter {
} }
pub fn resume_execution<'a, E: Externals + 'a>(&mut self, return_val: Option<RuntimeValue>, externals: &'a mut E) -> Result<Option<RuntimeValue>, Trap> { pub fn resume_execution<'a, E: Externals + 'a>(&mut self, return_val: Option<RuntimeValue>, externals: &'a mut E) -> Result<Option<RuntimeValue>, Trap> {
use std::mem::swap; use core::mem::swap;
// Ensure that the VM is resumable. This is checked in `FuncInvocation::resume_execution`. // Ensure that the VM is resumable. This is checked in `FuncInvocation::resume_execution`.
assert!(self.state.is_resumable()); assert!(self.state.is_resumable());

View File

@ -1,7 +1,9 @@
use std::u32; #[allow(unused_imports)]
use std::fmt; use alloc::prelude::*;
use std::cell::RefCell; use alloc::rc::Rc;
use std::rc::Rc; use core::u32;
use core::fmt;
use core::cell::RefCell;
use parity_wasm::elements::ResizableLimits; use parity_wasm::elements::ResizableLimits;
use Error; use Error;
use func::FuncRef; use func::FuncRef;
@ -16,7 +18,7 @@ use module::check_limits;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TableRef(Rc<TableInstance>); pub struct TableRef(Rc<TableInstance>);
impl ::std::ops::Deref for TableRef { impl ::core::ops::Deref for TableRef {
type Target = TableInstance; type Target = TableInstance;
fn deref(&self) -> &TableInstance { fn deref(&self) -> &TableInstance {
&self.0 &self.0

View File

@ -12,8 +12,8 @@ struct HostErrorWithCode {
error_code: u32, error_code: u32,
} }
impl ::std::fmt::Display for HostErrorWithCode { impl ::core::fmt::Display for HostErrorWithCode {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> Result<(), ::core::fmt::Error> {
write!(f, "{}", self.error_code) write!(f, "{}", self.error_code)
} }
} }

View File

@ -23,10 +23,10 @@ fn assert_error_properties() {
fn unsigned_to_runtime_value() { fn unsigned_to_runtime_value() {
use super::RuntimeValue; use super::RuntimeValue;
let overflow_i32: u32 = ::std::i32::MAX as u32 + 1; let overflow_i32: u32 = ::core::i32::MAX as u32 + 1;
assert_eq!(RuntimeValue::from(overflow_i32).try_into::<u32>().unwrap(), overflow_i32); assert_eq!(RuntimeValue::from(overflow_i32).try_into::<u32>().unwrap(), overflow_i32);
let overflow_i64: u64 = ::std::i64::MAX as u64 + 1; let overflow_i64: u64 = ::core::i64::MAX as u64 + 1;
assert_eq!(RuntimeValue::from(overflow_i64).try_into::<u64>().unwrap(), overflow_i64); assert_eq!(RuntimeValue::from(overflow_i64).try_into::<u64>().unwrap(), overflow_i64);
} }

View File

@ -1,4 +1,4 @@
use std::borrow::Cow; use alloc::borrow::Cow;
use parity_wasm::elements::{ use parity_wasm::elements::{
FunctionType, ValueType as EValueType, GlobalType, TableType, MemoryType}; FunctionType, ValueType as EValueType, GlobalType, TableType, MemoryType};

View File

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

View File

@ -1,4 +1,6 @@
use std::u32; #[allow(unused_imports)]
use alloc::prelude::*;
use core::u32;
use parity_wasm::elements::{Instruction, BlockType, ValueType, TableElementType, Func, FuncBody}; use parity_wasm::elements::{Instruction, BlockType, ValueType, TableElementType, Func, FuncBody};
use common::{DEFAULT_MEMORY_INDEX, DEFAULT_TABLE_INDEX}; use common::{DEFAULT_MEMORY_INDEX, DEFAULT_TABLE_INDEX};
use validation::context::ModuleContext; use validation::context::ModuleContext;
@ -1726,7 +1728,7 @@ impl Sink {
} }
fn emit_br_table(&mut self, targets: &[Target], default: Target) { fn emit_br_table(&mut self, targets: &[Target], default: Target) {
use std::iter; use core::iter;
let pc = self.cur_pc(); let pc = self.cur_pc();
let mut isa_targets = Vec::new(); let mut isa_targets = Vec::new();
@ -1757,7 +1759,7 @@ impl Sink {
/// ///
/// Panics if the label is already resolved. /// Panics if the label is already resolved.
fn resolve_label(&mut self, label: LabelId) { fn resolve_label(&mut self, label: LabelId) {
use std::mem; use core::mem;
if let (Label::Resolved(_), _) = self.labels[label.0] { if let (Label::Resolved(_), _) = self.labels[label.0] {
panic!("Trying to resolve already resolved label"); panic!("Trying to resolve already resolved label");

View File

@ -1,6 +1,8 @@
#[allow(unused_imports)]
use alloc::prelude::*;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::error; use std::error;
use std::fmt; use core::fmt;
use hashmap_core::HashSet; use hashmap_core::HashSet;
use parity_wasm::elements::{ use parity_wasm::elements::{
BlockType, External, GlobalEntry, GlobalType, Internal, MemoryType, Module, Instruction, BlockType, External, GlobalEntry, GlobalType, Internal, MemoryType, Module, Instruction,
@ -47,7 +49,7 @@ pub struct ValidatedModule {
pub module: Module, pub module: Module,
} }
impl ::std::ops::Deref for ValidatedModule { impl ::core::ops::Deref for ValidatedModule {
type Target = Module; type Target = Module;
fn deref(&self) -> &Module { fn deref(&self) -> &Module {
&self.module &self.module

View File

@ -1,3 +1,5 @@
#[allow(unused_imports)]
use alloc::prelude::*;
use parity_wasm::elements::{Local, ValueType}; use parity_wasm::elements::{Local, ValueType};
use validation::Error; use validation::Error;

View File

@ -1,7 +1,7 @@
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use nan_preserving_float::{F32, F64}; use nan_preserving_float::{F32, F64};
use std::mem::transmute; use core::mem::transmute;
use std::{f32, i32, i64, u32, u64}; use core::{f32, i32, i64, u32, u64};
use TrapKind; use TrapKind;
#[derive(Debug)] #[derive(Debug)]
@ -780,7 +780,7 @@ macro_rules! impl_float {
return round; return round;
} }
use std::ops::Rem; use core::ops::Rem;
if round.rem(2.0) == 1.0 { if round.rem(2.0) == 1.0 {
self.floor() self.floor()
} else if round.rem(2.0) == -1.0 { } else if round.rem(2.0) == -1.0 {
@ -795,7 +795,7 @@ macro_rules! impl_float {
// This instruction corresponds to what is sometimes called "minNaN" in other languages. // This instruction corresponds to what is sometimes called "minNaN" in other languages.
fn min(self, other: $type) -> $type { fn min(self, other: $type) -> $type {
if self.is_nan() || other.is_nan() { if self.is_nan() || other.is_nan() {
return ::std::$intermediate::NAN.into(); return ::core::$intermediate::NAN.into();
} }
self.min(other) self.min(other)
@ -803,13 +803,13 @@ macro_rules! impl_float {
// This instruction corresponds to what is sometimes called "maxNaN" in other languages. // This instruction corresponds to what is sometimes called "maxNaN" in other languages.
fn max(self, other: $type) -> $type { fn max(self, other: $type) -> $type {
if self.is_nan() || other.is_nan() { if self.is_nan() || other.is_nan() {
return ::std::$intermediate::NAN.into(); return ::core::$intermediate::NAN.into();
} }
self.max(other) self.max(other)
} }
fn copysign(self, other: $type) -> $type { fn copysign(self, other: $type) -> $type {
use std::mem::size_of; use core::mem::size_of;
if self.is_nan() { if self.is_nan() {
return self; return self;