Skip to content

Commit

Permalink
Add bindings for store.GC() (bytecodealliance#35)
Browse files Browse the repository at this point in the history
* Add bindings for `store.GC()`

* Try harder to hit the GC
  • Loading branch information
alexcrichton authored Jul 22, 2020
1 parent 5cbe5ab commit ae850e4
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
64 changes: 64 additions & 0 deletions reftypes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package wasmtime

import (
"errors"
"runtime"
"testing"
)

Expand Down Expand Up @@ -267,3 +268,66 @@ func TestRefTypesWrap(t *testing.T) {
panic("bad ret")
}
}

type GcHit struct {
hit bool
}

type ObjToDrop struct {
ptr *GcHit
}

func newObjToDrop() (*ObjToDrop, *GcHit) {
gc := &GcHit{hit: false}
obj := &ObjToDrop{ptr: gc}
runtime.SetFinalizer(obj, func(obj *ObjToDrop) {
obj.ptr.hit = true
})
return obj, gc
}

func TestGlobalFinalizer(t *testing.T) {
store := refTypesStore()
global, err := NewGlobal(
store,
NewGlobalType(NewValType(KindExternref), true),
ValExternref(nil),
)
if err != nil {
panic(err)
}
obj, gc := newObjToDrop()
global.Set(ValExternref(obj))
runtime.GC()
if gc.hit {
panic("gc too early")
}
global.Set(ValExternref(nil))
// try real hard to get the Go GC to run the destructor
for i := 0; i < 10; i++ {
runtime.GC()
}
if !gc.hit {
panic("dtor not run")
}
}

func TestFuncFinalizer(t *testing.T) {
instance, store := refTypesInstance(`
(module (func (export "f") (param externref)))
`)
f := instance.GetExport("f").Func()
obj, gc := newObjToDrop()
_, err := f.Call(obj)
if err != nil {
panic(err)
}
store.GC()
// try real hard to get the Go GC to run the destructor
for i := 0; i < 10; i++ {
runtime.GC()
}
if !gc.hit {
panic("dtor not run")
}
}
10 changes: 10 additions & 0 deletions store.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ func (store *Store) InterruptHandle() (*InterruptHandle, error) {
return handle, nil
}

// GC will clean up any `externref` values that are no longer actually
// referenced.
//
// This function is not required to be called for correctness, it's only an
// optimization if desired to clean out any extra `externref` values.
func (store *Store) GC() {
C.wasmtime_store_gc(store.ptr())
runtime.KeepAlive(store)
}

func (store *Store) ptr() *C.wasm_store_t {
store.freelist.clear()
ret := store._ptr
Expand Down

0 comments on commit ae850e4

Please sign in to comment.