Repository navigation
Save/restore Windows TIB fields during context switches - #32
Conversation
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.
WalkthroughThe 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
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. Comment |
There was a problem hiding this comment.
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 calleeCaller 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 headroomRisk 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 assertsLayout 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
📒 Files selected for processing (1)
src/coroutines.zig(5 hunks)
🔇 Additional comments (3)
src/coroutines.zig (3)
59-67: Windows Context init defaults — OKZero-initializing TIB fields here and filling them in setup() is correct.
87-183: Windows x64: TIB save/restore in switchContext — looks correctOffsets 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 rightfiber_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).
There was a problem hiding this comment.
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
📒 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 structensures proper ABI compatibility.Note: This is a breaking change to the public
ContextAPI 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 startsstack_limit(low address) = bottom of stack where overflow detection occursdeallocation_stack= base address for deallocationThis will enable
__chkstkto use the correct stack bounds for each coroutine.Minor note: In Windows,
deallocation_stackis typically set lower thanstack_limitto 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 onstack_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.
* 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
Summary
Fixes Windows coroutine crashes by properly saving and restoring Thread Information Block (TIB) fields during context switches.
Without these updates,
__chkstkstack 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
Contextstructure on Windows x64 to store TIB fields:fiber_data(gs:[0x20])stack_base(gs:[0x08])stack_limit(gs:[0x10])deallocation_stack(gs:[0x1478])Updated
switchContextassembly to save/restore TIB values on every context switchInitialize TIB fields in
Coroutine.setup()with correct stack bounds for each coroutineReduced 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
Summary by CodeRabbit
Bug Fixes
Refactor
Documentation