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

222 lines
8.2 KiB
Go

package codegen_test
import (
"bytes"
"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"
)
// TestThreads drives cg_threads.wasm, whose guest spawns real agents through
// wasi thread-spawn, has them bump a counter with atomics on shared memory and
// notify, and joins them with memory.atomic.wait. wazero cannot be the
// reference here (its threads support has no wasi-threads host), so the
// expectations are the wasm's own deterministic semantics.
//
// The generated program is compiled and run with the race detector, which is
// the real assertion: a wasm thread is a goroutine, so any unsynchronised
// access to the shared linear memory — above all a grow that relocated it —
// surfaces as a race, not as a flake.
func TestThreadsVisibility(t *testing.T) {
// A plain store published by an atomic store must be visible to a
// goroutine-agent that acquires via an atomic load — the mutex fast-path
// pattern every C critical section relies on.
bin := testfixture.Wasm(t, "cg_threads_visibility.wasm")
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)
}
main := "package main\n\nimport (\n\t\"fmt\"\n\t\"gentest/pkg\"\n)\n\nfunc main() {\n\tm := pkg.New()\n\tfmt.Println(m.Run())\n}\n"
got := runGoSnippetRaceDetector(t, buf.String(), main, res.Sidecars, filesWithAux(res))
if strings.TrimSpace(got) != "4242" {
t.Errorf("cross-thread plain-store visibility: got %q, want 4242", got)
}
}
func TestThreadsMainToAgentWake(t *testing.T) {
// The main thread notifies a parked agent — the direction a C mutex
// handoff uses when main unlocks while an agent sleeps on the futex.
bin := testfixture.Wasm(t, "cg_threads_wake_dir.wasm")
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)
}
main := "package main\n\nimport (\n\t\"fmt\"\n\t\"gentest/pkg\"\n)\n\nfunc main() {\n\tm := pkg.New()\n\tfmt.Println(m.Run())\n}\n"
got := runGoSnippetRaceDetector(t, buf.String(), main, res.Sidecars, filesWithAux(res))
if strings.TrimSpace(got) != "7777" {
t.Errorf("main->agent wake: got %q, want 7777", got)
}
}
func TestThreadsMutexHandoff(t *testing.T) {
// Two threads hammer a Drepper futex mutex 50k times each; a lost
// waiter-bit observation wedges one side forever.
bin := testfixture.Wasm(t, "cg_threads_mutex.wasm")
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)
}
main := "package main\n\nimport (\n\t\"fmt\"\n\t\"gentest/pkg\"\n)\n\nfunc main() {\n\tm := pkg.New()\n\tfmt.Println(m.Run())\n}\n"
got := runGoSnippetRaceDetector(t, buf.String(), main, res.Sidecars, filesWithAux(res))
if strings.TrimSpace(got) != "100000" {
t.Errorf("mutex handoff: got %q, want 100000", got)
}
}
func TestThreadsMuslLock(t *testing.T) {
// musl's 2-int __lock/__unlock: the unlock side reads the waiters counter
// with a PLAIN load to decide whether to notify. Preserving wasm's
// coherent-plain-access semantics across goroutines is what keeps
// wasi-libc's malloc/stdio/internal locks from stranding threads.
bin := testfixture.Wasm(t, "cg_threads_musl_lock.wasm")
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)
}
main := "package main\n\nimport (\n\t\"fmt\"\n\t\"gentest/pkg\"\n)\n\nfunc main() {\n\tm := pkg.New()\n\tfmt.Println(m.Run())\n}\n"
// No -race here: wasm's shared-memory model makes plain cross-agent
// access a LEGAL race (coherent, tear-free words); Go's detector would
// flag every such access. The assertion is completion + the exact count.
got := runGoSnippetNoRace(t, buf.String(), main, res.Sidecars, filesWithAux(res))
if strings.TrimSpace(got) != "100000" {
t.Errorf("musl lock handoff: got %q, want 100000", got)
}
}
func TestThreads(t *testing.T) {
bin := testfixture.Wasm(t, "cg_threads.wasm")
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)
}
main := `package main
import (
"fmt"
"gentest/pkg"
)
func main() {
// The only wasi import (thread-spawn) is goroutine-backed and internal,
// so the generated constructor takes no host parameters at all.
m := pkg.New()
// 8 agents, each +1 on the counter, joined through atomic wait/notify.
fmt.Printf("joined -> %d\n", m.SpawnAndJoin(8))
// Growing a shared memory must preserve both contents and pointers:
// 2 pages * 65536 + 0xbeef = 131072 + 48879.
fmt.Printf("grown -> %d\n", m.GrowShared())
}
`
got := runGoSnippetRaceDetector(t, buf.String(), main, res.Sidecars, filesWithAux(res))
want := "joined -> 8\ngrown -> 179951\n"
if got != want {
t.Errorf("output mismatch\n--want--\n%s\n--got--\n%s", want, got)
}
if strings.Contains(got, "DATA RACE") {
t.Errorf("race detected:\n%s", got)
}
}
// runGoSnippetNoRace runs the generated program without the race detector —
// for wasm whose SHARED-memory plain accesses are legal wasm races that the
// Go detector would (correctly, but unhelpfully) flag.
func runGoSnippetNoRace(t *testing.T, generated, mainSrc string, sidecars map[string][]byte, auxFiles map[string][]byte) string {
t.Helper()
return runGoSnippetThreads(t, generated, mainSrc, sidecars, auxFiles, false)
}
// runGoSnippetRaceDetector is runGoSnippetWithAux with -race: a wasm thread is
// a goroutine, so the detector is the assertion that the shared-memory model
// (fixed slice header, atomic memSize, relocation-free grow) actually holds.
func runGoSnippetRaceDetector(t *testing.T, generated, mainSrc string, sidecars map[string][]byte, auxFiles map[string][]byte) string {
t.Helper()
return runGoSnippetThreads(t, generated, mainSrc, sidecars, auxFiles, true)
}
// filesWithAux merges Result.Files with Result.AuxFiles for the snippet
// runners: the aux files are part of the output contract — the shared-memory
// runtime (the image builders and their in-place variants) lives there, and
// snippets that exercise it must compile the full output.
func filesWithAux(res codegen.Result) map[string][]byte {
merged := map[string][]byte{}
for name, data := range res.Files {
merged[name] = data
}
for name, data := range res.AuxFiles {
merged[name] = data
}
return merged
}
func runGoSnippetThreads(t *testing.T, generated, mainSrc string, sidecars map[string][]byte, auxFiles map[string][]byte, race bool) string {
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 _, set := range []map[string][]byte{sidecars, auxFiles} {
for name, data := range set {
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)
}
runArgs := []string{"run"}
if race {
runArgs = append(runArgs, "-race")
}
runArgs = append(runArgs, ".")
cmd := exec.Command("go", runArgs...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("go run failed: %v\noutput:\n%s\ngenerated:\n%s", err, out, generated)
}
return string(out)
}