Skip to content

fix(lowering): return Err on stack underflow instead of panic — fuzz #113#117

Open
avrabe wants to merge 2 commits into
mainfrom
fix/fuzz-117-stack-underflow-pre-flight
Open

fix(lowering): return Err on stack underflow instead of panic — fuzz #113#117
avrabe wants to merge 2 commits into
mainfrom
fix/fuzz-117-stack-underflow-pre-flight

Conversation

@avrabe
Copy link
Copy Markdown
Contributor

@avrabe avrabe commented May 15, 2026

Summary

The gating fuzz harness `wasm_ops_lower_or_error` surfaced a panic on `FuzzInput { num_params: 1, ops: [I32DivS] }` on PR #113. The harness contract is "lower or return Err — no panics", so this is a regression that should block merge. This PR fixes the root cause and adds a regression test plus a permanent corpus seed.

Root cause

`OptimizerBridge::wasm_to_ir` synthesizes binary-op IR by referencing `OptReg(inst_id.saturating_sub(2))` / `saturating_sub(1)` as `src1`/`src2`. For a lone `I32DivS` (`inst_id == 0`), both saturating subtractions return 0 — the IR self-references its own dest as `src1`/`src2`. The resulting vreg v0 was never produced by any prior op, so the unmapped-vreg defensive panic at `optimizer_bridge.rs:1617` (added in PR #101 to replace silent R0 fallback) fired.

The defensive panic is correct for genuine internal compiler bugs (a `wasm_to_ir` gap like #93 / #109 would still trip it). The issue is that malformed wasm input — which the harness intentionally generates — was being conflated with internal bugs.

Fix

New `synth_core::wasm_stack_check::check_no_underflow(ops)` — a pre-flight wasm value-stack underflow detector. Called at the top of:

  • `OptimizerBridge::optimize_full`
  • `InstructionSelector::select_with_stack`

The check returns `Err(Error::ValidationError(...))` on underflow. The defensive panic at line 1617 is not removed — it still catches genuine wasm_to_ir gaps. The pre-flight check disambiguates "malformed wasm input" → typed `Err` from "synth internal bug" → loud panic.

Stack-effect modeling covers the FuzzOp surface (all i32/i64/f32/f64 arithmetic, conversions, locals, memory, `Select`). Control-flow ops (`Block`/`Loop`/`If`/`Else`/`Br`/`BrIf`/`Return`/`Call`/`Unreachable`) bail conservatively — they have block-type-dependent effects we can't compute without function signatures. Production callers come through the wasm decoder (wasmparser), which already does full validation; this is a safety net for direct callers.

Tests

  • `crates/synth-core/src/wasm_stack_check.rs` — 11 unit tests covering binary/unary/store/drop/select underflow, control-flow bail, and happy paths.
  • `crates/synth-synthesis/tests/regression_i32divs_lone_stack_underflow.rs` — 3 tests reproducing the fuzz crash exactly. Asserts both lowering paths (and the harness-shape combined path) return cleanly.

Full workspace test (excluding `synth-verify` / z3 — local network): 0 regressions. 241 `synth-synthesis` tests + 52 `synth-core` tests green.

Fuzz infrastructure

Added `fuzz/seed_corpus//` directory layout for committed regression seeds. The fuzz-smoke workflow now copies these into the per-target corpus before running, so this exact crash input gets replayed on every CI run — even if libfuzzer's random walk wouldn't rediscover it within the 60s budget.

First seed: `fuzz/seed_corpus/wasm_ops_lower_or_error/seed-pr117-i32divs-empty-stack` (10 bytes — the exact artifact uploaded by the #113 failing run).

Test plan

  • CI green (Test, Clippy, Format, Z3 Verification, Kani Verification, Bazel Build & Proofs)
  • Fuzz smoke gating harnesses (`wasm_ops_lower_or_error`, `wasm_to_ir_roundtrip_op_coverage`) green — the harness should now treat the seed as input and report no panic
  • No regression in existing AAPCS / i64 / regression test suites

🤖 Generated with Claude Code

avrabe added 2 commits May 15, 2026 14:32
v0.3.1 minimum-viable cross-function call support in the RISC-V
selector. WasmOp::Call(idx) no longer errors with `Unsupported` for
leaf-call shapes — it now lowers to a label-based RiscVOp::Call that
the ELF builder resolves to a PC-relative `auipc + jalr` when the
callee is in the same compilation unit.

Behavior:
  * Move top N vstack values (capped at 8) into a0..a(N-1).
  * Emit `RiscVOp::Call { label: format!("synth_func_{idx}") }`.
  * Push a fresh `a0` vreg as the return value.

What's deliberately deferred (documented in the lower_call doc + the
#[ignore]-marked `recursive_self_call_emits_two_call_ops` test):
  * Function-signature plumbing from the decoder. Without it, the
    selector can't know how many args to pop, so the v0.3.1 cut
    over-consumes the vstack on back-to-back calls with surviving
    results. v0.4 will pipe `FuncSig` through and lift this restriction.
  * Args beyond 8 (RV psABI says spill to stack at fixed offsets — not
    implemented).
  * Caller-side a0..a7 invalidation across the BL — callers wanting to
    survive a call should `drop` or `local.tee` their live values
    explicitly until v0.4 models this properly.
  * Multi-result returns (wasm 2.0).
  * Cross-`.text` relocations for multi-unit linking.

Tests:
  * `call_emits_label_and_argument_marshalling` — single-arg call, label
    encodes `synth_func_{idx}`.
  * `call_two_args_marshals_to_a0_a1` — two-arg call from i32.const seq.
  * `recursive_self_call_emits_two_call_ops` — #[ignore]'d documentation
    of the back-to-back-calls gap, to be flipped when v0.4 plumbing
    lands.

Total: 100 passing tests in synth-backend-riscv (was 99); 1 ignored
that documents the next milestone.
…113

The gating fuzz harness `wasm_ops_lower_or_error` surfaced a panic on
`FuzzInput { num_params: 1, ops: [I32DivS] }`. The harness contract is
"lower or return Err — no panics", and the panic was an unmapped-vreg
defensive assert (added in PR #101) firing on malformed wasm input.

Root cause:

  `OptimizerBridge::wasm_to_ir` synthesizes binary-op IR by referencing
  `OptReg(inst_id.saturating_sub(2))` / `saturating_sub(1)` as src1/src2.
  For a *lone* `I32DivS` (inst_id == 0), both saturating subtractions
  return 0 — the IR self-references its own dest as src1/src2. The
  resulting vreg v0 was never produced by any prior op, so the unmapped-
  vreg defensive panic at optimizer_bridge.rs:1617 fired.

Fix:

  New `synth_core::wasm_stack_check::check_no_underflow(ops)` — a
  pre-flight wasm value-stack underflow detector. Called at the top of:
    * `OptimizerBridge::optimize_full`
    * `InstructionSelector::select_with_stack`

  Stack-effect modeling covers the FuzzOp surface (all i32/i64/f32/f64
  arithmetic, conversions, locals, memory, select). Control-flow ops
  (Block/Loop/If/Else/Br/BrIf/Return/Call/Unreachable) bail
  conservatively — they have block-type-dependent effects we can't
  compute without function signatures. Production callers come through
  the wasm decoder (wasmparser), which already does full validation;
  this is a safety net for *direct callers* like the fuzz harnesses.

  The defensive panic at line 1617 is *not* removed — it still catches
  genuine wasm_to_ir gaps (the class of bug from issues #93, #109). The
  pre-flight check disambiguates "malformed wasm input" → typed Err
  from "synth internal bug" → loud panic.

Tests:

  * `crates/synth-core/src/wasm_stack_check.rs` — 11 unit tests covering
    binary/unary/store/drop/select underflow, control-flow bail, and
    happy paths.
  * `crates/synth-synthesis/tests/regression_i32divs_lone_stack_underflow.rs`
    — 3 tests reproducing the fuzz crash exactly. Asserts both lowering
    paths (and the harness-shape combined path) return cleanly.

  Full workspace test (excluding synth-verify / z3): 0 regressions
  (241 synth-synthesis tests, 52 synth-core tests, all green).

Fuzz infrastructure:

  Added `fuzz/seed_corpus/<target>/` directory layout for committed
  regression seeds. The fuzz-smoke workflow now copies these into the
  per-target corpus before running, so this crash input gets replayed
  on every CI run — even if libfuzzer's random walk wouldn't rediscover
  it within the 60s budget.

  First seed: `fuzz/seed_corpus/wasm_ops_lower_or_error/seed-pr117-
  i32divs-empty-stack` (10 bytes, the exact crash artifact uploaded by
  the failing #113 run).

Local verification:
  * `cargo test --workspace --exclude synth-verify` — 0 failures
  * `cargo clippy --package synth-core --package synth-synthesis
     --all-targets -- -D warnings` — clean
  * `cargo fmt --check` — clean
@codecov
Copy link
Copy Markdown

codecov Bot commented May 15, 2026

Codecov Report

❌ Patch coverage is 85.55556% with 26 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/synth-backend-riscv/src/selector.rs 73.68% 20 Missing ⚠️
crates/synth-core/src/wasm_stack_check.rs 94.11% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant