Commit f195425bc5 for golang

commit f195425bc563271661aebe20f95a1f88a31fb30b
Author: Carlos Amedee <carlos@golang.org>
Date:   Wed Nov 18 15:24:50 2026 -0500

    runtime, cmd/internal/obj/wasm: switch goroutines with Wasm continuations

    Under GOWASM=stackswitch, implement runtime.mcall and runtime.morestack
    in stackswitch_wasm.s, place the js and wasip1 entry points (calling
    wasm_scheduler_loop) in new stackswitch_js_wasm.s and
    stackswitch_wasip1_wasm.s files, and wrap the prologue's stack check in
    a loop in cmd/internal/obj/wasm so morestack can return directly instead
    of unwinding. Putting the stackswitch entry points in separate files and
    guarding the default functions without shifting lines keeps builds
    without GOWASM=stackswitch byte-identical. On js, wasm_export_resume
    runs runtime.handleEvent via wasm_scheduler_loop and throws if g is g0.

    Every goroutine switch goes through g0 on g0's Go stack, but g0 needs no
    Wasm continuation: its code runs on the Wasm stack of the goroutine that
    switched to it. A handoff between goroutines is therefore one suspend
    and one resume, while systemstack and stack growth without preemption
    need no continuation switch.

    This CL keeps the existing i32 unwind result rather than switching to
    exceptions: gogo returns 1 to unwind g0's frames back to mcall or
    morestack, and non-g0 frames return 1 to unwind abandoned frames when a
    new goroutine reuses a dead g's continuation (avoiding exceptions on
    goroutine exit, runtime.Goexit, and iter.Pull's stop), to unwind a
    recovered panic to wasm_goentry, or to pause or exit to the host via
    PAUSE. If functions later become () -> (), all of these unwind paths
    will need another mechanism (such as exceptions), and panic recovery
    will need a replacement for resume points.

    Pass --wasm-stack-switching-stack-size=8192 in go_js_wasm_exec so V8's
    continuation stacks match the 8 MB main stack (Wasmtime's
    -W max-wasm-stack, already 8 MB in go_wasip1_wasm_exec, sizes
    continuation stacks too).

    Cost. Time per operation compared with GOWASM unset, on the builders
    (benchstat, n=10, runs interleaved; every delta has p <= 0.001 except
    where a p is given). BlockAtDepth is a benchmark not in this CL: two
    goroutines each recurse N frames, then hand off over an unbuffered
    channel. Without stack switching, a switch unwinds and rewinds the
    Wasm stack, so its cost grows with N.

                            GOWASM unset    stackswitch     delta
        Wasmtime 50.0.1
        ChanSync             385.4n ± 7%    428.5n ± 3%    +11.2%
        ChanProdCons0        427.8n ± 2%    482.8n ± 3%    +12.9%
        CreateGoroutines     529.9n ± 2%    550.2n ± 2%     +3.8%
        StackGrowth          1.384µ ± 1%    1.579µ ± 1%    +14.1%
        BlockAtDepth/N=0     1.150µ ± 4%    1.189µ ± 4%     +3.4% (p=0.005)
        BlockAtDepth/N=16    1.277µ ± 4%    1.071µ ± 4%    -16.2%
        BlockAtDepth/N=128   3.943µ ± 4%    2.022µ ± 2%    -48.7%
        Node.js 26.13 (V8)
        ChanSync             425.6n ± 2%    632.2n ± 3%    +48.5%
        ChanProdCons0        434.9n ± 3%    652.4n ± 4%    +50.0%
        CreateGoroutines     455.1n ± 2%    675.5n ± 3%    +48.4%
        StackGrowth          1.373µ ± 9%    1.307µ ± 11%    -4.8% (p=0.023)
        BlockAtDepth/N=0     924.4n ± 2%    1.319µ ± 2%    +42.7%
        BlockAtDepth/N=16    1.280µ ± 3%    1.464µ ± 2%    +14.4%
        BlockAtDepth/N=128   3.626µ ± 6%    2.669µ ± 2%    -26.4%

    Engine limits. With the same engine flags, a goroutine gets about half
    the default port's stack depth. In a goroutine recursing through a
    small function, on Wasmtime with 8 MB, 250,000 frames worked and
    300,000 trapped with "call stack exhausted", where the default port
    handles 500,000; with -W max-wasm-stack=16777216, 500,000 worked. On V8
    with 8192 KB, 125,000 frames worked and 150,000 raised RangeError,
    where the default port handles 250,000. Each continuation also holds an
    engine stack. On the builders, Wasmtime ran 32,000 goroutines blocked
    at once and trapped with ENOMEM at 35,000 (vm.max_map_count is 65530);
    V8 ran 30,000 and aborted the process at 35,000 ("StackSegment
    Allocation failed - process out of memory"). The runtime cannot detect
    either beforehand.

    Known limitations until later CLs:
    - Every g that runs gets its own continuation, so starting more than
      about 30,000 goroutines at once fails as above, even if each exits
      right away (BenchmarkCreateGoroutinesSingle fails in every run on
      both engines). "runtime: pool dead goroutines' continuations under
      GOWASM=stackswitch" fixes this; until then, skip
      internal/sync.TestConcurrentCache.
    - A //go:wasmexport function that switches goroutines (including for a
      garbage collection) traps (Wasmtime reports "unhandled tag") until
      "runtime, cmd/internal/obj/wasm: run //go:wasmexport in a
      continuation"; until then, skip syscall/js.TestWasmExport.
    - On js, a synchronous host callback that returns while g still runs
      leaves its continuation in g's slot, which g's next suspend drops, so
      callbacks separated by suspends (or nested callbacks) create new
      continuations until "runtime: reuse one continuation per level of host
      callback".

    For #81963

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

diff --git a/lib/wasm/go_js_wasm_exec b/lib/wasm/go_js_wasm_exec
index 9855b4c436..6a86d88daf 100755
--- a/lib/wasm/go_js_wasm_exec
+++ b/lib/wasm/go_js_wasm_exec
@@ -16,6 +16,10 @@ DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
 # stack size limits.
 NODE_ARGS="--stack-size=8192"
 if [[ ",$GOWASM," == *",stackswitch,"* ]]; then
-	NODE_ARGS="$NODE_ARGS --experimental-wasm-wasmfx"
+	# Goroutines run on stack-switching stacks, which V8 sizes
+	# separately, with the same default of 984K.
+	# The size is fixed: on Node 26, --experimental-wasm-growable-stacks
+	# gave the same stack depth and memory use.
+	NODE_ARGS="$NODE_ARGS --experimental-wasm-wasmfx --wasm-stack-switching-stack-size=8192"
 fi
 exec node $NODE_ARGS "$DIR/wasm_exec_node.js" "$@"
diff --git a/src/cmd/internal/obj/wasm/wasmobj.go b/src/cmd/internal/obj/wasm/wasmobj.go
index 1ca5f13800..8f0de6a1ae 100644
--- a/src/cmd/internal/obj/wasm/wasmobj.go
+++ b/src/cmd/internal/obj/wasm/wasmobj.go
@@ -450,6 +450,15 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
 	if needMoreStack {
 		p := pMorestack

+		// With GOWASM=stackswitch, morestack returns to the
+		// prologue, which loops to check again, as on other
+		// architectures (CALL morestack; JMP start).
+		var loop *obj.Prog
+		if buildcfg.GOWASM.StackSwitch {
+			p = appendp(p, ALoop)
+			loop = p
+		}
+
 		if framesize <= abi.StackSmall {
 			// small stack: SP <= stackguard
 			// Get SP
@@ -486,19 +495,26 @@ func preprocess(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {

 		p = appendp(p, AIf)
 		// This CALL does *not* have a resume point after it
-		// (we already inserted all of the resume points). As
-		// a result, morestack will resume at the *previous*
-		// resume point (typically, the beginning of the
-		// function) and perform the morestack check again.
-		// This is why we don't need an explicit loop like
-		// other architectures.
+		// (we already inserted all of the resume points).
+		// Without GOWASM=stackswitch, morestack resumes at
+		// the *previous* resume point (typically, the
+		// beginning of the function) and performs the
+		// morestack check again, so we don't need an explicit
+		// loop like other architectures.
 		p = appendp(p, obj.ACALL, constAddr(0))
 		if s.Func().Text.From.Sym.NeedCtxt() {
 			p.To = obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: morestack}
 		} else {
 			p.To = obj.Addr{Type: obj.TYPE_MEM, Name: obj.NAME_EXTERN, Sym: morestackNoCtxt}
 		}
+		if loop != nil {
+			p = appendp(p, ABr)
+			p.To = obj.Addr{Type: obj.TYPE_BRANCH, Val: loop}
+		}
 		p = appendp(p, AEnd)
+		if loop != nil {
+			p = appendp(p, AEnd)
+		}
 	}

 	resumeIdx := func(p *obj.Prog) uint64 {
diff --git a/src/internal/sync/hashtriemap_test.go b/src/internal/sync/hashtriemap_test.go
index e2b5046ed6..9d41f16929 100644
--- a/src/internal/sync/hashtriemap_test.go
+++ b/src/internal/sync/hashtriemap_test.go
@@ -926,6 +926,9 @@ func init() {
 	}
 }

+// skipConcurrentCache, if set, is the reason to skip TestConcurrentCache.
+var skipConcurrentCache string
+
 // TestConcurrentCache tests HashTrieMap in a scenario where it is used as
 // the basis of a memory-efficient concurrent cache. We're specifically
 // looking to make sure that CompareAndSwap and CompareAndDelete are
@@ -934,6 +937,9 @@ func init() {
 //
 // This test is a regression test for issue #70970.
 func TestConcurrentCache(t *testing.T) {
+	if skipConcurrentCache != "" {
+		t.Skip(skipConcurrentCache)
+	}
 	t.Parallel()
 	type dummy [32]byte

diff --git a/src/internal/sync/stackswitch_wasm_test.go b/src/internal/sync/stackswitch_wasm_test.go
new file mode 100644
index 0000000000..f2e38fd07a
--- /dev/null
+++ b/src/internal/sync/stackswitch_wasm_test.go
@@ -0,0 +1,14 @@
+// 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 wasm.stackswitch
+
+package sync_test
+
+func init() {
+	// TODO(#81963): remove once dead goroutines' continuations are pooled
+	// across g's. Until then, each g gets its own continuation, and this
+	// test's 100,000 goroutines exhaust engine memory.
+	skipConcurrentCache = "continuations are not pooled across g's under GOWASM=stackswitch yet"
+}
diff --git a/src/runtime/asm_wasm.s b/src/runtime/asm_wasm.s
index 0fe9173397..cfd7c1fc0f 100644
--- a/src/runtime/asm_wasm.s
+++ b/src/runtime/asm_wasm.s
@@ -53,7 +53,7 @@ TEXT runtime·gogo(SB), NOSPLIT, $0-8

 	I32Const $1
 	Return
-
+#ifndef GOWASM_stackswitch // see stackswitch_wasm.s
 // func mcall(fn func(*g))
 // Switch to m->g0's stack, call fn(g).
 // Fn must never return. It should gogo(&g->sched)
@@ -103,7 +103,7 @@ TEXT runtime·mcall(SB), NOSPLIT, $0-8
 	Set SP

 	JMP runtime·badmcall2(SB)
-
+#endif
 // func systemstack(fn func())
 TEXT runtime·systemstack(SB), NOSPLIT, $0-8
 	// R0 = fn
@@ -217,7 +217,7 @@ TEXT runtime·switchToCrashStack0(SB), NOSPLIT, $0-8
 	// should never return
 	CALL	runtime·abort(SB)
 	UNDEF
-
+#ifndef GOWASM_stackswitch // see stackswitch_wasm.s
 // Called during function prolog when more stack is needed.
 //
 // The traceback routines see morestack on a g0 as being
@@ -266,7 +266,7 @@ TEXT runtime·morestack(SB), NOSPLIT, $0-0
 	MOVD g_sched+gobuf_sp(R2), SP
 	CALL runtime·newstack(SB)
 	UNDEF // crash if newstack returns
-
+#endif
 // morestack but not preserving ctxt.
 TEXT runtime·morestack_noctxt(SB),NOSPLIT,$0
 	MOVD $0, CTXT
diff --git a/src/runtime/rt0_js_wasm.s b/src/runtime/rt0_js_wasm.s
index cffd825c5b..f58a2ab59f 100644
--- a/src/runtime/rt0_js_wasm.s
+++ b/src/runtime/rt0_js_wasm.s
@@ -13,7 +13,7 @@ TEXT _rt0_wasm_js(SB),NOSPLIT,$0
 	Drop
 	I64Const $wasm_export_getsp(SB)
 	Drop
-
+#ifndef GOWASM_stackswitch // see stackswitch_js_wasm.s
 // wasm_export_run gets called from JavaScript. It initializes the Go runtime and executes Go code until it needs
 // to wait for an event. It does NOT follow the Go ABI. It has two WebAssembly parameters:
 // R0: argc (i32)
@@ -47,7 +47,7 @@ TEXT wasm_export_resume(SB),NOSPLIT,$0
 	Call wasm_pc_f_loop(SB)

 	Return
-
+#endif
 // wasm_export_getsp gets called from JavaScript to retrieve the SP.
 TEXT wasm_export_getsp(SB),NOSPLIT,$0
 	Get SP
diff --git a/src/runtime/rt0_wasip1_wasm.s b/src/runtime/rt0_wasip1_wasm.s
index a60566fe06..98ec03290a 100644
--- a/src/runtime/rt0_wasip1_wasm.s
+++ b/src/runtime/rt0_wasip1_wasm.s
@@ -4,7 +4,7 @@

 #include "go_asm.h"
 #include "textflag.h"
-
+#ifndef GOWASM_stackswitch // see stackswitch_wasip1_wasm.s
 TEXT _rt0_wasm_wasip1(SB),NOSPLIT,$0
 	MOVD $runtime·wasmStack+(m0Stack__size-16)(SB), SP

@@ -14,7 +14,7 @@ TEXT _rt0_wasm_wasip1(SB),NOSPLIT,$0
 	Call wasm_pc_f_loop(SB)

 	Return
-
+#endif
 TEXT _rt0_wasm_wasip1_lib(SB),NOSPLIT,$0
 	Call _rt0_wasm_wasip1(SB)
 	Return
diff --git a/src/runtime/stackswitch_js_wasm.s b/src/runtime/stackswitch_js_wasm.s
new file mode 100644
index 0000000000..91a99a917b
--- /dev/null
+++ b/src/runtime/stackswitch_js_wasm.s
@@ -0,0 +1,61 @@
+// 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 wasm.stackswitch
+
+#include "go_asm.h"
+#include "textflag.h"
+
+// The js entry points under GOWASM=stackswitch.
+// rt0_js_wasm.s has the versions for builds without GOWASM=stackswitch.
+
+// wasm_export_run gets called from JavaScript. It initializes the Go runtime and executes Go code until it needs
+// to wait for an event. It does NOT follow the Go ABI. It has two WebAssembly parameters:
+// R0: argc (i32)
+// R1: argv (i32)
+TEXT wasm_export_run(SB),NOSPLIT,$0
+	MOVD $runtime·wasmStack+(m0Stack__size-16)(SB), SP
+
+	Get SP
+	Get R0 // argc
+	I64ExtendI32U
+	I64Store $0
+
+	Get SP
+	Get R1 // argv
+	I64ExtendI32U
+	I64Store $8
+
+	I32Const $0 // entry PC_B
+	Call runtime·rt0_go(SB)
+	Drop
+	Call wasm_scheduler_loop(SB)
+	Return
+
+// wasm_export_resume gets called from JavaScript. It resumes the execution of Go code until it needs to wait for
+// an event.
+//
+// It runs handleEvent on g, from g's slot (see wasm_resume). If g paused,
+// its continuation is parked in wasm_goentry, which restarts at
+// g.sched.pc. If JavaScript calls back synchronously while g runs, g's
+// slot is initially null, so the host callback runs in a new continuation
+// that stays in g's slot when it pauses (reused by further callbacks until
+// g's next suspend replaces it).
+// Overwriting g.sched.pc is safe in both cases: nothing still needs the PC
+// it held. (It would not be safe for a goroutine parked in mcall or
+// morestack: RESUME_AFTER_G0 would take the change for a recovered panic.)
+TEXT wasm_export_resume(SB),NOSPLIT,$0
+	// g0 has no continuation; a host callback would clobber g0.sched.pc.
+	Get g
+	I64Load g_m(g)
+	I32WrapI64
+	I64Load $m_g0
+	I64Eq
+	If
+		CALLNORESUME runtime·wasmBadHostCall(SB)
+	End
+
+	MOVD $runtime·handleEvent(SB), g_sched+gobuf_pc(g)
+	Call wasm_scheduler_loop(SB)
+	Return
diff --git a/src/runtime/stackswitch_wasip1_wasm.s b/src/runtime/stackswitch_wasip1_wasm.s
new file mode 100644
index 0000000000..fbe5a0d7a6
--- /dev/null
+++ b/src/runtime/stackswitch_wasip1_wasm.s
@@ -0,0 +1,19 @@
+// 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 wasm.stackswitch
+
+#include "go_asm.h"
+#include "textflag.h"
+
+// _rt0_wasm_wasip1 under GOWASM=stackswitch. rt0_wasip1_wasm.s has the
+// version for builds without GOWASM=stackswitch, and _rt0_wasm_wasip1_lib.
+TEXT _rt0_wasm_wasip1(SB),NOSPLIT,$0
+	MOVD $runtime·wasmStack+(m0Stack__size-16)(SB), SP
+
+	I32Const $0 // entry PC_B
+	Call runtime·rt0_go(SB)
+	Drop
+	Call wasm_scheduler_loop(SB)
+	Return
diff --git a/src/runtime/stackswitch_wasm.s b/src/runtime/stackswitch_wasm.s
index c4b760f156..b814512839 100644
--- a/src/runtime/stackswitch_wasm.s
+++ b/src/runtime/stackswitch_wasm.s
@@ -32,8 +32,11 @@ TEXT ·wasmContTableGrow(SB), NOSPLIT, $0-12
 // PAUSE != 0 (checked after each resume), then clears PAUSE and returns
 // (signature () -> ()). Callers enter with global g set to the non-g0
 // goroutine to run next; g0 has no continuation (see stackswitch_wasmx.go).
-// Each $yield stores the yielded continuation back into the slot of the
-// goroutine just resumed, then resumes the goroutine now in g if PAUSE == 0.
+// Because g0 runs on the switching goroutine's Wasm stack, a handoff
+// between goroutines (g1 -> g0 -> g2) is one $yield suspend and one resume.
+// On each $yield, the yielded continuation is stored back into the slot of
+// the goroutine just resumed; if PAUSE == 0, the loop resumes the goroutine
+// now in g.
 TEXT wasm_scheduler_loop(SB), NOSPLIT, $0
 loop:
 	Loop
@@ -123,7 +126,7 @@ TEXT wasm_resume(SB), NOSPLIT, $0
 // which is past goexit's leading NOP, mid-function. goexit ends the
 // goroutine as on other architectures, through goexit1 and mcall(goexit0);
 // it unwinds back here (returning 1) when the continuation is reused or
-// the scheduler pauses.
+// the scheduler pauses (see RESUME_AFTER_G0).
 //
 // If the function returns non-zero (an unwind), or after runtime.goexit
 // returns, wasm_goentry suspends on $yield if PAUSE != 0. Then it restarts
@@ -255,3 +258,184 @@ entry:
 		Br entry
 	End
 	UNDEF
+
+// RESUME_AFTER_G0 finishes a switch to g0 whose code unwound back here (via
+// gogo or, on js, runtime.exit). owner is the g that this Wasm stack belongs
+// to; pc and goid are owner.sched.pc and owner.goid saved before switching.
+//
+// If PAUSE is set (runtime.exit on js), RESUME_AFTER_G0 returns 1 to keep
+// unwinding to wasm_goentry, which yields to wasm_scheduler_loop. Otherwise,
+// if gogo switched to another goroutine, it suspends this continuation,
+// which wasm_scheduler_loop stores in owner's slot and resumes when owner
+// runs again.
+//
+// A goroutine dies here in mcall(goexit0) (from runtime.goexit or
+// runtime.Goexit) or mcall(coroswitch_m) (coroutine exit): as on other
+// architectures, its frames are abandoned, not unwound. When a new goroutine
+// reuses owner, it resumes this continuation with a new goid, so
+// RESUME_AFTER_G0 returns 1 to unwind the dead frames to wasm_goentry, which
+// starts the new goroutine at g.sched.pc. Nothing re-enters the dead frames.
+//
+// If g.sched.pc changed (a recovered panic), RESUME_AFTER_G0 also returns 1
+// to unwind to wasm_goentry, which restarts at g.sched.pc. Otherwise it
+// falls through and the caller continues where owner switched.
+//
+// owner is a *g held in a Wasm local across the call on g0, where the
+// garbage collector, which scans only linear memory, can't see it. That is
+// safe because a g is never freed: allgs keeps every g reachable.
+#define RESUME_AFTER_G0(owner, pc, goid) \
+	Get PAUSE; \
+	If; \
+		I32Const $1; \
+		Return; \
+	End; \
+	Get g; \
+	Get owner; \
+	I64Ne; \
+	If; \
+		Suspend $const_wasmYieldTag; \
+	End; \
+	Get pc; \
+	I64Load g_sched+gobuf_pc(g); \
+	I64Ne; \
+	Get goid; \
+	I64Load g_goid(g); \
+	I64Ne; \
+	I32Or; \
+	If; \
+		I32Const $1; \
+		Return; \
+	End
+
+// func mcall(fn func(*g))
+// Switch to m.g0's stack, call fn(g).
+// Fn must never return. It should gogo(&g.sched)
+// to keep running g.
+//
+// fn runs on g0's Go stack but on this goroutine's Wasm stack; see
+// RESUME_AFTER_G0.
+TEXT runtime·mcall(SB), NOSPLIT, $0-8
+	MOVD fn+0(FP), CTXT
+	// R2 = m.g0
+	MOVD g_m(g), R1
+	MOVD m_g0(R1), R2
+
+	// Save the caller's PC and SP in g.sched, keeping caller's PC in R0.
+	MOVD 0(SP), R0
+	MOVD R0, g_sched+gobuf_pc(g)        // caller's PC
+	MOVD $fn+0(FP), g_sched+gobuf_sp(g) // caller's SP
+
+	// Calling mcall from g0 is a fatal runtime error.
+	Get g
+	Get R2
+	I64Eq
+	If
+		JMP runtime·badmcall(SB)
+	End
+
+	// R3 = the g this Wasm stack belongs to, R4 = its goroutine's goid.
+	MOVD g, R3
+	MOVD g_goid(g), R4
+
+	// Switch SP to g0's stack and push a synthetic mstart return address
+	// plus the gp argument for fn(gp).
+	I64Load (g_sched+gobuf_sp)(R2)
+	I64Const $16
+	I64Sub
+	I32WrapI64
+	Set SP
+	NOP	SP	// tell vet SP changed - stop checking offsets
+	MOVD $runtime·mstart(SB), 0(SP)
+	MOVD g, 8(SP)
+	MOVD R2, g
+
+	// Call fn. It returns 1 once gogo unwinds (or PAUSE is set).
+	I32Const $0 // entry PC_B
+	Get CTXT
+	I32WrapI64
+	I32Load $2 // PC_F
+	CallIndirect $0
+	I32Eqz
+	If
+		CALLNORESUME runtime·badmcall2(SB)
+		CALLNORESUME runtime·abort(SB)
+	End
+
+	RESUME_AFTER_G0(R3, R0, R4)
+	I32Const $0
+	Return
+
+// gogo, systemstack and morestack_noctxt are shared with the default port
+// in asm_wasm.s. gogo returns 1 to unwind g0's frames back to mcall or
+// morestack (see RESUME_AFTER_G0). systemstack needs no change: fn never
+// switches goroutines, so it runs on g0's Go stack but on this goroutine's
+// Wasm stack.
+
+// morestack is called from function f's prologue when more stack space is
+// required.
+//
+// newstack runs on g0's Go stack but on this goroutine's Wasm stack; see
+// RESUME_AFTER_G0. Unless RESUME_AFTER_G0 unwinds, morestack returns 0 to
+// f's prologue, which loops to recheck the stack bound (for example, if
+// newstack handled a preemption request without growing the stack), as on
+// other architectures.
+TEXT runtime·morestack(SB), NOSPLIT, $0-0
+	// R1 = g.m, R2 = m.g0
+	MOVD g_m(g), R1
+	MOVD m_g0(R1), R2
+
+	// Save f's context in g.sched, keeping f's PC in R0.
+	NOP	SP	// tell vet SP changed - stop checking offsets
+	MOVD 0(SP), R0
+	MOVD R0, g_sched+gobuf_pc(g)
+	MOVD $8(SP), g_sched+gobuf_sp(g) // f's SP
+	MOVD CTXT, g_sched+gobuf_ctxt(g)
+
+	// Cannot grow scheduler stack (m.g0).
+	Get g
+	Get R2
+	I64Eq
+	If
+		CALLNORESUME runtime·badmorestackg0(SB)
+		CALLNORESUME runtime·abort(SB)
+	End
+
+	// Cannot grow signal stack (m.gsignal).
+	Get g
+	I64Load m_gsignal(R1)
+	I64Eq
+	If
+		CALLNORESUME runtime·badmorestackgsignal(SB)
+		CALLNORESUME runtime·abort(SB)
+	End
+
+	// Record f's caller in m.morebuf.
+	MOVD 8(SP), m_morebuf+gobuf_pc(R1)
+	MOVD $16(SP), m_morebuf+gobuf_sp(R1) // f's caller's SP
+	MOVD g, m_morebuf+gobuf_g(R1)
+
+	// R3 = the g this Wasm stack belongs to, R4 = its goroutine's goid.
+	MOVD g, R3
+	MOVD g_goid(g), R4
+
+	// Switch SP to g0's stack and push a synthetic morestack return address.
+	I64Load (g_sched+gobuf_sp)(R2)
+	I64Const $8
+	I64Sub
+	I32WrapI64
+	Set SP
+	MOVD $runtime·morestack(SB), 0(SP)
+	MOVD R2, g
+
+	// Call newstack. It returns 1 once gogo unwinds (or PAUSE is set).
+	I32Const $0 // entry PC_B
+	Call runtime·newstack(SB)
+	I32Eqz
+	If
+		CALLNORESUME runtime·abort(SB) // newstack must not return
+	End
+
+	RESUME_AFTER_G0(R3, R0, R4)
+
+	I32Const $0
+	Return
diff --git a/src/runtime/stackswitch_wasm_test.go b/src/runtime/stackswitch_wasm_test.go
new file mode 100644
index 0000000000..92cd395fb4
--- /dev/null
+++ b/src/runtime/stackswitch_wasm_test.go
@@ -0,0 +1,188 @@
+// 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 wasm.stackswitch
+
+package runtime_test
+
+import (
+	"bytes"
+	itrace "internal/trace"
+	"io"
+	"iter"
+	"runtime"
+	"runtime/trace"
+	"sync"
+	"testing"
+	"time"
+)
+
+// TestWasmContReuseAfterExitAndPanic checks that a recycled g and its
+// continuation work across normal return, runtime.Goexit, and panic/recover.
+func TestWasmContReuseAfterExitAndPanic(t *testing.T) {
+	done := make(chan int32, 1)
+	for i := range 200 {
+		go func(i int) {
+			defer func() {
+				if r := recover(); r != nil {
+					done <- runtime.WasmContSlot()
+				}
+			}()
+			switch i % 3 {
+			case 0:
+				done <- runtime.WasmContSlot()
+			case 1:
+				defer func() {
+					done <- runtime.WasmContSlot()
+				}()
+				runtime.Goexit()
+			case 2:
+				panic("unwind")
+			}
+		}(i)
+		if slot := <-done; slot <= 0 {
+			t.Fatalf("iteration %d: invalid slot %d", i, slot)
+		}
+	}
+}
+
+// useStackKB uses about n KB of stack, so that the goroutine's stack grows
+// beyond its starting size.
+//
+//go:noinline
+func useStackKB(n int) int {
+	var buf [1024]byte
+	if n == 0 {
+		return int(buf[0])
+	}
+	return useStackKB(n-1) + int(buf[n%len(buf)])
+}
+
+// TestWasmGoexitReuse checks that g's exiting by return, runtime.Goexit
+// (including a deferred panic recovered during Goexit), or coroutine stop
+// (iter.Pull) are reused without growing the continuation table.
+func TestWasmGoexitReuse(t *testing.T) {
+	seq := func(yield func(int) bool) {
+		for i := 0; yield(i); i++ {
+		}
+	}
+	done := make(chan int32, 1)
+	round := func() {
+		for i := range 4 {
+			go func() {
+				switch i {
+				case 0:
+				case 1:
+					defer func() { recover() }()
+					defer func() { panic("in Goexit") }()
+					runtime.Goexit()
+				case 2:
+					runtime.Goexit()
+				case 3:
+					next, stop := iter.Pull(iter.Seq[int](seq))
+					next()
+					stop()
+				}
+			}()
+			go func() { done <- runtime.WasmContSlot() }()
+			if slot := <-done; slot <= 0 {
+				t.Fatalf("invalid slot %d", slot)
+			}
+		}
+	}
+	for range 100 {
+		round()
+	}
+	size := runtime.WasmContTableSize()
+	for range 1000 {
+		round()
+	}
+	if got := runtime.WasmContTableSize(); got != size {
+		t.Errorf("table grew from %d to %d slots while goroutines were reused", size, got)
+	}
+}
+
+// waitGoroutines yields until at most n goroutines exist, failing t if
+// they don't exit within a minute.
+func waitGoroutines(t *testing.T, n int) {
+	t.Helper()
+	deadline := time.Now().Add(time.Minute)
+	for runtime.NumGoroutine() > n {
+		if time.Now().After(deadline) {
+			t.Fatalf("%d goroutines still running, want at most %d", runtime.NumGoroutine(), n)
+		}
+		runtime.Gosched()
+	}
+}
+
+// TestWasmStackGrowth checks that goroutines can grow their stacks many
+// times over, across goroutine switches and garbage collections, which may
+// shrink the stacks.
+func TestWasmStackGrowth(t *testing.T) {
+	var wg sync.WaitGroup
+	for i := range 20 {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			for range 10 {
+				useStackKB(16 * (i%4 + 1))
+				runtime.Gosched()
+			}
+		}()
+	}
+	for range 10 {
+		runtime.GC()
+		runtime.Gosched()
+	}
+	wg.Wait()
+}
+
+// TestWasmTraceGoEnd checks that goroutines that exit by returning are traced
+// as ending: they exit through runtime.goexit and goexit1, as on other
+// architectures, so the trace stays valid.
+func TestWasmTraceGoEnd(t *testing.T) {
+	var buf bytes.Buffer
+	if err := trace.Start(&buf); err != nil {
+		t.Fatal(err)
+	}
+	const n = 10
+	base := runtime.NumGoroutine()
+	done := make(chan bool)
+	for range n {
+		go func() { done <- true }()
+	}
+	for range n {
+		<-done
+	}
+	waitGoroutines(t, base)
+	trace.Stop()
+
+	r, err := itrace.NewReader(&buf)
+	if err != nil {
+		t.Fatal(err)
+	}
+	ended := 0
+	for {
+		ev, err := r.ReadEvent()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			t.Fatalf("invalid trace: %v", err)
+		}
+		if ev.Kind() != itrace.EventStateTransition {
+			continue
+		}
+		st := ev.StateTransition()
+		if st.Resource.Kind != itrace.ResourceGoroutine {
+			continue
+		}
+		if from, to := st.Goroutine(); from != itrace.GoNotExist && to == itrace.GoNotExist {
+			ended++
+		}
+	}
+	if ended < n {
+		t.Errorf("%d goroutines traced as ending, want at least %d", ended, n)
+	}
+}
diff --git a/src/runtime/stackswitch_wasmx.go b/src/runtime/stackswitch_wasmx.go
index c5e91bf71f..4d4f0a927c 100644
--- a/src/runtime/stackswitch_wasmx.go
+++ b/src/runtime/stackswitch_wasmx.go
@@ -12,7 +12,14 @@
 // linker declares a continuation table, wasm table wasmContTable, and every
 // g owns one slot of it, recorded in g.wasmCont.index. A slot holds the g's
 // suspended continuation, or null if it has none: the g has not started yet,
-// or wasm_resume has taken the continuation out to resume it.
+// or wasm_resume has taken the continuation out to resume it. (On js, a
+// synchronous callback leaves its continuation in the slot of the g that
+// called into JavaScript; see wasm_export_resume.)
+//
+// When a goroutine exits, its frames are abandoned and its continuation
+// stays suspended in its g's slot. The next goroutine to run on that g
+// resumes it and unwinds the dead frames to wasm_goentry, which starts the
+// new goroutine on the same Wasm stack.
 //
 // m0.g0 has no continuation: its code runs on the Wasm stack of the
 // goroutine that switched to it. m0.g0 is allocated statically rather than by
@@ -113,3 +120,12 @@ func wasmBadEntry() {
 func wasmBadG() {
 	throw("wasm: wasm_goentry running on g0")
 }
+
+// wasmBadHostCall calls throw when a host callback enters Go while g is g0,
+// which has no continuation (for example, from a host import called on the
+// system stack).
+//
+//go:nosplit
+func wasmBadHostCall() {
+	throw("wasm: host called into Go while running on g0")
+}
diff --git a/src/syscall/js/js_test.go b/src/syscall/js/js_test.go
index 46af1d9c22..d9b378b6d6 100644
--- a/src/syscall/js/js_test.go
+++ b/src/syscall/js/js_test.go
@@ -88,7 +88,13 @@ 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
new file mode 100644
index 0000000000..24866d2cdf
--- /dev/null
+++ b/src/syscall/js/stackswitch_wasm_test.go
@@ -0,0 +1,15 @@
+// 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"
+}