Files
c71ddafe1b Back shared linear memories with anonymous mappings, not the Go heap (#56)
* 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]>
2026-08-27 10:53:10 +09:00

184 lines
5.9 KiB
Go

package codegen_test
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/goccy/wasm2go/internal/codegen"
"github.com/goccy/wasm2go/internal/testfixture"
"github.com/goccy/wasm2go/internal/wasm"
)
// TestTrapOpsArePreservedThroughDCE drives the cg_traps fixture: every
// export performs a trapping op, drops its result, then returns a
// constant. A correct translation must still trap at runtime —
// dead-code elimination must NOT remove the trapping op just because
// the result is unused. We compile each export through wasm2go, run
// it in a child process, and assert the process panicked (non-zero
// exit) with the expected wasm trap message.
func TestTrapOpsArePreservedThroughDCE(t *testing.T) {
bin := testfixture.Wasm(t, "cg_traps")
mod, err := wasm.Parse(bytes.NewReader(bin))
if err != nil {
t.Fatal(err)
}
cases := []struct {
export string
wantPanic string
}{
{"div_s32_drop_then_42", "wasm: integer divide by zero"},
{"div_u32_drop_then_42", "wasm: integer divide by zero"},
{"rem_s32_drop_then_42", "wasm: integer divide by zero"},
{"rem_u32_drop_then_42", "wasm: integer divide by zero"},
{"div_s64_drop_then_42", "wasm: integer divide by zero"},
{"trunc_f32_s_nan_drop_then_42", "wasm: invalid conversion to integer"},
}
var buf bytes.Buffer
res, err := codegen.Translate(&buf, mod, codegen.Options{Package: "pkg", OutputImportPath: "gentest/pkg"})
if err != nil {
t.Fatalf("translate: %v", err)
}
generated := buf.String()
for _, tc := range cases {
t.Run(tc.export, func(t *testing.T) {
method := codegen.ExportMethodName(tc.export)
main := fmt.Sprintf(`package main
import (
"fmt"
"gentest/pkg"
)
func main() {
m := pkg.New()
v := m.%s()
fmt.Printf("no-trap got=%%d\n", v)
}
`, method)
out, ok := runGoSnippetExpectPanic(t, generated, main, res.Sidecars, filesWithAux(res))
if ok {
t.Fatalf("expected panic for %s, got clean exit:\n%s", tc.export, out)
}
if !strings.Contains(out, tc.wantPanic) {
t.Errorf("expected panic with %q for %s, got:\n%s", tc.wantPanic, tc.export, out)
}
if strings.Contains(out, "no-trap got=") {
t.Errorf("%s returned cleanly — trap was DCE'd away:\n%s", tc.export, out)
}
})
}
}
// TestMemGrowDropEmitsOnceNotTwice asserts that an `(memory.grow ...)
// drop` sequence emits exactly one call to memoryGrow across the whole
// generated package. The earlier risk was that a side-effecting scalar
// whose result is dropped would emit both the hoisted assignment and
// a fresh side-effect statement; that would surface as two
// memoryGrow calls. The fixture has a single `(drop (memory.grow ...))`
// so exactly one call is correct.
func TestMemGrowDropEmitsOnceNotTwice(t *testing.T) {
bin := testfixture.Wasm(t, "cg_traps")
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"})
if err != nil {
t.Fatalf("translate: %v", err)
}
// Asm-always-on ships TWO emit paths in the same
// package — the per-arch asm sidecar (a `CALL ·memoryGrow(SB)`
// per arch.s file) and the pure-Go fallback (a
// `memoryGrow(m, ...)` call in pkg_pure.go) — chosen at build
// time by build constraints. The pre-asm-always-on shape was
// just one Go call in gen.go.
//
// The regression this test guards is "side-effecting op whose
// result is dropped emits its CALL twice in the SAME emit path".
// So we count per path and assert each path emits at most one.
goSrc := buf.String()
mainGoCalls := strings.Count(goSrc, "memoryGrow(m,")
pureGoCalls := 0
asmCallsPerArch := map[string]int{}
sweep := func(name string, data []byte) {
switch {
case strings.HasSuffix(name, ".s"):
asmCallsPerArch[name] = strings.Count(string(data), "CALL ·memoryGrow(SB)")
default:
pureGoCalls += strings.Count(string(data), "memoryGrow(m,")
}
}
for name, data := range res.Sidecars {
sweep(name, data)
}
for name, data := range res.Files {
sweep(name, data)
}
if mainGoCalls > 1 {
t.Errorf("memoryGrow emitted %d times in gen.go; want at most 1.\nsource:\n%s",
mainGoCalls, goSrc)
}
if pureGoCalls > 1 {
t.Errorf("memoryGrow emitted %d times in pkg_pure.go (or other Go file); want at most 1.",
pureGoCalls)
}
for name, n := range asmCallsPerArch {
if n > 1 {
t.Errorf("memoryGrow emitted %d times in %s; want at most 1.", n, name)
}
}
// Sanity: at least one of the emit paths must carry the call,
// otherwise the export's body is silently empty.
total := mainGoCalls + pureGoCalls
for _, n := range asmCallsPerArch {
total += n
}
if total == 0 {
t.Errorf("memoryGrow not emitted in any path — the export body is empty.")
}
}
// runGoSnippetExpectPanic is the panic-tolerant variant of
// runGoSnippet: it does NOT call t.Fatal on a non-zero exit. Returns
// (combined output, processExitedSuccessfully).
func runGoSnippetExpectPanic(t *testing.T, generated, mainSrc string, extraFiles ...map[string][]byte) (string, bool) {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module gentest\n\ngo 1.25.0\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(dir, "pkg"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "pkg", "gen.go"), []byte(generated), 0644); err != nil {
t.Fatal(err)
}
for _, files := range extraFiles {
for name, data := range files {
p := filepath.Join(dir, "pkg", name)
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, stripPureGuard(data), 0644); err != nil {
t.Fatal(err)
}
}
}
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(mainSrc), 0644); err != nil {
t.Fatal(err)
}
cmd := exec.Command("go", "run", ".")
cmd.Dir = dir
out, err := cmd.CombinedOutput()
return string(out), err == nil
}