A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
winch: handle unreachable try_table and fuel accounting (#14379)
Daniel Macovei82ba229d1077
diff --git a/crates/fuzzing/src/generators/config.rs b/crates/fuzzing/src/generators/config.rsindex 7ee400a3df..ce44de185f 100644--- a/crates/fuzzing/src/generators/config.rs+++ b/crates/fuzzing/src/generators/config.rs@@ -693,7 +693,6 @@ impl WasmtimeConfig {config.config.relaxed_simd_enabled = false;config.config.gc_enabled = false;config.config.reference_types_enabled = false;- config.config.exceptions_enabled = false;config.function_references_enabled = false;config.stack_switching = false;diff --git a/crates/fuzzing/src/oracles.rs b/crates/fuzzing/src/oracles.rsindex 199b53c00b..e9355664a1 100644--- a/crates/fuzzing/src/oracles.rs+++ b/crates/fuzzing/src/oracles.rs@@ -1004,17 +1004,9 @@ pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usi/// Execute a series of exception-related operations.pub fn exception_ops(mut fuzz_config: generators::Config, mut ops: ExceptionOps) -> Result<()> {- match fuzz_config.wasmtime.compiler_strategy {- // Winch doesn't support exceptions; force to Cranelift.- CompilerStrategy::Winch => {- fuzz_config.wasmtime.compiler_strategy = CompilerStrategy::CraneliftNative;- }- CompilerStrategy::CraneliftNative | CompilerStrategy::CraneliftPulley => {}- }-let module_cfg = &mut fuzz_config.module_config.config;- // Force exceptions + GC on (exceptions require GC).- module_cfg.gc_enabled = true;+ // Force exceptions, but don't force Wasm GC on: Winch doesn't support it,+ // and Cranelift should use its generated GC setting.module_cfg.exceptions_enabled = true;module_cfg.reference_types_enabled = true;diff --git a/tests/all/exceptions.rs b/tests/all/exceptions.rsindex d263c00121..812ecdddce 100644--- a/tests/all/exceptions.rs+++ b/tests/all/exceptions.rs@@ -179,6 +179,24 @@ fn try_table_unreachable_fallthrough_with_multi_value_results(config: &mut ConfiOk(())}+#[wasmtime_test(wasm_features(exceptions))]+#[cfg_attr(miri, ignore)]+fn try_table_after_return(config: &mut Config) -> Result<()> {+ let engine = Engine::new(config)?;+ let mut store = Store::new(&engine, ());+ let module = Module::new(+ &engine,+ r#"(module+ (func (export "f")+ (return)+ (try_table (catch_all 0))))"#,+ )?;+ let instance = Instance::new(&mut store, &module, &[])?;+ let f = instance.get_typed_func::<(), ()>(&mut store, "f")?;+ f.call(&mut store, ())?;+ Ok(())+}+#[wasmtime_test(wasm_features(exceptions))]#[cfg_attr(miri, ignore)]fn dynamic_tags(config: &mut Config) -> Result<()> {diff --git a/tests/all/fuel.rs b/tests/all/fuel.rsindex 30dc0133e5..5b176aecca 100644--- a/tests/all/fuel.rs+++ b/tests/all/fuel.rs@@ -694,6 +694,103 @@ fn custom_operator_cost(config: &mut Config) -> Result<()> {Ok(())}+#[wasmtime_test(wasm_features(tail_call))]+#[cfg_attr(miri, ignore)]+fn unreachable_control_operator_cost(config: &mut Config) -> Result<()> {+ // Use nonzero costs so charging unreachable control operators is observable.+ config.consume_fuel(true).operator_cost(OperatorCost {+ Block: 1,+ Loop: 1,+ If: 1,+ Else: 1,+ End: 1,+ ..Default::default()+ });+ let engine = Engine::new(config)?;+ for terminator in [+ "return",+ "unreachable",+ "return_call $leaf",+ "i32.const 0 return_call_indirect (type $t)",+ "br $exit",+ ] {+ let body = |dead: &str| {+ format!(+ r#"(param i32)+ block $exit+ local.get 0+ if+ {terminator}+ {dead}+ else+ i32.const 3 drop+ end+ i32.const 5 drop+ end+ i32.const 7 drop"#+ )+ };+ let module = Module::new(+ &engine,+ format!(+ r#"(module+ (type $t (func))+ (func $leaf (type $t))+ (table funcref (elem $leaf))+ (func (export "with_dead") {})+ (func (export "without_dead") {}))"#,+ body("block loop end i32.const 0 if else end end"),+ body(""),+ ),+ )?;+ let mut store = Store::new(&engine, ());+ let instance = Instance::new(&mut store, &module, &[])?;+ // Exercise both the terminating path and the reachable else/end joins.+ for condition in [0, 1] {+ let mut consumed = Vec::new();+ for export in ["with_dead", "without_dead"] {+ store.set_fuel(1_000)?;+ let run = instance.get_typed_func::<i32, ()>(&mut store, export)?;+ let result = run.call(&mut store, condition);+ if terminator == "unreachable" && condition == 1 {+ assert_eq!(+ result.unwrap_err().downcast::<Trap>()?,+ Trap::UnreachableCodeReached+ );+ } else {+ result?;+ }+ consumed.push(1_000 - store.get_fuel()?);+ }+ assert_eq!(consumed[0], consumed[1], "{terminator}, {condition}");+ }+ }+ Ok(())+}++#[wasmtime_test(wasm_features(exceptions, reference_types))]+#[cfg_attr(miri, ignore)]+fn unreachable_try_table_fuel(config: &mut Config) -> Result<()> {+ config.consume_fuel(true);+ let engine = Engine::new(config)?;+ let module = Module::new(+ &engine,+ r#"(module+ (func (export "run") (result i32)+ i32.const 42+ return+ (try_table)))"#,+ )?;+ let mut store = Store::new(&engine, ());+ store.set_fuel(100)?;+ let instance = Instance::new(&mut store, &module, &[])?;+ let run = instance.get_typed_func::<(), i32>(&mut store, "run")?;+ assert_eq!(run.call(&mut store, ())?, 42);+ // Only function entry and i32.const consume fuel.+ assert_eq!(store.get_fuel()?, 98);+ Ok(())+}+#[wasmtime_test(wasm_features(exceptions, reference_types))]#[cfg_attr(miri, ignore)]fn exceptions_with_fuel(config: &mut Config) -> Result<()> {diff --git a/winch/codegen/src/codegen/mod.rs b/winch/codegen/src/codegen/mod.rsindex c59499da8f..d07f59b1b4 100644--- a/winch/codegen/src/codegen/mod.rs+++ b/winch/codegen/src/codegen/mod.rs@@ -2358,7 +2358,10 @@ whereif !self.context.reachable {// `self.fuel_consumed` must be correctly flushed to memory when// entering an unreachable state.- ensure!(self.fuel_consumed == 0, CodeGenError::illegal_fuel_state())+ ensure!(self.fuel_consumed == 0, CodeGenError::illegal_fuel_state());+ // Control operators are still visited to track nesting and restore+ // reachability at `else` or `end`, but those visits must not charge fuel.+ return Ok(());}// Generally, most instructions require 1 fuel unit.diff --git a/winch/codegen/src/visitor.rs b/winch/codegen/src/visitor.rsindex 80d009c82b..f3398fc0df 100644--- a/winch/codegen/src/visitor.rs+++ b/winch/codegen/src/visitor.rs@@ -1905,6 +1905,14 @@ where// Record the handlers that apply to calls within this `try_table`. Their// landing pads are emitted when the control frame ends.fn visit_try_table(&mut self, try_table: TryTable) -> Self::Output {+ // When this `try_table` is unreachable at entry, its handlers cannot run.+ // Use a plain block to match its `end`, without registering catches.+ // Unreachable blocks do not record the machine-stack state needed to+ // emit landing pads.+ if !self.context.reachable {+ return self.visit_block(try_table.ty);+ }+let checkpoint = self.context.exception_handlers.take_checkpoint();let mut catches = Vec::with_capacity(try_table.catches.len());