Commit 6a241febce for golang

commit 6a241febce5d76c09d3d9c3709548ea026ac7880
Author: Carlos Amedee <carlos@golang.org>
Date:   Wed Nov 18 16:30:38 2026 -0500

    cmd/internal/testwasm: test the modules linked under GOWASM=stackswitch

    Add tests in cmd/internal/testwasm to verify the Wasm modules linked
    with and without GOWASM=stackswitch, checking that stack-switching
    additions are emitted when enabled and absent on the default port:

    - TestLinkedSections parses the linked modules directly to check section
      order, section contents, and types.
    - TestValidateLinked validates both builds with installed external tools
      (wasm-tools, wasmtime, node).

    For #81963

    Cq-Include-Trybots: luci.golang.try:gotip-js-wasm-stackswitch,gotip-wasip1-wasm_wasmtime-stackswitch
    Change-Id: Iabeaedf517a9bc82e4a5da64ba124160f883d175
    Reviewed-on: https://go-review.googlesource.com/c/go/+/865884
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Reviewed-by: David Chase <drchase@google.com>

diff --git a/src/cmd/internal/testwasm/module_test.go b/src/cmd/internal/testwasm/module_test.go
new file mode 100644
index 0000000000..8f5f36c5de
--- /dev/null
+++ b/src/cmd/internal/testwasm/module_test.go
@@ -0,0 +1,650 @@
+// Copyright 2026 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package testwasm
+
+import (
+	"bytes"
+	"cmd/internal/obj/wasm"
+	"encoding/binary"
+	"errors"
+	"flag"
+	"fmt"
+	"internal/testenv"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strconv"
+	"strings"
+	"sync"
+	"testing"
+)
+
+// Value types and section IDs of the Wasm binary format, named as in
+// cmd/link/internal/wasm.
+const (
+	I32  = 0x7F
+	I64  = 0x7E
+	F32  = 0x7D
+	F64  = 0x7C
+	V128 = 0x7B
+)
+
+const (
+	sectionCustom   = 0
+	sectionType     = 1
+	sectionImport   = 2
+	sectionFunction = 3
+	sectionTable    = 4
+	sectionMemory   = 5
+	sectionGlobal   = 6
+	sectionExport   = 7
+	sectionStart    = 8
+	sectionElement  = 9
+	sectionCode     = 10
+	sectionData     = 11
+	sectionTag      = 13
+)
+
+// contTableInitialSize is the initial size of the continuation table that
+// cmd/link/internal/wasm emits under GOWASM=stackswitch.
+const contTableInitialSize = 1024
+
+// helloSrc is the program linked by the tests below.
+const helloSrc = `package main
+
+func main() {
+	defer println("bye")
+	println("hello")
+}
+`
+
+type linkKey struct{ goos, gowasm string }
+
+var linkCache struct {
+	sync.Mutex
+	m map[linkKey]linkResult
+}
+
+type linkResult struct {
+	file string
+	err  error
+}
+
+// linkHello links helloSrc for goos/wasm with the given GOWASM setting
+// and returns the path of the module. Modules are linked at most once per
+// test binary.
+func linkHello(t *testing.T, goos, gowasm string) string {
+	t.Helper()
+	testenv.MustHaveGoBuild(t)
+	k := linkKey{goos, gowasm}
+	linkCache.Lock()
+	defer linkCache.Unlock()
+	if r, ok := linkCache.m[k]; ok {
+		if r.err != nil {
+			t.Fatal(r.err)
+		}
+		return r.file
+	}
+	if linkCache.m == nil {
+		linkCache.m = make(map[linkKey]linkResult)
+	}
+	r := buildHello(t, goos, gowasm)
+	linkCache.m[k] = r
+	if r.err != nil {
+		t.Fatal(r.err)
+	}
+	return r.file
+}
+
+var linkDir struct {
+	once sync.Once
+	dir  string
+	err  error
+}
+
+func buildHello(t *testing.T, goos, gowasm string) linkResult {
+	// The modules outlive the test that first links them, so use a
+	// directory that is shared by the tests and removed by TestMain.
+	linkDir.once.Do(func() {
+		linkDir.dir, linkDir.err = os.MkdirTemp("", "wasmlinktest")
+		if linkDir.err == nil {
+			linkDir.err = os.WriteFile(filepath.Join(linkDir.dir, "go.mod"), []byte("module hello\n"), 0666)
+		}
+		if linkDir.err == nil {
+			linkDir.err = os.WriteFile(filepath.Join(linkDir.dir, "hello.go"), []byte(helloSrc), 0666)
+		}
+	})
+	if linkDir.err != nil {
+		return linkResult{err: linkDir.err}
+	}
+	out := filepath.Join(linkDir.dir, fmt.Sprintf("hello_%s_%s.wasm", goos, gowasm))
+	cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-o", out, ".")
+	cmd.Dir = linkDir.dir
+	cmd.Env = append(cmd.Environ(), "GOOS="+goos, "GOARCH=wasm", "GOWASM="+gowasm)
+	if b, err := cmd.CombinedOutput(); err != nil {
+		return linkResult{err: fmt.Errorf("%v: %v\n%s", cmd, err, b)}
+	}
+	return linkResult{file: out}
+}
+
+func TestMain(m *testing.M) {
+	flag.Parse()
+	code := m.Run()
+	if linkDir.dir != "" {
+		os.RemoveAll(linkDir.dir)
+	}
+	os.Exit(code)
+}
+
+// A module is a parsed Wasm binary.
+type module struct {
+	sections []section
+}
+
+type section struct {
+	id      byte
+	name    string // for custom sections
+	payload []byte // without the custom section name
+}
+
+// parseModule splits the Wasm binary b into sections.
+func parseModule(b []byte) (*module, error) {
+	if !bytes.HasPrefix(b, []byte("\x00asm\x01\x00\x00\x00")) {
+		return nil, errors.New("bad magic or version")
+	}
+	r := &reader{b: b[8:]}
+	m := new(module)
+	for len(r.b) > 0 {
+		id := r.byte()
+		size := r.uleb()
+		payload := r.bytes(int(size))
+		if r.err != nil {
+			return nil, r.err
+		}
+		s := section{id: id, payload: payload}
+		if id == sectionCustom {
+			pr := &reader{b: payload}
+			s.name = pr.name()
+			s.payload = pr.b
+			if pr.err != nil {
+				return nil, pr.err
+			}
+		}
+		m.sections = append(m.sections, s)
+	}
+	return m, nil
+}
+
+// section returns the payload of the section with the given id, or nil.
+func (m *module) section(id byte) []byte {
+	for _, s := range m.sections {
+		if s.id == id {
+			return s.payload
+		}
+	}
+	return nil
+}
+
+func (m *module) customSection(name string) []byte {
+	for _, s := range m.sections {
+		if s.id == sectionCustom && s.name == name {
+			return s.payload
+		}
+	}
+	return nil
+}
+
+// types returns the encoded entries of the type section.
+func (m *module) types() ([][]byte, error) {
+	r := &reader{b: m.section(sectionType)}
+	n := r.uleb()
+	types := make([][]byte, 0, n)
+	for range n {
+		start := r.b
+		switch form := r.byte(); form {
+		case 0x60: // functype
+			r.valTypes()
+			r.valTypes()
+		case 0x5d: // conttype
+			r.sleb()
+		default:
+			return nil, fmt.Errorf("type %d: unexpected form %#x", len(types), form)
+		}
+		if r.err != nil {
+			return nil, r.err
+		}
+		types = append(types, start[:len(start)-len(r.b)])
+	}
+	return types, r.err
+}
+
+// funcTypes returns the type index of each function, imported or
+// defined, keyed by function name, from the import, function, and name
+// sections.
+func (m *module) funcTypes() (map[string]uint64, error) {
+	var typeIdx []uint64
+	r := &reader{b: m.section(sectionImport)}
+	for range r.uleb() {
+		r.name() // module
+		r.name() // name
+		if kind := r.byte(); kind != 0x00 {
+			return nil, fmt.Errorf("import %d: unexpected kind %#x", len(typeIdx), kind)
+		}
+		typeIdx = append(typeIdx, r.uleb())
+	}
+	r = &reader{b: m.section(sectionFunction), err: r.err}
+	for range r.uleb() {
+		typeIdx = append(typeIdx, r.uleb())
+	}
+	if r.err != nil {
+		return nil, r.err
+	}
+
+	names := m.customSection("name")
+	if names == nil {
+		return nil, errors.New("no name section")
+	}
+	r = &reader{b: names}
+	funcTypes := make(map[string]uint64)
+	for len(r.b) > 0 && r.err == nil {
+		id := r.byte()
+		sub := &reader{b: r.bytes(int(r.uleb()))}
+		if id != 0x01 { // function names
+			continue
+		}
+		for range sub.uleb() {
+			idx := sub.uleb()
+			name := sub.name()
+			if idx >= uint64(len(typeIdx)) {
+				return nil, fmt.Errorf("function %s: index %d out of range", name, idx)
+			}
+			funcTypes[name] = typeIdx[idx]
+		}
+		if sub.err != nil {
+			return nil, sub.err
+		}
+	}
+	return funcTypes, r.err
+}
+
+// numFuncs returns the number of functions defined (not imported) by m.
+func (m *module) numFuncs() uint64 {
+	r := &reader{b: m.section(sectionFunction)}
+	return r.uleb()
+}
+
+type reader struct {
+	b   []byte
+	err error
+}
+
+func (r *reader) fail(err error) {
+	if r.err == nil {
+		r.err = err
+	}
+	r.b = nil
+}
+
+func (r *reader) byte() byte {
+	if len(r.b) == 0 {
+		r.fail(errors.New("unexpected end of data"))
+		return 0
+	}
+	c := r.b[0]
+	r.b = r.b[1:]
+	return c
+}
+
+func (r *reader) bytes(n int) []byte {
+	if n < 0 || n > len(r.b) {
+		r.fail(errors.New("unexpected end of data"))
+		return nil
+	}
+	b := r.b[:n]
+	r.b = r.b[n:]
+	return b
+}
+
+func (r *reader) uleb() uint64 {
+	var v uint64
+	for shift := 0; shift < 64; shift += 7 {
+		c := r.byte()
+		v |= uint64(c&0x7f) << shift
+		if c&0x80 == 0 {
+			return v
+		}
+	}
+	r.fail(errors.New("LEB128 overflow"))
+	return 0
+}
+
+func (r *reader) sleb() int64 {
+	var v int64
+	for shift := 0; shift < 64; shift += 7 {
+		c := r.byte()
+		v |= int64(c&0x7f) << shift
+		if c&0x80 == 0 {
+			if shift+7 < 64 && c&0x40 != 0 {
+				v |= -1 << (shift + 7)
+			}
+			return v
+		}
+	}
+	r.fail(errors.New("LEB128 overflow"))
+	return 0
+}
+
+func (r *reader) name() string {
+	return string(r.bytes(int(r.uleb())))
+}
+
+func (r *reader) valTypes() {
+	for range r.uleb() {
+		switch t := r.byte(); t {
+		case 0x63, 0x64: // (ref null ht), (ref ht)
+			r.sleb()
+		case I32, I64, F32, F64, V128, 0x70, 0x6f: // numtypes, vectype, funcref, externref
+		default:
+			r.fail(fmt.Errorf("unexpected valtype %#x", t))
+		}
+	}
+}
+
+// uleb returns the unsigned LEB128 encoding of v.
+func uleb(v uint64) []byte {
+	return binary.AppendUvarint(nil, v)
+}
+
+func cat(bs ...[]byte) []byte {
+	return bytes.Join(bs, nil)
+}
+
+// TestLinkedSections links helloSrc with and without GOWASM=stackswitch
+// and checks section order, the tag and table sections, and continuation
+// and function types. For the default build, it checks that the tag
+// section, continuation table, continuation types, and stack-switching
+// functions are absent.
+func TestLinkedSections(t *testing.T) {
+	var (
+		typeGo    = []byte{0x60, 0x01, I32, 0x01, I32} // (i32) -> (i32): PC_B -> unwind
+		typeEmpty = []byte{0x60, 0x00, 0x00}           // () -> ()
+		typeCont  = []byte{0x5d, 0x01}                 // (cont 1)
+		contRef   = []byte{0x63, wasm.ContinuationTypeIndex}
+	)
+
+	for _, goos := range targetGOOSes(t) {
+		t.Run(goos, func(t *testing.T) {
+			t.Run("stackswitch", func(t *testing.T) {
+				m := parseLinked(t, linkHello(t, goos, "stackswitch"))
+
+				// The tag section declares $yield and $exit (tags 0-1),
+				// both of type 1, () -> ().
+				if got, want := m.section(sectionTag), []byte{
+					0x02,       // 2 tags
+					0x00, 0x01, // tag 0 ($yield): exception attribute, type 1
+					0x00, 0x01, // tag 1 ($exit): exception attribute, type 1
+				}; !bytes.Equal(got, want) {
+					t.Errorf("tag section = % x, want % x", got, want)
+				}
+				if wasm.ExitTagIndex != 1 {
+					t.Errorf("wasm.ExitTagIndex = %d, want 1", wasm.ExitTagIndex)
+				}
+				checkSectionOrder(t, m, []byte{
+					sectionType, sectionImport, sectionFunction, sectionTable, sectionMemory,
+					sectionTag, sectionGlobal, sectionExport, sectionElement, sectionCode, sectionData,
+				})
+
+				// Table 0 holds a funcref for each defined function; table 1 holds
+				// continuations.
+				if got, want := m.section(sectionTable), cat(
+					[]byte{0x02},                           // 2 tables
+					[]byte{0x70, 0x00}, uleb(m.numFuncs()), // funcref, min only
+					contRef, []byte{0x00}, uleb(contTableInitialSize), // (ref null $cont), min only
+				); !bytes.Equal(got, want) {
+					t.Errorf("table section = % x, want % x", got, want)
+				}
+
+				types, err := m.types()
+				if err != nil {
+					t.Fatal(err)
+				}
+				for i, want := range [][]byte{typeGo, typeEmpty, typeCont} {
+					if i >= len(types) || !bytes.Equal(types[i], want) {
+						t.Errorf("type %d = % x, want % x", i, at(types, i), want)
+					}
+				}
+				for i, typ := range types[3:] {
+					if typ[0] != 0x60 {
+						t.Errorf("type %d = % x, want a function type", i+3, typ)
+					}
+				}
+
+				checkFuncTypes(t, m, types, map[string][]byte{
+					"wasm_scheduler_loop": typeEmpty,
+					"wasm_goentry":        typeEmpty,
+					"wasm_resume":         cat([]byte{0x60, 0x01, I32, 0x01}, contRef), // (i32) -> (ref null $cont)
+					"runtime.deferreturn": typeGo,
+					"main.main":           typeGo,
+				})
+			})
+
+			t.Run("default", func(t *testing.T) {
+				m := parseLinked(t, linkHello(t, goos, ""))
+
+				if m.section(sectionTag) != nil {
+					t.Errorf("unexpected tag section without GOWASM=stackswitch")
+				}
+				checkSectionOrder(t, m, []byte{
+					sectionType, sectionImport, sectionFunction, sectionTable, sectionMemory,
+					sectionGlobal, sectionExport, sectionElement, sectionCode, sectionData,
+				})
+
+				if got, want := m.section(sectionTable), cat(
+					[]byte{0x01},                           // 1 table
+					[]byte{0x70, 0x00}, uleb(m.numFuncs()), // funcref, min only
+				); !bytes.Equal(got, want) {
+					t.Errorf("table section = % x, want % x", got, want)
+				}
+
+				types, err := m.types()
+				if err != nil {
+					t.Fatal(err)
+				}
+				if len(types) == 0 || !bytes.Equal(types[0], typeGo) {
+					t.Errorf("type 0 = % x, want % x", at(types, 0), typeGo)
+				}
+				for i, typ := range types {
+					if typ[0] != 0x60 || bytes.Contains(typ, contRef) {
+						t.Errorf("type %d = % x, want a function type without continuation references", i, typ)
+					}
+				}
+
+				checkFuncTypes(t, m, types, map[string][]byte{
+					"wasm_pc_f_loop":      typeEmpty,
+					"runtime.deferreturn": typeGo,
+					"main.main":           typeGo,
+				})
+				funcTypes, err := m.funcTypes()
+				if err != nil {
+					t.Fatal(err)
+				}
+				for _, name := range []string{"wasm_scheduler_loop", "wasm_resume", "wasm_goentry"} {
+					if _, ok := funcTypes[name]; ok {
+						t.Errorf("unexpected function %s without GOWASM=stackswitch", name)
+					}
+				}
+			})
+		})
+	}
+}
+
+func parseLinked(t *testing.T, file string) *module {
+	t.Helper()
+	b, err := os.ReadFile(file)
+	if err != nil {
+		t.Fatal(err)
+	}
+	m, err := parseModule(b)
+	if err != nil {
+		t.Fatalf("parsing %s: %v", file, err)
+	}
+	return m
+}
+
+// checkSectionOrder checks that the non-custom sections of m have the
+// given ids, in order.
+func checkSectionOrder(t *testing.T, m *module, want []byte) {
+	t.Helper()
+	var got []byte
+	for _, s := range m.sections {
+		if s.id != sectionCustom {
+			got = append(got, s.id)
+		}
+	}
+	if !bytes.Equal(got, want) {
+		t.Errorf("section ids = %v, want %v", got, want)
+	}
+}
+
+// checkFuncTypes checks the encoded types of the named functions.
+func checkFuncTypes(t *testing.T, m *module, types [][]byte, want map[string][]byte) {
+	t.Helper()
+	funcTypes, err := m.funcTypes()
+	if err != nil {
+		t.Fatal(err)
+	}
+	for name, wantType := range want {
+		idx, ok := funcTypes[name]
+		if !ok {
+			t.Errorf("no function %s", name)
+			continue
+		}
+		if got := at(types, int(idx)); !bytes.Equal(got, wantType) {
+			t.Errorf("type of %s = %d (% x), want % x", name, idx, got, wantType)
+		}
+	}
+}
+
+func at(types [][]byte, i int) []byte {
+	if i < 0 || i >= len(types) {
+		return nil
+	}
+	return types[i]
+}
+
+// A validator is an external tool that validates Wasm modules.
+type validator struct {
+	name string
+	// args returns the command line validating file, or nil if the tool
+	// cannot validate modules with the given GOWASM setting.
+	args func(t *testing.T, path, file, gowasm string) []string
+}
+
+var validators = []validator{
+	{"wasm-tools", func(t *testing.T, path, file, gowasm string) []string {
+		features := "wasm2"
+		if gowasm == "stackswitch" {
+			features = "wasm3,stack-switching"
+		}
+		return []string{path, "validate", "--features", features, file}
+	}},
+	{"wasmtime", func(t *testing.T, path, file, gowasm string) []string {
+		// Older Wasmtime releases reject -W options for the proposals they
+		// predate, so pass only those this one lists.
+		help, _ := exec.Command(path, "compile", "-W", "help").CombinedOutput()
+		var known []string
+		for _, p := range []string{"stack-switching", "exceptions", "function-references", "gc"} {
+			if bytes.Contains(help, []byte(" "+p+"[=y|n]")) {
+				known = append(known, p)
+			}
+		}
+		val := "=n"
+		if gowasm == "stackswitch" {
+			if len(known) < 4 {
+				return nil
+			}
+			val = "=y"
+		}
+		args := []string{path, "compile", "-o", os.DevNull}
+		if len(known) > 0 {
+			// Enable the proposals under GOWASM=stackswitch, or disable the known
+			// ones otherwise (a release that predates a proposal cannot accept a
+			// module using it).
+			args = append(args, "-W", strings.Join(known, val+",")+val)
+		}
+		return append(args, file)
+	}},
+	{"node", func(t *testing.T, path, file, gowasm string) []string {
+		args := []string{path}
+		if gowasm == "stackswitch" {
+			// Node.js versions before 26 implement an older encoding of the
+			// stack-switching proposal.
+			if v := nodeMajorVersion(path); v < 26 {
+				return nil
+			}
+			// The V8 flag enabling stack switching was renamed in Node.js 27.
+			flag := ""
+			for _, f := range []string{"--wasm-wasmfx", "--experimental-wasm-wasmfx"} {
+				if exec.Command(path, f, "-e", "").Run() == nil {
+					flag = f
+					break
+				}
+			}
+			if flag == "" {
+				return nil
+			}
+			args = append(args, flag)
+		}
+		return append(args, "-e", `new WebAssembly.Module(require("fs").readFileSync(process.argv[1]))`, file)
+	}},
+}
+
+// nodeMajorVersion returns the major version of the Node.js binary at
+// path, or 0 if it cannot be determined.
+func nodeMajorVersion(path string) int {
+	out, err := exec.Command(path, "--version").Output()
+	if err != nil {
+		return 0
+	}
+	major, _, _ := strings.Cut(strings.TrimPrefix(strings.TrimSpace(string(out)), "v"), ".")
+	v, err := strconv.Atoi(major)
+	if err != nil {
+		return 0
+	}
+	return v
+}
+
+// TestValidateLinked links helloSrc with and without GOWASM=stackswitch
+// and validates each module with every installed validator above. With
+// GOWASM=stackswitch, validators enable stack switching and its
+// prerequisite proposals (exception handling, typed function references,
+// and GC). Without it, those proposals are disabled where possible to
+// verify that the module does not use them.
+func TestValidateLinked(t *testing.T) {
+	for _, v := range validators {
+		t.Run(v.name, func(t *testing.T) {
+			path, err := exec.LookPath(v.name)
+			if err != nil {
+				t.Skipf("%s not found in $PATH", v.name)
+			}
+			for _, goos := range targetGOOSes(t) {
+				for _, gowasm := range []string{"", "stackswitch"} {
+					t.Run(goos+"/GOWASM="+gowasm, func(t *testing.T) {
+						file := linkHello(t, goos, gowasm)
+						args := v.args(t, path, file, gowasm)
+						if args == nil {
+							t.Skipf("%s does not support the required stack-switching proposals", path)
+						}
+						cmd := testenv.Command(t, args[0], args[1:]...)
+						out, err := cmd.CombinedOutput()
+						if err != nil {
+							t.Errorf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, out)
+						}
+					})
+				}
+			}
+		})
+	}
+}