Commit 28e60c4c3a for golang
commit 28e60c4c3af1e1148d743104b6c4c2ee65b00331
Author: Carlos Amedee <carlos@golang.org>
Date: Wed Oct 28 17:00:19 2026 -0400
runtime: add wasm_scheduler_loop, wasm_resume, and wasm_goentry
Add the functions that drive goroutine continuations under
GOWASM=stackswitch. Nothing calls them yet; the next CL does.
Remove wasmContG0Slot and runtime.wasm_g0entry because g0 has no
continuation, and rename runtime.wasm_goentry to wasm_goentry in the
assembler and linker. Support (ref null $cont) locals in
cmd/internal/obj/wasm for wasm_resume.
For #81963
Cq-Include-Trybots: luci.golang.try:gotip-js-wasm-stackswitch,gotip-wasip1-wasm_wasmtime-stackswitch
Change-Id: I7b202aff188c49575bdda5c810fa20a71b90bed2
Reviewed-on: https://go-review.googlesource.com/c/go/+/858782
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>
Reviewed-by: David Chase <drchase@google.com>
diff --git a/src/cmd/internal/obj/wasm/wasmobj.go b/src/cmd/internal/obj/wasm/wasmobj.go
index cd614de186..1ca5f13800 100644
--- a/src/cmd/internal/obj/wasm/wasmobj.go
+++ b/src/cmd/internal/obj/wasm/wasmobj.go
@@ -1191,8 +1191,7 @@ var notUsePC_B = map[string]bool{
"memeqbody": true,
"memcmp": true,
"memchr": true,
- "runtime.wasm_goentry": true,
- "runtime.wasm_g0entry": true,
+ "wasm_goentry": true,
"wasm_scheduler_loop": true,
"wasm_resume": true,
}
@@ -1233,16 +1232,25 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
case "_rt0_wasm_js", "_rt0_wasm_wasip1", "_rt0_wasm_wasip1_lib",
"_rt0_wasm32_wasip1", "_rt0_wasm32_wasip1_lib",
"wasm_export_run", "wasm_export_resume", "wasm_export_getsp",
- "runtime.wasmDiv", "runtime.wasmTruncS", "runtime.wasmTruncU", "memeqbody",
- "runtime.wasm_goentry", "runtime.wasm_g0entry", "wasm_scheduler_loop", "wasm_resume":
+ "runtime.wasmDiv", "runtime.wasmTruncS", "runtime.wasmTruncU", "memeqbody":
varDecls = []*varDecl{}
useAssemblyRegMap()
+ case "wasm_scheduler_loop":
+ varDecls = []*varDecl{{count: 1, typ: i32}} // R0
+ useAssemblyRegMap()
case "wasm_pc_f_loop":
varDecls = []*varDecl{}
if ctxt.Arch.PtrSize == 4 {
varDecls = []*varDecl{{count: 1, typ: i32}}
}
useAssemblyRegMap()
+ case "wasm_goentry":
+ varDecls = []*varDecl{{count: 2, typ: i64}} // R0, R1
+ useAssemblyRegMap()
+ case "wasm_resume":
+ // R0 is the i32 slot parameter.
+ varDecls = []*varDecl{{count: 1, typ: contRef}} // R1
+ useAssemblyRegMap()
case "wasm_pc_f_loop_export":
varDecls = []*varDecl{{count: 2, typ: i32}}
if ctxt.Arch.PtrSize == 4 {
@@ -1320,6 +1328,9 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
for _, decl := range varDecls {
writeUleb128(w, decl.count)
w.WriteByte(byte(decl.typ))
+ if decl.typ == contRef {
+ w.WriteByte(ContinuationTypeIndex)
+ }
}
if hasLocalSP {
@@ -1599,7 +1610,7 @@ func assemble(ctxt *obj.Link, s *obj.LSym, newprog obj.ProgAlloc) {
w.WriteByte(0x01) // size of handler table
w.WriteByte(0x00) // "on" clause with handler, not switch
writeUleb128(w, YieldTagIndex) // tag $yield ->
- w.WriteByte(0x00) // label 0 (hard-coded for the implementation in asm_wasm.s)
+ w.WriteByte(0x00) // label 0 (hard-coded for wasm_resume in stackswitch_wasm.s)
case AMemoryCopy:
w.WriteByte(0x00)
@@ -1683,6 +1694,11 @@ const (
f32 valueType = 0x7D
f64 valueType = 0x7C
v128 valueType = 0x7b
+
+ // contRef is (ref null $cont), a nullable reference to the continuation
+ // type, for locals under GOWASM=stackswitch. It is encoded as 0x63
+ // followed by ContinuationTypeIndex.
+ contRef valueType = 0x63
)
func regType(reg int16) valueType {
diff --git a/src/cmd/internal/obj/wasm/wasmobj_test.go b/src/cmd/internal/obj/wasm/wasmobj_test.go
index 19b095f16b..8e20ccff6a 100644
--- a/src/cmd/internal/obj/wasm/wasmobj_test.go
+++ b/src/cmd/internal/obj/wasm/wasmobj_test.go
@@ -453,3 +453,28 @@ func assembleOneDiag(t *testing.T, p *obj.Prog) []string {
}
return diags
}
+
+// TestAssembleContRefLocal checks that wasm_resume declares its R1 local as
+// (ref null $cont) and that Get and Set R1 use it.
+func TestAssembleContRefLocal(t *testing.T) {
+ setStackSwitch(t, true)
+ ctxt := obj.Linknew(&Linkwasm)
+ ctxt.DiagFunc = t.Errorf
+ s := &obj.LSym{Name: "wasm_resume"}
+ s.NewFuncInfo()
+ get := &obj.Prog{Ctxt: ctxt, As: AGet, From: regAddr(REG_R1)}
+ get.Link = &obj.Prog{Ctxt: ctxt, As: ASet, To: regAddr(REG_R1)}
+ get.Link.Link = &obj.Prog{Ctxt: ctxt, As: AGet, From: regAddr(REG_R1)}
+ s.Func().Text = get
+ assemble(ctxt, s, nil)
+
+ want := []byte{
+ 0x01, 0x01, 0x63, ContinuationTypeIndex, // 1 local declaration: 1 x (ref null $cont)
+ 0x20, 0x01, // local.get 1
+ 0x22, 0x01, // local.tee 1 (Set R1; Get R1)
+ 0x0B, // end
+ }
+ if !bytes.Equal(s.P, want) {
+ t.Errorf("got % x, want % x", s.P, want)
+ }
+}
diff --git a/src/cmd/link/internal/wasm/asm.go b/src/cmd/link/internal/wasm/asm.go
index 0a2fca563e..d925dad31e 100644
--- a/src/cmd/link/internal/wasm/asm.go
+++ b/src/cmd/link/internal/wasm/asm.go
@@ -187,8 +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
- "runtime.wasm_goentry": {Params: []byte{}}, //
- "runtime.wasm_g0entry": {Params: []byte{}}, //
+ "wasm_goentry": {Params: []byte{}}, //
}
// pcBase is the base value for PCs on GOARCH=wasm.
diff --git a/src/runtime/stackswitch_wasm.s b/src/runtime/stackswitch_wasm.s
index a8dae6b499..c4b760f156 100644
--- a/src/runtime/stackswitch_wasm.s
+++ b/src/runtime/stackswitch_wasm.s
@@ -27,3 +27,231 @@ TEXT ·wasmContTableGrow(SB), NOSPLIT, $0-12
TableGrow $const_wasmContTable // SP, previous size or -1
I32Store ret+8(FP)
RET
+
+// wasm_scheduler_loop resumes goroutine continuations in a loop until
+// 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.
+TEXT wasm_scheduler_loop(SB), NOSPLIT, $0
+loop:
+ Loop
+ // Push the slot twice (Tee and Get): g may change before
+ // wasm_resume returns, so the first copy stays on the stack for
+ // TableSet.
+ I32Load (g_wasmCont+wasmContPerG_index)(g)
+ Tee R0
+ Get R0
+ Call wasm_resume(SB)
+ TableSet $const_wasmContTable
+
+ Get PAUSE
+ I32Eqz
+ BrIf loop
+ End
+
+ I32Const $0
+ Set PAUSE
+
+ Return
+
+// wasm_resume resumes the continuation in wasmContTable slot R0 (signature
+// (slot i32) -> (ref null $cont)) and returns the continuation that
+// suspends on $yield, which the caller stores back into the slot. If the
+// slot is null, the goroutine has no continuation yet: wasm_resume creates
+// one that starts at wasm_goentry (ContNew). Otherwise it clears the slot:
+// resuming consumes the continuation, so the slot must not keep the
+// reference. Either way, a slot is null while its goroutine runs.
+//
+// Resume transfers control to wasm_goentry (for a new continuation) or to
+// where the continuation last suspended. When that code suspends on $yield,
+// control returns here and Resume's (on $yield 0) handler branches to
+// label 0 (the function's body as a block), jumping to the end of
+// wasm_resume and returning the suspended continuation.
+TEXT wasm_resume(SB), NOSPLIT, $0
+ // R1 (a ref null $cont local) = the continuation in slot R0.
+ Get R0
+ TableGet $const_wasmContTable
+ Set R1
+ Get R1
+ RefIsNull
+ If
+ RefFunc wasm_goentry(SB)
+ ContNew
+ Set R1
+ Else
+ Get R0
+ RefNull
+ TableSet $const_wasmContTable
+ End
+
+ Get R1
+ Resume
+
+ // Continuations never return normally; they always suspend.
+ UNDEF
+
+// wasm_goentry is the root function of every goroutine continuation
+// (signature () -> ()). It never returns: a continuation is never finished.
+//
+// That goes against what Wasm stack switching expects: a continuation should
+// eventually return, and an engine may not free one that stays suspended,
+// even after the last reference to it is dropped. (Wasmtime 50 frees no
+// continuation stacks at all; V8 collects an unreferenced suspended
+// continuation.) Instead of finishing a dead goroutine's continuation, the
+// runtime reuses it for a later goroutine, so the number of continuations is
+// bounded without help from the engine. TODO(#81963): finish continuations
+// once goroutine exit no longer unwinds by returning 1, for example by
+// throwing out of gogo or with resume_throw.
+//
+// A Go PC holds the function index PC_F in bits 16..47 and the block index
+// PC_B in the low 16 bits. On entry, and each time it restarts at entry,
+// wasm_goentry expects:
+// - g set to the goroutine that owns this continuation (not g0),
+// - SP set to the stack pointer at which g.sched.pc runs (for a new
+// goroutine, runtime.goexit+PCQuantum is at 0(SP)),
+// - CTXT set to the closure context for g.sched.pc, and
+// - g.sched.pc != 0 with PC_B == 0 (a function entry).
+// It calls wasmBadG if g is g0 and wasmBadEntry if g.sched.pc is not a
+// function entry.
+//
+// It calls the function at PC_F with CallIndirect $0 (type 0 is
+// wasm.GoFuncTypeIndex). If the function returns normally (0) 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
+// 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.
+//
+// If the function returns non-zero (an unwind), or after runtime.goexit
+// returns, wasm_goentry suspends on $yield if PAUSE != 0. Then it restarts
+// at g.sched.pc: at its entry for a goroutine that reuses this continuation
+// or resumes from the host, or mid-function for a recovered panic, whose
+// 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.
+TEXT wasm_goentry(SB), NOSPLIT, $0
+entry:
+ Loop
+ // g0 has no continuation.
+ Get g
+ I64Load g_m(g)
+ I32WrapI64
+ I64Load $m_g0
+ I64Eq
+ If
+ CALLNORESUME runtime·wasmBadG(SB)
+ End
+
+ // R0 = the PC to call; R1 = 1 once a recovered panic restarted
+ // the goroutine mid-function.
+ MOVD g_sched+gobuf_pc(g), R0
+ MOVD $0, R1
+
+ // A goroutine starts (or resumes from the host) only at a function
+ // entry: its PC_B is 0, and its PC is non-zero.
+ Get R0
+ I64Eqz
+ Get R0
+ I64Const $0xffff
+ I64And
+ I64Eqz
+ I32Eqz
+ I32Or
+ If
+ CALLNORESUME runtime·wasmBadEntry(SB)
+ End
+
+ done:
+ Block
+ loop:
+ Loop
+ // Push PC_B and PC_F of R0.
+ Get R0
+ I32WrapI64
+ I32Const $0xffff
+ I32And // PC_B
+
+ Get R0
+ I64Const $16
+ I64ShrU
+ I32WrapI64 // PC_F
+
+ // Type 0 is wasm.GoFuncTypeIndex, (PC_B i32) -> (i32).
+ CallIndirect $0
+ I32Eqz
+ If
+ // A normal return. RET added 8 to SP: the return
+ // PC is at -8(SP).
+ Get SP
+ I32Const $8
+ I32Sub
+ I64Load $0
+ Set R0
+
+ // If the goroutine's function returned to
+ // runtime.goexit+PCQuantum, the goroutine is done.
+ Get R0
+ I64Const $runtime·goexit(SB)
+ I64Const $1 // PCQuantum
+ I64Add
+ I64Eq
+ BrIf done
+
+ // TODO(#81963): drop this case once a recovered
+ // panic unwinds to the recovering frame. After a
+ // restart mid-function, continue at the caller's
+ // post-CALL resume point.
+ Get R1
+ I64Eqz
+ Get R0
+ I64Const $0xffff
+ I64And
+ I64Eqz
+ I32Or
+ If
+ CALLNORESUME runtime·wasmBadReturn(SB)
+ End
+ Br loop
+ End
+
+ // Callees set PAUSE only when they unwind.
+ Get PAUSE
+ If
+ // Yield to wasm_scheduler_loop when pausing to the
+ // host.
+ Suspend $const_wasmYieldTag
+ Br entry
+ End
+
+ // An unwind inside the continuation: another goroutine
+ // reuses it (PC_B == 0), or a recovered panic resumes
+ // mid-function (PC_B != 0).
+ MOVD g_sched+gobuf_pc(g), R0
+ Get R0
+ I64Const $0xffff
+ I64And
+ I64Eqz
+ BrIf entry
+ MOVD $1, R1
+ Br loop
+ End
+ End
+
+ // The goroutine is done. goexit returns 1 when this continuation
+ // is reused for a new goroutine (which starts at entry) or when
+ // the scheduler pauses to the host.
+ I32Const $0 // entry PC_B
+ Call runtime·goexit(SB)
+ Drop
+ Get PAUSE
+ If
+ Suspend $const_wasmYieldTag
+ End
+ Br entry
+ End
+ UNDEF
diff --git a/src/runtime/stackswitch_wasmx.go b/src/runtime/stackswitch_wasmx.go
index d89a711cfd..c5e91bf71f 100644
--- a/src/runtime/stackswitch_wasmx.go
+++ b/src/runtime/stackswitch_wasmx.go
@@ -11,14 +11,15 @@
// cannot be stored in linear memory, so they cannot live in a g. Instead the
// 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 the g has not started yet.
+// 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.
//
-// m0.g0 is allocated statically rather than by malg, so its index is the zero
-// value: slot wasmContG0Slot belongs to it. malg gives every other g a slot
-// of its own, starting at 1, which the g and its continuation keep for their
-// existence, including while the g is on a free list. Like the g's
-// themselves, slots are never freed, so the table grows to the number of g's
-// ever allocated.
+// 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
+// malg, so its index is 0 and slot 0 is unused. malg gives every other g a
+// slot of its own, starting at 1, which the g keeps permanently, including
+// while the g is on a free list. Like the g's themselves, slots are never
+// freed, so the table grows to the number of g's ever allocated.
//
// WebAssembly runs a single thread, so the allocation state below needs no locking.
@@ -31,15 +32,17 @@ const (
// contTableInitialSize. Assembly refers to it as $const_wasmContTable.
wasmContTable = 1
- // wasmContG0Slot is m0.g0's slot in the continuation table.
- // Assembly refers to it as $const_wasmContG0Slot.
- wasmContG0Slot = 0
+ // wasmYieldTag is the Wasm tag index for $yield, which Suspend and
+ // Resume use to switch continuations. It must match
+ // cmd/internal/obj/wasm.YieldTagIndex. Assembly refers to it as
+ // $const_wasmYieldTag.
+ wasmYieldTag = 0
)
// wasmContPerG is the per-g state of WebAssembly stack switching.
type wasmContPerG struct {
- // index is the g's slot in the continuation table: wasmContG0Slot for
- // m0.g0, and a slot of its own, assigned by malg, for every other g.
+ // index is the g's slot in the continuation table, assigned by malg.
+ // It is 0, an unused slot, for m0.g0.
index int32
}
@@ -82,3 +85,31 @@ func wasmContTableSize() int32
// wasmContTableGrow appends delta null slots to the continuation table and
// returns its previous size, or -1 if it cannot grow (table.grow).
func wasmContTableGrow(delta int32) int32
+
+// 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.
+//
+//go:nosplit
+func wasmBadReturn() {
+ throw("wasm: unexpected return to wasm_goentry")
+}
+
+// wasmBadEntry calls throw when wasm_goentry sees a zero g.sched.pc or a
+// non-zero PC_B (not a function entry).
+//
+//go:nosplit
+func wasmBadEntry() {
+ throw("wasm: goroutine start PC is not a function entry")
+}
+
+// wasmBadG calls throw when wasm_goentry runs with g == g.m.g0, which has no
+// continuation.
+//
+//go:nosplit
+func wasmBadG() {
+ throw("wasm: wasm_goentry running on g0")
+}