Repository navigation
Extract Windows TIB handling to support ARM64 - #111
Conversation
Refactor Windows Thread Information Block (TIB) handling in coroutines to support both x86_64 and ARM64 Windows platforms. Changes: - Add WindowsTIB struct to encapsulate TIB fields (fiber_data, deallocation_stack, stack_limit, stack_base) - Use comptime type selection for ExtraContext (WindowsTIB on Windows, void elsewhere) - Add extra field to Context struct for both x86_64 and aarch64 - Optimize x86_64 TIB save/restore to load TEB pointer once via gs:0x30 (following boost.context pattern) - Add ARM64 Windows TIB handling using x18 register (TEB pointer) - Use comptime string concatenation to conditionally include Windows- specific assembly code - Update Coroutine.setup() to initialize TIB for both architectures TIB offsets are shared between x86_64 and ARM64 (0x20, 0x1478, 0x10, 0x08) as they reference the same TEB structure layout.
WalkthroughAdded an OS-specific ExtraContext (WindowsTIB on Windows, void otherwise), appended Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
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 |
Use load/store pair instructions (ldp/stp) for ARM64 Windows TIB field access, reducing memory operations from 8 to 6 per context switch (following boost.context pattern). Changes: - Use stp to store fiber_data and deallocation_stack together - Use ldp/stp for stack_base and stack_limit (consecutive in TEB) - Handle register ordering to match TEB layout vs struct layout - Reduces instruction count by 25% while maintaining correctness
Use load/store pair instructions for saving/restoring sp and fp in the base ARM64 context switch, reducing instructions from 4 to 2. Changes: - Save: Use stp to store sp and fp together - Restore: Use ldp to load sp and fp together - Applies same optimization pattern to both Windows and non-Windows paths
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/coroutines.zig (1)
413-418: Add clarifying comments for inverted stack naming.The logic is correct, but the variable naming is confusing: the local
stack_basevariable refers to the low address, while the TIBstack_basefield refers to the high address. Adding comments to clarify this inversion would help future maintainers.if (builtin.os.tag == .windows) { self.context.extra.fiber_data = 0; // No fiber data for our coroutines - self.context.extra.stack_base = stack_end; // Top of stack (high address) - self.context.extra.stack_limit = stack_base; // Bottom of stack (low address) - self.context.extra.deallocation_stack = stack_base; // Allocation base + self.context.extra.stack_base = stack_end; // TIB stack_base = top of stack (high address) + self.context.extra.stack_limit = stack_base; // TIB stack_limit = bottom of stack (low address) + self.context.extra.deallocation_stack = stack_base; // TIB deallocation_stack = allocation base }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/coroutines.zig(6 hunks)
🔇 Additional comments (3)
src/coroutines.zig (3)
32-39: Clean comptime design for Windows-specific context.The WindowsTIB struct and ExtraContext alias use comptime effectively to add Windows-specific fields only when needed, with zero overhead on other platforms. The approach is straightforward and maintainable.
198-223: Confirm testing on ARM64 Windows.The ARM64 TIB save/restore assembly looks correct based on the struct layout and x18 register usage. However, the PR mentions tests only ran on Linux x86_64. Please confirm this code has been tested (or will be tested) on actual ARM64 Windows hardware before merging, as inline assembly errors often only manifest at runtime.
90-123: TEB offset 0x1478 is verified as correct—no issues found.The DeallocationStack field is at offset 0x1478 in the x64 TEB structure, so the code is handling it correctly. The offset is large but legitimate; the TEB layout extends to that position. The optimization of loading the TEB pointer once and reusing it across saves/restores is sound.
…parentheses The Windows assembler (LLVM's integrated assembler) was unable to resolve numeric forward labels (0f) when conditional assembly blocks were concatenated without parentheses. Wrapping the if/else expressions in parentheses ensures proper evaluation before concatenation, allowing the assembler to correctly parse the numeric labels.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/coroutines.zig (1)
198-223: ARM64 TIB handling is correct but could use a comment.The register swaps in the ARM64 code (lines 203-204, 218-219) are intentional to map TEB memory layout to WindowsTIB struct field order. Consider adding a brief comment explaining that
ldpthenstpwith swapped registers reorders stack_base/stack_limit to match the struct.Example:
+ \\ // Swap order: TEB has stack_base@0x08, stack_limit@0x10 + \\ // but WindowsTIB struct has stack_limit then stack_base \\ ldp x11, x10, [x18, #0x08] \\ stp x10, x11, [x0, #40]
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/coroutines.zig(6 hunks)
🔇 Additional comments (6)
src/coroutines.zig (6)
41-55: Clean architecture using comptime type selection.The use of
ExtraContextto conditionally add Windows-specific fields is clean and doesn't bloat the Context on other platforms. The extern struct ensures the assembly offsets stay predictable.
59-75: Correct initialization approach.Leaving
extraas undefined here is appropriate since Windows TIB fields are properly initialized later inCoroutine.setup(). On non-Windows platforms whereExtraContextis void, this is a harmless no-op.
84-123: x86_64 TIB handling looks correct.Loading TEB pointer once from
gs:0x30then accessing fields is efficient and follows the boost.context pattern mentioned in the PR. The save/restore operations correctly map TEB offsets to WindowsTIB struct layout.
413-418: TIB initialization is correct but variable naming could be clearer.The initialization is correct, but note that the local variable
stack_base(line 396) refers to the low address while the TIB fieldstack_base(line 415) refers to the high address. This follows Windows conventions (stack grows downward) but might trip up readers. The code correctly assigns:
stack_end(high) → TIBstack_base(top of stack)stack_base(low) → TIBstack_limit(bottom of stack)
32-37: TEB offset 0x1478 is correct for both x64 and ARM64 Windows.The deallocation_stack offset of 0x1478 is documented for 64-bit Windows TEB, and ARM64 uses the x18 register to hold the TEB pointer in user mode, mirroring the x64 architecture. The codebase correctly applies this offset consistently across both platforms. Note that hardcoded TEB offsets are fragile as the TEB structure can change with new Windows versions, but this is an architectural constraint beyond the scope of this change.
78-418: The review comment is based on incorrect assumptions.The CI workflow explicitly tests on
windows-latestalongside Linux and macOS. The test suite includes multiple runtime tests insrc/runtime.zigthat exercise the coroutine system through task spawning and execution, which means the context-switching code (including Windows TIB handling) gets tested on Windows as part of the CI pipeline.The PR description mentioning "All 152 tests pass on Linux x86_64" doesn't mean Windows tests don't run—it's just highlighting the development environment. The actual CI matrix shows tests run on all three platforms, so the Windows-specific code paths are already being validated in the continuous integration pipeline.
Likely an incorrect or invalid review comment.
Swap stack_base and stack_limit field order to match their layout in the Windows TEB structure (stack_base at 0x08, stack_limit at 0x10). Benefits: - Clearer correspondence between struct and TEB layout - Fields now consecutive in both our struct and TEB - Enables potential future optimization using paired loads on x86_64 - More maintainable - field order matches Windows documentation
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/coroutines.zig (1)
32-37: Consider reordering WindowsTIB fields to match TEB layout.The struct fields are ordered differently than their TEB offsets (stack_base is at 0x08, stack_limit at 0x10, fiber_data at 0x20, deallocation_stack at 0x1478). While the code works correctly because assembly explicitly accesses each offset, ordering the fields by their TEB offset would make the mapping clearer.
const WindowsTIB = extern struct { - fiber_data: u64, // TEB offset 0x20 - deallocation_stack: u64, // TEB offset 0x1478 stack_base: u64, // TEB offset 0x08 stack_limit: u64, // TEB offset 0x10 + fiber_data: u64, // TEB offset 0x20 + deallocation_stack: u64, // TEB offset 0x1478 };Note: This would require updating the assembly offsets in switchContext to match the new layout.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/coroutines.zig(6 hunks)
🔇 Additional comments (5)
src/coroutines.zig (5)
42-55: Clean architecture-specific Context with conditional TIB support.The addition of
extra: ExtraContextis well-designed: on Windows it contains TIB fields (32 bytes), on other platforms it's void (0 bytes). This keeps the Context struct lean on non-Windows platforms while supporting Windows requirements.
59-75: Proper initialization of extra field.Setting
extra = undefinedis correct here. The field is properly initialized later in Coroutine.setup() for coroutine contexts, and for the parent context, the first switchContext save operation will populate it with current TEB values.
84-190: x86_64 TIB handling looks correct, but untested on Windows.The assembly correctly:
- Loads TEB pointer once via gs:0x30 (efficient)
- Saves/restores all four TIB fields at correct offsets
- Uses comptime concatenation to conditionally include Windows paths
However, the PR mentions tests only pass on Linux x86_64, where this Windows-specific code path isn't exercised.
Run these changes on an actual Windows x86_64 system to verify the TIB handling works correctly. The assembly looks right, but low-level code like this needs real hardware validation.
191-314: ARM64 Windows TIB handling appears correct, but completely untested.The assembly correctly:
- Uses x18 as TEB pointer (correct for ARM64 Windows)
- Accesses all TIB fields at the right offsets
- Uses efficient ldp/stp instructions for paired operations
The logic matches the x86_64 implementation and should work correctly. However, this ARM64 Windows code path is completely new and has zero test coverage (PR only tested on Linux x86_64).
This code must be tested on actual ARM64 Windows hardware before merging. While the assembly looks correct, there's no way to verify it works without running it on the target platform. Low-level assembly mistakes can cause crashes or corruption that won't show up until runtime.
413-418: Correct Windows TIB initialization for coroutine stacks.The TIB fields are properly initialized:
fiber_data = 0(no fiber data)stack_baseandstack_limitcorrectly map to the coroutine's stack boundariesdeallocation_stackset to the allocation baseThe comptime guard ensures this only runs on Windows where the fields exist.
Summary
Refactor Windows Thread Information Block (TIB) handling in coroutines to support both x86_64 and ARM64 Windows platforms.
Changes
WindowsTIBstruct to encapsulate TIB fields (fiber_data,deallocation_stack,stack_limit,stack_base)ExtraContext(WindowsTIBon Windows,voidelsewhere)extrafield toContextstruct for both x86_64 and aarch64 architecturesgs:0x30(following boost.context pattern)Coroutine.setup()to initialize TIB for both architecturesTechnical Details
TIB Offsets
TIB offsets are shared between x86_64 and ARM64 as they reference the same TEB structure layout:
fiber_data: 0x20deallocation_stack: 0x1478stack_limit: 0x10stack_base: 0x08TEB Access Methods
gs:0x30, then access TIB fields as offsets from that pointerTesting
All 152 tests pass on Linux x86_64.