Commit 7f75be471b for golang

commit 7f75be471b51220011cc751a6ce4acfe0508810f
Author: Carlos Amedee <carlos@golang.org>
Date:   Wed Oct 28 17:00:19 2026 -0400

    cmd/internal/obj/wasm, cmd/link/internal/wasm: test existing encodings

    This change adds tests for TableGet, TableSet, continuation types,
    contRef value-type encoding, RefNull, and ContNew opcodes.

    Test the opcodes of the table, reference, and stack-switching
    instructions, the immediates that the assembler writes for them
    (including ContNew's type and Resume's handler table) and their
    end-to-end assembly in cmd/asm, Suspend's refresh of the local SP, the
    linker's continuation type indices and type-section encodings, and the
    contRef value-type encoding.

    For #81963

    Change-Id: I022b3fc756027c6e004271366df9731eb6930030
    Reviewed-on: https://go-review.googlesource.com/c/go/+/864022
    Auto-Submit: Carlos Amedee <carlos@golang.org>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Reviewed-by: Cherry Mui <cherryyz@google.com>

diff --git a/src/cmd/asm/internal/asm/endtoend_test.go b/src/cmd/asm/internal/asm/endtoend_test.go
index 3c1cf1dfac..835347e915 100644
--- a/src/cmd/asm/internal/asm/endtoend_test.go
+++ b/src/cmd/asm/internal/asm/endtoend_test.go
@@ -7,6 +7,7 @@ package asm
 import (
 	"bufio"
 	"bytes"
+	"encoding/hex"
 	"fmt"
 	"internal/buildcfg"
 	"os"
@@ -204,6 +205,11 @@ Diff:
 		t.FailNow()
 	}

+	if goarch == "wasm" {
+		checkWasmEncodings(t, top, hexByLine)
+		return
+	}
+
 	for p := top; p != nil; p = p.Link {
 		if p.As == obj.ATEXT {
 			text = p.From.Sym
@@ -258,6 +264,48 @@ Diff:

 }

+// checkWasmEncodings checks the instruction encodings in hexByLine for Wasm.
+// On Wasm, p.Pc is a resume-point index (PC_B), not a byte offset, so the
+// generic check, which slices text.P by p.Pc, can't find an instruction's
+// bytes. Instead, it relies on Wasm emitting a function's code in order:
+// each encoding must match the bytes that follow those of the previous
+// annotated line. A TEXT line's encoding is the function's locals
+// declaration and prologue. So every byte that the assembler emits must
+// belong to an annotated line.
+func checkWasmEncodings(t *testing.T, top *obj.Prog, hexByLine map[string]string) {
+	var code []byte
+	for p := top; p != nil; p = p.Link {
+		if p.As == obj.ATEXT {
+			code = p.From.Sym.P
+		}
+		hexes := hexByLine[p.Line()]
+		if hexes == "" {
+			continue
+		}
+		delete(hexByLine, p.Line())
+		want, err := hex.DecodeString(hexes)
+		if err != nil {
+			t.Errorf("%s: bad encoding %q: %v", p, hexes, err)
+			continue
+		}
+		have := code[:min(len(want), len(code))]
+		code = code[len(have):]
+		if !bytes.Equal(have, want) {
+			t.Errorf("%s: have encoding %x, want %s", p, have, hexes)
+		}
+	}
+	if len(hexByLine) > 0 {
+		var missing []string
+		for key := range hexByLine {
+			missing = append(missing, key)
+		}
+		sort.Strings(missing)
+		for _, line := range missing {
+			t.Errorf("%s: did not find instruction encoding", line)
+		}
+	}
+}
+
 func isHexes(s string) bool {
 	if s == "" {
 		return false
@@ -548,3 +596,7 @@ func TestRISCV64Validation(t *testing.T) {
 func TestS390XEndToEnd(t *testing.T) {
 	testEndToEnd(t, "s390x", "s390x")
 }
+
+func TestWasmEndToEnd(t *testing.T) {
+	testEndToEnd(t, "wasm", "wasm")
+}
diff --git a/src/cmd/asm/internal/asm/testdata/wasm.s b/src/cmd/asm/internal/asm/testdata/wasm.s
new file mode 100644
index 0000000000..eaba839b1a
--- /dev/null
+++ b/src/cmd/asm/internal/asm/testdata/wasm.s
@@ -0,0 +1,20 @@
+// 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.
+
+#include "../../../../../runtime/textflag.h"
+
+// The encodings are checked in order (see checkWasmEncodings). The TEXT
+// line's encoding is the locals declaration (one i32, the local SP) and
+// the prologue that loads the local SP from the global SP.
+TEXT testWasm(SB), NOSPLIT, $0-0                          // 01017f23002101
+	TableGet $1                                       // 2501
+	TableSet $1                                       // 2601
+	TableGrow $1                                      // fc0f01
+	TableSize $1                                      // fc1001
+	RefNull                                           // d002
+	RefIsNull                                         // d1
+	RefFunc testWasm(SB)                              // d2
+	ContNew                                           // e002
+	Suspend                                           // e20023002101
+	Resume                                            // e30201000000
diff --git a/src/cmd/internal/obj/wasm/wasmobj.go b/src/cmd/internal/obj/wasm/wasmobj.go
index e67a4d1f13..da9c553e1f 100644
--- a/src/cmd/internal/obj/wasm/wasmobj.go
+++ b/src/cmd/internal/obj/wasm/wasmobj.go
@@ -100,6 +100,12 @@ var Register = map[string]int16{
 // The index at which to insert special continuation and its block type, for WasmFX extension.
 const ContinuationTypeIndex = 2

+// EmptyFuncTypeIndex is the type section index of the function signature
+// () -> (), used for all tags and as the underlying function type of
+// ContinuationTypeIndex under GOWASM=stackswitch.
+// Must match initStackSwitchingTypes in cmd/link/internal/wasm.
+const EmptyFuncTypeIndex = 1
+
 var registerNames []string

 func init() {
diff --git a/src/cmd/internal/obj/wasm/wasmobj_test.go b/src/cmd/internal/obj/wasm/wasmobj_test.go
index 1592b9fcf0..056eebb0de 100644
--- a/src/cmd/internal/obj/wasm/wasmobj_test.go
+++ b/src/cmd/internal/obj/wasm/wasmobj_test.go
@@ -10,10 +10,11 @@ import (
 	"testing"
 )

-// TestWriteOpcode checks one opcode from each encoding range. Vector
-// instructions are the 0xFD prefix followed by a ULEB128-encoded opcode
-// index, so the cases below bracket both points where that index grows a
-// byte: 0x07F to 0x080 and 0x0FF to 0x100.
+// TestWriteOpcode checks opcodes from each encoding range, including all
+// reference and stack-switching opcodes. Vector instructions are the 0xFD
+// prefix followed by a ULEB128-encoded opcode index, so the cases below
+// bracket both points where that index grows a byte: 0x07F to 0x080 and
+// 0x0FF to 0x100.
 func TestWriteOpcode(t *testing.T) {
 	tests := []struct {
 		as   obj.As
@@ -23,10 +24,27 @@ func TestWriteOpcode(t *testing.T) {
 		{AEnd, []byte{0x0B}},
 		{ADrop, []byte{0x1A}},
 		{ALocalGet, []byte{0x20}},
+		{ATableGet, []byte{0x25}},
+		{ATableSet, []byte{0x26}}, // last before the gap at 0x27
 		{AI32Load, []byte{0x28}},
 		{ARefNull, []byte{0xD0}},
+		{ARefIsNull, []byte{0xD1}},
+		{ARefFunc, []byte{0xD2}},
+		// AContBind, AResumeThrow, AResumeThrowRef, and ASwitch are not
+		// implemented in assemble; their rows here only pin the opcode
+		// numbers (and the AContNew..ASwitch enum order in a.out.go).
 		{AContNew, []byte{0xE0}},
+		{AContBind, []byte{0xE1}},
+		{ASuspend, []byte{0xE2}},
+		{AResume, []byte{0xE3}},
+		{AResumeThrow, []byte{0xE4}},
+		{AResumeThrowRef, []byte{0xE5}},
+		{ASwitch, []byte{0xE6}},
 		{AI32TruncSatF32S, []byte{0xFC, 0x00}},
+		// TableGrow and TableSize also check the order of the 0xFC
+		// instructions in a.out.go, which writeOpcode relies on.
+		{ATableGrow, []byte{0xFC, 0x0F}},
+		{ATableSize, []byte{0xFC, 0x10}},

 		{AV128Load, []byte{0xFD, 0x00}},                            // index 0x000
 		{AI32x4ExtaddPairwiseI16x8U, []byte{0xFD, 0x7F}},           // index 0x07F
@@ -44,3 +62,79 @@ func TestWriteOpcode(t *testing.T) {
 		}
 	}
 }
+
+// TestAssembleTableAndRef checks the encodings that assemble writes for
+// table, reference, and stack-switching instructions.
+func TestAssembleTableAndRef(t *testing.T) {
+	tests := []struct {
+		name string
+		prog obj.Prog
+		want []byte
+	}{
+		{"TableGet", obj.Prog{As: ATableGet, From: constAddr(1)}, []byte{0x25, 0x01}},
+		{"TableSet", obj.Prog{As: ATableSet, From: constAddr(1)}, []byte{0x26, 0x01}},
+		{"TableGrow", obj.Prog{As: ATableGrow, From: constAddr(1)}, []byte{0xFC, 0x0F, 0x01}},
+		{"TableSize", obj.Prog{As: ATableSize, From: constAddr(1)}, []byte{0xFC, 0x10, 0x01}},
+		{"RefNull", obj.Prog{As: ARefNull}, []byte{0xD0, ContinuationTypeIndex}},
+		{"RefIsNull", obj.Prog{As: ARefIsNull}, []byte{0xD1}},
+		{"ContNew", obj.Prog{As: AContNew}, []byte{0xE0, ContinuationTypeIndex}},
+		{"Suspend", obj.Prog{As: ASuspend}, []byte{0xE2, 0x00}},
+		// Continuation type, then 1 handler: on-label clause (0x00), tag 0, label 0.
+		{"Resume", obj.Prog{As: AResume}, []byte{0xE3, ContinuationTypeIndex, 0x01, 0x00, 0x00, 0x00}},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := assembleOne(t, &tt.prog); !bytes.Equal(got, tt.want) {
+				t.Errorf("got % x, want % x", got, tt.want)
+			}
+		})
+	}
+}
+
+// TestAssembleSuspendUpdatesLocalSP verifies that ASuspend refreshes the
+// function's cached local SP from global SP when hasLocalSP is true.
+func TestAssembleSuspendUpdatesLocalSP(t *testing.T) {
+	ctxt := obj.Linknew(&Linkwasm)
+	ctxt.DiagFunc = t.Errorf
+	s := &obj.LSym{Name: "test.f"} // Standard Go function with a local SP cache.
+	s.NewFuncInfo()
+	s.Func().Text = &obj.Prog{Ctxt: ctxt, As: ASuspend}
+	assemble(ctxt, s, nil)
+
+	want := []byte{
+		0x01, 0x01, 0x7F, // 1 local declaration: 1 x i32 (SP cache)
+		0x23, 0x00, 0x21, 0x01, // global.get 0; local.set 1
+		0xE2, 0x00, // suspend 0 ($yield)
+		0x23, 0x00, 0x21, 0x01, // global.get 0; local.set 1
+		0x0B, // end
+	}
+	if !bytes.Equal(s.P, want) {
+		t.Errorf("got % x, want % x", s.P, want)
+	}
+}
+
+// newTestFunc returns a minimal Wasm function symbol ("runtime.notInitialized").
+// runtime.notInitialized is special-cased in assemble's switch on s.Name:
+// empty varDecls (zero locals), the assembly register map, and no local-SP
+// prologue, so tests can inspect raw instruction encodings.
+func newTestFunc() (*obj.Link, *obj.LSym) {
+	ctxt := obj.Linknew(&Linkwasm)
+	s := &obj.LSym{Name: "runtime.notInitialized"}
+	s.NewFuncInfo()
+	return ctxt, s
+}
+
+// assembleOne assembles a single instruction p and returns the encoded
+// instruction bytes (stripped of the 0x00 local count and trailing 0x0B end).
+func assembleOne(t *testing.T, p *obj.Prog) []byte {
+	t.Helper()
+	ctxt, s := newTestFunc()
+	ctxt.DiagFunc = t.Errorf
+	p.Ctxt = ctxt
+	s.Func().Text = p
+	assemble(ctxt, s, nil)
+	if len(s.P) < 2 || s.P[0] != 0x00 || s.P[len(s.P)-1] != 0x0B {
+		t.Fatalf("unexpected function framing: % x", s.P)
+	}
+	return s.P[1 : len(s.P)-1]
+}
diff --git a/src/cmd/link/internal/wasm/asm.go b/src/cmd/link/internal/wasm/asm.go
index 5da9955237..15a1e66d8a 100644
--- a/src/cmd/link/internal/wasm/asm.go
+++ b/src/cmd/link/internal/wasm/asm.go
@@ -319,13 +319,7 @@ func asmb(ctxt *ld.Link, ldr *loader.Loader) {
 // asmb writes the final WebAssembly module binary.
 // Spec: https://webassembly.github.io/spec/core/binary/modules.html
 func (st *wasm32State) asmb2(ctxt *ld.Link, ldr *loader.Loader) {
-	types := []*wasmFuncType{
-		// For normal Go functions, the single parameter is PC_B,
-		// the return value is
-		// 0 if the function returned normally or
-		// 1 if the stack needs to be unwound.
-		{Params: []byte{I32}, Results: []byte{I32}},
-	}
+	types := newTypes()

 	if buildcfg.GOWASM.StackSwitch {
 		initStackSwitchingTypes(&types)
@@ -496,11 +490,26 @@ func lookupType(sig *wasmFuncType, types *[]*wasmFuncType) uint32 {
 // contTableInitialSize is the initial capacity of the continuation table.
 const contTableInitialSize = 1024

+// newTypes returns the initial function type table, seeded with the Go
+// function signature (PC_B i32) -> (i32) at index 0.
+func newTypes() []*wasmFuncType {
+	return []*wasmFuncType{
+		// For normal Go functions, the single parameter is PC_B,
+		// the return value is
+		// 0 if the function returned normally or
+		// 1 if the stack needs to be unwound.
+		{Params: []byte{I32}, Results: []byte{I32}},
+	}
+}
+
 // initStackSwitchingTypes registers the fixed-index WasmFX continuation types
 // at the top of types so their indices remain constant across all Go programs.
 func initStackSwitchingTypes(types *[]*wasmFuncType) {
-	// Force () -> () function type to be at index 1.
+	// Force () -> () function type to be at index 1 (wasm.EmptyFuncTypeIndex).
 	emptyFuncType := lookupType(&wasmFuncType{Params: []byte{}, Results: []byte{}}, types)
+	if emptyFuncType != wasm.EmptyFuncTypeIndex {
+		panic("wasm: EmptyFuncTypeIndex is not at the expected index")
+	}

 	// Continuation type (cont $emptyFuncType) at index 2 (wasm.ContinuationTypeIndex).
 	if uint32(len(*types)) != wasm.ContinuationTypeIndex {
@@ -539,19 +548,25 @@ func writeTypeSec(ctxt *ld.Link, types []*wasmFuncType) {
 	writeUleb128(ctxt.Out, uint64(len(types)))

 	for _, t := range types {
-		if t.isCont {
-			ctxt.Out.WriteByte(0x5d)                // conttype
-			writeSleb128(ctxt.Out, int64(t.contOf)) // underlying functype index (s33)
-			continue
-		}
-		ctxt.Out.WriteByte(0x60) // functype
-		writeValTypes(ctxt.Out, t.Params)
-		writeValTypes(ctxt.Out, t.Results)
+		writeFuncType(ctxt.Out, t)
 	}

 	writeSecSize(ctxt, sizeOffset)
 }

+// writeFuncType writes a single type entry (functype or conttype) in the type
+// section.
+func writeFuncType(w io.ByteWriter, t *wasmFuncType) {
+	if t.isCont {
+		w.WriteByte(0x5d)                // conttype
+		writeSleb128(w, int64(t.contOf)) // underlying functype index (s33)
+		return
+	}
+	w.WriteByte(0x60) // functype
+	writeValTypes(w, t.Params)
+	writeValTypes(w, t.Results)
+}
+
 // writeContRefType writes the Wasm reference type (ref null $ContinuationTypeIndex).
 func writeContRefType(w io.ByteWriter) {
 	w.WriteByte(0x63)                           // ref null
diff --git a/src/cmd/link/internal/wasm/asm_test.go b/src/cmd/link/internal/wasm/asm_test.go
new file mode 100644
index 0000000000..aa95791917
--- /dev/null
+++ b/src/cmd/link/internal/wasm/asm_test.go
@@ -0,0 +1,70 @@
+// 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 wasm
+
+import (
+	"bytes"
+	"cmd/internal/obj/wasm"
+	"testing"
+)
+
+// TestInitStackSwitchingTypes verifies that newTypes and
+// initStackSwitchingTypes register the Go function signature (i32) -> (i32) at
+// index 0, the () -> () signature at wasm.EmptyFuncTypeIndex (1), and the
+// continuation type (cont 1) at wasm.ContinuationTypeIndex (2), encode their
+// type-section bytes, and preserve those indices across subsequent lookupType
+// calls.
+func TestInitStackSwitchingTypes(t *testing.T) {
+	types := newTypes()
+	initStackSwitchingTypes(&types)
+
+	if len(types) != 3 {
+		t.Fatalf("len(types) = %d, want 3", len(types))
+	}
+	if ft := types[0]; ft.isCont || !bytes.Equal(ft.Params, []byte{I32}) || !bytes.Equal(ft.Results, []byte{I32}) {
+		t.Errorf("types[0] = %+v, want func (i32) -> (i32)", ft)
+	}
+	if ft := types[wasm.EmptyFuncTypeIndex]; ft.isCont || len(ft.Params) != 0 || len(ft.Results) != 0 {
+		t.Errorf("types[%d] = %+v, want func () -> ()", wasm.EmptyFuncTypeIndex, ft)
+	}
+	if ct := types[wasm.ContinuationTypeIndex]; !ct.isCont || ct.contOf != wasm.EmptyFuncTypeIndex {
+		t.Errorf("types[%d] = %+v, want (cont %d)", wasm.ContinuationTypeIndex, ct, wasm.EmptyFuncTypeIndex)
+	}
+
+	wantBytes := [][]byte{
+		{0x60, 0x01, I32, 0x01, I32},
+		{0x60, 0x00, 0x00},
+		{0x5d, byte(wasm.EmptyFuncTypeIndex)},
+	}
+	var buf bytes.Buffer
+	for i, want := range wantBytes {
+		buf.Reset()
+		writeFuncType(&buf, types[i])
+		if got := buf.Bytes(); !bytes.Equal(got, want) {
+			t.Errorf("writeFuncType(types[%d]) = % x, want % x", i, got, want)
+		}
+	}
+
+	// Subsequent lookups of () -> () must reuse wasm.EmptyFuncTypeIndex without shifting later types.
+	if got := lookupType(&wasmFuncType{Params: []byte{}, Results: []byte{}}, &types); got != wasm.EmptyFuncTypeIndex {
+		t.Errorf("lookupType(() -> ()) = %d, want %d", got, wasm.EmptyFuncTypeIndex)
+	}
+
+	// Adding a new function type must append at index 3 without disturbing indices 0..2.
+	if got := lookupType(&wasmFuncType{Params: []byte{I64}, Results: []byte{I64}}, &types); got != 3 {
+		t.Errorf("lookupType((i64) -> (i64)) = %d, want 3", got)
+	}
+}
+
+// TestWriteValTypesContRef verifies that writeValTypes expands contRef to
+// (ref null $ContinuationTypeIndex) (0x63 <s33>).
+func TestWriteValTypesContRef(t *testing.T) {
+	var w bytes.Buffer
+	writeValTypes(&w, []byte{I64, contRef})
+	want := []byte{0x02, I64, 0x63, byte(wasm.ContinuationTypeIndex)}
+	if !bytes.Equal(w.Bytes(), want) {
+		t.Errorf("got % x, want % x", w.Bytes(), want)
+	}
+}