hybridgroup / mechanoid

Mechanoid is a framework for WebAssembly applications on embedded systems and IoT devices.
https://mechanoid.io
Apache License 2.0
174 stars 8 forks source link

engine: add simplistic ExternalReferences type to manage external references #8

Closed deadprogram closed 7 months ago

deadprogram commented 7 months ago

In similar spirit to #6 this PR introduces ExternalReferences type to manage external references managed by host, but used from guest modules.

This would be the host side:

thing := testingType{val1: "hello", val2: "world"}
ref := eng.Interpreter.References.Add(unsafe.Pointer(&thing))

instance.Call("here_is_thing", ref)

The guest side:


type externref uintptr
var thing externref

//go:wasmimport host foo
func foo(what externref)

//go:wasmimport host bar
func bar(what externref)

//go:export here_is_thing
func here(something externref) {
    thing = something
    foo(thing)
}

//go:export sometime_later
func sometime() {
    bar(thing)
}
orsinium commented 7 months ago

The most canonical way to do that is through a table of externref type. IDK if it's supported by wasman from the host side and by tinygo from the guest side but it's certainly the most close to the wasm spec solution.

deadprogram commented 7 months ago

@orsinium I will look into that possibility more fully. However, I think that there is not yet anything exposing that to the guest side in TinyGo.

deadprogram commented 7 months ago

After reading a bit more, I think we should not base providing this capability on table implementation of externref.

Most actual use cases in the wild I could find receive an externref back from some host function, and then just use as a param when calling other host functions.

Separately, I added a more random way to generate a new reference ID.

orsinium commented 7 months ago

I'm curious to see where and how Remove will be called. It's easy to leak the references.

deadprogram commented 7 months ago

I'm curious to see where and how Remove will be called. It's easy to leak the references.

Likewise. Let's find out...