1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// SPDX-License-Identifier: Apache-2.0
//! x86-64 context switch primitives — ported from `runtime/asm_amd64.s` and
//! `runtime/preempt_amd64.s`.
//!
//! Public entry points:
//! - [`gogo`] — restore a saved `Gobuf` and resume a goroutine.
//! - [`mcall`] — save current G, switch to g0's stack, call a fn.
//! - [`async_preempt_trampoline`] — save all GPRs + XMMs, call `async_preempt2`,
//! restore, ret to interrupted PC. *(v0.2.0 — Step 4)*
//! - [`systemstack`] — run a closure on g0's stack.
//!
//! ## Design vs Go's approach
//!
//! Go uses the `FS` segment register (Linux) or `GS` (macOS) as a TLS pointer
//! to the current G, accessed from assembly via `get_tls`. We use a Rust
//! `thread_local!` (`CURRENT_G` in `g.rs`) updated from the Rust wrapper,
//! keeping the naked asm free of OS-specific TLS segment tricks.
//!
//! ## Calling convention
//!
//! **System V AMD64 (Linux, macOS)** — arguments in `rdi`, `rsi`, `rdx`, `rcx`, `r8`, `r9`.
//! Caller-saved: `rax`, `rcx`, `rdx`, `rsi`, `rdi`, `r8`–`r11`.
//! Callee-saved: `rbx`, `rbp`, `r12`–`r15`.
//! Stack: 16-byte aligned before a `call`. No shadow space.
//!
//! **Microsoft x64 (Windows)** — arguments in `rcx`, `rdx`, `r8`, `r9`.
//! Caller-saved: `rax`, `rcx`, `rdx`, `r8`–`r11`.
//! Callee-saved: `rbx`, `rbp`, `rdi`, `rsi`, `r12`–`r15`, `xmm6`–`xmm15`.
//! Stack: 16-byte aligned before a `call`. **Caller must allocate 32 bytes
//! of shadow space below RSP before any `call`** — the callee may write its
//! first four register arguments there. Without it a callee that spills its
//! first argument (`rcx`) would write to `[rsp+8]`, which equals `g0.stack.hi+8`
//! — just past the end of the VirtualAlloc region → `STATUS_ACCESS_VIOLATION`.
//!
//! ## Gobuf field offsets (verified by compile-time assertions in `g.rs`)
//! ```text
//! 0 sp
//! 8 pc
//! 16 g
//! 24 ctxt
//! 32 ret
//! 40 lr (unused on x86-64)
//! 48 bp
//! ```
//!
//! ## Assembly syntax
//! Rust's `naked_asm!` on x86-64 uses Intel syntax by default.
use addr_of_mut;
use ;
use ;
// ---------------------------------------------------------------------------
// gogo — restore saved state and jump
// ---------------------------------------------------------------------------
/// Restore register state from `buf` and resume execution at `buf.pc`.
///
/// Ported from `runtime·gogo` in `runtime/asm_amd64.s`.
///
/// Register usage (System V AMD64 — Linux / macOS):
/// - `rdi` = buf (*mut Gobuf, first arg)
///
/// Register usage (Microsoft x64 — Windows):
/// - `rcx` = buf (*mut Gobuf, first arg)
///
/// Common: `rax` = scratch (target pc), `rbp` / `rsp` restored from Gobuf.
///
/// ## Callee-saved register restoration
///
/// `gogo_asm` resumes execution at `buf.pc`, which (for a `mcall`-yielded
/// goroutine) is the instruction *immediately after* `call mcall_asm`. The
/// Rust function that called `mcall` follows the platform ABI, which means
/// it may hold live values in callee-saved registers across the call. We
/// restore those slots here so the caller's frame sees the exact register
/// state it left behind, not whatever the scheduler happened to leave there.
///
/// System V AMD64 (Linux/macOS) callee-saved GPRs: RBX, R12, R13, R14, R15
/// (plus RBP, which we already restore from `bp`). No callee-saved XMM/YMM.
// System V AMD64 ABI (Linux, macOS): first argument in rdi.
pub unsafe extern "C" !
// Microsoft x64 ABI (Windows): first argument in rcx.
// Microsoft x64 callee-saved GPRs add RDI and RSI vs. System V, plus the
// full 128 bits of XMM6–XMM15.
pub unsafe extern "C" !
// ---------------------------------------------------------------------------
// mcall — save current G's state and switch to g0
// ---------------------------------------------------------------------------
/// Save the current goroutine's registers into `g_sched`, switch to g0's
/// stack, and call `fn_ptr(g)`. Never returns via the normal path.
///
/// The return type is `()` (not `!`) deliberately: the Rust compiler must
/// generate a proper epilogue for `mcall()` *after* the `call mcall_asm`
/// instruction. When `gogo` later resumes a goroutine it jumps to
/// `g_sched.pc`, which points at that epilogue. Executing the epilogue
/// unwinds the `mcall` and caller (`gosched`/`gopark`) frames normally —
/// exactly the same sequence Go uses.
///
/// Ported from `runtime·mcall` in `runtime/asm_amd64.s`.
///
/// ## Calling conventions
///
/// **System V AMD64 (Linux, macOS)** — argument registers on entry:
/// - `rdi` = g, `rsi` = g_sched, `rdx` = g0_gobuf, `rcx` = fn_ptr
///
/// **Microsoft x64 (Windows)** — argument registers on entry:
/// - `rcx` = g, `rdx` = g_sched, `r8` = g0_gobuf, `r9` = fn_ptr
///
/// In both ABIs `[rsp]` on entry holds the return address pushed by the
/// `call mcall_asm` instruction. Caller SP = `rsp + 8`.
// System V AMD64 ABI (Linux, macOS): args in rdi, rsi, rdx, rcx.
//
// ## Callee-saved register save
//
// `mcall_asm` is invoked by a Rust function that obeys the platform ABI: it
// expects callee-saved GPRs (RBX, R12–R15 on System V, plus RBP) to be
// preserved across the call. But the goroutine is then yielded — the
// scheduler will run arbitrary code on this M and may clobber every register.
// Without saving the callee-saves here, the caller would resume with
// scheduler garbage in RBX/R12–R15 → corruption.
//
// We save them into `g_sched.regs[..]` (slots [0..5]). `gogo_asm` restores
// them when the goroutine is resumed. Order: [rbx, r12, r13, r14, r15].
pub unsafe extern "C"
// Microsoft x64 ABI (Windows): args in rcx, rdx, r8, r9.
//
// Microsoft x64 callee-saved registers: RBX, RBP, RDI, RSI, R12–R15, plus
// the full 128 bits of XMM6–XMM15. We save all of them except RBP (already
// saved separately in `g_sched.bp`); the XMM slots live in the same
// `gobuf.regs` array after the GPRs and are accessed with `movdqu` because
// the array is only 8-byte aligned. Missing the XMM saves manifested as
// STATUS_HEAP_CORRUPTION on Windows CI: a resumed goroutine continued with
// scheduler garbage in XMM6+, corrupting whatever its vectorised code
// touched next.
pub unsafe extern "C"
// ---------------------------------------------------------------------------
// Public wrappers
// ---------------------------------------------------------------------------
/// Resume goroutine `g` by restoring its saved register state and jumping.
///
/// Updates `CURRENT_G` before the context switch so any code running after
/// the switch sees the correct current goroutine. The caller must have
/// initialised `g.sched.sp` and `g.sched.pc` before calling.
///
/// On Windows, the TEB `StackBase` / `StackLimit` fields are updated to
/// reflect the goroutine's custom stack bounds before the RSP switch.
/// Windows' exception dispatcher (`RtlDispatchException`) validates that
/// the faulting RSP is inside `[TEB.StackLimit, TEB.StackBase)` before
/// walking frame-based handlers. Without this update, any `catch_unwind`
/// inside a goroutine is silently bypassed and the process terminates with
/// `0xe06d7363` (STATUS_CPP_EH_EXCEPTION).
///
/// Ported from the `execute` → `gogo` path in `runtime/proc.go` +
/// `runtime/asm_amd64.s`.
pub unsafe !
/// Save the current goroutine's state into `g.sched` and switch to g0's
/// stack, calling `fn_ptr(g)` there.
///
/// `fn_ptr` must eventually call `schedule()` or hand off via `gogo()` and
/// must not return to its caller.
///
/// The return type is `()` (not `!`) for the same reason as `mcall_asm`: the
/// compiler must emit an epilogue (`leave; ret`) after `callq mcall_asm` so
/// that `gogo` can resume the goroutine by jumping to that epilogue and
/// returning through the call stack normally.
///
/// Requires `G0_SCHED` to be initialised by `M::new` (step 6); panics in
/// debug builds if it has not been set yet.
///
/// Ported from `runtime·mcall` in `runtime/proc.go` + `runtime/asm_amd64.s`.
///
/// ## Why `#[inline(never)]` is load-bearing
///
/// `mcall` reads the thread-local `G0_SCHED` and passes the resulting gobuf
/// pointer to `mcall_asm`, which switches RSP onto that g0 stack. The call
/// to `mcall_asm` is a *suspension point*: the goroutine may resume on a
/// different OS thread (another M `gogo`s it). If `mcall` is inlined into a
/// caller that yields more than once (e.g. a `gosched()` loop), LLVM CSEs the
/// `G0_SCHED` TLS accessor and keeps the **slot address** in a callee-saved
/// register across the suspension. After a cross-thread resume that cached
/// address still points at the *old* thread's slot, so the next yield runs
/// the scheduler on the old M's g0 stack — corrupting the live scheduler
/// frames of whatever that M is doing (observed as SIGBUS `ret`-to-heap in
/// release builds with GOMAXPROCS ≥ 2). Keeping `mcall` out-of-line forces
/// the TLS slot address to be re-derived on the current thread at every
/// suspension, the same rule Go enforces by forbidding TLS caching across
/// `mcall`/`gopark` in its compiler.
pub unsafe
// ---------------------------------------------------------------------------
// systemstack — run a closure on g0's stack
// ---------------------------------------------------------------------------
/// Low-level stack switch: save goroutine RSP/RBP, switch to `g0_sp`, call
/// `thunk(arg)` on g0's stack, then restore the goroutine's RSP/RBP and return.
///
/// ## Register layout on entry (System V AMD64 — Linux / macOS)
/// - `rdi` = g0_sp (target stack pointer, aligned to 16 bytes inside)
/// - `rsi` = arg (opaque closure pointer, forwarded to thunk)
/// - `rdx` = thunk (function to call on g0's stack)
///
/// ## Register layout on entry (Microsoft x64 — Windows)
/// - `rcx` = g0_sp
/// - `rdx` = arg
/// - `r8` = thunk
///
/// ## Safety
/// `g0_sp` must be a valid, accessible stack address for this OS thread's g0.
/// `thunk` must not panic or longjmp.
///
/// Ported from `runtime·systemstack` in `runtime/asm_amd64.s`.
// called by systemstack; no callers until systemstack is used
unsafe extern "C"
/// Windows x64 variant: rcx=g0_sp, rdx=arg, r8=thunk.
// called by systemstack; no callers until systemstack is used
unsafe extern "C"
/// Run `f` on the M's g0 (system) stack, then return to the current goroutine.
///
/// If already on g0 (scheduler context — `CURRENT_G` is null), `f` is called
/// directly without any stack switch.
///
/// ## How the switch works
///
/// `gogo` saves g0's stack pointer into the thread-local `G0_SCHED.sp` every
/// time it switches into a goroutine. While the goroutine runs, g0 is idle —
/// its stack memory is allocated and valid, just not active. `systemstack`
/// reads that saved SP, uses `systemstack_call` (a naked helper) to swap RSP,
/// calls `f` on g0's stack, and restores RSP before returning.
///
/// The closure `f` is stored in a `ManuallyDrop` slot on the goroutine's own
/// stack. The goroutine stack memory remains valid throughout the switch (only
/// RSP changes), so the pointer passed to the thunk is always live.
///
/// Ported from `systemstack` in `runtime/asm_amd64.s`.
// future callers: stack growth, signal handlers, GC hooks
pub unsafe
// ---------------------------------------------------------------------------
// async_preempt_trampoline — Step 4: async signal-based preemption
// ---------------------------------------------------------------------------
/// Trampoline injected by the SIGURG handler to preempt a running goroutine.
///
/// This is the Unix (System V) body. Windows has no POSIX signals, so there
/// the equivalent trampoline is injected via `SuspendThread` + `SetThreadContext`
/// (`preempt_m_windows` in `sched.rs`) and the body differs only in its call-site
/// shadow space — see the `#[cfg(windows)]` sibling at the end of this file.
///
/// The SIGURG handler redirects the goroutine's `RIP` to this function and
/// pushes the original `RIP` onto the goroutine's stack (decrements `RSP` and
/// writes the original PC to `[RSP]`). When the goroutine resumes after the
/// signal returns, execution begins here — exactly as if the goroutine had been
/// called with a normal `call` instruction.
///
/// ## Register layout on entry
/// - `[RSP]` = original `RIP` (the preemption point; serves as the return address)
/// - `RSP+8 .. RSP+136` = the interrupted function's System V red zone,
/// preserved untouched (redirect_to_async_preempt stores the resume PC at
/// `rsp − 136`, not `rsp − 8`, so this frame cannot clobber red-zone
/// locals of an interrupted leaf function; the final `ret 128` undoes the
/// displacement)
/// - `RSP+136..` = goroutine's live stack at the moment of preemption
/// - All other registers: unchanged (intact from the interrupted state)
///
/// ## Frame layout (built by this function)
/// ```text
/// [RSP+0 .. RSP+7]: RFLAGS (8 B, saved by pushfq)
/// [RSP+8 .. RSP+127]: 15 × 8 B GPRs: RBP R15 R14 R13 R12 R11 R10 R9
/// R8 RDI RSI RDX RCX RBX RAX
/// [RSP+128 .. RSP+383]: 264 B XMM area (16 × 16 B data + 8 B pad)
/// ```
///
/// Total frame: 8 + 120 + 264 = 392 B.
///
/// ## Stack alignment
/// On entry `RSP % 16 == 8` (redirect pushed original RIP).
/// After `pushfq` (8 B): `RSP % 16 == 0`.
/// After 15 GPR pushes (120 B): `RSP % 16 == 8`.
/// After `sub rsp, 264` (264 B): `RSP % 16 == 0`. Correct for a call site.
///
/// Ported from the auto-generated `asyncPreempt` in `runtime/preempt_amd64.s`.
pub unsafe extern "C"
/// Win64 variant of [`async_preempt_trampoline`] (non-Windows version above).
///
/// `preempt_m_windows` (in `sched.rs`) injects a call to this function by
/// editing the suspended thread's `CONTEXT`: it stores the resume `RIP` at
/// `rsp − 128 − 8` and points `RIP` here — exactly the same scheme as the Unix
/// `redirect_to_async_preempt` amd64 branch, so the entry invariant
/// (`[RSP]` = resume PC, `RSP % 16 == 8`) and the closing `ret 128` are
/// identical to the Unix body. Win64 has no red zone, so skipping 128 bytes is
/// merely harmless slack that keeps the trampoline byte-identical to the Unix
/// one apart from the one delta below.
///
/// **The only difference from the Unix body** is the call site: the Win64 ABI
/// requires the caller to reserve **32 bytes of shadow space** above the return
/// address for the callee to spill its register parameters into. The Unix body
/// reserves none (System V has no shadow space); doing the same here would let
/// `async_preempt2`'s prologue write through the shadow region and clobber the
/// saved frame-base (`push rax`). We therefore allocate `8 + 32 = 40` bytes
/// (8 to restore call-site alignment, 32 shadow) instead of 8.
///
/// Like the Unix version this over-saves every register Win64 marks
/// callee-saved (RBX/RBP/RSI/RDI/R12–R15, XMM6–15) plus all caller-saved ones,
/// which is exactly what an arbitrary interrupted point requires.
pub unsafe extern "C"