diff options
Diffstat (limited to 'crates/types')
| -rw-r--r-- | crates/types/src/archive.rs | 2 | ||||
| -rw-r--r-- | crates/types/src/instructions.rs | 37 | ||||
| -rw-r--r-- | crates/types/src/lib.rs | 96 | ||||
| -rw-r--r-- | crates/types/src/reference.rs | 109 | ||||
| -rw-r--r-- | crates/types/src/types.rs | 158 | ||||
| -rw-r--r-- | crates/types/src/value.rs | 34 |
6 files changed, 309 insertions, 127 deletions
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index 99238ab..9904a7d 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -7,7 +7,7 @@ use crate::Module; #[rustfmt::skip] const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS"; -const TWASM_VERSION: &[u8; 2] = b"04"; +const TWASM_VERSION: &[u8; 2] = b"05"; fn validate_magic(wasm: &[u8]) -> Result<usize, TwasmError> { if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX { diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index a53576e..1160fa5 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -54,6 +54,14 @@ pub enum ConstInstruction { V128Const([u8; 16]), GlobalGet(GlobalAddr), Ref(RefValue), + RefI31, + AnyConvertExtern, + ExternConvertAny, + StructNew(TypeAddr), + StructNewDefault(TypeAddr), + ArrayNew(TypeAddr), + ArrayNewDefault(TypeAddr), + ArrayNewFixed(TypeAddr, u32), I32Add, I32Sub, I32Mul, @@ -272,6 +280,35 @@ pub enum Instruction { RefFunc(FuncAddr), RefIsNull, RefAsNonNull, + RefI31, + I31GetS, + I31GetU, + RefEq, + RefTest(RefType), + RefCast(RefType), + BrOnCast(u32, RefType, bool), + + // > GC Objects + StructNew(TypeAddr), + StructNewDefault(TypeAddr), + StructGet(TypeAddr, u32), + StructGetS(TypeAddr, u32), + StructGetU(TypeAddr, u32), + StructSet(TypeAddr, u32), + ArrayNew(TypeAddr), + ArrayNewDefault(TypeAddr), + ArrayNewFixed(TypeAddr, u32), + ArrayNewData(TypeAddr, DataAddr), + ArrayNewElem(TypeAddr, ElemAddr), + ArrayGet(TypeAddr), + ArrayGetS(TypeAddr), + ArrayGetU(TypeAddr), + ArraySet(TypeAddr), + ArrayLen, + ArrayFill(TypeAddr), + ArrayCopy(TypeAddr, TypeAddr), + ArrayInitData(TypeAddr, DataAddr), + ArrayInitElem(TypeAddr, ElemAddr), // > Numeric Instructions // See <https://webassembly.github.io/spec/core/binary/instructions.html#numeric-instructions> diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 0b15927..c461296 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -22,9 +22,11 @@ const fn max_page_count(page_size: u64) -> u64 { mod instructions; mod reference; +mod types; mod value; pub use instructions::*; pub use reference::*; +pub use types::*; pub use value::*; #[cfg(feature = "archive")] @@ -81,10 +83,10 @@ pub struct ModuleInner { /// Contains data from to the `code`, `func`, and `type` sections of the original WebAssembly module. pub funcs: Box<[Arc<WasmFunction>]>, - /// A vector of type definitions, indexed by `TypeAddr` + /// The dense type definitions, indexed by `TypeAddr`. /// /// Corresponds to the `type` section of the original WebAssembly module. - pub func_types: Box<[FuncType]>, + pub types: TypeSection, /// Function index to type index mapping in module index space, including imports. pub func_type_idxs: Box<[TypeAddr]>, @@ -135,7 +137,7 @@ impl Module { pub fn imports(&self) -> impl Iterator<Item = ModuleImport<'_>> { self.0.imports.iter().filter_map(|import| { let ty = match &import.kind { - ImportKind::Function(type_idx) => Some(ImportType::Func(self.0.func_types.get(*type_idx as usize)?)), + ImportKind::Function(type_idx) => Some(ImportType::Func(self.0.types.get(*type_idx)?.as_func()?)), ImportKind::Table(table_ty) => Some(ImportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ImportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ImportType::Global(global_ty)), @@ -178,7 +180,7 @@ impl Module { let import = imports.nth(index)?; match &import.kind { - ImportKind::Function(type_idx) => Some(ExportType::Func(module.func_types.get(*type_idx as usize)?)), + ImportKind::Function(type_idx) => Some(ExportType::Func(module.types.get(*type_idx)?.as_func()?)), ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)), @@ -194,7 +196,7 @@ impl Module { imported_type(&self.0, ExternalKind::Func, idx)? } else { let type_idx = *self.0.func_type_idxs.get(idx)?; - ExportType::Func(self.0.func_types.get(type_idx as usize)?) + ExportType::Func(self.0.types.get(type_idx)?.as_func()?) } } ExternalKind::Table => { @@ -360,90 +362,6 @@ impl ExternVal { } } -/// The type of a WebAssembly Function. -/// -/// See <https://webassembly.github.io/spec/core/syntax/types.html#function-types> -#[derive(Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct FuncType { - data: Box<[WasmType]>, - param_count: u16, -} - -impl FuncType { - /// Create a new function type. - pub fn new(params: &[WasmType], results: &[WasmType]) -> Self { - let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect(); - Self { data, param_count: params.len() as u16 } - } - - /// Get the parameter types of this function type. - pub fn params(&self) -> &[WasmType] { - &self.data[..self.param_count as usize] - } - - /// Get the result types of this function type. - pub fn results(&self) -> &[WasmType] { - &self.data[self.param_count as usize..] - } - - /// Compare function types while resolving concrete references in their respective type spaces. - pub fn equivalent(&self, types: &[FuncType], other: &Self, other_types: &[FuncType]) -> bool { - fn refs_equal( - left_types: &[FuncType], - left: RefType, - right_types: &[FuncType], - right: RefType, - visited: &mut alloc::vec::Vec<(u32, u32)>, - ) -> bool { - if left.is_nullable() != right.is_nullable() { - return false; - } - match (left.type_index(), right.type_index()) { - (Some(left_idx), Some(right_idx)) => { - if visited.contains(&(left_idx, right_idx)) { - return true; - } - let (Some(left), Some(right)) = - (left_types.get(left_idx as usize), right_types.get(right_idx as usize)) - else { - return false; - }; - visited.push((left_idx, right_idx)); - funcs_equal(left, left_types, right, right_types, visited) - } - (None, None) => left.abstract_heap_type() == right.abstract_heap_type(), - _ => false, - } - } - - fn funcs_equal( - left: &FuncType, - left_types: &[FuncType], - right: &FuncType, - right_types: &[FuncType], - visited: &mut alloc::vec::Vec<(u32, u32)>, - ) -> bool { - left.params().len() == right.params().len() - && left.results().len() == right.results().len() - && left.params().iter().chain(left.results()).zip(right.params().iter().chain(right.results())).all( - |(&left, &right)| match (left, right) { - (WasmType::Ref(left), WasmType::Ref(right)) => { - refs_equal(left_types, left, right_types, right, visited) - } - _ => left == right, - }, - ) - } - - if core::ptr::eq(types, other_types) && self == other { - return true; - } - funcs_equal(self, types, other, other_types, &mut alloc::vec::Vec::new()) - } -} - #[derive(Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index ee66965..884d330 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -1,3 +1,12 @@ +const HOST_REF_TAG: u32 = 1 << 30; + +const fn encode_host_ref(addr: u32) -> Option<u32> { + if addr >= HOST_REF_TAG - 1 { + return None; + } + Some((addr | HOST_REF_TAG).wrapping_add(1).wrapping_mul(2)) +} + /// An abstract WebAssembly heap type. /// /// This contains exactly the abstract heap types in core Wasm 3.0. @@ -31,7 +40,8 @@ pub enum AbstractHeapType { /// [nullable:1 concrete:1 payload:30] /// ``` /// -/// For concrete types, `payload` is a module type index. +/// For concrete types, `payload` is a module type index before instantiation +/// and a canonical store type address at runtime. /// Otherwise, it is an [`AbstractHeapType`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -116,9 +126,7 @@ impl RefType { #[inline] pub const fn is_func(self) -> bool { - // TODO(wasm3): Classify concrete refs from the module type definition once GC types are represented. - self.is_concrete() - || matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc)) + matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc)) } #[inline] @@ -132,6 +140,7 @@ impl RefType { } } +/// A host-facing WebAssembly reference value. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -143,19 +152,9 @@ pub enum RefValue { Exn(ExnRef), } -impl RefValue { - /// Return the reference's raw representation, or `None` for null. - pub const fn raw(self) -> Option<u32> { - match self { - Self::Null => None, - Self::Func(value) => Some(value.addr()), - Self::Extern(value) => Some(value.addr()), - Self::Any(value) => Some(value.raw()), - Self::Exn(value) => Some(value.addr()), - } - } -} - +/// A reference to a function in a store. +/// +/// The payload is the function's store-local address. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -173,6 +172,11 @@ impl FuncRef { } } +/// An opaque external reference. +/// +/// Packed as `[payload:31 i31:1]`. Host addresses use the upper payload +/// category, Store-managed objects use the lower category, and odd values +/// contain an externalized i31. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -181,15 +185,35 @@ pub struct ExternRef(u32); impl ExternRef { #[inline] pub const fn new(addr: u32) -> Self { - Self(addr) + let Some(value) = Self::try_new(addr) else { panic!("external reference address is too large") }; + value } + /// Creates an external reference when `addr` fits the runtime encoding. #[inline] - pub const fn addr(self) -> u32 { + pub const fn try_new(addr: u32) -> Option<Self> { + match encode_host_ref(addr) { + Some(raw) => Some(Self(raw)), + None => None, + } + } + + #[doc(hidden)] + #[inline] + pub const fn from_raw(raw: u32) -> Self { + Self(raw) + } + + #[doc(hidden)] + #[inline] + pub const fn raw(self) -> u32 { self.0 } } +/// A reference to an exception in a store. +/// +/// The payload is the exception's store-local address. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -207,14 +231,30 @@ impl ExnRef { } } +/// A WebAssembly `anyref` value. +/// +/// Packed as: +/// +/// ```text +/// [payload:31 i31:1] +/// ``` +/// +/// Odd values contain an inline signed i31. Non-zero even values are reserved +/// for store-managed references, and zero is reserved for null by the runtime. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct AnyRef(u32); impl AnyRef { - // Odd values are inline i31s. - // Even values are GC object handles. + /// Creates a host reference when `addr` fits the runtime encoding. + #[inline] + pub const fn from_host(addr: u32) -> Option<Self> { + match encode_host_ref(addr) { + Some(raw) => Some(Self(raw)), + None => None, + } + } #[doc(hidden)] #[inline] @@ -234,22 +274,21 @@ impl AnyRef { if self.0 & 1 == 1 { Some((self.0 as i32) >> 1) } else { None } } - pub const fn from_gc_addr(addr: u32) -> Option<Self> { - match addr.checked_add(1) { - Some(raw) => match raw.checked_mul(2) { - Some(raw) => Some(Self(raw)), - None => None, - }, - None => None, - } - } - - pub const fn gc_addr(self) -> Option<u32> { - if self.0 != 0 && self.0 & 1 == 0 { Some(self.0 / 2 - 1) } else { None } - } - #[inline] pub const fn raw(self) -> u32 { self.0 } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_reference_encoding_is_checked_and_unique() { + assert_ne!(AnyRef::from_host(0), AnyRef::from_host(1)); + assert!(AnyRef::from_host(HOST_REF_TAG - 2).is_some()); + assert!(AnyRef::from_host(HOST_REF_TAG - 1).is_none()); + assert!(ExternRef::try_new(u32::MAX).is_none()); + } +} diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs new file mode 100644 index 0000000..214ada6 --- /dev/null +++ b/crates/types/src/types.rs @@ -0,0 +1,158 @@ +use alloc::boxed::Box; + +use crate::{TypeAddr, WasmType}; + +/// The dense type index space of a WebAssembly module. +#[derive(Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct TypeSection { + /// Types in module index order. + pub types: Box<[SubType]>, + /// Number of types in each recursive group, in section order. + pub rec_group_lengths: Box<[u32]>, +} + +impl TypeSection { + #[inline] + pub fn get(&self, index: TypeAddr) -> Option<&SubType> { + self.types.get(index as usize) + } + + #[inline] + pub fn len(&self) -> usize { + self.types.len() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.types.is_empty() + } +} + +/// A type with optional declared subtyping. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct SubType { + pub is_final: bool, + pub supertype: Option<TypeAddr>, + pub composite: CompositeType, +} + +impl SubType { + #[inline] + pub const fn as_func(&self) -> Option<&FuncType> { + self.composite.as_func() + } + + #[inline] + pub const fn as_struct(&self) -> Option<&StructType> { + self.composite.as_struct() + } + + #[inline] + pub const fn as_array(&self) -> Option<&ArrayType> { + self.composite.as_array() + } +} + +/// A function, struct, or array type. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum CompositeType { + Func(FuncType), + Struct(StructType), + Array(ArrayType), +} + +impl CompositeType { + #[inline] + pub const fn as_func(&self) -> Option<&FuncType> { + match self { + Self::Func(ty) => Some(ty), + _ => None, + } + } + + #[inline] + pub const fn as_struct(&self) -> Option<&StructType> { + match self { + Self::Struct(ty) => Some(ty), + _ => None, + } + } + + #[inline] + pub const fn as_array(&self) -> Option<&ArrayType> { + match self { + Self::Array(ty) => Some(ty), + _ => None, + } + } +} + +/// The type of a WebAssembly function. +/// +/// See <https://webassembly.github.io/spec/core/syntax/types.html#function-types> +#[derive(Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct FuncType { + data: Box<[WasmType]>, + param_count: u16, +} + +impl FuncType { + /// Create a new function type. + pub fn new(params: &[WasmType], results: &[WasmType]) -> Self { + let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect(); + Self { data, param_count: params.len() as u16 } + } + + /// Get the parameter types of this function type. + pub fn params(&self) -> &[WasmType] { + &self.data[..self.param_count as usize] + } + + /// Get the result types of this function type. + pub fn results(&self) -> &[WasmType] { + &self.data[self.param_count as usize..] + } +} + +/// A WebAssembly struct type. +#[derive(Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct StructType { + pub fields: Box<[FieldType]>, +} + +/// A WebAssembly array type. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ArrayType { + pub field: FieldType, +} + +/// A struct field or array element type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct FieldType { + pub storage: StorageType, + pub mutable: bool, +} + +/// A field's packed or unpacked storage type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum StorageType { + I8, + I16, + Value(WasmType), +} diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 92c660b..f0a576b 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -54,7 +54,7 @@ impl WasmValue { | (Self::V128(_), WasmType::V128) => true, (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { - ty.is_concrete() || matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) + matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) } (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern)) @@ -62,12 +62,42 @@ impl WasmValue { (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => { matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Exn)) } - (Self::Ref(RefValue::Any(_)), WasmType::Ref(ty)) => !ty.is_func() && !ty.is_extern() && !ty.is_exn(), + (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => matches!( + (value.as_i31(), ty.abstract_heap_type()), + ( + Some(_), + Some(crate::AbstractHeapType::I31 | crate::AbstractHeapType::Eq | crate::AbstractHeapType::Any) + ) | (None, Some(crate::AbstractHeapType::Any)) + ), _ => false, } } } +#[cfg(test)] +mod tests { + use super::*; + use crate::{AbstractHeapType, AnyRef, FuncRef, RefType}; + + #[test] + fn concrete_references_require_store_type_information() { + let concrete = WasmType::Ref(RefType::new_concrete(false, 0).unwrap()); + + assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); + assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); + } + + #[test] + fn i31_only_matches_its_store_independent_supertypes() { + let value = WasmValue::from(AnyRef::from_i31(0).unwrap()); + + for ty in [AbstractHeapType::I31, AbstractHeapType::Eq, AbstractHeapType::Any] { + assert!(value.matches_type(WasmType::Ref(RefType::new_abstract(false, ty)))); + } + assert!(!value.matches_type(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::Struct)))); + } +} + impl Debug for WasmValue { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { |
