Commit 395913f525 for golang

commit 395913f525b171f2ceeedc9a47c4eccf32fd1e72
Author: Carlos Amedee <carlos@golang.org>
Date:   Wed Nov 18 15:32:00 2026 -0500

    runtime, cmd/internal/obj/wasm: run //go:wasmexport in a continuation

    Under GOWASM=stackswitch, a //go:wasmexport wrapper currently calls the
    Go function directly on the host's Wasm stack, so switching goroutines
    or parking inside it traps for lack of a suspend handler.

    Run exported functions in a continuation under wasm_host_loop instead,
    replacing wasm_pc_f_loop_export under GOWASM=stackswitch. The wrapper
    calls the new runtime helper wasm_export_call with the target PC; when
    the function returns normally to the active wrapper on the same g and
    stack offset, wasm_goentry ends the loop and returns control to the
    wrapper to load the result. Calls made from a host import while g is
    running use a pooled or new continuation, as for a js.FuncOf callback,
    and host calls into Go while g is g0 are fatal.

    Enforce three invariants for export calls:
    - Calls must return in LIFO order; an outer call returning while an
      inner one is active is fatal.
    - A goroutine cannot exit while running an active export call; a per-g
      counter checked in mcall makes both normal exit (goexit0) and
      coroutine exit (coroexit) fatal, matching gdestroy on other
      architectures, so the call cannot be stranded and its g cannot be
      reused while active.
    - An export call whose loop ends without returning to the wrapper
      undoes its export state and traps rather than returning an
      uninitialized result.
    Without stack switching, out-of-order returns and non-returning calls
    are not detected and the wrapper returns garbage.

    Re-enable syscall/js.TestWasmExport and add assembler, runtime, and
    host-engine tests (in a new cmd/internal/testwasm package) covering
    export calls on js and wasip1, continuation reuse across repeated calls
    from a host import, panic recovery, out-of-order returns, and goroutine
    exit (including coroutine exit). Register cmd/internal/testwasm in
    cmd/dist as a host test for js and wasip1 builders, so that its tests
    run with each builder's node or Wasmtime.

    Cost. A host loop calling a trivial //go:wasmexport function, compared
    with GOWASM unset (benchstat, n=10, runs interleaved; p <= 0.001):

                              GOWASM unset    stackswitch     delta
        Wasmtime 50.0.1        3.495n ± 1%    27.21n ± 1%   +678.5%
        Node.js 26.13 (V8)     10.31n ± 1%    119.2n ± 2%  +1056.5%

    Each call adds one resume and one suspend (wasm_export_call →
    wasm_host_loop → wasm_resume → wasm_goentry).

    Known limitations at this CL:
    - os.Exit after a panic recovered below a nested export call traps on
      hosts where go.exit returns (browsers); fixed by "runtime: throw
      $exit from exit under GOWASM=stackswitch".

    For #81963

    Cq-Include-Trybots: luci.golang.try:gotip-js-wasm-stackswitch,gotip-wasip1-wasm_wasmtime-stackswitch
    Change-Id: I8854dfb79c334cbb429bcca4ae847b9195be2cbf
    Reviewed-on: https://go-review.googlesource.com/c/go/+/865883
    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>
    Auto-Submit: Carlos Amedee <carlos@golang.org>

diff --git a/src/cmd/dist/test.go b/src/cmd/dist/test.go
index d1073de903..cf4aeb7732 100644
--- a/src/cmd/dist/test.go
+++ b/src/cmd/dist/test.go
@@ -1085,6 +1085,15 @@ func (t *tester) registerTests() {
 				runOnHost: true,
 			},
 		)
+		// Run and validate linked modules using the builder's Wasm
+		// engine (node for js, wasmtime for wasip1) when in $PATH.
+		t.registerTest("cmd/internal/testwasm",
+			&goTest{
+				variant:   "host",
+				pkg:       "cmd/internal/testwasm",
+				runOnHost: true,
+			},
+		)
 	}
 }

diff --git a/src/cmd/internal/obj/wasm/wasmobj.go b/src/cmd/internal/obj/wasm/wasmobj.go
index dcd5b5962a..93206e4318 100644
--- a/src/cmd/internal/obj/wasm/wasmobj.go
+++ b/src/cmd/internal/obj/wasm/wasmobj.go
@@ -208,6 +208,7 @@ var (
 	morestackNoCtxt       *obj.LSym
 	sigpanic              *obj.LSym
 	wasm_pc_f_loop_export *obj.LSym
+	wasmExportCall        *obj.LSym
 	runtimeNotInitialized *obj.LSym
 )

@@ -241,6 +242,9 @@ func instinit(ctxt *obj.Link) {
 	morestackNoCtxt = ctxt.Lookup("runtime.morestack_noctxt")
 	sigpanic = ctxt.LookupABI("runtime.sigpanic", obj.ABIInternal)
 	wasm_pc_f_loop_export = ctxt.Lookup("wasm_pc_f_loop_export")
+	// Looked up in every build, like wasm_pc_f_loop_export; only
+	// GOWASM=stackswitch builds refer to it.
+	wasmExportCall = ctxt.Lookup("wasm_export_call")
 	runtimeNotInitialized = ctxt.Lookup("runtime.notInitialized")
 }

@@ -1111,24 +1115,36 @@ func genWasmExportWrapper(ctxt *obj.Link, s *obj.LSym, appendp func(p *obj.Prog,
 	}
 	p = appendp(p, AI64Const, retAddr)
 	p = appendp(p, AI64Store, constAddr(0))
-	// Set PC_B parameter to function entry
-	p = appendp(p, AI32Const, constAddr(0))
-	p = appendp(p, ACall, obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: we.WrappedSym})
-	// Return value is on the top of the stack, indicating whether to unwind the Wasm stack.
-	// In the unwinding case, we call wasm_pc_f_loop_export to handle stack switch and rewinding,
-	// until a normal return (non-unwinding) back to this function.
-	p = appendp(p, AIf)
-	if ctxt.Arch.PtrSize == 4 {
-		// Stop at this exact logical continuation token.
-		p = appendp(p, AI32Const, retAddr)
+	if buildcfg.GOWASM.StackSwitch {
+		if ctxt.Arch.PtrSize == 4 {
+			ctxt.Diag("%s: GOWASM=stackswitch requires 64-bit PCs for //go:wasmexport", s.Name)
+		}
+		// The Go function may suspend to switch goroutines, so it cannot
+		// run on the host's Wasm stack. wasm_export_call runs it from its
+		// entry PC in a continuation under wasm_host_loop until it returns
+		// to this wrapper.
+		p = appendp(p, AI64Const, obj.Addr{Type: obj.TYPE_ADDR, Name: obj.NAME_EXTERN, Sym: we.WrappedSym})
+		p = appendp(p, ACall, obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: wasmExportCall})
 	} else {
-		p = appendp(p, AI64Const, retAddr)
-		p = appendp(p, AI64Const, constAddr(16))
-		p = appendp(p, AI64ShrU)
-		p = appendp(p, AI32WrapI64)
+		// Set PC_B parameter to function entry
+		p = appendp(p, AI32Const, constAddr(0))
+		p = appendp(p, ACall, obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: we.WrappedSym})
+		// Return value is on the top of the stack, indicating whether to unwind the Wasm stack.
+		// In the unwinding case, we call wasm_pc_f_loop_export to handle stack switch and rewinding,
+		// until a normal return (non-unwinding) back to this function.
+		p = appendp(p, AIf)
+		if ctxt.Arch.PtrSize == 4 {
+			// Stop at this exact logical continuation token.
+			p = appendp(p, AI32Const, retAddr)
+		} else {
+			p = appendp(p, AI64Const, retAddr)
+			p = appendp(p, AI64Const, constAddr(16))
+			p = appendp(p, AI64ShrU)
+			p = appendp(p, AI32WrapI64)
+		}
+		p = appendp(p, ACall, obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: wasm_pc_f_loop_export})
+		p = appendp(p, AEnd)
 	}
-	p = appendp(p, ACall, obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: wasm_pc_f_loop_export})
-	p = appendp(p, AEnd)

 	// Load result
 	if len(we.Results) > 1 {
@@ -1190,6 +1206,7 @@ var notUsePC_B = map[string]bool{
 	"wasm_export_getsp":       true,
 	"wasm_pc_f_loop":          true,
 	"wasm_pc_f_loop_export":   true,
+	"wasm_export_call":        true,
 	"gcWriteBarrier":          true,
 	"runtime.gcWriteBarrier1": true,
 	"runtime.gcWriteBarrier2": true,
@@ -1274,6 +1291,10 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 			varDecls[0].count++
 		}
 		useAssemblyRegMap()
+	case "wasm_export_call":
+		// R0 is the i64 pc parameter.
+		varDecls = []*varDecl{{count: 2, typ: i32}, {count: 1, typ: i64}} // R1, R2, R3
+		useAssemblyRegMap()
 	case "wasm_host_loop":
 		varDecls = []*varDecl{{count: 2, typ: i32}, {count: 1, typ: i64}} // R0, R1, R2
 		useAssemblyRegMap()
diff --git a/src/cmd/internal/obj/wasm/wasmobj_test.go b/src/cmd/internal/obj/wasm/wasmobj_test.go
index 3161f75c91..5baf7a73e3 100644
--- a/src/cmd/internal/obj/wasm/wasmobj_test.go
+++ b/src/cmd/internal/obj/wasm/wasmobj_test.go
@@ -480,3 +480,38 @@ func TestAssembleContRefLocal(t *testing.T) {
 		t.Errorf("got % x, want % x", s.P, want)
 	}
 }
+
+// TestExportWrapperStackSwitch checks that, under GOWASM=stackswitch, the
+// wrapper of a //go:wasmexport function calls wasm_export_call with the
+// wrapped function's PC rather than calling the function directly.
+func TestExportWrapperStackSwitch(t *testing.T) {
+	for _, on := range []bool{false, true} {
+		setStackSwitch(t, on)
+		ctxt := obj.Linknew(&Linkwasm)
+		ctxt.DiagFunc = t.Errorf
+		instinit(ctxt)
+		wrapped := ctxt.Lookup("test.f")
+		s := ctxt.Lookup("test.f.wrapper")
+		s.NewFuncInfo()
+		s.Func().WasmExport = &obj.WasmExport{WrappedSym: wrapped}
+		s.Func().Text = &obj.Prog{Ctxt: ctxt, As: obj.ATEXT, From: obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: s}, To: obj.Addr{Type: obj.TYPE_TEXTSIZE, Val: int32(0)}}
+		preprocess(ctxt, s, ctxt.NewProg)
+		var calls []string
+		var pcArg bool
+		for p := s.Func().Text; p != nil; p = p.Link {
+			if p.As == ACall && p.To.Sym != nil {
+				calls = append(calls, p.To.Sym.Name)
+			}
+			if p.As == AI64Const && p.From.Type == obj.TYPE_ADDR && p.From.Sym == wrapped && p.Link != nil && p.Link.As == ACall && p.Link.To.Sym == wasmExportCall {
+				pcArg = true
+			}
+		}
+		if on {
+			if !slices.Contains(calls, "wasm_export_call") || slices.Contains(calls, "test.f") || !pcArg {
+				t.Errorf("stackswitch: calls %q, want wasm_export_call with test.f's PC", calls)
+			}
+		} else if slices.Contains(calls, "wasm_export_call") || !slices.Contains(calls, "test.f") {
+			t.Errorf("default: calls %q, want test.f and no wasm_export_call", calls)
+		}
+	}
+}
diff --git a/src/cmd/internal/testwasm/doc.go b/src/cmd/internal/testwasm/doc.go
new file mode 100644
index 0000000000..d6fad0789d
--- /dev/null
+++ b/src/cmd/internal/testwasm/doc.go
@@ -0,0 +1,9 @@
+// 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 holds tests that link Go programs for js/wasm and
+// wasip1/wasm and run or validate the resulting modules with real Wasm
+// engines and tools (such as Node.js, Wasmtime, and wasm-tools) when they
+// are installed.
+package testwasm
diff --git a/src/cmd/internal/testwasm/target_test.go b/src/cmd/internal/testwasm/target_test.go
new file mode 100644
index 0000000000..1e68d09157
--- /dev/null
+++ b/src/cmd/internal/testwasm/target_test.go
@@ -0,0 +1,33 @@
+// 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 (
+	"flag"
+	"testing"
+)
+
+// target is set by cmd/dist when it runs this package on the host for a
+// js or wasip1 builder. targetGOOSes uses it to limit tests to that GOOS
+// and skip targets other than js/wasm and wasip1/wasm.
+var target = flag.String("target", "", "if set, the GOOS/GOARCH of the builder these tests run for")
+
+// targetGOOSes returns the GOOSes to link test modules for, or skips t
+// if -target is unsupported.
+func targetGOOSes(t *testing.T) []string {
+	switch *target {
+	case "":
+		if testing.Short() {
+			return []string{"wasip1"}
+		}
+		return []string{"js", "wasip1"}
+	case "js/wasm":
+		return []string{"js"}
+	case "wasip1/wasm":
+		return []string{"wasip1"}
+	}
+	t.Skipf("no Wasm module tests for -target=%s", *target)
+	return nil
+}
diff --git a/src/cmd/internal/testwasm/wasmexport_test.go b/src/cmd/internal/testwasm/wasmexport_test.go
new file mode 100644
index 0000000000..941de0296f
--- /dev/null
+++ b/src/cmd/internal/testwasm/wasmexport_test.go
@@ -0,0 +1,263 @@
+// 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"
+	"internal/testenv"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"slices"
+	"strings"
+	"testing"
+)
+
+const wasmExportSrc = `package main
+
+import "runtime"
+
+func main() {}
+
+//go:noinline
+func grow(n int) int {
+	var buf [256]byte
+	if n == 0 {
+		return int(buf[0])
+	}
+	return grow(n-1) + int(buf[1])
+}
+
+//go:wasmexport add
+func add(a int32, b int64) int64 {
+	ch := make(chan int64)
+	go func() { ch <- b }()
+	runtime.GC()
+	grow(1000)
+	return int64(a) + <-ch
+}
+
+//go:wasmexport recov
+func recov() (r int32) {
+	defer func() {
+		if recover() != nil {
+			r = 42
+		}
+	}()
+	panicky()
+	return 7
+}
+
+//go:noinline
+func panicky() { panic("panicky") }
+`
+
+// TestWasmExportStackSwitchWasmtime builds a wasip1 library with
+// GOWASM=stackswitch and calls //go:wasmexport functions from wasmtime, if
+// a version supporting stack switching is in $PATH. add switches
+// goroutines, runs the GC, and grows its stack, which it can do only in a
+// continuation (wasm_export_call). recov recovers a panic before returning
+// to the export wrapper.
+func TestWasmExportStackSwitchWasmtime(t *testing.T) {
+	testenv.MustHaveGoBuild(t)
+	if !slices.Contains(targetGOOSes(t), "wasip1") {
+		t.Skip("wasip1 not among the targets")
+	}
+	wasmtime, err := exec.LookPath("wasmtime")
+	if err != nil {
+		t.Skip("wasmtime not found in $PATH")
+	}
+	help, _ := testenv.Command(t, wasmtime, "run", "-W", "help").CombinedOutput()
+	for _, p := range []string{"stack-switching", "function-references", "gc"} {
+		if !bytes.Contains(help, []byte(" "+p+"[=y|n]")) {
+			t.Skipf("%s does not support -W %s", wasmtime, p)
+		}
+	}
+	dir := t.TempDir()
+	src := filepath.Join(dir, "main.go")
+	if err := os.WriteFile(src, []byte(wasmExportSrc), 0o666); err != nil {
+		t.Fatal(err)
+	}
+	lib := filepath.Join(dir, "lib.wasm")
+	cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-buildmode=c-shared", "-o", lib, src)
+	cmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm", "GOWASM=stackswitch")
+	if out, err := cmd.CombinedOutput(); err != nil {
+		t.Fatalf("go build: %v\n%s", err, out)
+	}
+	for _, tc := range []struct {
+		args []string
+		want string
+	}{
+		{[]string{"add", "1", "2"}, "3"},
+		{[]string{"recov"}, "42"},
+	} {
+		args := []string{"run",
+			"-W", "max-wasm-stack=8388608",
+			"-W", "stack-switching=y,function-references=y,gc=y",
+			"--invoke", tc.args[0], lib}
+		cmd = testenv.Command(t, wasmtime, append(args, tc.args[1:]...)...)
+		var stderr bytes.Buffer
+		cmd.Stderr = &stderr
+		out, err := cmd.Output()
+		if err != nil {
+			t.Fatalf("wasmtime: %v\nstdout: %s\nstderr: %s", err, out, stderr.Bytes())
+		}
+		if got := strings.TrimSpace(string(out)); got != tc.want {
+			t.Errorf("%v = %q, want %s\nstderr: %s", tc.args, got, tc.want, stderr.Bytes())
+		}
+	}
+}
+
+// wasmExportOrderSrc makes two //go:wasmexport calls that return out of
+// order. Goroutines g1 and g2 both start in worker, so they call the host
+// import, and the host calls testExport, at the same offset below their
+// g.stack.hi. g1's call (#1) blocks until g2's call (#2), nested on the
+// host's stack, releases it and blocks forever, so g1 returns from #1 while
+// #2 is active, which is fatal. _gotest.callExport is provided by
+// wasm_exec.js: it calls testExport0, then testExport.
+const wasmExportOrderSrc = `package main
+
+//go:wasmimport _gotest callExport
+func callExport(a int32, b int64) int64
+
+//go:wasmexport testExport0
+func testExport0() {}
+
+var started, release = make(chan bool), make(chan bool)
+
+//go:wasmexport testExport
+func testExport(a int32, b int64) int64 {
+	if a == 1 {
+		started <- true
+		<-release
+	} else {
+		release <- true
+		select {}
+	}
+	return b
+}
+
+//go:noinline
+func worker(a int32) {
+	println("returned", callExport(a, 0))
+}
+
+func main() {
+	go worker(1)
+	<-started
+	go worker(2)
+	select {}
+}
+`
+
+// TestWasmExportOutOfOrderReturn checks that, under GOWASM=stackswitch, an
+// outer //go:wasmexport call returning on another goroutine while an inner
+// one is active is fatal, even though the two calls have the same wrapper
+// SP offset: the goroutine's g is part of the call's identity.
+func TestWasmExportOutOfOrderReturn(t *testing.T) {
+	out := runJSStackSwitch(t, wasmExportOrderSrc)
+	if want := "fatal error: wasm: out-of-order //go:wasmexport return"; !bytes.Contains(out, []byte(want)) {
+		t.Errorf("output does not contain %q:\n%s", want, out)
+	}
+	if bytes.Contains(out, []byte("returned")) {
+		t.Errorf("an export call returned:\n%s", out)
+	}
+}
+
+// wasmExportGoexitSrc calls runtime.Goexit in a //go:wasmexport function
+// that the host calls from an import. Without the exit check, nothing would
+// be runnable, so on js beforeIdle would start a goroutine to pause, which
+// could reuse the exited goroutine's g.
+const wasmExportGoexitSrc = `package main
+
+import "runtime"
+
+//go:wasmimport _gotest callExport
+func callExport(a int32, b int64) int64
+
+//go:wasmexport testExport0
+func testExport0() {}
+
+//go:wasmexport testExport
+func testExport(a int32, b int64) int64 {
+	runtime.Goexit()
+	return b
+}
+
+func main() {
+	go func() {
+		println("returned", callExport(1, 2))
+	}()
+	select {}
+}
+`
+
+// wasmExportCoroGoexitSrc is wasmExportGoexitSrc with the export called
+// from a coroutine (iter.Pull), whose goroutine exits through coroexit
+// rather than goexit0.
+var wasmExportCoroGoexitSrc = strings.NewReplacer(
+	`import "runtime"`, `import ("iter"; "runtime")`,
+	`println("returned", callExport(1, 2))`,
+	`next, _ := iter.Pull(func(func(int) bool) { println("returned", callExport(1, 2)) }); next()`,
+).Replace(wasmExportGoexitSrc)
+
+// TestWasmExportGoexit checks that, under GOWASM=stackswitch, a goroutine
+// exiting while running a //go:wasmexport call is immediately fatal: the
+// call cannot return, and a new goroutine reusing the g must not be
+// mistaken for the original goroutine.
+func TestWasmExportGoexit(t *testing.T) {
+	for name, src := range map[string]string{"goexit": wasmExportGoexitSrc, "coroexit": wasmExportCoroGoexitSrc} {
+		t.Run(name, func(t *testing.T) {
+			out := runJSStackSwitch(t, src)
+			if want := "fatal error: wasm: goroutine exited during a //go:wasmexport call"; !bytes.Contains(out, []byte(want)) {
+				t.Errorf("output does not contain %q:\n%s", want, out)
+			}
+			if bytes.Contains(out, []byte("returned")) || bytes.Contains(out, []byte("RuntimeError")) {
+				t.Errorf("unexpected output:\n%s", out)
+			}
+		})
+	}
+}
+
+// runJSStackSwitch builds src for js/wasm with GOWASM=stackswitch, runs it
+// with lib/wasm/go_js_wasm_exec, and returns its output, which it expects
+// to report a failure. It skips t unless node supports stack switching.
+func runJSStackSwitch(t *testing.T, src string) []byte {
+	t.Helper()
+	testenv.MustHaveGoBuild(t)
+	if !slices.Contains(targetGOOSes(t), "js") {
+		t.Skip("js not among the targets")
+	}
+	node, err := exec.LookPath("node")
+	if err != nil {
+		t.Skip("node not found in $PATH")
+	}
+	// go_js_wasm_exec passes --experimental-wasm-wasmfx under
+	// GOWASM=stackswitch. Node.js versions before 26 implement an older
+	// encoding of the stack-switching proposal.
+	check := `process.exit(parseInt(process.versions.node) >= 26 ? 0 : 1)`
+	if exec.Command(node, "--experimental-wasm-wasmfx", "-e", check).Run() != nil {
+		t.Skipf("%s does not support stack switching", node)
+	}
+	dir := t.TempDir()
+	file := filepath.Join(dir, "main.go")
+	if err := os.WriteFile(file, []byte(src), 0o666); err != nil {
+		t.Fatal(err)
+	}
+	prog := filepath.Join(dir, "prog.wasm")
+	env := append(os.Environ(), "GOOS=js", "GOARCH=wasm", "GOWASM=stackswitch")
+	cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-o", prog, file)
+	cmd.Env = env
+	if out, err := cmd.CombinedOutput(); err != nil {
+		t.Fatalf("go build: %v\n%s", err, out)
+	}
+	cmd = testenv.Command(t, filepath.Join(testenv.GOROOT(t), "lib", "wasm", "go_js_wasm_exec"), prog)
+	cmd.Env = env
+	out, err := cmd.CombinedOutput()
+	if err == nil {
+		t.Fatalf("program succeeded, want failure\n%s", out)
+	}
+	return out
+}
diff --git a/src/cmd/link/internal/wasm/asm.go b/src/cmd/link/internal/wasm/asm.go
index bc5e7a6f24..2ff4e28c6d 100644
--- a/src/cmd/link/internal/wasm/asm.go
+++ b/src/cmd/link/internal/wasm/asm.go
@@ -187,6 +187,7 @@ var wasmFuncTypes = map[string]*wasmFuncType{
 	"memchr":                  {Params: []byte{I32, I32, I32}, Results: []byte{I32}},      // s, c, len -> index
 	"wasm_scheduler_loop":     {Params: []byte{}},                                         //
 	"wasm_resume":             {Params: []byte{I32}, Results: []byte{contRef}},            // slot -> cont
+	"wasm_export_call":        {Params: []byte{I64}},                                      // pc
 	"wasm_host_loop":          {Params: []byte{}},                                         //
 	"wasm_goentry":            {Params: []byte{}},                                         //
 }
diff --git a/src/runtime/sizeof_test.go b/src/runtime/sizeof_test.go
index d0583b7912..ff36bc78c0 100644
--- a/src/runtime/sizeof_test.go
+++ b/src/runtime/sizeof_test.go
@@ -20,9 +20,9 @@ func TestSizeof(t *testing.T) {
 	const _64bit = unsafe.Sizeof(uintptr(0)) == 8
 	const xreg = unsafe.Sizeof(runtime.XRegPerG{})         // Varies per architecture
 	const valgrind = unsafe.Sizeof(runtime.ValgrindPerG{}) // Non-zero only with the valgrind build tag
-	// Non-zero only with GOWASM=stackswitch, where g.wasmCont and the
-	// padding after it add 8 bytes.
-	const wasmCont = 2 * unsafe.Sizeof(runtime.WasmContPerG{})
+	// Non-zero only with GOWASM=stackswitch, where g.wasmCont and any
+	// padding after it add its size rounded up to 8 bytes.
+	const wasmCont = (unsafe.Sizeof(runtime.WasmContPerG{}) + 7) &^ 7
 	var tests = []struct {
 		val     any     // type as a value
 		_32bit  uintptr // size on 32bit platforms
diff --git a/src/runtime/stackswitch_js_wasm_test.go b/src/runtime/stackswitch_js_wasm_test.go
index f7c409e650..c819ddbfac 100644
--- a/src/runtime/stackswitch_js_wasm_test.go
+++ b/src/runtime/stackswitch_js_wasm_test.go
@@ -12,10 +12,87 @@ import (
 	"testing"
 )

+// wasmExportCallExport is provided by wasm_exec.js. It calls the
+// testExport0 and testExport exports below from the host, while the calling
+// goroutine is running.
+//
+//go:wasmimport _gotest callExport
+func wasmExportCallExport(a int32, b int64) int64
+
+// wasmExportMode selects what testExport does when the host calls it.
+var wasmExportMode string
+
+var wasmExportSink []byte
+
+//go:wasmexport testExport0
+func wasmExportTest0() {}
+
+//go:wasmexport testExport
+func wasmExportTest(a int32, b int64) int64 {
+	switch wasmExportMode {
+	case "alloc":
+		wasmExportSink = make([]byte, 1<<20)
+	case "growstack":
+		wasmExportGrow(1000)
+	case "goroutine":
+		ch := make(chan int64)
+		go func() { ch <- b }()
+		return int64(a) + <-ch
+	case "gc":
+		runtime.GC()
+	}
+	return int64(a) + b
+}
+
+//go:noinline
+func wasmExportGrow(n int) int {
+	var buf [256]byte
+	if n == 0 {
+		return int(buf[0])
+	}
+	return wasmExportGrow(n-1) + int(buf[1])
+}
+
+// TestWasmExportStackSwitch calls a //go:wasmexport function from a host
+// import under GOWASM=stackswitch. The export runs in a continuation under a
+// nested wasm_host_loop (wasm_export_call), so it may allocate, grow its
+// stack, run GC, and switch goroutines.
+func TestWasmExportStackSwitch(t *testing.T) {
+	for _, mode := range []string{"trivial", "alloc", "growstack", "goroutine", "gc"} {
+		t.Run(mode, func(t *testing.T) {
+			wasmExportMode = mode
+			defer func() { wasmExportMode = "" }()
+			if got, want := wasmExportCallExport(1, 2), int64(3); got != want {
+				t.Errorf("callExport(1, 2) = %d, want %d", got, want)
+			}
+		})
+	}
+}
+
 // wasmContInUse returns the number of continuations not in the pool, which
 // includes any left behind by host calls into Go.
 func wasmContInUse() int32 { return runtime.WasmContCreated() - runtime.WasmContPooled() }

+// TestWasmExportContinuations checks that //go:wasmexport calls made while
+// the calling goroutine runs reuse a pooled continuation instead of
+// leaving one behind each time.
+func TestWasmExportContinuations(t *testing.T) {
+	base := runtime.NumGoroutine()
+	ch := make(chan int)
+	wasmExportCallExport(1, 2) // create the pooled continuation
+	waitGoroutines(t, base)
+	before := wasmContInUse()
+	for i := range 200 {
+		wasmExportCallExport(1, 2)
+		go func() { ch <- i }() // switch goroutines, suspending this one
+		<-ch
+	}
+	waitGoroutines(t, base)
+	if d := wasmContInUse() - before; d > 0 {
+		t.Errorf("continuations in use grew by %d over 200 export calls, want 0", d)
+	}
+}
+
 // wasmCallJS calls f through JavaScript, so that f runs in a synchronous
 // callback on a new host level.
 func wasmCallJS(f func()) {
diff --git a/src/runtime/stackswitch_wasm.s b/src/runtime/stackswitch_wasm.s
index 99fb01283a..53ca97edcd 100644
--- a/src/runtime/stackswitch_wasm.s
+++ b/src/runtime/stackswitch_wasm.s
@@ -174,6 +174,8 @@ TEXT wasm_resume(SB), NOSPLIT, $0
 //
 // It calls the function at PC_F with CallIndirect $0 (type 0 is
 // wasm.GoFuncTypeIndex). If the function returns normally (0) to
+// the wrapper of the active //go:wasmexport call, the export call is done
+// (see wasm_export_call). If it returns normally to
 // runtime.goexit+PCQuantum, the goroutine is done: wasm_goentry calls
 // runtime.goexit at its entry (PC_B == 0), not at runtime.goexit+PCQuantum,
 // which is past goexit's leading NOP, mid-function. goexit ends the
@@ -188,8 +190,8 @@ TEXT wasm_resume(SB), NOSPLIT, $0
 // recovering frame resumes at its deferreturn call (PC_B != 0). Each
 // function entered mid-function returns normally to its caller's resume
 // point, which wasm_goentry calls in turn since the caller's Wasm frame is
-// gone. That is the only normal return allowed other than to goexit; any
-// other calls wasmBadReturn.
+// gone. That is the only normal return allowed other than to the active
+// //go:wasmexport wrapper or goexit; any other calls wasmBadReturn.
 TEXT wasm_goentry(SB), NOSPLIT, $0
 entry:
 	Loop
@@ -249,6 +251,48 @@ entry:
 					I64Load $0
 					Set R0

+					// If it returns to the wrapper of the active
+					// //go:wasmexport call, mark the call done and suspend
+					// with PAUSE set so wasm_host_loop returns to
+					// wasm_export_call (and then the wrapper). The next
+					// resume restarts at g.sched.pc.
+					Get R0
+					I64Const $16
+					I64ShrU
+					I32WrapI64 // PC_F
+					I32Const $runtime·wasmExportStop(SB)
+					I32Load $0
+					I32Eq
+					If
+						// Export calls must return in LIFO order: check that g
+						// and the wrapper's SP offset (g.stack.hi - (SP - 8))
+						// match the active call (see wasmExportStop).
+						I64Load (g_stack+stack_hi)(g)
+						I32WrapI64
+						Get SP
+						I32Const $8
+						I32Sub
+						I32Sub
+						I32Const $runtime·wasmExportSP(SB)
+						I32Load $0
+						I32Ne
+						Get g
+						I32Const $runtime·wasmExportG(SB)
+						I64Load $0
+						I64Ne
+						I32Or
+						If
+							CALLNORESUME runtime·wasmBadExportReturn(SB)
+						End
+						I32Const $runtime·wasmExportStop(SB)
+						I32Const $-1
+						I32Store $0
+						I32Const $1
+						Set PAUSE
+						Suspend $const_wasmYieldTag
+						Br entry
+					End
+
 					// If the goroutine's function returned to
 					// runtime.goexit+PCQuantum, the goroutine is done.
 					Get R0
@@ -270,6 +314,12 @@ entry:
 					I64Eqz
 					I32Or
 					If
+						// While g runs a //go:wasmexport call, a return
+						// to another wrapper is out of order.
+						I32Load (g_wasmCont+wasmContPerG_exports)(g)
+						If
+							CALLNORESUME runtime·wasmBadExportReturn(SB)
+						End
 						CALLNORESUME runtime·wasmBadReturn(SB)
 					End
 					Br loop
@@ -485,6 +535,27 @@ TEXT runtime·mcall(SB), NOSPLIT, $0-8
 		JMP runtime·badmcall(SB)
 	End

+	// A goroutine must not exit while running a //go:wasmexport call (see
+	// wasmContPerG.exports). It exits in mcall(goexit0) (runtime.Goexit,
+	// or a return to goexit) or, for a coroutine, in mcall(coroswitch_m)
+	// with g.coroexit set (coroexit); both end in gdestroy.
+	I32Load (g_wasmCont+wasmContPerG_exports)(g)
+	If
+		Get CTXT
+		I32WrapI64
+		I32Load $2 // fn's PC_F
+		I64Const $runtime·goexit0(SB)
+		I64Const $16
+		I64ShrU
+		I32WrapI64
+		I32Eq
+		I32Load8U g_coroexit(g)
+		I32Or
+		If
+			CALLNORESUME runtime·wasmBadExportExit(SB)
+		End
+	End
+
 	// R3 = the g this Wasm stack belongs to, R4 = its goroutine's goid.
 	MOVD g, R3
 	MOVD g_goid(g), R4
@@ -639,7 +710,10 @@ TEXT wasm_host_loop(SB), NOSPLIT, $0
 	// goroutine that reuses R2 after the callback's goroutine exits cannot
 	// end the level: a js callback ends only when the original goroutine
 	// returns from handleEvent, and while its event is pending,
-	// beforeIdle starts no goroutine that pauses.
+	// beforeIdle starts no goroutine that pauses. For an export call, the
+	// goroutine cannot exit while the call is active (see
+	// wasmContPerG.exports), so no new goroutine can reuse its g to end the
+	// level.
 	Get R2
 	Get g
 	I64Ne
@@ -661,3 +735,131 @@ TEXT wasm_host_loop(SB), NOSPLIT, $0
 	TableSet $const_wasmContTable
 	POOL_INC
 	Return
+
+// wasm_export_call runs the Go function at pc (R0) for the wrapper of a
+// //go:wasmexport function, generated by cmd/internal/obj/wasm. The wrapper
+// has stored the function's arguments and its own return address at SP, as
+// for a call.
+//
+// The Go function may switch goroutines (suspending the Wasm stack), so it
+// cannot run on the host's stack. It runs in a continuation via g's slot
+// under wasm_host_loop, as wasm_export_resume runs
+// runtime.handleEvent: if the host called in while g is running, g's slot
+// is null, and a pooled or new continuation runs it (see wasm_resume).
+// wasm_goentry ends the loop when the function returns to the
+// wrapper: it checks that the wrapper's PC_F, g and the wrapper's SP (as an
+// offset below g.stack.hi) match wasmExportStop, wasmExportG and
+// wasmExportSP, sets wasmExportStop to -1, and suspends with PAUSE set.
+// Nested export calls save and restore all three, and must return in LIFO
+// order. An export call that ends without returning to the wrapper (the
+// program exits, or, on js, the scheduler pauses because every goroutine is
+// blocked) traps: it has no result to return.
+//
+// Overwriting g.sched.pc is safe: g is running (the host called in during
+// one of its calls to the host) or parked by a PAUSE suspend in
+// wasm_goentry, which restarts at g.sched.pc anyway.
+TEXT wasm_export_call(SB), NOSPLIT, $0
+	// Calling into Go while g is g0 would clobber g0's sched.pc.
+	Get g
+	I64Load g_m(g)
+	I32WrapI64
+	I64Load $m_g0
+	I64Eq
+	If
+		CALLNORESUME runtime·wasmBadHostCall(SB)
+	End
+
+	// R1, R2, R3 = the previous wasmExportStop, wasmExportSP and
+	// wasmExportG.
+	I32Const $runtime·wasmExportStop(SB)
+	I32Load $0
+	Set R1
+	I32Const $runtime·wasmExportSP(SB)
+	I32Load $0
+	Set R2
+	I32Const $runtime·wasmExportG(SB)
+	I64Load $0
+	Set R3
+
+	// wasmExportStop = PC_F of the wrapper, from the return address at
+	// 0(SP); wasmExportSP = g.stack.hi - SP; wasmExportG = g.
+	I32Const $runtime·wasmExportStop(SB)
+	Get SP
+	I32Load $2
+	I32Store $0
+	I32Const $runtime·wasmExportSP(SB)
+	I64Load (g_stack+stack_hi)(g)
+	I32WrapI64
+	Get SP
+	I32Sub
+	I32Store $0
+	I32Const $runtime·wasmExportG(SB)
+	Get g
+	I64Store $0
+
+	// g.wasmCont.exports++ for the duration of the call.
+	Get g
+	I32WrapI64
+	I32Load (g_wasmCont+wasmContPerG_exports)(g)
+	I32Const $1
+	I32Add
+	I32Store $(g_wasmCont+wasmContPerG_exports)
+
+	MOVD R0, g_sched+gobuf_pc(g)
+	Call wasm_host_loop(SB)
+
+	// wasm_goentry sets wasmExportStop to -1 when the function returns.
+	// Otherwise the call ended without a result. The program may have
+	// exited, so trap rather than call throw.
+	I32Const $runtime·wasmExportStop(SB)
+	I32Load $0
+	I32Const $-1
+	I32Ne
+	If
+		// Undo the call's state first: if the host catches the trap,
+		// a late return to this wrapper must not match stale state.
+		// Decrement exports on the call's g (wasmExportG, which may not
+		// be g) and restore wasmExportStop, wasmExportSP and
+		// wasmExportG. R0 (pc) is free now.
+		I32Const $runtime·wasmExportG(SB)
+		I64Load $0
+		Set R0
+		Get R0
+		I32WrapI64
+		Get R0
+		I32WrapI64
+		I32Load $(g_wasmCont+wasmContPerG_exports)
+		I32Const $1
+		I32Sub
+		I32Store $(g_wasmCont+wasmContPerG_exports)
+		I32Const $runtime·wasmExportStop(SB)
+		Get R1
+		I32Store $0
+		I32Const $runtime·wasmExportSP(SB)
+		Get R2
+		I32Store $0
+		I32Const $runtime·wasmExportG(SB)
+		Get R3
+		I64Store $0
+		UNDEF
+	End
+
+	// The call is done, on g, which wasm_goentry checked:
+	// g.wasmCont.exports--.
+	Get g
+	I32WrapI64
+	I32Load (g_wasmCont+wasmContPerG_exports)(g)
+	I32Const $1
+	I32Sub
+	I32Store $(g_wasmCont+wasmContPerG_exports)
+
+	I32Const $runtime·wasmExportStop(SB)
+	Get R1
+	I32Store $0
+	I32Const $runtime·wasmExportSP(SB)
+	Get R2
+	I32Store $0
+	I32Const $runtime·wasmExportG(SB)
+	Get R3
+	I64Store $0
+	Return
diff --git a/src/runtime/stackswitch_wasmx.go b/src/runtime/stackswitch_wasmx.go
index 1b61db69ab..fa3aa467d4 100644
--- a/src/runtime/stackswitch_wasmx.go
+++ b/src/runtime/stackswitch_wasmx.go
@@ -66,6 +66,17 @@ type wasmContPerG struct {
 	// goroutine's first resume until it pools the slot on exit (see
 	// POOL_PUSH).
 	index int32
+
+	// exports is the number of active //go:wasmexport calls running on
+	// this g (see wasm_export_call). The goroutine must not exit while it
+	// is non-zero: the calls could not return, and wasm_goentry and
+	// wasm_host_loop identify a call by its g, which a new goroutine may
+	// reuse. mcall throws if the goroutine calls it to exit:
+	// mcall(goexit0), from runtime.Goexit, or mcall(coroswitch_m) from
+	// coroexit, for a coroutine. On other architectures, gdestroy, which
+	// both reach, throws for a goroutine that exits in a call from C into
+	// Go, which locks it to its thread (cgocallbackg).
+	exports int32
 }

 var (
@@ -180,10 +191,12 @@ func wasmContTableGrow(delta int32) int32

 // Host calls into Go.
 //
-// The host may call back into Go while Go runs a host import, such as a
-// js.FuncOf callback (wasm_export_resume) during syscall/js.valueCall. Each
-// such call runs a nested wasm_host_loop on a new host level, on top of the
-// native frames of the host and of the continuation that called the import.
+// The host may call back into Go while Go runs a //go:wasmimport function
+// (including gojs imports such as syscall/js.valueCall), via a js.FuncOf
+// callback (wasm_export_resume) or a //go:wasmexport function
+// (wasm_export_call). Each such call runs a nested wasm_host_loop on a new
+// host level, on top of the native frames of the host and of the
+// continuation that called the import.

 var (
 	// wasmHostDepth is the number of host calls into Go in progress.
@@ -222,12 +235,31 @@ func wasmHostGrow() {
 	wasmContFree[n] = slot
 }

+// wasmExportStop is the PC_F (function index) of the //go:wasmexport wrapper
+// whose call wasm_export_call is running, or -1 if none (or if it just
+// returned). wasmExportG is the goroutine the host called in on, and
+// wasmExportSP is its g.stack.hi minus the wrapper's SP at the call, which
+// stays the same if the stack moves. wasm_goentry ends the export call when
+// the exported function returns to that wrapper on that g at that SP.
+//
+// The SP offset alone does not identify the call: goroutines started the
+// same way can enter export calls at the same offset. Together, g and the
+// offset do: nested export calls on the same g have distinct offsets, a g
+// is never freed (allgs keeps every g reachable), and a goroutine cannot
+// exit while running an export call (see wasmContPerG.exports), so its g
+// cannot be reused while the call is active.
+var (
+	wasmExportStop int32 = -1
+	wasmExportSP   int32
+	wasmExportG    guintptr
+)
+
 // Called from stackswitch_wasm.s.

 // wasmBadReturn calls throw when a function returns normally to wasm_goentry
-// with a return address other than runtime.goexit+PCQuantum, unless a
-// recovered panic restarted the goroutine mid-function and the return
-// address is a resume point after a call.
+// with a return address other than the active //go:wasmexport wrapper or
+// runtime.goexit+PCQuantum, unless a recovered panic restarted the goroutine
+// mid-function and the return address is a resume point after a call.
 //
 //go:nosplit
 func wasmBadReturn() {
@@ -275,3 +307,22 @@ func wasmBadPool() {
 func wasmBadHostCall() {
 	throw("wasm: host called into Go while running on g0")
 }
+
+// wasmBadExportExit calls throw when a goroutine exits (runtime.Goexit, or a
+// coroutine's exit) while running a //go:wasmexport call (see
+// wasmContPerG.exports).
+//
+//go:nosplit
+func wasmBadExportExit() {
+	throw("wasm: goroutine exited during a //go:wasmexport call")
+}
+
+// wasmBadExportReturn calls throw when a //go:wasmexport function returns to
+// the wrapper of the active export call on another goroutine or at another
+// SP, or to another wrapper while its goroutine runs an export call: an
+// outer export call returned before an inner one.
+//
+//go:nosplit
+func wasmBadExportReturn() {
+	throw("wasm: out-of-order //go:wasmexport return")
+}
diff --git a/src/syscall/js/js_test.go b/src/syscall/js/js_test.go
index d9b378b6d6..46af1d9c22 100644
--- a/src/syscall/js/js_test.go
+++ b/src/syscall/js/js_test.go
@@ -88,13 +88,7 @@ func growStack(n int64) {
 	}
 }

-// skipWasmExport, if set, is the reason to skip TestWasmExport.
-var skipWasmExport string
-
 func TestWasmExport(t *testing.T) {
-	if skipWasmExport != "" {
-		t.Skip(skipWasmExport)
-	}
 	testExportCalled = false
 	a := int32(123)
 	b := int64(456)
diff --git a/src/syscall/js/stackswitch_wasm_test.go b/src/syscall/js/stackswitch_wasm_test.go
deleted file mode 100644
index 24866d2cdf..0000000000
--- a/src/syscall/js/stackswitch_wasm_test.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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.
-
-//go:build js && wasm && wasm.stackswitch
-
-package js_test
-
-func init() {
-	// TODO(#81963): remove once //go:wasmexport functions run in a
-	// continuation. Until then, a //go:wasmexport function that switches
-	// goroutines (as in testExport, or during garbage collection) traps,
-	// because its $yield suspend has no handler.
-	skipWasmExport = "//go:wasmexport functions can't switch goroutines under GOWASM=stackswitch yet"
-}