WebAssembly / binaryen

Optimizer and compiler/toolchain library for WebAssembly
Apache License 2.0
7.5k stars 745 forks source link

`wasm-opt` produces an error when given a valid WebAssembly loop #5047

Open HeliosPanoptes opened 2 years ago

HeliosPanoptes commented 2 years ago

Bug Description

echo "`binaryen/bin/wasm-opt --version` | `uname -m`"
wasm-opt version 101 (version_101-62-g35f9da76d) | x86_64

git rev-parse HEAD
35f9da76d53401ba4de054f4db631ce4177b32f1

wasm-opt produces an error when given a valid Wasm loop. The issue seems to be that when parsing the Wasm binary to Binaryen-IR, the parameter of the loop is ignored.

Steps to reproduce

Reduced test case:

;; wasm_opt_loop_bug.wat

(module
  (func $main (result i32)
    (local $counter i32)
    i32.const 2
    local.set $counter
    i32.const 38
    loop (param i32) (result i32)  ;; label = @1
      i32.const 2
      i32.add
      local.get $counter
      i32.const -1
      i32.add
      local.tee $counter
      br_if 0 (;@1;)
    end)
  (export "_main" (func $main)))

Compile to WebAssembly:

wat2wasm wasm_opt_loop_bug.wat

Zip of .wat and .wasm: wasm_opt_loop_bug.zip

Run wasm-opt on the binary

$ wasm-opt --all-features ../xsmith-bugs-found/webassembly/wasm-opt/wasm_opt_loop_bug.wasm

[wasm-validator error in function 0] loop with value and body must match types, on
(loop $label$1 (result i32)
 (br_if $label$1
  (local.tee $0
   (i32.add
    (local.get $0)
    (i32.const -1)
   )
  )
 )
)

Expected behavior

I would expect the output of wasm-opt to essentially give the same file back without errors.

Actual behavior

The error above.

Additional context

This bug was found when trying to reduce a test case with wasm-reduce.

As a sanity check that the Wasm program is a valid program, wat2wasm from WABT will compile the text format to binary format without any errors, and Wasmer will correctly run the program:

$ wasmer wasm_opt_loop_bug.wasm -i _main

42

This test case is derived from a program created by Wasmlike, an Xsmith-based random program generator. https://www.flux.utah.edu/project/xsmith

kripken commented 2 years ago

Unfortunately, loop etc. input parameters are features of multivalue that we don't support yet. It would be good to have a clear error on this, if we can.