wagon icon indicating copy to clipboard operation
wagon copied to clipboard

wasm: functions in FunctionIndexSpace include wrong contents

Open hajimehoshi opened this issue 4 years ago • 2 comments

  1. Build a hello-world wasm:
package main

func main() {
        println("Hello, World!")
}
GOOS=js GOARCH=wasm go build -o test.wasm helloworld.go 
  1. Run the below code:
package main

import (
        "fmt"
        "os"

        "github.com/go-interpreter/wagon/wasm"
)

func main() {
        f, err := os.Open("test.wasm")
        if err != nil {
                panic(err)
        }
        defer f.Close()

        mod, err := wasm.ReadModule(f, nil)
        if err != nil {
                panic(err)
        }

        fn := mod.FunctionIndexSpace[0]
        fmt.Printf("name: %q\n", fn.Name) // This is empty. That's fine since this is an imported function 'debug'.                                                                                                                           
        fmt.Printf("len(code): %d\n", len(fn.Body.Code)) // This is not empty. That's unexpected. This content is for the first function as 'go.buildid'.                                                                                     
}

It looks like the function's index and its instructions don't match. Some of the first functions should be imported functions, but include instructions for other functions. I think the function bodies are shifted.

hajimehoshi avatar Feb 27 '20 16:02 hajimehoshi

https://github.com/go-interpreter/wagon/blob/cbbdf0893ce4f79668a13c0879a7f143bdd0f472/wasm/index.go#L76-L80

The names are shifted with numImports, which is correct, while Sig and Body are not shifted, maybe? I'm not confident.

hajimehoshi avatar Feb 27 '20 17:02 hajimehoshi

Hello, I read in detail, found that the problem comes with numImports, when you don't provide a imported module but the wasm file need it, the numImports is not equal to len(FunctionIndexSpace). https://github.com/go-interpreter/wagon/blob/dc6758ca7262efb2ef987e32e09f648300b4d007/wasm/index.go#L84-L85 So I had a pr #193 I am not sure if we can do it in this way. Thanks.

zhangzhiqiangcs avatar Apr 14 '20 03:04 zhangzhiqiangcs