mirror of
https://github.com/hanzoai/wasm2go.git
synced 2026-10-30 15:06:48 +00:00
* Back shared linear memories with anonymous mappings, not the Go heap A shared memory is allocated at its declared ceiling LENGTH once (agents deref the base pointer concurrently, so the array must never move). On the Go heap that size is a trap: the FIRST make is lazily paged, but a freed ceiling-sized span gets zeroed when the allocator reuses it — so the second instance a process builds and discards (e.g. the private builder engines behind the copy-on-write image tiers) memclrs the whole ceiling. With llama's 8 GiB ceiling that measured ~8 GB of dirty resident pages for memory nothing had touched, on every process, regardless of model size; guests with small ceilings (spidermonkey's 256 MiB) had the same behaviour hidden under the noise floor. Generated constructors for SHARED memories now call the sharedimage runtime's AllocSharedMemory: anonymous, private, zero-fill-on-demand pages outside the GC heap, fresh from the OS on every call, with a finalizer on the module preserving the heap allocation's reclaim semantics (a module kept reachable — say by a parked agent goroutine — keeps its memory). Platforms without mmap keep the historical make. The sharedimage aux files thereby become a compile-time dependency of shared-memory output, which they were always documented to be: the gcasm capture tree and the test snippet runners now include Result.AuxFiles instead of silently dropping them. Pinned by a fixture with a 1 GiB ceiling: the constructor must route through AllocSharedMemory, and building + discarding three instances must hold process RSS far under one ceiling. Co-Authored-By: Claude Fable 5 <[email protected]> * Add in-place image builders: the builder writes the image file directly The image tiers built their template by booting a throwaway instance on private memory, copying its linear memory into a heap buffer, and writing that to the image file — the same bytes crossing memory up to three times, and (before the off-heap change) the trigger for the ceiling-zeroing regression. Elide all of it: NewSharedImageInPlace / NewSharedSnapshotInPlace hand the builder a MAP_SHARED mapping of the (sparse) image file, so every page the build touches is written once, straight into the file's page cache, and IS the image. Building now dirties exactly the touched pages, and they are file-backed — the kernel can write them back and evict under pressure, which anonymous pages cannot offer. The data-segment kind keeps its contract (carry NOTHING above the segments): the builder's BSS is punched back out of the file (truncate down, re-extend sparse) before instances map it. The builder's mapping stays valid until the module is unreachable, via the same finalizer discipline as AllocSharedMemory. Constructing a module ON caller memory needs the declared initial size, so generated packages now export InitialMemoryBytes: what NewWithMemory's memSize must be when the provided memory is fresh zeros rather than an existing image. Pinned by the sharedmem_ceiling fixture: a snapshot instance inherits the builder's BSS write, a data-segment-image instance must not. Co-Authored-By: Claude Fable 5 <[email protected]> * Drop the dead make-expression path for shared memories Review feedback on the constructor emission: the make() call expression was built for every memory and then discarded whenever the shared branch (AllocSharedMemory) or the caller-memory branch replaced it, and the shared branch assigned a capArg nothing consumes. Select the memory expression in one switch instead — each variant builds only what it emits. Co-Authored-By: Claude Fable 5 <[email protected]> * Remove AllocSharedMemory: the in-place builders are the fix Review feedback: with the image tiers built in place, no default path allocates a discarded ceiling-length shared memory any more, and the paths the anonymous-mmap constructor change still claimed to protect do not hold up. The fallback engines exist precisely because mmap is unavailable or failing — an mmap-based allocator cannot be their safety net (its no-mmap variant was plain make anyway), and the debugging escape hatch is not a production path to engineer for. Embedders still building images through throwaway plain-constructor engines migrate to the in-place builders when their bundles roll forward. Generated constructors go back to make for shared memories, the capture tree no longer needs the aux files (nothing in generated constructors references them; the snippet harnesses keep them because embedder-level tests exercise the image API), and the off-heap constructor test goes away with the machinery it pinned. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
185 lines
5.0 KiB
Go
185 lines
5.0 KiB
Go
package codegen_test
|
|
|
|
import (
|
|
"bytes"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/goccy/wasm2go/internal/codegen"
|
|
"github.com/goccy/wasm2go/internal/testfixture"
|
|
"github.com/goccy/wasm2go/internal/wasm"
|
|
)
|
|
|
|
// TestRecoverTrapsAreSurfacedAsErrors compiles the cg_recover fixture
|
|
// through wasm2go with the per-export Inv_<svc>_<mt> wrapper turned on
|
|
// and asserts the trap-recovery contract end-to-end:
|
|
//
|
|
// - a wasm trap inside the wrapped body does NOT propagate as a Go
|
|
// panic; the deferred recover surfaces it as a non-nil error
|
|
// whose message begins with "wasm trap:";
|
|
// - every mutable global is restored to the value it had at wrapper
|
|
// entry, even when the trap fires AFTER the body has mutated it
|
|
// (every fixture export writes 999 to the global before trapping);
|
|
// - the no-trap control export returns its computed value AND keeps
|
|
// the post-call global state the wasm body produced (i.e. the
|
|
// restore path only runs on the recovery branch);
|
|
// - 5000 consecutive trap+recover cycles do not leak goroutines and
|
|
// do not let the Go heap grow without bound. We force a GC and
|
|
// bound the post-loop heap delta at 1 MiB.
|
|
func TestRecoverTrapsAreSurfacedAsErrors(t *testing.T) {
|
|
bin := testfixture.Wasm(t, "cg_recover")
|
|
mod, err := wasm.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
res, err := codegen.Translate(&buf, mod, codegen.Options{
|
|
Package: "pkg",
|
|
OutputImportPath: "gentest/pkg",
|
|
BulkExportPrefix: "w_",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("translate: %v", err)
|
|
}
|
|
|
|
main := `package main
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime"
|
|
"strings"
|
|
|
|
"gentest/pkg"
|
|
)
|
|
|
|
func checkTrap(label string, err error) {
|
|
if err == nil {
|
|
fmt.Printf("%s-FAIL-no-err\n", label)
|
|
return
|
|
}
|
|
if !strings.Contains(err.Error(), "wasm trap") {
|
|
fmt.Printf("%s-FAIL-bad-msg %q\n", label, err.Error())
|
|
return
|
|
}
|
|
fmt.Printf("%s-OK\n", label)
|
|
}
|
|
|
|
func main() {
|
|
m := pkg.New()
|
|
if g := m.GetG(); g != 100 {
|
|
fmt.Printf("init-FAIL g=%d want=100\n", g)
|
|
return
|
|
}
|
|
fmt.Println("init-OK")
|
|
|
|
// div-by-zero, unreachable, OOB-load all recover and restore m.G.
|
|
_, e1 := pkg.Inv_1_0(m, 0, 0)
|
|
checkTrap("trap-divz", e1)
|
|
if g := m.GetG(); g != 100 {
|
|
fmt.Printf("restore-divz-FAIL g=%d\n", g)
|
|
return
|
|
}
|
|
fmt.Println("restore-divz-OK")
|
|
|
|
_, e2 := pkg.Inv_1_1(m, 0, 0)
|
|
checkTrap("trap-unreachable", e2)
|
|
if g := m.GetG(); g != 100 {
|
|
fmt.Printf("restore-unreachable-FAIL g=%d\n", g)
|
|
return
|
|
}
|
|
fmt.Println("restore-unreachable-OK")
|
|
|
|
_, e3 := pkg.Inv_1_2(m, 0, 0)
|
|
checkTrap("trap-nantrunc", e3)
|
|
if g := m.GetG(); g != 100 {
|
|
fmt.Printf("restore-nantrunc-FAIL g=%d\n", g)
|
|
return
|
|
}
|
|
fmt.Println("restore-nantrunc-OK")
|
|
|
|
// No-trap control: returns l0+l1, leaves global at 999
|
|
// (the body's last write committed because nothing trapped).
|
|
v, err := pkg.Inv_2_0(m, 5, 7)
|
|
if err != nil {
|
|
fmt.Printf("notrap-FAIL err=%v\n", err)
|
|
return
|
|
}
|
|
if v != 12 {
|
|
fmt.Printf("notrap-FAIL v=%d want=12\n", v)
|
|
return
|
|
}
|
|
if g := m.GetG(); g != 999 {
|
|
fmt.Printf("notrap-restore-leak-FAIL g=%d want=999\n", g)
|
|
return
|
|
}
|
|
fmt.Println("notrap-OK")
|
|
|
|
// Stress: 5000 trap+recover cycles. The wrapper itself must not
|
|
// leak Go-side resources, so we assert no new goroutines, a
|
|
// bounded Go-heap delta (< 1 MiB after a forced GC), and a
|
|
// constant wasm linear-memory slice length (the wasm body never
|
|
// calls memory.grow, so the slice that backs m.memory must stay
|
|
// the same size — any growth here would imply the wrapper or
|
|
// recover path re-allocated it).
|
|
m.ResetG()
|
|
memLenBefore := len(m.Memory())
|
|
runtime.GC()
|
|
gr1 := runtime.NumGoroutine()
|
|
var s1, s2 runtime.MemStats
|
|
runtime.ReadMemStats(&s1)
|
|
for i := 0; i < 5000; i++ {
|
|
if _, err := pkg.Inv_1_0(m, 0, 0); err == nil {
|
|
fmt.Printf("stress-FAIL-iter-%d-no-err\n", i)
|
|
return
|
|
}
|
|
}
|
|
runtime.GC()
|
|
runtime.ReadMemStats(&s2)
|
|
gr2 := runtime.NumGoroutine()
|
|
if gr2 != gr1 {
|
|
fmt.Printf("stress-goroutine-leak-FAIL before=%d after=%d\n", gr1, gr2)
|
|
return
|
|
}
|
|
delta := int64(s2.HeapAlloc) - int64(s1.HeapAlloc)
|
|
const heapDeltaCap = 1 << 20 // 1 MiB
|
|
if delta > heapDeltaCap {
|
|
fmt.Printf("stress-heap-leak-FAIL delta=%d cap=%d\n", delta, heapDeltaCap)
|
|
return
|
|
}
|
|
if memLenAfter := len(m.Memory()); memLenAfter != memLenBefore {
|
|
fmt.Printf("stress-memlen-FAIL before=%d after=%d\n", memLenBefore, memLenAfter)
|
|
return
|
|
}
|
|
if g := m.GetG(); g != 100 {
|
|
fmt.Printf("stress-global-FAIL g=%d want=100\n", g)
|
|
return
|
|
}
|
|
fmt.Println("stress-OK")
|
|
}
|
|
|
|
`
|
|
|
|
out := strings.TrimSpace(runGoSnippet(t, buf.String(), main, res.Sidecars, filesWithAux(res)))
|
|
want := []string{
|
|
"init-OK",
|
|
"trap-divz-OK",
|
|
"restore-divz-OK",
|
|
"trap-unreachable-OK",
|
|
"restore-unreachable-OK",
|
|
"trap-nantrunc-OK",
|
|
"restore-nantrunc-OK",
|
|
"notrap-OK",
|
|
"stress-OK",
|
|
}
|
|
got := strings.Split(out, "\n")
|
|
if len(got) != len(want) {
|
|
t.Fatalf("output line count mismatch: got %d, want %d\noutput:\n%s", len(got), len(want), out)
|
|
}
|
|
for i, w := range want {
|
|
if strings.TrimSpace(got[i]) != w {
|
|
t.Errorf("line %d: got %q want %q\nfull output:\n%s", i, got[i], w, out)
|
|
}
|
|
}
|
|
}
|