A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Component model: catch exceptions at component barriers and turn into traps. (#13613)
Chris Fallinf1b49f1610b8
diff --git a/crates/c-api/include/wasmtime/trap.h b/crates/c-api/include/wasmtime/trap.hindex 1d3747a592..523c3c56c4 100644--- a/crates/c-api/include/wasmtime/trap.h+++ b/crates/c-api/include/wasmtime/trap.h@@ -142,6 +142,8 @@ enum wasmtime_trap_code_enum {/// was being used in a synchronous operation or tried to use it in a/// synchronous operation while it was added to a waitable set.WASMTIME_TRAP_CODE_WAITABLE_SYNC_AND_ASYNC = 48,+ /// An exception propagated out of a component without being caught.+ WASMTIME_TRAP_CODE_UNCAUGHT_EXCEPTION = 49,};/**diff --git a/crates/c-api/src/trap.rs b/crates/c-api/src/trap.rsindex c8383152a8..9a77c3f6f5 100644--- a/crates/c-api/src/trap.rs+++ b/crates/c-api/src/trap.rs@@ -55,6 +55,7 @@ const _: () = {assert!(Trap::ReferenceCountOverflow as u8 == 46);assert!(Trap::StreamOpTooBig as u8 == 47);assert!(Trap::WaitableSyncAndAsync as u8 == 48);+ assert!(Trap::UncaughtException as u8 == 49);};#[repr(C)]diff --git a/crates/cranelift/src/compiler/component.rs b/crates/cranelift/src/compiler/component.rsindex 9688cb3b52..61cc9e6872 100644--- a/crates/cranelift/src/compiler/component.rs+++ b/crates/cranelift/src/compiler/component.rs@@ -3,7 +3,9 @@use crate::alias_region_key::{AliasRegionKey, VmType};use crate::func_environ::BuiltinFunctions;use crate::trap::TranslateTrap;-use crate::{TRAP_CANNOT_LEAVE_COMPONENT, TRAP_INTERNAL_ASSERT, compiler::Compiler};+use crate::{+ TRAP_CANNOT_LEAVE_COMPONENT, TRAP_INTERNAL_ASSERT, TRAP_UNCAUGHT_EXCEPTION, compiler::Compiler,+};use cranelift_codegen::cursor::FuncCursor;use cranelift_codegen::ir::condcodes::IntCC;use cranelift_codegen::ir::{self, InstBuilder, MemFlagsData, Value};@@ -1266,11 +1268,38 @@ impl<'a> TrampolineCompiler<'a> {// takes ourselves out of the chain here but that's ok since the// caller is only used for store/limits and that same info is// stored, but elsewhere, in the component context.- self.builder.ins().call_indirect(+ //+ // The destructor is another component's code and this+ // intrinsic is the boundary between the two components,+ // so per the component model's canonical ABI an exception+ // thrown by the destructor and not caught within its+ // component must become a trap rather than unwinding into+ // the calling component. That's implemented here with a+ // catch-all exception handler.+ let continuation = self.builder.create_block();+ let uncaught_exception = self.builder.create_block();+ self.builder.set_cold_block(uncaught_exception);+ let dfg = &mut self.builder.func.dfg;+ let exception_table = dfg.exception_tables.push(ir::ExceptionTableData::new(sig_ref,+ ir::BlockCall::new(continuation, None, &mut dfg.value_lists),+ [ir::ExceptionTableItem::Default(ir::BlockCall::new(+ uncaught_exception,+ None,+ &mut dfg.value_lists,+ ))],+ ));+ self.builder.ins().try_call_indirect(func_addr,&[callee_vmctx, caller_vmctx, rep],+ exception_table,);+ self.builder.switch_to_block(uncaught_exception);+ self.builder.seal_block(uncaught_exception);+ let (mut traps, builder) = self.traps();+ traps.trap(builder, TRAP_UNCAUGHT_EXCEPTION);+ self.builder.switch_to_block(continuation);+ self.builder.seal_block(continuation);}if let Some(old_may_block) = old_may_block {diff --git a/crates/cranelift/src/lib.rs b/crates/cranelift/src/lib.rsindex ee88cfd32c..208e2abff6 100644--- a/crates/cranelift/src/lib.rs+++ b/crates/cranelift/src/lib.rs@@ -75,6 +75,8 @@ pub const TRAP_CONTINUATION_ALREADY_CONSUMED: TrapCode =TrapCode::unwrap_user(Trap::ContinuationAlreadyConsumed as u8 + TRAP_OFFSET);pub const TRAP_CAST_FAILURE: TrapCode =TrapCode::unwrap_user(Trap::CastFailure as u8 + TRAP_OFFSET);+pub const TRAP_UNCAUGHT_EXCEPTION: TrapCode =+ TrapCode::unwrap_user(Trap::UncaughtException as u8 + TRAP_OFFSET);/// Creates a new cranelift `Signature` with no wasm params/results for the/// given calling convention.diff --git a/crates/environ/src/component/translate/adapt.rs b/crates/environ/src/component/translate/adapt.rsindex baedeedf70..69d310a507 100644--- a/crates/environ/src/component/translate/adapt.rs+++ b/crates/environ/src/component/translate/adapt.rs@@ -206,7 +206,11 @@ impl<'data> Translator<'_, 'data> {// the module using standard core wasm translation, and then fills out// the dfg metadata for each adapter.for (module_id, adapter_module) in state.adapter_modules.iter() {- let mut module = fact::Module::new(self.types.types(), self.tunables);+ let mut module = fact::Module::new(+ self.types.types(),+ self.tunables,+ *self.validator.features(),+ );let mut names = Vec::with_capacity(adapter_module.adapters.len());for adapter in adapter_module.adapters.iter() {let name = format!("adapter{}", adapter.as_u32());diff --git a/crates/environ/src/fact.rs b/crates/environ/src/fact.rsindex 935d746eb7..302bc00162 100644--- a/crates/environ/src/fact.rs+++ b/crates/environ/src/fact.rs@@ -32,6 +32,7 @@ use crate::{};use std::collections::HashMap;use wasm_encoder::*;+use wasmparser::WasmFeatures;mod core_types;mod signature;@@ -61,6 +62,9 @@ pub struct Module<'a> {/// Type information from the creator of this `Module`types: &'a ComponentTypesBuilder,+ /// The Wasm features enabled for validation of this module.+ features: WasmFeatures,+/// Core wasm type section that's incrementally builtcore_types: core_types::CoreTypes,@@ -259,10 +263,15 @@ enum HelperLocation {impl<'a> Module<'a> {/// Creates an empty module.- pub fn new(types: &'a ComponentTypesBuilder, tunables: &'a Tunables) -> Module<'a> {+ pub fn new(+ types: &'a ComponentTypesBuilder,+ tunables: &'a Tunables,+ features: WasmFeatures,+ ) -> Module<'a> {Module {tunables,types,+ features,core_types: Default::default(),core_imports: Default::default(),imported: Default::default(),diff --git a/crates/environ/src/fact/trampoline.rs b/crates/environ/src/fact/trampoline.rsindex ecadeab348..d046a998b7 100644--- a/crates/environ/src/fact/trampoline.rs+++ b/crates/environ/src/fact/trampoline.rs@@ -35,7 +35,7 @@ use crate::{FuncIndex, GlobalIndex, IndexType, Trap};use std::collections::HashMap;use std::mem;use std::ops::Range;-use wasm_encoder::{BlockType, Encode, Instruction, Instruction::*, MemArg, ValType};+use wasm_encoder::{BlockType, Catch, Encode, Instruction, Instruction::*, MemArg, ValType};use wasmtime_component_util::{DiscriminantSize, FlagsSize};use super::DataModel;@@ -689,6 +689,11 @@ impl<'a, 'b> Compiler<'a, 'b> {/// This allows the host to delay copying the parameters until the callee/// signals readiness by clearing its backpressure flag.fn compile_async_start_adapter(mut self, adapter: &AdapterData, sig: &Signature) {+ // Note that unlike `compile_sync_to_sync_adapter` no exception+ // barrier is emitted here: this function is invoked by the host, so+ // an exception thrown by any guest code it calls (e.g. `realloc`)+ // unwinds to the host rather than into another component, and the+ // host already catches it at that boundary.let param_locals = sig.params.iter()@@ -712,6 +717,9 @@ impl<'a, 'b> Compiler<'a, 'b> {/// callee to caller when that intrinsic is called rather than when the/// callee task fully completes (which may happen much later).fn compile_async_return_adapter(mut self, adapter: &AdapterData, sig: &Signature) {+ // As with `compile_async_start_adapter`, no exception barrier is+ // emitted here: the host invokes this function and already catches+ // exceptions unwinding out of it.let param_locals = sig.params.iter()@@ -748,6 +756,8 @@ impl<'a, 'b> Compiler<'a, 'b> {lower_sig: &Signature,lift_sig: &Signature,) {+ self.enter_exception_barrier(&lower_sig.results);+// Check the instance flags required for this trampoline.//// This inserts the initial check required by `canon_lower` that the@@ -902,6 +912,8 @@ impl<'a, 'b> Compiler<'a, 'b> {}}+ self.exit_exception_barrier();+self.finish()}@@ -3867,6 +3879,71 @@ impl<'a, 'b> Compiler<'a, 'b> {self.instruction(Unreachable);}+ /// Emits the prologue of an exception barrier wrapping the body of a+ /// function.+ ///+ /// An adapter is the boundary between two components, and the+ /// component model's canonical ABI specifies that an exception+ /// which propagates out of a component without being caught+ /// becomes a trap rather than unwinding into the other+ /// component. To implement that, the entire body of an adapter+ /// function is wrapped in a `try_table` whose `catch_all` clause+ /// traps. This catches exceptions thrown not only by the callee+ /// itself but also by any other guest functions the adapter+ /// invokes (e.g. `realloc`).+ ///+ /// The generated structure, completed by `exit_exception_barrier`,+ /// is:+ ///+ /// ```wasm+ /// block (result ...) ;; carries results past the handler+ /// block ;; catch_all landing pad+ /// try_table (result ...) (catch_all 0)+ /// ;; ... body ...+ /// end+ /// br 1 ;; done; carry results past the handler+ /// end+ /// ;; an exception was caught: raise a trap+ /// unreachable+ /// end+ /// ```+ ///+ /// This is only done when the exceptions proposal is enabled.+ fn enter_exception_barrier(&mut self, results: &[ValType]) {+ if !self.module.features.exceptions() {+ return;+ }+ let block_ty = match results.len() {+ 0 => BlockType::Empty,+ 1 => BlockType::Result(results[0]),+ _ => BlockType::FunctionType(self.module.core_types.function(&[], results)),+ };+ // Outer block: carries the body's results past the handler.+ self.instruction(Block(block_ty));+ // Inner block: the landing pad targeted by the `catch_all` clause.+ self.instruction(Block(BlockType::Empty));+ self.instruction(TryTable(block_ty, vec![Catch::All { label: 0 }].into()));+ }++ /// Emits the epilogue of an exception barrier started with+ /// `enter_exception_barrier`: the body's results jump past the+ /// `catch_all` landing pad, which turns a caught exception into a+ /// trap.+ fn exit_exception_barrier(&mut self) {+ if !self.module.features.exceptions() {+ return;+ }+ // End of the `try_table`.+ self.instruction(End);+ // Normal completion: jump over the handler, carrying the results.+ self.instruction(Br(1));+ // End of the inner block: the `catch_all` landing pad.+ self.instruction(End);+ self.trap(Trap::UncaughtException);+ // End of the outer block; the body's results flow out.+ self.instruction(End);+ }+/// Flushes out the current `code` instructions into the destination/// function.///diff --git a/crates/environ/src/trap_encoding.rs b/crates/environ/src/trap_encoding.rsindex 9bdc78fbef..85a52828a9 100644--- a/crates/environ/src/trap_encoding.rs+++ b/crates/environ/src/trap_encoding.rs@@ -275,6 +275,9 @@ generate_trap_type! {/// synchronous operation while it was added to a waitable set.WaitableSyncAndAsync = "waitable cannot be used synchronously while added to a waitable set",+ /// An exception propagated out of a component without being caught.+ UncaughtException = "uncaught exception propagated out of component",+// if adding a variant here be sure to update `trap.rs` and `trap.h` as// mentioned above}diff --git a/tests/disas/component-model/direct-adapter-calls-inlining.wat b/tests/disas/component-model/direct-adapter-calls-inlining.watindex 0d666aa0aa..cabaa03df8 100644--- a/tests/disas/component-model/direct-adapter-calls-inlining.wat+++ b/tests/disas/component-model/direct-adapter-calls-inlining.wat@@ -86,56 +86,75 @@;; @00ee jump block2;;;; block2:+;; jump block6+;;+;; block8(v10: i64):+;; jump block5+;;+;; block6:;; @00ee v5 = load.i64 notrap aligned readonly can_move region1 v0+72-;; v12 = load.i64 notrap aligned readonly can_move region2 v5+136-;; v13 = load.i32 notrap aligned region4 v12-;; v14 = iconst.i32 1-;; v15 = band v13, v14 ; v14 = 1-;; v11 = iconst.i32 0-;; v17 = icmp eq v15, v11 ; v11 = 0-;; brif v17, block4, block5+;; v15 = load.i64 notrap aligned readonly can_move region2 v5+136+;; v16 = load.i32 notrap aligned region4 v15+;; v17 = iconst.i32 1+;; v18 = band v16, v17 ; v17 = 1+;; v14 = iconst.i32 0+;; v20 = icmp eq v18, v14 ; v14 = 0+;; brif v20, block9, block10;;-;; block4:-;; v21 = load.i64 notrap aligned readonly can_move region6 v5+88-;; v20 = load.i64 notrap aligned readonly can_move region5 v5+104-;; v19 = iconst.i32 23-;; call_indirect sig1, v21(v20, v5, v19) ; v19 = 23+;; block9:+;; v24 = load.i64 notrap aligned readonly can_move region6 v5+88+;; v23 = load.i64 notrap aligned readonly can_move region5 v5+104+;; v22 = iconst.i32 23+;; try_call_indirect v24(v23, v5, v22), sig1, block11, [ context v5, default: block8(exn0) ] ; v22 = 23+;;+;; block11:;; trap user12;;-;; block5:-;; v22 = load.i64 notrap aligned readonly can_move region3 v5+112-;; v23 = load.i32 notrap aligned region4 v22-;; v24 = iconst.i32 -2-;; v25 = band v23, v24 ; v24 = -2-;; store notrap aligned region4 v25, v22-;; v55 = iconst.i32 1-;; v56 = bor v23, v55 ; v55 = 1-;; store notrap aligned region4 v56, v22-;; jump block6+;; block10:+;; v29 = load.i64 notrap aligned readonly can_move region3 v5+112+;; v30 = load.i32 notrap aligned region4 v29+;; v31 = iconst.i32 -2+;; v32 = band v30, v31 ; v31 = -2+;; store notrap aligned region4 v32, v29+;; v62 = iconst.i32 1+;; v63 = bor v30, v62 ; v62 = 1+;; store notrap aligned region4 v63, v29+;; jump block13;;-;; block6:+;; block13:+;; jump block14+;;+;; block14:+;; jump block12+;;+;; block12:+;; v43 = load.i32 notrap aligned region4 v15+;; v64 = iconst.i32 -2+;; v65 = band v43, v64 ; v64 = -2+;; store notrap aligned region4 v65, v15+;; v66 = iconst.i32 1+;; v67 = bor v43, v66 ; v66 = 1+;; store notrap aligned region4 v67, v15;; jump block7;;;; block7:-;; jump block8-;;-;; block8:-;; v36 = load.i32 notrap aligned region4 v12-;; v57 = iconst.i32 -2-;; v58 = band v36, v57 ; v57 = -2-;; store notrap aligned region4 v58, v12-;; v59 = iconst.i32 1-;; v60 = bor v36, v59 ; v59 = 1-;; store notrap aligned region4 v60, v12+;; jump block4+;;+;; block5:+;; v26 = iconst.i32 49+;; call_indirect.i64 sig1, v24(v23, v5, v26) ; v26 = 49+;; trap user12+;;+;; block4:;; jump block3;;;; block3:-;; jump block9+;; jump block15;;-;; block9:+;; block15:;; @00f0 jump block1;;;; block1:-;; v47 = iconst.i32 1276-;; @00f0 return v47 ; v47 = 1276+;; v54 = iconst.i32 1276+;; @00f0 return v54 ; v54 = 1276;; }diff --git a/tests/disas/component-model/direct-adapter-calls-x64.wat b/tests/disas/component-model/direct-adapter-calls-x64.watindex 7bcadcae1d..3dcbe79db1 100644--- a/tests/disas/component-model/direct-adapter-calls-x64.wat+++ b/tests/disas/component-model/direct-adapter-calls-x64.wat@@ -85,41 +85,65 @@;; movq %rsp, %rbp;; movq 8(%rdi), %r10;; movq 0x18(%r10), %r10-;; addq $0x20, %r10+;; addq $0x50, %r10;; cmpq %rsp, %r10-;; ja 0xe7-;; 79: subq $0x10, %rsp-;; movq %rbx, (%rsp)-;; movq 0x88(%rdi), %rbx-;; movl (%rbx), %eax+;; ja 0x147+;; 79: subq $0x40, %rsp+;; movq %rbx, 0x10(%rsp)+;; movq %r12, 0x18(%rsp)+;; movq %r13, 0x20(%rsp)+;; movq %r14, 0x28(%rsp)+;; movq %r15, 0x30(%rsp)+;; movq %rdi, (%rsp)+;; movq (%rsp), %rdi+;; movq 0x88(%rdi), %r8+;; movl (%r8), %eax+;; movq %r8, 8(%rsp);; testl $1, %eax-;; je 0xd3-;; 95: movq 0x70(%rdi), %rax+;; je 0x115+;; b8: movq (%rsp), %rdi+;; movq 0x70(%rdi), %rax;; movl (%rax), %ecx;; movq %rcx, %rsi;; andl $0xfffffffe, %esi;; movl %esi, (%rax);; orl $1, %ecx;; movl %ecx, (%rax)-;; movq %rdi, %rax-;; movq 0x48(%rax), %rdi-;; movq %rax, %rsi+;; movq 0x48(%rdi), %rdi+;; movq (%rsp), %rsi;; callq 0-;; movl (%rbx), %ecx-;; movq %rcx, %rdx-;; andl $0xfffffffe, %edx-;; movl %edx, (%rbx)+;; ├─╼ exception frame offset: SP = FP - 0x40+;; ╰─╼ exception handler: default handler, context at [SP+0x0], handler=0x12e+;; movq 8(%rsp), %r8+;; movl (%r8), %ecx+;; movq %rcx, %rsi+;; andl $0xfffffffe, %esi+;; movl %esi, (%r8);; orl $1, %ecx-;; movl %ecx, (%rbx)-;; movq (%rsp), %rbx-;; addq $0x10, %rsp+;; movl %ecx, (%r8)+;; movq 0x10(%rsp), %rbx+;; movq 0x18(%rsp), %r12+;; movq 0x20(%rsp), %r13+;; movq 0x28(%rsp), %r14+;; movq 0x30(%rsp), %r15+;; addq $0x40, %rsp;; movq %rbp, %rsp;; popq %rbp;; retq-;; d3: movq %rdi, %rsi-;; d6: movq 0x58(%rsi), %rax-;; da: movq 0x68(%rsi), %rdi-;; de: movl $0x17, %edx-;; e3: callq *%rax-;; e5: ud2-;; e7: ud2+;; 115: movq (%rsp), %rcx+;; 119: movq 0x58(%rcx), %rax+;; 11d: movq 0x68(%rcx), %rdi+;; 121: movl $0x17, %edx+;; 126: movq (%rsp), %rsi+;; 12a: callq *%rax+;; ├─╼ exception frame offset: SP = FP - 0x40+;; ╰─╼ exception handler: default handler, context at [SP+0x0], handler=0x12e+;; 12c: ud2+;; 12e: movq (%rsp), %rcx+;; 132: movq 0x58(%rcx), %rax+;; 136: movq 0x68(%rcx), %rdi+;; 13a: movl $0x31, %edx+;; 13f: movq (%rsp), %rsi+;; 143: callq *%rax+;; 145: ud2+;; 147: ud2diff --git a/tests/disas/component-model/direct-adapter-calls.wat b/tests/disas/component-model/direct-adapter-calls.watindex 09b7f5e26b..83cc212593 100644--- a/tests/disas/component-model/direct-adapter-calls.wat+++ b/tests/disas/component-model/direct-adapter-calls.wat@@ -114,39 +114,64 @@;; stack_limit = gv2;;;; block0(v0: i64, v1: i64, v2: i32):-;; @0077 v5 = load.i64 notrap aligned readonly can_move region1 v0+136-;; @0077 v6 = load.i32 notrap aligned region2 v5-;; @0079 v7 = iconst.i32 1-;; @007b v8 = band v6, v7 ; v7 = 1+;; @007b jump block4+;;+;; block6(v7: i64):+;; @007b jump block3+;;+;; block4:+;; @0080 v9 = load.i64 notrap aligned readonly can_move region1 v0+136+;; @0080 v10 = load.i32 notrap aligned region2 v9+;; @0082 v11 = iconst.i32 1+;; @0084 v12 = band v10, v11 ; v11 = 1;; @0075 v4 = iconst.i32 0-;; @007c v10 = icmp eq v8, v4 ; v4 = 0-;; @007d brif v10, block2, block3+;; @0085 v14 = icmp eq v12, v4 ; v4 = 0+;; @0086 brif v14, block7, block8+;;+;; block7:+;; @008a v19 = load.i64 notrap aligned readonly can_move region4 v0+88+;; @008a v18 = load.i64 notrap aligned readonly can_move region3 v0+104+;; @0088 v16 = iconst.i32 23+;; @008a try_call_indirect v19(v18, v0, v16), sig0, block9, [ context v0, default: block6(exn0) ] ; v16 = 23+;;+;; block9:+;; @008c trap user12;;-;; block2:-;; @0081 v15 = load.i64 notrap aligned readonly can_move region4 v0+88-;; @0081 v14 = load.i64 notrap aligned readonly can_move region3 v0+104-;; @007f v12 = iconst.i32 23-;; @0081 call_indirect sig0, v15(v14, v0, v12) ; v12 = 23-;; @0083 trap user12+;; block8:+;; @008e v20 = load.i64 notrap aligned readonly can_move region5 v0+112+;; @008e v21 = load.i32 notrap aligned region2 v20+;; @0090 v22 = iconst.i32 -2+;; @0092 v23 = band v21, v22 ; v22 = -2+;; @0093 store notrap aligned region2 v23, v20+;; v60 = iconst.i32 1+;; v61 = bor v21, v60 ; v60 = 1+;; @009c store notrap aligned region2 v61, v20+;; @009e v31 = load.i64 notrap aligned readonly can_move region6 v0+72+;; @009e try_call fn0(v31, v0, v2), sig1, block10(ret0), [ context v0, default: block6(exn0) ]+;;+;; block10(v32: i32):+;; @00a2 v34 = load.i32 notrap aligned region2 v9+;; v62 = iconst.i32 -2+;; v63 = band v34, v62 ; v62 = -2+;; @00a7 store notrap aligned region2 v63, v9+;; v64 = iconst.i32 1+;; v65 = bor v34, v64 ; v64 = 1+;; @00b0 store notrap aligned region2 v65, v9+;; @00b2 jump block5(v32)+;;+;; block5(v6: i32):+;; @00b3 jump block2(v6);;;; block3:-;; @0085 v16 = load.i64 notrap aligned readonly can_move region5 v0+112-;; @0085 v17 = load.i32 notrap aligned region2 v16-;; @0087 v18 = iconst.i32 -2-;; @0089 v19 = band v17, v18 ; v18 = -2-;; @008a store notrap aligned region2 v19, v16-;; v52 = iconst.i32 1-;; v53 = bor v17, v52 ; v52 = 1-;; @0093 store notrap aligned region2 v53, v16-;; @0095 v27 = load.i64 notrap aligned readonly can_move region6 v0+72-;; @0095 v28 = call fn0(v27, v0, v2)-;; @0099 v30 = load.i32 notrap aligned region2 v5-;; @009d v32 = band v30, v18 ; v18 = -2-;; @009e store notrap aligned region2 v32, v5-;; v54 = bor v30, v52 ; v52 = 1-;; @00a7 store notrap aligned region2 v54, v5-;; @00a9 jump block1+;; v66 = load.i64 notrap aligned readonly can_move region4 v0+88+;; v67 = load.i64 notrap aligned readonly can_move region3 v0+104+;; @00b6 v43 = iconst.i32 49+;; @00b8 call_indirect sig0, v66(v67, v0, v43) ; v43 = 49+;; @00ba trap user12;;-;; block1:-;; @00a9 return v28+;; block2(v5: i32):+;; @00bc jump block1(v5)+;;+;; block1(v3: i32):+;; @00bc return v3;; }diff --git a/tests/misc_testsuite/component-model/async/exceptions.wast b/tests/misc_testsuite/component-model/async/exceptions.wastnew file mode 100644index 0000000000..d0e2fccb7f--- /dev/null+++ b/tests/misc_testsuite/component-model/async/exceptions.wast@@ -0,0 +1,218 @@+;;! component_model_async = true+;;! exceptions = true+;;! reference_types = true++;; Tests for the interaction of Wasm exceptions and async lifts/lowers.+;;+;; Unlike the sync->sync case (see `../exceptions.wast`) the fused adapters+;; for calls involving an async lift or lower do not invoke guest code+;; directly: the host drives the callee (and the parameter/result translation+;; functions) itself, so an exception unwinding out of any of that guest code+;; reaches the host, which catches it and reports an error. These tests pin+;; that behavior: if fused-adapter codegen is ever optimized to call guest+;; code directly on these paths, these tests will fail and the adapters+;; involved will need exception barriers like the sync->sync one.+;;+;; In each case the `b` parameter selects when the exception is thrown:+;; `false` throws in the first phase of the call (initial callee invocation)+;; and `true` in a later phase (callback or post-yield).++;; sync->async+(component definition $A+ (component $A+ (core module $a+ (tag $t)+ (func (export "run") (param i32) (result i32)+ local.get 0+ if throw $t end+ i32.const 1 (; CALLBACK_CODE_YIELD ;)+ )+ (func (export "cb") (param i32 i32 i32) (result i32) throw $t)+ )+ (core instance $a (instantiate $a))+ (func (export "run") async (param "b" bool)+ (canon lift (core func $a "run") async (callback (func $a "cb"))))+ )+ (component $B+ (import "a" (instance $a+ (export "run" (func async (param "b" bool)))+ ))++ (core func $run (canon lower (func $a "run")))+ (core module $b+ (import "" "run" (func $run (param i32)))++ (func (export "run") (param i32)+ block $a+ try_table (catch_all $a)+ (call $run (local.get 0))+ return+ end+ end+ unreachable+ )+ )+ (core instance $b (instantiate $b+ (with "" (instance+ (export "run" (func $run))+ ))+ ))+ (func (export "run") async (param "b" bool) (canon lift (core func $b "run")))+ )+ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "a" (instance $a))))+ (export "run" (func $b "run"))+)++(component instance $A $A)+(assert_trap (invoke "run" (bool.const false)) "thrown Wasm exception")+(component instance $A $A)+(assert_trap (invoke "run" (bool.const true)) "thrown Wasm exception")++;; async->sync+(component definition $A+ (component $A+ (core module $a+ (import "" "yield" (func $yield (result i32)))+ (tag $t)+ (func (export "run") (param i32)+ local.get 0+ if call $yield drop end+ throw $t+ )+ )+ (core func $yield (canon thread.yield))+ (core instance $a (instantiate $a+ (with "" (instance+ (export "yield" (func $yield))+ ))+ ))+ (func (export "run") async (param "b" bool) (canon lift (core func $a "run")))+ )+ (component $B+ (import "a" (instance $a+ (export "run" (func async (param "b" bool)))+ ))++ (core func $run (canon lower (func $a "run") async))++ (core module $libc (memory (export "m") 1))+ (core instance $libc (instantiate $libc))+ (core func $waitable-set.new (canon waitable-set.new))+ (core func $waitable.join (canon waitable.join))+ (core func $waitable-set.wait (canon waitable-set.wait (memory $libc "m")))++ (core module $b+ (import "" "run" (func $run (param i32) (result i32)))+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))+ (import "" "waitable.join" (func $waitable.join (param i32 i32)))+ (import "" "waitable-set.wait" (func $waitable-set.wait (param i32 i32) (result i32)))++ (func (export "run") (param i32)+ (local $subtask i32)+ (local $ws i32)+ block $a+ try_table (catch_all $a)+ (local.set $subtask+ (i32.shr_u (call $run (local.get 0)) (i32.const 4)))+ (local.set $ws (call $waitable-set.new))+ (call $waitable.join (local.get $subtask) (local.get $ws))+ (call $waitable-set.wait (local.get $ws) (i32.const 0))+ unreachable+ end+ unreachable+ end+ unreachable+ )+ )+ (core instance $b (instantiate $b+ (with "" (instance+ (export "run" (func $run))+ (export "waitable-set.new" (func $waitable-set.new))+ (export "waitable.join" (func $waitable.join))+ (export "waitable-set.wait" (func $waitable-set.wait))+ ))+ ))+ (func (export "run") async (param "b" bool) (canon lift (core func $b "run")))+ )+ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "a" (instance $a))))+ (export "run" (func $b "run"))+)++(component instance $A $A)+(assert_trap (invoke "run" (bool.const false)) "thrown Wasm exception")+(component instance $A $A)+(assert_trap (invoke "run" (bool.const true)) "thrown Wasm exception")++;; async->async+(component definition $A+ (component $A+ (core module $a+ (tag $t)+ (func (export "run") (param i32) (result i32)+ local.get 0+ if throw $t end+ i32.const 1 (; CALLBACK_CODE_YIELD ;)+ )+ (func (export "cb") (param i32 i32 i32) (result i32) throw $t)+ )+ (core instance $a (instantiate $a))+ (func (export "run") async (param "b" bool)+ (canon lift (core func $a "run") async (callback (func $a "cb"))))+ )+ (component $B+ (import "a" (instance $a+ (export "run" (func async (param "b" bool)))+ ))++ (core func $run (canon lower (func $a "run") async))++ (core module $libc (memory (export "m") 1))+ (core instance $libc (instantiate $libc))+ (core func $waitable-set.new (canon waitable-set.new))+ (core func $waitable.join (canon waitable.join))+ (core func $waitable-set.wait (canon waitable-set.wait (memory $libc "m")))++ (core module $b+ (import "" "run" (func $run (param i32) (result i32)))+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))+ (import "" "waitable.join" (func $waitable.join (param i32 i32)))+ (import "" "waitable-set.wait" (func $waitable-set.wait (param i32 i32) (result i32)))++ (func (export "run") (param i32)+ (local $subtask i32)+ (local $ws i32)+ block $a+ try_table (catch_all $a)+ (local.set $subtask+ (i32.shr_u (call $run (local.get 0)) (i32.const 4)))+ (local.set $ws (call $waitable-set.new))+ (call $waitable.join (local.get $subtask) (local.get $ws))+ (call $waitable-set.wait (local.get $ws) (i32.const 0))+ unreachable+ end+ unreachable+ end+ unreachable+ )+ )+ (core instance $b (instantiate $b+ (with "" (instance+ (export "run" (func $run))+ (export "waitable-set.new" (func $waitable-set.new))+ (export "waitable.join" (func $waitable.join))+ (export "waitable-set.wait" (func $waitable-set.wait))+ ))+ ))+ (func (export "run") async (param "b" bool) (canon lift (core func $b "run")))+ )+ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "a" (instance $a))))+ (export "run" (func $b "run"))+)++(component instance $A $A)+(assert_trap (invoke "run" (bool.const false)) "thrown Wasm exception")+(component instance $A $A)+(assert_trap (invoke "run" (bool.const true)) "thrown Wasm exception")diff --git a/tests/misc_testsuite/component-model/exceptions.wast b/tests/misc_testsuite/component-model/exceptions.wastnew file mode 100644index 0000000000..21d9957417--- /dev/null+++ b/tests/misc_testsuite/component-model/exceptions.wast@@ -0,0 +1,237 @@+;;! exceptions = true+;;! multi_memory = true+;;! function_references = true+;;! bulk_memory = true+;;! reference_types = true++;; Tests for the interaction of Wasm exceptions and the component model.+;;+;; The component model's canonical ABI specifies that an exception thrown+;; within one component must not propagate to another component; instead it+;; becomes a trap at the component boundary.+;;+;; Each test below links two components: $A exports a function which (or+;; whose canonical-ABI helpers) may throw, and $B calls it across the+;; component boundary from inside a `try_table` whose `catch_all` must never+;; observe an exception from $A. If the exception leaks into $B, its handler+;; executes `unreachable`, producing a distinct trap message from the+;; expected "uncaught exception" trap.++;; An exception thrown by the callee and not caught within $A: the+;; cross-component call must trap rather than unwind into $B.+(component+ (component $A+ (core module $m+ (tag $t)+ (func (export "f") (throw $t)))+ (core instance $i (instantiate $m))+ (func (export "f") (canon lift (core func $i "f"))))++ (component $B+ (import "f" (func $f))+ (core func $f-core (canon lower (func $f)))+ (core module $m+ (import "" "f" (func $f))+ (func (export "run")+ (block $caught+ (try_table (catch_all $caught)+ (call $f))+ (return))+ ;; the exception leaked across the component boundary+ unreachable))+ (core instance $i (instantiate $m+ (with "" (instance (export "f" (func $f-core))))))+ (func (export "run") (canon lift (core func $i "run"))))++ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "f" (func $a "f"))))+ (export "run" (func $b "run"))+)+(assert_trap (invoke "run") "uncaught exception propagated out of component")++;; An exception thrown and caught entirely within $A: nothing crosses the+;; component boundary, so the call completes normally.+(component+ (component $A+ (core module $m+ (tag $t)+ (func $throw (throw $t))+ (func (export "f")+ (block $caught+ (try_table (catch_all $caught)+ (call $throw)))))+ (core instance $i (instantiate $m))+ (func (export "f") (canon lift (core func $i "f"))))++ (component $B+ (import "f" (func $f))+ (core func $f-core (canon lower (func $f)))+ (core module $m+ (import "" "f" (func $f))+ (func (export "run")+ (block $caught+ (try_table (catch_all $caught)+ (call $f))+ (return))+ unreachable))+ (core instance $i (instantiate $m+ (with "" (instance (export "f" (func $f-core))))))+ (func (export "run") (canon lift (core func $i "run"))))++ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "f" (func $a "f"))))+ (export "run" (func $b "run"))+)+(assert_return (invoke "run"))++;; An exception thrown by the callee's `realloc`, which the adapter invokes+;; to lower the string argument into $A's memory before calling the callee:+;; it likewise must not unwind into $B.+(component+ (component $A+ (core module $m+ (tag $t)+ (memory (export "memory") 1)+ (func (export "realloc") (param i32 i32 i32 i32) (result i32)+ (throw $t))+ (func (export "f") (param i32 i32)))+ (core instance $i (instantiate $m))+ (func (export "f") (param "s" string)+ (canon lift (core func $i "f")+ (memory $i "memory")+ (realloc (func $i "realloc")))))++ (component $B+ (import "f" (func $f (param "s" string)))+ (core module $libc+ (memory (export "memory") 1)+ (data (i32.const 16) "hello"))+ (core instance $libc (instantiate $libc))+ (core func $f-core (canon lower (func $f) (memory $libc "memory")))+ (core module $m+ (import "" "f" (func $f (param i32 i32)))+ (func (export "run")+ (block $caught+ (try_table (catch_all $caught)+ (call $f (i32.const 16) (i32.const 5)))+ (return))+ unreachable))+ (core instance $i (instantiate $m+ (with "" (instance (export "f" (func $f-core))))))+ (func (export "run") (canon lift (core func $i "run"))))++ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "f" (func $a "f"))))+ (export "run" (func $b "run"))+)+(assert_trap (invoke "run") "uncaught exception propagated out of component")++;; An exception thrown by the callee's `post-return` function, which the+;; adapter invokes after the callee returns: it likewise must not unwind+;; into $B.+(component+ (component $A+ (core module $m+ (tag $t)+ (func (export "f"))+ (func (export "post-f") (throw $t)))+ (core instance $i (instantiate $m))+ (func (export "f")+ (canon lift (core func $i "f") (post-return (func $i "post-f")))))++ (component $B+ (import "f" (func $f))+ (core func $f-core (canon lower (func $f)))+ (core module $m+ (import "" "f" (func $f))+ (func (export "run")+ (block $caught+ (try_table (catch_all $caught)+ (call $f))+ (return))+ unreachable))+ (core instance $i (instantiate $m+ (with "" (instance (export "f" (func $f-core))))))+ (func (export "run") (canon lift (core func $i "run"))))++ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "f" (func $a "f"))))+ (export "run" (func $b "run"))+)+(assert_trap (invoke "run") "uncaught exception propagated out of component")++;; An exception thrown by a resource destructor: component $B drops a+;; resource owned by component $A whose destructor throws. The+;; `resource.drop` intrinsic is likewise a boundary between the two+;; components, so the exception must become a trap rather than unwind into+;; $B.+(component+ (component $A+ ;; The destructor must be supplied when the resource type is declared,+ ;; which is before the module defining the "real" (throwing) destructor+ ;; can be instantiated, since that module imports `resource.new` for the+ ;; type. Route the destructor through a mutable function reference in a+ ;; shim module which is patched after instantiation.+ (core module $shim+ (type $f (func (param i32)))+ (global $dtor-global (export "dtor-global") (mut (ref $f)) (ref.func $dummy))+ (func $dummy (param i32) unreachable)+ (func (export "dtor") (param i32)+ local.get 0+ global.get $dtor-global+ call_ref $f))+ (core instance $shim (instantiate $shim))++ (type $t (resource (rep i32) (dtor (func $shim "dtor"))))+ (core func $t.new (canon resource.new $t))++ (core module $a+ (import "" "t.new" (func $t.new (param i32) (result i32)))+ (tag $t)+ (func (export "run") (result i32) (call $t.new (i32.const 0)))+ (func (export "dtor-real") (param i32) (throw $t)))+ (core instance $a (instantiate $a+ (with "" (instance (export "t.new" (func $t.new))))))++ (core module $patch+ (type $f (func (param i32)))+ (import "shim" "dtor-global" (global $dtor-global (mut (ref $f))))+ (import "a" "dtor-real" (func $dtor-real (param i32)))+ (func $init (global.set $dtor-global (ref.func $dtor-real)))+ (start $init)+ (elem declare func $dtor-real))+ (core instance (instantiate $patch+ (with "shim" (instance $shim))+ (with "a" (instance $a))))++ (export $t' "t" (type $t))+ (func (export "run") (result (own $t')) (canon lift (core func $a "run"))))++ (component $B+ (import "a" (instance $a+ (export "t" (type $t (sub resource)))+ (export "run" (func (result (own $t))))))++ (core func $run (canon lower (func $a "run")))+ (alias export $a "t" (type $t))+ (core func $t.drop (canon resource.drop $t))+ (core module $b+ (import "" "run" (func $run (result i32)))+ (import "" "t.drop" (func $t.drop (param i32)))+ (func (export "run")+ (block $caught+ (try_table (catch_all $caught)+ (call $t.drop (call $run)))+ (return))+ unreachable))+ (core instance $b (instantiate $b+ (with "" (instance+ (export "run" (func $run))+ (export "t.drop" (func $t.drop))))))+ (func (export "run") (canon lift (core func $b "run"))))++ (instance $a (instantiate $A))+ (instance $b (instantiate $B (with "a" (instance $a))))+ (export "run" (func $b "run"))+)+(assert_trap (invoke "run") "uncaught exception propagated out of component")