Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

panic: runtime error: invalid memory address or nil pointer dereference #406

Open
wwwAngHua opened this issue Mar 19, 2024 · 1 comment
Open
Labels
❓ question Further information is requested

Comments

@wwwAngHua
Copy link

Problem description:

I used tinygo to compile a wasm file, and an error occurred when I used wasmer-go to read, compile and execute the file again.

Steps to reproduce

main.go

package main

import (
	"fmt"
	"os"

	"github.com/wasmerio/wasmer-go/wasmer"
)

func main() {
	engine := wasmer.NewEngine()
	store := wasmer.NewStore(engine)

	wasmBytes, err := os.ReadFile("test.wasm")
	if err != nil {
		fmt.Println("Error reading Wasm file:", err)
		return
	}

	module, err := wasmer.NewModule(store, wasmBytes)
	if err != nil {
		fmt.Println("Error compiling Wasm module:", err)
		return
	}

	instance, err := wasmer.NewInstance(module, nil)
	if err != nil {
		fmt.Println("Error instantiating Wasm module:", err)
		return
	}

	sumFunc, err := instance.Exports.GetFunction("sum")
	if err != nil {
		fmt.Println("Error getting function from Wasm module:", err)
		return
	}

	result, err := sumFunc(10, 20)
	if err != nil {
		fmt.Println("Error calling function from Wasm module:", err)
		return
	}

	fmt.Println("Result:", result)
}

wasm.go

package main

import (
	"syscall/js"
)

func sum(this js.Value, args []js.Value) interface{} {
	if len(args) != 2 {
		return "Invalid number of arguments. Expected 2."
	}

	num1 := args[0].Float()
	num2 := args[1].Float()
	result := num1 + num2
	return result
}

func main() {
	js.Global().Set("sum", js.FuncOf(sum))
	done := make(chan struct{}, 0)
	<-done
}

Expected behavior

The sum function exists and it should return the correct result.

Actual behavior

~/study/wasm tinygo build -o test.wasm -target wasm ./wasm.go

~/study/wasm go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10de47342]

goroutine 1 [running]:
github.com/wasmerio/wasmer-go/wasmer.(*ImportObject).intoInner(0x0, 0xc0000ca000)
        /Users/wanghua/go/pkg/mod/github.com/wasmerio/wasmer-go@v1.0.4/wasmer/import_object.go:36 +0x142
github.com/wasmerio/wasmer-go/wasmer.NewInstance(0xc0000ca000, 0x0)
        /Users/wanghua/go/pkg/mod/github.com/wasmerio/wasmer-go@v1.0.4/wasmer/instance.go:31 +0x45
main.main()
        /Users/wanghua/study/wasm/main.go:30 +0x149
exit status 2

JavaScript

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Go WebAssembly Calculator</title>
    <script src="./wasm_exec.js"></script>
    <script>
      window.onload = function () {
        const go = new Go();
        WebAssembly.instantiateStreaming(
          fetch("./test.wasm"),
          go.importObject
        ).then((res) => {
          go.run(res.instance);
        });
      };

      function calculate() {
        const num1 = parseFloat(document.getElementById("num1").value);
        const num2 = parseFloat(document.getElementById("num2").value);
        console.log(window);
        const result = window.sum(num1, num2);

        document.getElementById("result").innerHTML = result;
        return new Promise(() => {});
      }
    </script>
  </head>
  <body>
    <h1>Simple Calculator</h1>

    <input type="number" id="num1" value="1" placeholder="Number 1" /> <br />
    <input type="number" id="num2" value="2" placeholder="Number 2" /><br />

    <button onclick="calculate()">Calculate</button>

    <h2>Result: <span id="result"></span></h2>
  </body>
</html>

Output:
Uncaught TypeError: window.sum is not a function at calculate (index.html:23:31) at HTMLButtonElement.onclick(index.html:36:35)

@wwwAngHua wwwAngHua added the ❓ question Further information is requested label Mar 19, 2024
@wwwAngHua
Copy link
Author

wwwAngHua commented Mar 19, 2024

package main

import (
	"fmt"
	"os"

	wasmer "github.com/wasmerio/wasmer-go/wasmer"
)

func main() {
	wasmBytes, _ := os.ReadFile("test.wasm")

	engine := wasmer.NewEngine()
	store := wasmer.NewStore(engine)

	// Compiles the module
	module, _ := wasmer.NewModule(store, wasmBytes)

	// Instantiates the module
	importObject := wasmer.NewImportObject()
	instance, _ := wasmer.NewInstance(module, importObject)

	// Gets the `sum` exported function from the WebAssembly instance.
	sum, _ := instance.Exports.GetFunction("sum")

	// Calls that exported function with Go standard values. The WebAssembly
	// types are inferred and values are casted automatically.
	result, _ := sum(5, 37)

	fmt.Println(result) // 42!
}
~/study/wasm go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x10038efbd]

goroutine 1 [running]:
main.main()
        /Users/wanghua/study/wasm/main.go:24 +0x9d
exit status 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
❓ question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant