Skip to content

Save/restore Windows TIB fields during context switches - #32

Merged
lalinsky merged 3 commits into
mainfrom
save-windows-tib-fields
Oct 7, 2025
Merged

lalinsky merged 3 commits into
mainfrom
save-windows-tib-fields

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 7, 2025 •

Copy link
Copy Markdown
Owner

Summary

Fixes Windows coroutine crashes by properly saving and restoring Thread Information Block (TIB) fields during context switches.

Without these updates, __chkstk stack probing checks the wrong stack limits (from the original thread stack instead of the coroutine stack), causing segmentation faults and preventing proper exception handling.

Changes

  • Extended Context structure on Windows x64 to store TIB fields:

    • fiber_data (gs:[0x20])
    • stack_base (gs:[0x08])
    • stack_limit (gs:[0x10])
    • deallocation_stack (gs:[0x1478])
  • Updated switchContext assembly to save/restore TIB values on every context switch

  • Initialize TIB fields in Coroutine.setup() with correct stack bounds for each coroutine

  • Reduced default stack size on Linux from 1MB to 256KB (Windows still needs 2MB due to higher ABI overhead)

Impact

This enables proper stack overflow detection on Windows. Tests now correctly detect genuine stack overflows instead of crashing due to incorrect TIB values pointing to the wrong stack.

Test plan

  • Run full test suite on Windows
  • Run full test suite on Linux/macOS to ensure no regressions
  • Verify stack overflow detection works correctly

Summary by CodeRabbit

  • Bug Fixes

    • Improved coroutine stability on Windows x86_64 by correctly preserving and updating Windows thread stack metadata during context switches and coroutine setup, reducing crashes in coroutine-heavy scenarios.
  • Refactor

    • Reduced default coroutine stack size on non-Windows platforms from 1MB to 256KB (Windows remains 2MB), lowering memory usage and enabling more concurrent coroutines by default.
  • Documentation

    • Added guidance for testing Windows builds on Linux using available tooling.

Windows requires updating the Thread Information Block (TIB) when
switching between coroutine stacks. Without these updates, __chkstk
stack probing checks the wrong stack limits, causing segfaults.

Changes:
- Extended Context structure on Windows x64 to store TIB fields:
  * fiber_data (gs:[0x20])
  * stack_base (gs:[0x08])
  * stack_limit (gs:[0x10])
  * deallocation_stack (gs:[0x1478])

- Updated switchContext to save/restore TIB values on context switch

- Initialize TIB fields in Coroutine.setup() with correct stack bounds

This fix enables proper stack overflow detection on Windows. Tests now
correctly detect genuine stack overflows instead of crashing due to
incorrect TIB values.
@coderabbitai

coderabbitai Bot commented Oct 7, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The PR reduces the default non-Windows coroutine stack size, extends the x86_64 Windows Context struct with Windows TIB fields, initializes those fields when creating a coroutine, and updates switchContext and entry/trampoline code on x86_64 Windows to save/restore and apply TIB values during swaps.

Changes

Cohort / File(s) Summary
Stack sizing (non-Windows)
src/coroutines.zig
Reduced default coroutine stack size from 1MB (1024*1024) to 256KB (256*1024) for non-Windows targets; Windows default remains 2MB.
Windows x86_64 Context struct & init
src/coroutines.zig
Extended public Context (extern struct) for x86_64 Windows to include TIB-related fields (fiber_data, stack_base, stack_limit, deallocation_stack) and updated initContext to initialize these fields when creating a coroutine.
Context switching (Win x86_64)
src/coroutines.zig
switchContext (x86_64 Windows path) now saves/restores Windows TIB fields around the swap and updates the system TIB with the target context’s values.
Coroutine entry & trampoline (Win x86_64)
src/coroutines.zig
Adjusted coroEntry/trampoline to account for Windows ABI (shadow space, return address layout) and set up TIB-related values for new coroutines.
Docs: Windows testing note
CLAUDE.md
Added instruction on how to test Windows builds on Linux using zig and wine.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Creator as Coroutine Creator
  participant ContextObj as Context
  participant SysTIB as Windows TIB
  participant Runner as Coroutine

  rect rgb(240,248,255)
  note over Creator,ContextObj: Coroutine creation (x86_64 Windows)
  Creator->>ContextObj: initContext(stack_ptr, stack_len)
  ContextObj->>ContextObj: set regs, rsp, rip, trampoline
  ContextObj->>ContextObj: fiber_data = 0
  ContextObj->>ContextObj: stack_base/stack_limit = from stack
  ContextObj->>ContextObj: deallocation_stack = stack_base
  end

  rect rgb(245,255,245)
  note over Runner,SysTIB: Context switch (save current, load next)
  Runner->>ContextObj: switchContext(current, next)
  ContextObj->>SysTIB: read current TIB fields
  ContextObj->>ContextObj: save regs + TIB -> current
  ContextObj->>ContextObj: load regs + TIB <- next
  ContextObj->>SysTIB: write next TIB fields
  ContextObj-->>Runner: transfer execution to next
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A rabbit stacks the bytes just so,
From mega to quarter-meg we go.
On Windows hills the TIBs align,
We swap and hop in proper time.
Coroutines leap — soft whiskers show. 🐇✨

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 succinctly describes the main change to save and restore Windows Thread Information Block fields during context switches, matching the pull request’s primary objective without extraneous details or noise.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch save-windows-tib-fields

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f6adb5 and e3414be.

📒 Files selected for processing (1)
  • CLAUDE.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CLAUDE.md

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/coroutines.zig (1)

380-387: Windows x64 ABI: missing 32-byte shadow space for callee

Caller must reserve 32 bytes of home space. Current code only pushes a dummy return address; a callee may write into non-reserved memory. Allocate shadow space and adjust offsets.

-                asm volatile (
-                    \\ pushq $0
-                    \\ leaq 8(%%rsp), %%rcx
-                    \\ jmpq *8(%%rsp)
-                );
+                asm volatile (
+                    \\ pushq $0
+                    \\ subq $32, %%rsp              // reserve shadow space
+                    \\ leaq 40(%%rsp), %%rcx        // pointer to CoroutineData
+                    \\ jmpq *40(%%rsp)              // jump to CoroutineData.func
+                );
🧹 Nitpick comments (2)
src/coroutines.zig (2)

19-19: Non-Windows default stack cut to 256KB — verify headroom

Risk of regressions for deep recursion/large frames. Please confirm test coverage for worst-case stacks and document the change. Consider per-target defaults or keeping a higher debug default.


33-42: Context layout extended with TIB fields — add offset asserts

Layout matches asm (0/8/16/24/32/40/48). Add compile-time asserts to prevent future drift.

+comptime {
+    if (builtin.os.tag == .windows and builtin.cpu.arch == .x86_64) {
+        assert(@offsetOf(Context, "rsp") == 0);
+        assert(@offsetOf(Context, "rbp") == 8);
+        assert(@offsetOf(Context, "rip") == 16);
+        assert(@offsetOf(Context, "fiber_data") == 24);
+        assert(@offsetOf(Context, "stack_base") == 32);
+        assert(@offsetOf(Context, "stack_limit") == 40);
+        assert(@offsetOf(Context, "deallocation_stack") == 48);
+    }
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 29ce096 and 869a93b.

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

59-67: Windows Context init defaults — OK

Zero-initializing TIB fields here and filling them in setup() is correct.


87-183: Windows x64: TIB save/restore in switchContext — looks correct

Offsets and ordering are coherent; TIB is restored before target code does any stack ops. Clobbers defensively cover non-volatiles and vector regs, which is appropriate for a context switch.


452-461: Initialize TIB for coroutine stacks — values look right

fiber_data=0, stack_base=high, stack_limit=low, deallocation_stack=allocation base (low) are appropriate for __chkstk and exception handling.

The Windows x64 calling convention requires the caller to allocate 32 bytes
of shadow space (home space) for the first 4 register parameters, regardless
of whether the callee uses them. This space must be allocated before calling
any function with callconv(.c).

@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 (1)
src/coroutines.zig (1)

87-183: Drop unnecessary MMX/AVX-512 clobbers. No SIMD intrinsics or vector operations were found in the codebase—remove mm0–mm7 and zmm0–zmm31 from the inline-asm clobber list to avoid over-constraining the compiler.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 869a93b and 1f6adb5.

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

33-46: LGTM! Context struct extended correctly for Windows TIB.

The four TIB fields (fiber_data, stack_base, stack_limit, deallocation_stack) are added with correct gs: segment offsets matching the Windows x64 Thread Environment Block structure. The use of extern struct ensures proper ABI compatibility.

Note: This is a breaking change to the public Context API on Windows x86_64, as the struct size increases from 24 bytes to 56 bytes.


59-67: LGTM! TIB fields correctly initialized to zero.

Zero-initialization is appropriate here since these fields will be properly set in Coroutine.setup() once the stack bounds are known.


382-387: LGTM! Windows x64 shadow space correctly allocated.

The code properly allocates 32 bytes of shadow space before the return address, as required by the Windows x64 calling convention. The CoroutineData pointer is correctly loaded into RCX (first argument register), and the function pointer is accessed at the correct offset.


457-463: LGTM! TIB fields correctly initialized with coroutine stack bounds.

The TIB fields are properly initialized:

  • stack_base (high address) = top of stack where stack pointer starts
  • stack_limit (low address) = bottom of stack where overflow detection occurs
  • deallocation_stack = base address for deallocation

This will enable __chkstk to use the correct stack bounds for each coroutine.

Minor note: In Windows, deallocation_stack is typically set lower than stack_limit to account for guard pages. Here they're identical because user-space coroutines don't have OS-managed guard pages. This is acceptable but means stack overflow detection relies solely on stack_limit.


19-19: Remove the stack size TODO and keep 256 KB default
No large stack allocations (>1 KB) or deep recursion found in non-Windows code; the reduced default is safe.

@lalinsky
lalinsky merged commit 0d5e00e into main Oct 7, 2025
@lalinsky
lalinsky deleted the save-windows-tib-fields branch October 7, 2025 13:51
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Split file_open into file_open and file_create operations

Separates opening existing files from creating new files to provide
clearer semantics and more appropriate flag structures.

Changes:
- FileOpen now takes FileOpenFlags with mode enum (read_only, write_only, read_write)
- FileCreate takes FileCreateFlags with read, truncate, and exclusive bools plus mode_t
- Updated fs.openat() to open existing files only
- Added fs.createat() for creating new files
- Added file_create operation to all backends (io_uring native, others via thread pool)
- Updated test to use FileCreate and added read/write validation

* Fix mode parameter type in openat() for BSD systems

Cast literal 0 to mode_t to satisfy BSD's variadic function requirements.

* Move mode into FileCreateFlags and add O_CLOEXEC

- Move mode parameter from FileCreate.init() into FileCreateFlags struct
- This makes the API more consistent with FileOpenFlags
- Add O_CLOEXEC flag to io_uring FileOpen and FileCreate operations
- Prevents file descriptor leaks across exec() calls
- The thread pool path already sets CLOEXEC, now io_uring path matches
@coderabbitai coderabbitai Bot mentioned this pull request Jan 7, 2026
1 task done
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