github.com/wasilibs/nottinygc@v0.7.2-0.20240312114022-d59c9478ef51/finalizer_test.go (about)

     1  // Copyright wasilibs authors
     2  // SPDX-License-Identifier: MIT
     3  
     4  package nottinygc
     5  
     6  import (
     7  	"runtime"
     8  	"testing"
     9  )
    10  
    11  func TestFinalizer(t *testing.T) {
    12  	finalized := 0
    13  	allocFinalized(10, func() {
    14  		finalized++
    15  	})
    16  
    17  	runtime.GC()
    18  
    19  	if finalized == 0 {
    20  		t.Errorf("finalizer not called")
    21  	}
    22  }
    23  
    24  //go:noinline
    25  func allocFinalized(num int, cb func()) {
    26  	f := &finalized{
    27  		a: 100,
    28  		b: "foo",
    29  	}
    30  
    31  	runtime.SetFinalizer(f, func(f interface{}) {
    32  		cb()
    33  	})
    34  
    35  	// Recurse to create some more stack frames or else the shadow stack
    36  	// may still not have been reset, causing GC to find the inaccessible
    37  	// pointers.
    38  	if num > 1 {
    39  		allocFinalized(num-1, cb)
    40  	}
    41  }
    42  
    43  type finalized struct {
    44  	a int
    45  	b string
    46  }