diff --git a/src/backend/mod.rs b/src/backend/mod.rs index 8854253..4549c4e 100644 --- a/src/backend/mod.rs +++ b/src/backend/mod.rs @@ -216,7 +216,12 @@ impl<'a> WasmFuncBackend<'a> { let from_ty = self.body.values[self.body.resolve_alias(from)] .ty(&self.body.type_pool) .unwrap(); - assert_eq!(from_ty, to_ty); + assert!( + from_ty.is_subtype_of(to_ty), + "block argument type {} is not a subtype of {}", + from_ty, + to_ty + ); if ctx.locals.values[from].len() == 1 { assert_eq!(from_ty, ctx.locals.locals[ctx.locals.values[from][0]]); } @@ -1006,8 +1011,8 @@ impl<'a> WasmFuncBackend<'a> { Some(wasm_encoder::Instruction::CallRef(sig_index.index() as u32)) } Operator::RefIsNull => Some(wasm_encoder::Instruction::RefIsNull), - Operator::RefNull { sig_index } => Some(wasm_encoder::Instruction::RefNull( - wasm_encoder::HeapType::Concrete(sig_index.index() as u32), + Operator::RefNull { ty } => Some(wasm_encoder::Instruction::RefNull( + wasm_encoder::RefType::from(*ty).heap_type, )), Operator::RefFunc { func_index } => { Some(wasm_encoder::Instruction::RefFunc(func_index.index() as u32)) @@ -1643,9 +1648,8 @@ fn const_init(ty: Type, value: Option) -> wasm_encoder::ConstExpr { Type::I64 => wasm_encoder::ConstExpr::i64_const(bits as i64), Type::F32 => wasm_encoder::ConstExpr::f32_const(f32::from_bits(bits as u32).into()), Type::F64 => wasm_encoder::ConstExpr::f64_const(f64::from_bits(bits as u64).into()), - Type::TypedFuncRef(true, sig) if bits == 0 => { - let hty = wasm_encoder::HeapType::Concrete(sig); - wasm_encoder::ConstExpr::ref_null(hty) + Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(true, _) if bits == 0 => { + wasm_encoder::ConstExpr::ref_null(wasm_encoder::RefType::from(ty).heap_type) } _ => unimplemented!(), } diff --git a/src/frontend.rs b/src/frontend.rs index 2960add..86a8254 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -12,7 +12,7 @@ use addr2line::gimli; use anyhow::{bail, Result}; use fxhash::{FxHashMap, FxHashSet}; use log::trace; -use std::convert::TryFrom; +use std::convert::{TryFrom, TryInto}; use wasmparser::{BlockType, DataKind, ExternalKind, KnownCustom, Name, Parser, Payload, TypeRef}; /// Options to control the Wasm-to-bytecode translation process. @@ -98,7 +98,7 @@ fn element_type(items: &wasmparser::ElementItems) -> Result { wasmparser::ElementItems::Expressions(ty, _) if *ty == wasmparser::RefType::FUNCREF || ty.type_index().is_some() => { - Ok((*ty).into()) + Ok((*ty).try_into()?) } wasmparser::ElementItems::Expressions(ty, _) => bail!(FrontendError::UnsupportedFeature( format!("Unsupported element segment type: {:?}", ty) @@ -164,13 +164,14 @@ fn memory_data(ty: &wasmparser::MemoryType) -> Result { } /// Converts a table type to a `TableData` with no elements. Returns -/// `FrontendError::UnsupportedFeature` for a 64-bit table. +/// `FrontendError::UnsupportedFeature` for a 64-bit table and for an +/// element type that `Type` cannot represent. fn table_data(ty: &wasmparser::TableType) -> Result { if ty.table64 { bail!(FrontendError::UnsupportedFeature("64-bit table".into())); } Ok(TableData { - ty: ty.element_type.into(), + ty: ty.element_type.try_into()?, initial: ty.initial, max: ty.maximum, initializer: None, @@ -238,9 +239,14 @@ fn handle_payload<'a>( Payload::TypeSection(reader) => { for rec_group in reader { for ty in rec_group?.into_types() { + if ty.composite_type.shared { + bail!(FrontendError::UnsupportedFeature( + "shared type in type section".into() + )); + } match &ty.composite_type.inner { wasmparser::CompositeInnerType::Func(fty) => { - module.signatures.push(fty.into()); + module.signatures.push(fty.try_into()?); } _ => bail!(FrontendError::UnsupportedFeature( "non-function type in type section".into() @@ -265,7 +271,7 @@ fn handle_payload<'a>( } TypeRef::Global(ty) => { let mutable = ty.mutable; - let ty = ty.content_type.into(); + let ty = ty.content_type.try_into()?; let global = module.globals.push(GlobalData { ty, value: None, @@ -322,7 +328,7 @@ fn handle_payload<'a>( for global in reader { let global = global?; let mutable = global.ty.mutable; - let ty = global.ty.content_type.into(); + let ty = global.ty.content_type.try_into()?; let init_expr = parse_init_expr(&global.init_expr)?; module.globals.push(GlobalData { ty, @@ -549,7 +555,7 @@ fn handle_payload<'a>( let table = Table::from(table_index.unwrap_or(0)); let ty = match &element.items { wasmparser::ElementItems::Functions(_) => Type::FuncRef, - wasmparser::ElementItems::Expressions(ty, _) => (*ty).into(), + wasmparser::ElementItems::Expressions(ty, _) => (*ty).try_into()?, }; module.active_element_segments.push(ActiveElementSegment { index, @@ -671,7 +677,7 @@ pub(crate) fn parse_body<'a>( for _ in 0..locals.get_count() { let (count, ty) = locals.read()?; for _ in 0..count { - ret.locals.push(ty.into()); + ret.locals.push(ty.try_into()?); } } let locals = ret.locals.clone(); @@ -900,7 +906,10 @@ impl LocalTracker { Type::F32 => body.add_op(at_block, Operator::F32Const { value: 0 }, &[], &[ty]), Type::F64 => body.add_op(at_block, Operator::F64Const { value: 0 }, &[], &[ty]), Type::V128 => body.add_op(at_block, Operator::V128Const { value: 0 }, &[], &[ty]), - _ => todo!("unsupported type: {:?}", ty), + Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(true, _) => { + body.add_op(at_block, Operator::RefNull { ty }, &[], &[ty]) + } + Type::TypedFuncRef(false, _) => todo!("unsupported type: {:?}", ty), }; log::trace!( "created default value {} of type {} at block {}", @@ -1618,7 +1627,10 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { | wasmparser::Operator::RefFunc { .. } | wasmparser::Operator::MemoryFill { .. } | wasmparser::Operator::MemoryCopy { .. } => { - self.emit(Operator::try_from(&op).unwrap(), loc)? + let op = Operator::try_from(&op).map_err(|()| { + FrontendError::UnsupportedFeature(format!("Unsupported operator: {:?}", op)) + })?; + self.emit(op, loc)? } wasmparser::Operator::Nop => {} @@ -1851,7 +1863,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } wasmparser::Operator::Block { blockty } => { - let (params, results) = self.block_params_and_results(*blockty); + let (params, results) = self.block_params_and_results(*blockty)?; let out = self.body.add_block(); self.add_block_params(out, &results[..]); let start_depth = if self.reachable { @@ -1869,7 +1881,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } wasmparser::Operator::Loop { blockty } => { - let (params, results) = self.block_params_and_results(*blockty); + let (params, results) = self.block_params_and_results(*blockty)?; let header = self.body.add_block(); self.add_block_params(header, ¶ms[..]); let initial_args = if self.reachable { @@ -1895,7 +1907,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } wasmparser::Operator::If { blockty } => { - let (params, results) = self.block_params_and_results(*blockty); + let (params, results) = self.block_params_and_results(*blockty)?; let if_true = self.body.add_block(); let if_false = self.body.add_block(); let join = self.body.add_block(); @@ -1983,10 +1995,10 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { } } - fn block_params_and_results(&self, ty: BlockType) -> (Vec, Vec) { - match ty { + fn block_params_and_results(&self, ty: BlockType) -> Result<(Vec, Vec)> { + Ok(match ty { BlockType::Empty => (vec![], vec![]), - BlockType::Type(ret_ty) => (vec![], vec![ret_ty.into()]), + BlockType::Type(ret_ty) => (vec![], vec![ret_ty.try_into()?]), BlockType::FuncType(sig_idx) => { let sig = &self.module.signatures[Signature::from(sig_idx)]; ( @@ -1994,7 +2006,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { Vec::from(sig.returns.clone()), ) } - } + }) } fn relative_frame(&mut self, relative_depth: u32) -> &mut Frame { @@ -2156,7 +2168,12 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> { let args = &mut self.body.arg_pool[input_operands]; for (i, &input) in inputs.into_iter().enumerate().rev() { let (stack_top_ty, stack_top) = self.op_stack.pop().unwrap(); - assert_eq!(stack_top_ty, input); + assert!( + stack_top_ty.is_subtype_of(input), + "operand type {} is not a subtype of {}", + stack_top_ty, + input + ); args[i] = stack_top; } log::trace!(" -> operands: {:?}", input_operands); diff --git a/src/ir.rs b/src/ir.rs index 7f99bf4..d03bde1 100644 --- a/src/ir.rs +++ b/src/ir.rs @@ -1,12 +1,14 @@ //! Intermediate representation for Wasm. use crate::declare_entity; +use crate::FrontendError; +use std::convert::{TryFrom, TryInto}; /// Types in waffle's IR. /// /// These types correspond to (a subset of) the primitive Wasm value -/// types: integers, floats, SIMD vectors, and function references -/// (optionally typed). +/// types: integers, floats, SIMD vectors, function references +/// (optionally typed), and external references. /// /// Every SSA value in a function body has a `Type`, unless it is a /// tuple (multi-value or zero-value result). @@ -32,31 +34,61 @@ pub enum Type { V128, /// A function reference. FuncRef, + /// A nullable external reference (`externref`). + ExternRef, /// A typed function reference, optionally nullable, and with type /// specified by a signature index in the module's signature /// index-space. TypedFuncRef(bool, u32), } -impl From for Type { - fn from(ty: wasmparser::ValType) -> Self { +impl TryFrom for Type { + type Error = FrontendError; + + fn try_from(ty: wasmparser::ValType) -> Result { match ty { - wasmparser::ValType::I32 => Type::I32, - wasmparser::ValType::I64 => Type::I64, - wasmparser::ValType::F32 => Type::F32, - wasmparser::ValType::F64 => Type::F64, - wasmparser::ValType::V128 => Type::V128, - wasmparser::ValType::Ref(r) => r.into(), + wasmparser::ValType::I32 => Ok(Type::I32), + wasmparser::ValType::I64 => Ok(Type::I64), + wasmparser::ValType::F32 => Ok(Type::F32), + wasmparser::ValType::F64 => Ok(Type::F64), + wasmparser::ValType::V128 => Ok(Type::V128), + wasmparser::ValType::Ref(r) => r.try_into(), } } } -impl From for Type { - fn from(ty: wasmparser::RefType) -> Self { - match ty.type_index() { - Some(idx) => { - let nullable = ty.is_nullable(); - Type::TypedFuncRef(nullable, idx.as_module_index().unwrap()) +/// Converts a reference type to a `Type`. Nullable `func` and `extern` +/// references convert to `FuncRef` and `ExternRef`, and references to a +/// module type index convert to `TypedFuncRef`. Every other reference +/// type returns `FrontendError::UnsupportedFeature`: non-nullable +/// abstract references, shared abstract references, exact references, +/// references to a rec-group type index, and abstract heap types other +/// than `func` and `extern`. +impl TryFrom for Type { + type Error = FrontendError; + + fn try_from(ty: wasmparser::RefType) -> Result { + use wasmparser::{AbstractHeapType, HeapType, UnpackedIndex}; + match (ty.heap_type(), ty.is_nullable()) { + (HeapType::Concrete(UnpackedIndex::Module(idx)), nullable) => { + Ok(Type::TypedFuncRef(nullable, idx)) } - None => Type::FuncRef, + ( + HeapType::Abstract { + shared: false, + ty: AbstractHeapType::Func, + }, + true, + ) => Ok(Type::FuncRef), + ( + HeapType::Abstract { + shared: false, + ty: AbstractHeapType::Extern, + }, + true, + ) => Ok(Type::ExternRef), + _ => Err(FrontendError::UnsupportedFeature(format!( + "Unsupported reference type: {}", + ty + ))), } } } @@ -70,6 +102,7 @@ impl std::fmt::Display for Type { Type::F64 => write!(f, "f64"), Type::V128 => write!(f, "v128"), Type::FuncRef => write!(f, "funcref"), + Type::ExternRef => write!(f, "externref"), Type::TypedFuncRef(nullable, idx) => write!( f, "funcref({}, {})", @@ -88,7 +121,9 @@ impl From for wasm_encoder::ValType { Type::F32 => wasm_encoder::ValType::F32, Type::F64 => wasm_encoder::ValType::F64, Type::V128 => wasm_encoder::ValType::V128, - Type::FuncRef | Type::TypedFuncRef(..) => wasm_encoder::ValType::Ref(ty.into()), + Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(..) => { + wasm_encoder::ValType::Ref(ty.into()) + } } } } @@ -97,6 +132,7 @@ impl From for wasm_encoder::RefType { fn from(ty: Type) -> wasm_encoder::RefType { match ty { Type::FuncRef => wasm_encoder::RefType::FUNCREF, + Type::ExternRef => wasm_encoder::RefType::EXTERNREF, Type::TypedFuncRef(nullable, idx) => wasm_encoder::RefType { nullable, heap_type: wasm_encoder::HeapType::Concrete(idx), @@ -106,6 +142,24 @@ impl From for wasm_encoder::RefType { } } +impl Type { + /// Returns `true` if a value of type `self` is valid where a value of + /// type `other` is expected: the types are equal, `self` is a typed + /// function reference and `other` is `FuncRef`, or both are typed + /// function references with the same signature index and `other` is + /// nullable or `self` is not. Signature indices are compared by + /// index, not by the signatures they refer to. + pub(crate) fn is_subtype_of(self, other: Type) -> bool { + match (self, other) { + (Type::TypedFuncRef(..), Type::FuncRef) => true, + (Type::TypedFuncRef(sub_nullable, sub_sig), Type::TypedFuncRef(nullable, sig)) => { + sub_sig == sig && (nullable || !sub_nullable) + } + _ => self == other, + } + } +} + // Per-module index spaces: // A signature (list of parameter types and list of return types) in diff --git a/src/ir/module.rs b/src/ir/module.rs index 5854561..880fed8 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -4,9 +4,10 @@ use super::{ }; use crate::entity::{EntityRef, EntityVec}; use crate::ir::{Debug, DebugMap, FunctionBody}; -use crate::{backend, frontend}; +use crate::{backend, frontend, FrontendError}; use anyhow::Result; use std::collections::BTreeMap; +use std::convert::{TryFrom, TryInto}; pub use crate::frontend::FrontendOptions; @@ -225,25 +226,29 @@ pub struct GlobalData { pub mutable: bool, } -impl From<&wasmparser::FuncType> for SignatureData { - fn from(fty: &wasmparser::FuncType) -> Self { - Self { +impl TryFrom<&wasmparser::FuncType> for SignatureData { + type Error = FrontendError; + + fn try_from(fty: &wasmparser::FuncType) -> Result { + Ok(Self { params: fty .params() .iter() - .map(|&ty| ty.into()) - .collect::>(), + .map(|&ty| ty.try_into()) + .collect::, _>>()?, returns: fty .results() .iter() - .map(|&ty| ty.into()) - .collect::>(), - } + .map(|&ty| ty.try_into()) + .collect::, _>>()?, + }) } } -impl From for SignatureData { - fn from(fty: wasmparser::FuncType) -> Self { - (&fty).into() +impl TryFrom for SignatureData { + type Error = FrontendError; + + fn try_from(fty: wasmparser::FuncType) -> Result { + (&fty).try_into() } } diff --git a/src/op_traits.rs b/src/op_traits.rs index 9d70a70..b5bbc8b 100644 --- a/src/op_traits.rs +++ b/src/op_traits.rs @@ -956,9 +956,7 @@ pub fn op_outputs( Ok(Vec::from(module.signatures[*sig_index].returns.clone()).into()) } Operator::RefIsNull => Ok(Cow::Borrowed(&[Type::I32])), - Operator::RefNull { sig_index } => { - Ok(vec![Type::TypedFuncRef(true, sig_index.index() as u32)].into()) - } + Operator::RefNull { ty } => Ok(vec![*ty].into()), Operator::RefFunc { func_index } => { let ty = module.funcs[*func_index].sig(); Ok(vec![Type::TypedFuncRef(true, ty.index() as u32)].into()) @@ -2078,7 +2076,7 @@ impl std::fmt::Display for Operator { Operator::CallRef { sig_index } => write!(f, "call_ref<{}>", sig_index)?, Operator::RefIsNull => write!(f, "ref_is_null")?, - Operator::RefNull { sig_index } => write!(f, "ref_null<{}>", sig_index)?, + Operator::RefNull { ty } => write!(f, "ref_null<{}>", ty)?, Operator::RefFunc { func_index } => write!(f, "ref_func<{}>", func_index)?, } diff --git a/src/ops.rs b/src/ops.rs index 0e78d3b..3e8a30c 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -15,7 +15,7 @@ //! control flow (these become `Terminator` instructions). use crate::{entity::EntityRef, Func, Global, Memory, Signature, Table, Type}; -use std::convert::TryFrom; +use std::convert::{TryFrom, TryInto}; pub use wasmparser::{Ieee32, Ieee64}; /// An argument to a memory load or store, specifying which memory, @@ -660,8 +660,10 @@ pub enum Operator { sig_index: Signature, }, RefIsNull, + /// `ty` is the result type: `FuncRef`, `ExternRef`, or a nullable + /// `TypedFuncRef`. RefNull { - sig_index: Signature, + ty: Type, }, RefFunc { func_index: Func, @@ -695,9 +697,9 @@ impl<'a, 'b> std::convert::TryFrom<&'b wasmparser::Operator<'a>> for Operator { &wasmparser::Operator::LocalTee { .. } => Err(()), &wasmparser::Operator::LocalGet { .. } => Err(()), &wasmparser::Operator::Select => Ok(Operator::Select), - &wasmparser::Operator::TypedSelect { ty } => { - Ok(Operator::TypedSelect { ty: ty.into() }) - } + &wasmparser::Operator::TypedSelect { ty } => Ok(Operator::TypedSelect { + ty: ty.try_into().map_err(|_| ())?, + }), &wasmparser::Operator::GlobalGet { global_index } => Ok(Operator::GlobalGet { global_index: Global::from(global_index), }), @@ -1306,11 +1308,12 @@ impl<'a, 'b> std::convert::TryFrom<&'b wasmparser::Operator<'a>> for Operator { sig_index: Signature::from(type_index), }), &wasmparser::Operator::RefIsNull => Ok(Operator::RefIsNull), - &wasmparser::Operator::RefNull { - hty: wasmparser::HeapType::Concrete(wasmparser::UnpackedIndex::Module(sig)), - } => Ok(Operator::RefNull { - sig_index: Signature::from(sig), - }), + &wasmparser::Operator::RefNull { hty } => { + let ty = wasmparser::RefType::new(true, hty).ok_or(())?; + Ok(Operator::RefNull { + ty: ty.try_into().map_err(|_| ())?, + }) + } &wasmparser::Operator::RefFunc { function_index } => Ok(Operator::RefFunc { func_index: Func::from(function_index), }), diff --git a/tests/reference_types.rs b/tests/reference_types.rs new file mode 100644 index 0000000..fad609e --- /dev/null +++ b/tests/reference_types.rs @@ -0,0 +1,60 @@ +//! Tests for the reference types that the IR represents and the ones +//! the frontend rejects. + +use waffle::wasmparser::Validator; +use waffle::{FrontendError, FrontendOptions, GlobalData, Module, Type}; + +#[test] +fn externref_is_preserved() { + let bytes = wat::parse_str("(module (func (result externref) (ref.null extern)))").unwrap(); + let module = Module::from_wasm_bytes(&bytes, &FrontendOptions::default()).unwrap(); + Validator::new() + .validate_all(&module.to_wasm_bytes().unwrap()) + .unwrap(); +} + +#[test] +fn nullable_reference_globals_without_a_value_are_null() { + let mut module = Module::empty(); + for ty in [Type::FuncRef, Type::ExternRef] { + module.globals.push(GlobalData { + ty, + value: None, + mutable: false, + }); + } + let bytes = module.to_wasm_bytes().unwrap(); + Validator::new().validate_all(&bytes).unwrap(); +} + +/// Parses `wat` and expands every function body, and asserts that one of +/// the two steps returns `FrontendError::UnsupportedFeature`. +fn assert_unsupported(wat: &str) { + let bytes = wat::parse_str(wat).unwrap(); + let result = Module::from_wasm_bytes(&bytes, &FrontendOptions::default()) + .and_then(|mut module| module.expand_all_funcs()); + let err = result + .err() + .unwrap_or_else(|| panic!("module was accepted: {}", wat)); + assert!( + matches!( + err.downcast_ref::(), + Some(FrontendError::UnsupportedFeature(_)) + ), + "unexpected error for {}: {:?}", + wat, + err + ); +} + +#[test] +fn unrepresentable_reference_types_are_unsupported() { + assert_unsupported("(module (type (shared (func))))"); + assert_unsupported("(module (func (param (ref func))))"); + assert_unsupported("(module (func (param (ref extern))))"); + assert_unsupported("(module (table 1 anyref))"); + assert_unsupported("(module (import \"\" \"\" (global nullfuncref)))"); + assert_unsupported("(module (func (local i31ref)))"); + assert_unsupported("(module (func (block (result exnref) (unreachable)) (drop)))"); + assert_unsupported("(module (func (drop (ref.null any))))"); +} diff --git a/tests/roundtrip/ref-block-param-subtyping.wat b/tests/roundtrip/ref-block-param-subtyping.wat new file mode 100644 index 0000000..27a7abc --- /dev/null +++ b/tests/roundtrip/ref-block-param-subtyping.wat @@ -0,0 +1,5 @@ +(module + (func $f (export "f") (param funcref i32) (result i32) + (if (local.get 1) + (then (local.set 0 (ref.func $f)))) + (ref.is_null (local.get 0)))) diff --git a/tests/roundtrip/ref-local-defaults.wat b/tests/roundtrip/ref-local-defaults.wat new file mode 100644 index 0000000..79d357a --- /dev/null +++ b/tests/roundtrip/ref-local-defaults.wat @@ -0,0 +1,5 @@ +(module + (type $t (func)) + (func (local funcref) (drop (local.get 0))) + (func (result externref) (local externref) (local.get 0)) + (func (result (ref null $t)) (local (ref null $t)) (local.get 0))) diff --git a/tests/roundtrip/ref-null-abstract.wat b/tests/roundtrip/ref-null-abstract.wat new file mode 100644 index 0000000..be78b44 --- /dev/null +++ b/tests/roundtrip/ref-null-abstract.wat @@ -0,0 +1,2 @@ +(module + (func (result externref) (ref.null extern))) diff --git a/tests/roundtrip/ref-operand-subtyping.wat b/tests/roundtrip/ref-operand-subtyping.wat new file mode 100644 index 0000000..d4cb457 --- /dev/null +++ b/tests/roundtrip/ref-operand-subtyping.wat @@ -0,0 +1,12 @@ +(module + (type $t (func)) + (table 1 funcref) + (elem (i32.const 0) func $f) + + (func $f (type $t)) + + (func $call-non-nullable (param (ref $t)) + (call_ref $t (local.get 0))) + + (func $funcref-operand + (table.set (i32.const 0) (ref.func $f))))