Skip to content

Commit

Permalink
Merge branch 'main' into dev/cemonem-structured-ctrl2
Browse files Browse the repository at this point in the history
Signed-off-by: Cem Onem <[email protected]>
  • Loading branch information
Cem Onem committed Dec 17, 2024
2 parents e35beae + f1fd142 commit db296f6
Show file tree
Hide file tree
Showing 25 changed files with 5,379 additions and 156 deletions.
104 changes: 103 additions & 1 deletion src/core/error.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use alloc::format;
use alloc::string::{String, ToString};

use crate::core::indices::GlobalIdx;
use crate::validation_stack::ValidationStackEntry;
use crate::RefType;
use core::fmt::{Display, Formatter};
use core::str::Utf8Error;

use crate::core::reader::section_header::SectionTy;
use crate::core::reader::types::ValType;

use super::indices::{DataIdx, MemIdx};
use super::indices::{DataIdx, ElemIdx, FuncIdx, MemIdx, TableIdx, TypeIdx};

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RuntimeError {
Expand All @@ -16,6 +21,18 @@ pub enum RuntimeError {
// https://github.com/wasmi-labs/wasmi/blob/37d1449524a322817c55026eb21eb97dd693b9ce/crates/core/src/trap.rs#L265C5-L265C27
BadConversionToInteger,
MemoryAccessOutOfBounds,
TableAccessOutOfBounds,
ElementAccessOutOfBounds,
UninitializedElement,
SignatureMismatch,
ExpectedAValueOnTheStack,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum StoreInstantiationError {
ActiveDataWriteOutOfBounds,
I64ValueOutOfReach(String),
MissingValueOnTheStack,
}

#[derive(Debug, PartialEq, Eq, Clone)]
Expand All @@ -41,6 +58,7 @@ pub enum Error {
EndInvalidValueStack,
InvalidLocalIdx,
InvalidValidationStackValType(Option<ValType>),
InvalidValidationStackType(ValidationStackEntry),
ExpectedAnOperand,
InvalidLimitsType(u8),
InvalidMutType(u8),
Expand All @@ -50,11 +68,23 @@ pub enum Error {
InvalidGlobalIdx(GlobalIdx),
GlobalIsConst,
RuntimeError(RuntimeError),
FoundUnspecifiedValTypes,
MemoryIsNotDefined(MemIdx),
// mem.align, wanted alignment
ErroneousAlignment(u32, u32),
NoDataSegments,
DataSegmentNotFound(DataIdx),
UnknownTable,
TableIsNotDefined(TableIdx),
ElementIsNotDefined(ElemIdx),
DifferentRefTypes(RefType, RefType),
ExpectedARefType(ValType),
WrongRefTypeForInteropValue(RefType, RefType),
FunctionIsNotDefined(FuncIdx),
ReferencingAnUnreferencedFunction(FuncIdx),
FunctionTypeIsNotDefined(TypeIdx),
StoreInstantiationError(StoreInstantiationError),
OnlyFuncRefIsAllowed,
InvalidLabelIdx(usize),
ValidationCtrlStackEmpty,
ElseWithoutMatchingIf,
Expand Down Expand Up @@ -118,6 +148,9 @@ impl Display for Error {
Error::InvalidValidationStackValType(ty) => f.write_fmt(format_args!(
"An unexpected type was found on the stack when trying to pop another: `{ty:?}`"
)),
Error::InvalidValidationStackType(ty) => f.write_fmt(format_args!(
"An unexpected type was found on the stack: `{ty:?}`"
)),
Error::InvalidLimitsType(ty) => {
f.write_fmt(format_args!("An invalid limits type was found: {ty:#x?}"))
}
Expand All @@ -134,6 +167,7 @@ impl Display for Error {
)),
Error::GlobalIsConst => f.write_str("A const global cannot be written to"),
Error::RuntimeError(err) => err.fmt(f),
Error::FoundUnspecifiedValTypes => f.write_str("Found UnspecifiedValTypes"),
Error::ExpectedAnOperand => f.write_str("Expected a ValType"), // Error => f.write_str("Expected an operand (ValType) on the stack")
Error::MemoryIsNotDefined(memidx) => f.write_fmt(format_args!(
"C.mems[{}] is NOT defined when it should be",
Expand All @@ -149,6 +183,41 @@ impl Display for Error {
Error::DataSegmentNotFound(data_idx) => {
f.write_fmt(format_args!("Data Segment {} not found", data_idx))
}
Error::UnknownTable => f.write_str("Unknown Table"),
Error::TableIsNotDefined(table_idx) => f.write_fmt(format_args!(
"C.tables[{}] is NOT defined when it should be",
table_idx
)),
Error::ElementIsNotDefined(elem_idx) => f.write_fmt(format_args!(
"C.elems[{}] is NOT defined when it should be",
elem_idx
)),
Error::DifferentRefTypes(rref1, rref2) => f.write_fmt(format_args!(
"RefType {:?} is NOT equal to RefType {:?}",
rref1, rref2
)),
Error::ExpectedARefType(found_valtype) => f.write_fmt(format_args!(
"Expected a RefType, found a {:?} instead",
found_valtype
)),
Error::WrongRefTypeForInteropValue(ref_given, ref_wanted) => f.write_fmt(format_args!(
"Wrong RefType for InteropValue: Given {:?} - Needed {:?}",
ref_given, ref_wanted
)),
Error::FunctionIsNotDefined(func_idx) => f.write_fmt(format_args!(
"C.functions[{}] is NOT defined when it should be",
func_idx
)),
Error::ReferencingAnUnreferencedFunction(func_idx) => f.write_fmt(format_args!(
"Referenced a function ({}) that was not referenced in validation",
func_idx
)),
Error::FunctionTypeIsNotDefined(func_ty_idx) => f.write_fmt(format_args!(
"C.fn_types[{}] is NOT defined when it should be",
func_ty_idx
)),
Error::StoreInstantiationError(err) => err.fmt(f),
Error::OnlyFuncRefIsAllowed => f.write_str("Only FuncRef is allowed"),
Error::InvalidLabelIdx(label_idx) => {
f.write_fmt(format_args!("invalid label index {}", label_idx))
}
Expand All @@ -174,6 +243,33 @@ impl Display for RuntimeError {
RuntimeError::StackSmash => f.write_str("Stack smashed"),
RuntimeError::BadConversionToInteger => f.write_str("Bad conversion to integer"),
RuntimeError::MemoryAccessOutOfBounds => f.write_str("Memory access out of bounds"),
RuntimeError::TableAccessOutOfBounds => f.write_str("Table access out of bounds"),
RuntimeError::ElementAccessOutOfBounds => f.write_str("Element access out of bounds"),
RuntimeError::UninitializedElement => f.write_str("Uninitialized element"),
RuntimeError::SignatureMismatch => f.write_str("Indirect call signature mismatch"),
RuntimeError::ExpectedAValueOnTheStack => {
f.write_str("Expected a value on the stack, but None was found")
}
}
}
}

impl Display for StoreInstantiationError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
use StoreInstantiationError::*;
match self {
ActiveDataWriteOutOfBounds => {
f.write_str("Active data writing in memory is out of bounds")
}
I64ValueOutOfReach(s) => f.write_fmt(format_args!(
"I64 value {}is out of reach",
if !s.is_empty() {
format!("for {s} ")
} else {
"".to_string()
}
)),
MissingValueOnTheStack => f.write_str(""),
}
}
}
Expand All @@ -185,3 +281,9 @@ impl From<RuntimeError> for Error {
Self::RuntimeError(value)
}
}

impl From<StoreInstantiationError> for Error {
fn from(value: StoreInstantiationError) -> Self {
Self::StoreInstantiationError(value)
}
}
15 changes: 12 additions & 3 deletions src/core/reader/types/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use crate::{
indices::MemIdx,
reader::{span::Span, WasmReadable},
},
read_constant_expression::read_constant_instructions,
read_constant_expression::read_constant_expression,
validation_stack::ValidationStack,
};

use super::UnwrapValidatedExt;
Expand All @@ -31,12 +32,17 @@ pub struct DataModeActive {

impl WasmReadable for DataSegment {
fn read(wasm: &mut crate::core::reader::WasmReader) -> crate::Result<Self> {
use crate::{NumType, ValType};
let mode = wasm.read_var_u32()?;
let data_sec: DataSegment = match mode {
0 => {
// active { memory 0, offset e }
trace!("Data section: active");
let offset = { read_constant_instructions(wasm, None, None)? };
let mut valid_stack = ValidationStack::new();
let offset =
{ read_constant_expression(wasm, &mut valid_stack, None, None, None)? };

valid_stack.assert_pop_val_type(ValType::NumType(NumType::I32))?;

let byte_vec = wasm.read_vec(|el| el.read_u8())?;

Expand Down Expand Up @@ -81,7 +87,10 @@ impl WasmReadable for DataSegment {
0 => {
// active { memory 0, offset e }
trace!("Data section: active");
let offset = { read_constant_instructions(wasm, None, None).unwrap_validated() };
let offset = {
read_constant_expression(wasm, &mut ValidationStack::new(), None, None, None)
.unwrap_validated()
};

let byte_vec = wasm
.read_vec(|el| Ok(el.read_u8().unwrap_validated()))
Expand Down
Loading

0 comments on commit db296f6

Please sign in to comment.