Skip to content

Fix Windows coroutine crashes by using correct calling convention - #3

Merged
lalinsky merged 2 commits into
mainfrom
fix-windows-coroutine-crashes
Sep 26, 2025
Merged

lalinsky merged 2 commits into
mainfrom
fix-windows-coroutine-crashes

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 26, 2025 •

Copy link
Copy Markdown
Owner

Summary

Fixes crashes on Windows when running coroutines, which were caused by a calling convention mismatch in the coroutine entry point.

Root Cause

The coroEntry() function was using System V calling convention (passing first parameter in RDI) on all platforms, but on Windows x64, the calling convention expects the first parameter in RCX. This caused the coroutine wrapper function to receive garbage as its first parameter, leading to crashes when trying to access the coroutine data structure.

Changes

  • Main fix: Update coroEntry() to use RCX instead of RDI for the first parameter on Windows
  • Add missing registers to inline assembly clobber lists for better correctness
  • Add missing x9 to ARM64 clobber list (used as scratch register in the assembly)

Test Results

  • ✅ Windows: sleep.exe now runs correctly under Wine
  • ✅ Linux: No regressions, still works as expected
  • ✅ Both platforms complete the 10-second sleep demo successfully

The fix is minimal and targeted - essentially just changing one register name in the Windows path of coroEntry().

Summary by CodeRabbit

  • Bug Fixes

    • Fixed coroutine entry on Windows x86_64 to match platform calling conventions, preventing crashes and incorrect returns.
    • Corrected register handling during context switches on x86_64 and AArch64, avoiding state corruption and improving stability across platforms.
  • Refactor

    • Streamlined coroutine context-switch logic to reduce overhead and improve reliability, yielding smoother performance under load.
    • Harmonized behavior across Windows, Linux, and AArch64 environments for more predictable coroutine execution.

The main issue was that coroEntry() was passing the coroutine data
pointer in RDI (System V convention) on all platforms, but Windows x64
calling convention expects the first parameter in RCX.

This caused the coroutine wrapper function to receive garbage as its
first parameter, leading to crashes when accessing coroutine data.

Changes:
- Fix coroEntry() to use RCX instead of RDI on Windows
- Add missing registers to clobber lists for completeness
- Add missing x9 to ARM64 clobber list (used as scratch register)
@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 23 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between d6a2e5f and 3714e8a.

📒 Files selected for processing (1)
  • src/coroutines.zig (3 hunks)

Walkthrough

Updates the coroutine context-switch and entry assembly in src/coroutines.zig. Revises clobber lists for x86_64 and AArch64. Adds a Windows-specific x86_64 branch in coroEntry to use rcx instead of rdi for the return address slot when performing the indirect jump.

Changes

Cohort / File(s) Summary
x86_64 context switch and entry updates
src/coroutines.zig
switchContext: modifies x86_64 inline asm clobber set (now clobbers rdx, rbx, rdi, rsi, r12–r15, xmm6–xmm15). coroEntry: adds OS split; Windows uses rcx as return-address slot; non-Windows uses rdi; preserves push-and-jmp pattern.
AArch64 clobber adjustments
src/coroutines.zig
switchContext: updates AArch64 clobbers, removing prior v8–v15 set and adjusting to include x9 and other registers per new list.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant SC as switchContext
  participant CPU
  participant CE as coroEntry
  participant F as TargetFunction

  Caller->>SC: invoke(old_ctx, new_ctx)
  SC->>CPU: save/restore regs (per updated clobbers)
  CPU-->>Caller: switched stack/regs

  note over CE,CPU: Coroutine first entry

  alt x86_64 Windows
    CE->>CE: write return slot in rcx
  else x86_64 non-Windows
    CE->>CE: write return slot in rdi
  end
  CE->>CE: push return address
  CE-->>F: indirect jmp to function pointer
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

I twitch my ears at registers’ dance,
rdi or rcx—platform’s stance.
Stacks align, the coroutines glide,
xmm tails tucked, we context-switch stride.
On silent paws through call frames deep,
I hop to entry—then leap to sleep. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely describes the core fix of the pull request, namely resolving Windows coroutine crashes by adopting the correct calling convention, and it directly reflects the primary change made in the code.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/coroutines.zig (3)

149-149: The AArch64 clobber list still includes SIMD registers v8-v15.

The clobber list includes both the general-purpose register x9 and SIMD registers v8-v15. According to the AAPCS64 calling convention, v8-v15 are callee-saved registers, so they shouldn't need to be in the clobber list unless this assembly modifies them directly.

Apply this diff to remove the callee-saved SIMD registers from the clobber list:

-            : "x9", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x29", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "memory"
+            : "x9", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x29", "memory"

175-178: Consider adding a comment explaining the calling convention difference.

While the fix is correct, it would be helpful for future maintainers to understand why this platform-specific branching is necessary.

Add a comment explaining the calling convention difference:

             if (builtin.os.tag == .windows) {
+                // Windows x64 ABI: first integer arg in RCX
                 asm volatile (
                     \\ pushq $0
                     \\ leaq 8(%%rsp), %%rcx
                     \\ jmpq *8(%%rsp)
                 );
             } else {
+                // System V AMD64 ABI: first integer arg in RDI
                 asm volatile (

130-130: Exclude non-volatile XMM registers from clobber list on Windows
Wrap the x86_64 asm block’s clobber list in an OS check (e.g. if (builtin.os.tag != .windows)) to omit "xmm6"…"xmm15" on Windows, where those registers are callee-saved.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a108a52 and d6a2e5f.

📒 Files selected for processing (1)
  • src/coroutines.zig (3 hunks)
🔇 Additional comments (1)
src/coroutines.zig (1)

172-186: Windows x64 calling convention fix looks correct.

The change correctly addresses the Windows x64 ABI difference where the first integer argument is passed in RCX instead of RDI. This aligns with the Microsoft x64 calling convention and should resolve the crashes described in the PR.

Clarifies why different registers (RCX vs RDI) are used for the first
function argument on Windows vs Unix-like systems in the coroutine entry point.
@lalinsky
lalinsky merged commit bbb18aa into main Sep 26, 2025
@lalinsky
lalinsky deleted the fix-windows-coroutine-crashes branch September 26, 2025 21:55
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Add NetBSD CI run

* Add OpenBSD CI run

* Revert "Add OpenBSD CI run"

This reverts commit 10699ed422b87a5c3befd5c28f8dc3dc828c2eba.

* Initial version of kqueue backend

* Add custom EV_ERROR

* Sync using sshfs

* Fix errno handling and upgrade NetBSD CI to 10.1

- Fix double errno evaluation in AsyncImpl.init() that could report wrong error
- Upgrade NetBSD CI to version 10.1 for EVFILT_USER support (added in NetBSD 10.0)

* Revert "Sync using sshfs"

This reverts commit b2cc6be4a79723f721965abfc67a04e2b787917e.

* Build BSD targets natively in VMs instead of cross-compiling

Changes the CI workflow to download Zig binaries and build natively
on FreeBSD and NetBSD VMs instead of cross-compiling from Ubuntu.
This ensures tests run against the native BSD libc rather than Zig's
libc, which was causing behavioral differences.

* Revert "Build BSD targets natively in VMs instead of cross-compiling"

This reverts commit 450f9cd7ab9674f0834f82ab7a1e9ca1ccc3c295.

* Add diagnostic logging for kqueue constants

Logs the exact numeric values of EVFILT_USER, EV.* and NOTE.*
constants, Kevent structure size and field offsets, and detailed
error information when kevent() fails. This will help identify
differences between Zig's libc and native BSD libc.

* Fix bitcast compilation error for EVFILT.USER

* Fix NOTE_TRIGGER constant value for BSD systems

std.c incorrectly defines NOTE_TRIGGER as 0x08000000, but BSD
systems actually use 0x01000000. This was causing errno 9 (EBADF)
when trying to trigger EVFILT_USER events with cross-compiled binaries.

Added correct NOTE_TRIGGER constant and diagnostic logging to compare
std.c values with correct BSD values.

* Fix EVFILT_USER constant value for BSD systems

std.c incorrectly defines EVFILT.USER as 1 for NetBSD, but it should
be 8. The value 1 is actually EVFILT_WRITE. This was causing errno 9
(EBADF) when trying to register EVFILT_USER events.

Also fixed NOTE_TRIGGER which was incorrectly set to 0x08000000
(NOTE_SIGNAL) instead of 0x01000000.

Added diagnostic logging to show both std.c and correct values.

* Fix EVFILT_USER values for all BSD platforms

std.c has incorrect EVFILT_USER values. The correct platform-specific
values are:
- NetBSD: 8 (positive, std.c incorrectly has 1)
- FreeBSD: -11 (negative)
- macOS: -10 (negative)

Also fixed NOTE_TRIGGER (std.c has 0x08000000 which is NOTE_SIGNAL,
correct value is 0x01000000).

This fixes errno 9 (EBADF) when registering EVFILT_USER events.

* Cleanup

* cleanupg

* Fix typo

* Optimize kqueue backend with EV_ONESHOT

Use EV_ONESHOT flag to eliminate unnecessary EV_DELETE syscalls.
Events now auto-remove after firing, reducing syscalls per I/O operation.

Changes:
- Registration now uses EV_ONESHOT instead of EV_CLEAR
- Remove explicit queueUnregister() for normal completions
- Add re-registration for spurious wakeups (when EV_ONESHOT consumes event)
- Keep explicit EV_DELETE for cancellations only
lalinsky added a commit that referenced this pull request Jan 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant