Skip to content

Commit

Permalink
Merge pull request #4 from teonite/enable_sign_ext_support
Browse files Browse the repository at this point in the history
Enable sign ext proposal support
  • Loading branch information
mpapierski authored Sep 9, 2024
2 parents 734e06b + f8ca169 commit 0ee646b
Show file tree
Hide file tree
Showing 39 changed files with 315 additions and 166 deletions.
12 changes: 6 additions & 6 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: Rust - Continuous Integration

on:
push:
branches: [ casper-main ]
branches: [ main ]
pull_request:
branches: [ casper-main ]
branches: [ main ]

jobs:
check:
Expand Down Expand Up @@ -184,10 +184,10 @@ jobs:
with:
version: '0.18.0'
args: --workspace
- name: Upload to codecov.io
uses: codecov/[email protected]
with:
token: ${{secrets.CODECOV_TOKEN}}
# - name: Upload to codecov.io
# uses: codecov/[email protected]
# with:
# token: ${{secrets.CODECOV_TOKEN}}
- name: Archive code coverage results
uses: actions/upload-artifact@v1
with:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
Cargo.lock
spec/target
.idea
.direnv
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ virtual_memory = ["casper-wasmi-core/virtual_memory", "std"]

reduced-stack-buffer = [ "casper-wasm/reduced-stack-buffer" ]

sign_ext = ["casper-wasm/sign_ext", "validation/sign_ext" ]

[workspace]
members = ["validation", "core", "wasmi_v1", "cli"]
exclude = []
Expand Down
2 changes: 1 addition & 1 deletion benches/benches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@ fn bench_execute_memory_fill_v1(c: &mut Criterion) {
});
assert!(mem.data(&store)[ptr..(ptr + len)]
.iter()
.all(|byte| (*byte as u8) == value));
.all(|byte| { *byte } == value));
});
}

Expand Down
24 changes: 12 additions & 12 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use casper_wasmi::{
use clap::Parser;
use core::fmt::Write;
use std::fs;
use wasmi_v1 as wasmi;
use wasmi_v1 as casper_wasmi;

/// Simple program to greet a person
#[derive(Parser, Debug)]
Expand Down Expand Up @@ -53,7 +53,7 @@ fn main() -> Result<()> {

/// Converts the given `.wat` into `.wasm`.
fn wat2wasm(wat: &str) -> Result<Vec<u8>, wat::Error> {
wat::parse_str(&wat)
wat::parse_str(wat)
}

/// Returns the contents of the given `.wasm` or `.wat` file.
Expand All @@ -63,7 +63,7 @@ fn wat2wasm(wat: &str) -> Result<Vec<u8>, wat::Error> {
/// If `wasm_file` is not a valid `.wasm` or `.wat` file.
fn read_wasm_or_wat(wasm_file: &str) -> Result<Vec<u8>> {
let mut file_contents =
fs::read(&wasm_file).map_err(|_| anyhow!("failed to read Wasm file {wasm_file}"))?;
fs::read(wasm_file).map_err(|_| anyhow!("failed to read Wasm file {wasm_file}"))?;
if wasm_file.ends_with(".wat") {
let wat = String::from_utf8(file_contents)
.map_err(|error| anyhow!("failed to read UTF-8 file {wasm_file}: {error}"))?;
Expand All @@ -87,12 +87,12 @@ fn load_wasm_func(
wasm_bytes: &[u8],
func_name: &str,
) -> Result<(Func, Store<()>)> {
let engine = wasmi::Engine::default();
let mut store = wasmi::Store::new(&engine, ());
let module = wasmi::Module::new(&engine, &mut &wasm_bytes[..]).map_err(|error| {
let engine = casper_wasmi::Engine::default();
let mut store = casper_wasmi::Store::new(&engine, ());
let module = casper_wasmi::Module::new(&engine, &mut &wasm_bytes[..]).map_err(|error| {
anyhow!("failed to parse and validate Wasm module {wasm_file}: {error}")
})?;
let mut linker = <wasmi::Linker<()>>::new();
let mut linker = <casper_wasmi::Linker<()>>::new();
let instance = linker
.instantiate(&mut store, &module)
.and_then(|pre| pre.start(&mut store))
Expand All @@ -113,8 +113,8 @@ fn load_wasm_func(

/// Returns a [`Vec`] of `(&str, FuncType)` describing the exported functions of the [`Module`].
///
/// [`Module`]: [`wasmi::Module`]
fn exported_funcs(module: &wasmi::Module) -> Vec<(&str, FuncType)> {
/// [`Module`]: [`casper_wasmi::Module`]
fn exported_funcs(module: &casper_wasmi::Module) -> Vec<(&str, FuncType)> {
module
.exports()
.filter_map(|export| {
Expand All @@ -129,8 +129,8 @@ fn exported_funcs(module: &wasmi::Module) -> Vec<(&str, FuncType)> {

/// Returns a [`String`] displaying a list of exported functions from the [`Module`].
///
/// [`Module`]: [`wasmi::Module`]
fn display_exported_funcs(module: &wasmi::Module) -> String {
/// [`Module`]: [`casper_wasmi::Module`]
fn display_exported_funcs(module: &casper_wasmi::Module) -> String {
let exported_funcs = exported_funcs(module)
.into_iter()
.map(|(name, func_type)| display_exported_func(name, &func_type));
Expand Down Expand Up @@ -241,7 +241,7 @@ fn print_execution_start(wasm_file: &str, func_name: &str, func_args: &[Value])
println!(") ...");
}

/// Prints the results of the Wasm computation in a human readable form.
/// Prints the results of the Wasm computation in a human-readable form.
fn print_pretty_results(results: &[Value]) {
let pretty_results = results
.iter()
Expand Down
18 changes: 9 additions & 9 deletions core/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
nan_preserving_float::{F32, F64},
TrapCode,
};
use core::{f32, fmt, fmt::Display, i32, i64, u32, u64};
use core::{f32, fmt, fmt::Display};

/// Type of a value.
///
Expand Down Expand Up @@ -400,8 +400,8 @@ impl FromValue for bool {
impl FromValue for i8 {
#[inline]
fn from_value(val: Value) -> Option<Self> {
let min = i8::min_value() as i32;
let max = i8::max_value() as i32;
let min = i8::MIN as i32;
let max = i8::MAX as i32;
match val {
Value::I32(val) if min <= val && val <= max => Some(val as i8),
_ => None,
Expand All @@ -415,8 +415,8 @@ impl FromValue for i8 {
impl FromValue for i16 {
#[inline]
fn from_value(val: Value) -> Option<Self> {
let min = i16::min_value() as i32;
let max = i16::max_value() as i32;
let min = i16::MIN as i32;
let max = i16::MAX as i32;
match val {
Value::I32(val) if min <= val && val <= max => Some(val as i16),
_ => None,
Expand All @@ -430,8 +430,8 @@ impl FromValue for i16 {
impl FromValue for u8 {
#[inline]
fn from_value(val: Value) -> Option<Self> {
let min = u8::min_value() as i32;
let max = u8::max_value() as i32;
let min = u8::MIN as i32;
let max = u8::MAX as i32;
match val {
Value::I32(val) if min <= val && val <= max => Some(val as u8),
_ => None,
Expand All @@ -445,8 +445,8 @@ impl FromValue for u8 {
impl FromValue for u16 {
#[inline]
fn from_value(val: Value) -> Option<Self> {
let min = u16::min_value() as i32;
let max = u16::max_value() as i32;
let min = u16::MIN as i32;
let max = u16::MAX as i32;
match val {
Value::I32(val) if min <= val && val <= max => Some(val as u16),
_ => None,
Expand Down
2 changes: 1 addition & 1 deletion core/src/vmem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl VirtualMemory {
///
/// # Errors
///
/// - If `len` should not exceed `isize::max_value()`
/// - If `len` should not exceed `isize::MAX`
/// - If `len` should be greater than 0.
/// - If the operating system returns an error upon virtual memory allocation.
pub fn new(len: usize) -> Result<Self, VirtualMemoryError> {
Expand Down
2 changes: 1 addition & 1 deletion examples/tictactoe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ mod tictactoe {
if !(0..9).contains(&idx) {
return Err(Error::OutOfRange);
}
if self.board[idx as usize] != None {
if self.board[idx as usize].is_some() {
return Err(Error::AlreadyOccupied);
}
self.board[idx as usize] = Some(player);
Expand Down
37 changes: 36 additions & 1 deletion src/isa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,17 @@ pub enum Instruction<'a> {
I64ReinterpretF64,
F32ReinterpretI32,
F64ReinterpretI64,

#[cfg(feature = "sign_ext")]
I32Extend8S,
#[cfg(feature = "sign_ext")]
I32Extend16S,
#[cfg(feature = "sign_ext")]
I64Extend8S,
#[cfg(feature = "sign_ext")]
I64Extend16S,
#[cfg(feature = "sign_ext")]
I64Extend32S,
}

/// The internally-stored instruction type. This differs from `Instruction` in that the `BrTable`
Expand All @@ -356,7 +367,9 @@ pub(crate) enum InstructionInternal {
Br(Target),
BrIfEqz(Target),
BrIfNez(Target),
BrTable { count: u32 },
BrTable {
count: u32,
},
BrTableTarget(Target),

Unreachable,
Expand Down Expand Up @@ -533,6 +546,17 @@ pub(crate) enum InstructionInternal {
I64ReinterpretF64,
F32ReinterpretI32,
F64ReinterpretI64,

#[cfg(feature = "sign_ext")]
I32Extend8S,
#[cfg(feature = "sign_ext")]
I32Extend16S,
#[cfg(feature = "sign_ext")]
I64Extend8S,
#[cfg(feature = "sign_ext")]
I64Extend16S,
#[cfg(feature = "sign_ext")]
I64Extend32S,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -789,6 +813,17 @@ impl<'a> Iterator for InstructionIter<'a> {
InstructionInternal::I64ReinterpretF64 => Instruction::I64ReinterpretF64,
InstructionInternal::F32ReinterpretI32 => Instruction::F32ReinterpretI32,
InstructionInternal::F64ReinterpretI64 => Instruction::F64ReinterpretI64,

#[cfg(feature = "sign_ext")]
InstructionInternal::I32Extend8S => Instruction::I32Extend8S,
#[cfg(feature = "sign_ext")]
InstructionInternal::I32Extend16S => Instruction::I32Extend16S,
#[cfg(feature = "sign_ext")]
InstructionInternal::I64Extend8S => Instruction::I64Extend8S,
#[cfg(feature = "sign_ext")]
InstructionInternal::I64Extend16S => Instruction::I64Extend16S,
#[cfg(feature = "sign_ext")]
InstructionInternal::I64Extend32S => Instruction::I64Extend32S,
};

self.position += 1;
Expand Down
2 changes: 0 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,6 @@ pub(crate) mod value {
LittleEndianConvert,
TransmuteInto,
TryTruncateInto,
Value as RuntimeValue,
ValueType,
WrapInto,
};
}
Expand Down
4 changes: 2 additions & 2 deletions src/memory/mmap_bytebuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ impl ByteBuf {

/// Creates a new byte buffer with the given initial length.
pub fn new(len: usize) -> Result<Self, String> {
if len > isize::max_value() as usize {
return Err("`len` should not exceed `isize::max_value()`".into());
if len > isize::MAX as usize {
return Err("`len` should not exceed `isize::MAX`".into());
}
let mem = VirtualMemory::new(Self::ALLOCATION_SIZE).map_err(|error| error.to_string())?;
Ok(Self { mem, len })
Expand Down
1 change: 0 additions & 1 deletion src/memory/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use core::{
cmp,
fmt,
ops::Range,
u32,
};

#[cfg(all(feature = "virtual_memory", target_pointer_width = "64"))]
Expand Down
12 changes: 6 additions & 6 deletions src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ impl ModuleInstance {
let module = loaded_module.module();
let instance = ModuleRef(Rc::new(ModuleInstance::default()));

for &Type::Function(ref ty) in module.type_section().map(|ts| ts.types()).unwrap_or(&[]) {
for Type::Function(ty) in module.type_section().map(|ts| ts.types()).unwrap_or(&[]) {
let signature = Rc::new(Signature::from_elements(ty));
instance.push_signature(signature);
}
Expand All @@ -268,7 +268,7 @@ impl ModuleInstance {
};

match (import.external(), extern_val) {
(&External::Function(fn_type_idx), &ExternVal::Func(ref func)) => {
(&External::Function(fn_type_idx), ExternVal::Func(func)) => {
let expected_fn_type = instance
.signature_by_index(fn_type_idx)
.expect("Due to validation function type should exists");
Expand All @@ -283,15 +283,15 @@ impl ModuleInstance {
}
instance.push_func(func.clone())
}
(&External::Table(ref tt), &ExternVal::Table(ref table)) => {
(External::Table(tt), ExternVal::Table(table)) => {
match_limits(table.limits(), tt.limits())?;
instance.push_table(table.clone());
}
(&External::Memory(ref mt), &ExternVal::Memory(ref memory)) => {
(External::Memory(mt), ExternVal::Memory(memory)) => {
match_limits(memory.limits(), mt.limits())?;
instance.push_memory(memory.clone());
}
(&External::Global(ref gl), &ExternVal::Global(ref global)) => {
(External::Global(gl), ExternVal::Global(global)) => {
if gl.content_type() != global.elements_value_type() {
return Err(Error::Instantiation(format!(
"Expect global with {:?} type, but provided global with {:?} type",
Expand Down Expand Up @@ -554,7 +554,7 @@ impl ModuleInstance {
let extern_val = match *import_entry.external() {
External::Function(fn_ty_idx) => {
let types = module.type_section().map(|s| s.types()).unwrap_or(&[]);
let &Type::Function(ref func_type) = types
let Type::Function(func_type) = types
.get(fn_ty_idx as usize)
.expect("Due to validation functions should have valid types");
let signature = Signature::from_elements(func_type);
Expand Down
Loading

0 comments on commit 0ee646b

Please sign in to comment.