Skip to content

fix(windows): enter guest startup on an arena-backed main stack - #3965

Merged
oneandonlydean merged 5 commits into
boykopovar:mainfrom
eliasbruno124-dev:fix/windows-guest-main-stack
Nov 14, 2026
Merged

oneandonlydean merged 5 commits into
boykopovar:mainfrom
eliasbruno124-dev:fix/windows-guest-main-stack

Conversation

@eliasbruno124-dev

@eliasbruno124-dev eliasbruno124-dev commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What

Enter Windows guest initialization and the ELF entry on a committed GuestArena stack. Native module loading stays on the host stack, preserving #679's low native-stack policy and its protection against fragmenting fixed guest mappings.

In the retained TLOU Part II Remastered PPSA15508/01.002.000 comparison, the allocator rounds the stack address down to a 1 GiB boundary and compares it with an initialized zero field. The low host stack also rounds to zero, selecting an uninitialized allocator and dereferencing null at original VA 0x1b60f2. With the guest stack, that allocation returns a valid pointer and the title goes on.

The libc helper preserves the thread and TLS, updates Windows stack bounds and enters a fresh unwind root. It uses the native reservation's capacity plus a 64 KiB inaccessible bottom region and keeps the stack alive through shutdown. Setup failures clean up on the original stack; missing helper exports fail explicitly. Console stack placement, capacity and accounting remain unmeasured and are recorded in the libc technical debt.

EnterGuestMainStack_nid_no_patch now has one signature on both systems. #7532, merged on 2026-11-03, added the Linux helper to libkernel as APS5_VABI (void* arguments, void (APS5_VABI* entry)(void*)), and GuestModuleArgsHost.cpp, the stand-in several relinker tests install as libc.prx, defines it that way. This branch had a one-argument Microsoft-convention export of the same name in libc, which the Windows entry stub called with the entry in rcx; against the stand-in that call jumped to whatever rsi held, which is the guest_zero_finalizer crash Superseabas and BunnyFl reported and relativespace2K traced. The libc export now takes the same two arguments in the same convention and hands arguments to the entry in rdi; the stub passes a null argument block and the entry in rsi (xor edi, edi; lea rsi, [rip+entry]; call rax). The stand-in is unchanged. Windows still resolves the helper from libc.prx, the library every Windows conversion loads, while Linux resolves it from libkernel.prx; the libkernel implementation is compiled for Linux only.

The kernel-variant import fixtures install the runtime image as host libc.prx, so that image must export the guest-main-stack entry helper. The maintainer's fixture correction is preserved.

Merge order: #6540 and #10157 have merged, #7135 was closed unmerged on 2026-11-08. The main-thread exit integration still depends on corrected #7149, which is open and conflicts with main; this branch does not resolve that. #7594 adds MXCSR initialization at the same startup area, a separate operation.

Tested

Current head bc0ee29e4c: the four earlier commits rebased onto main 439f320158 without conflicts, authors preserved, plus fix(windows): match the Linux guest main-stack entry signature. Windows 11 Pro 10.0.26300, MSYS2 UCRT64 GCC 16.2.0-6, Release, full build, nothing else merged.

  • All 247 tests of the relinker directory pass, as they do on main 439f320158 built the same way; guest_zero_finalizer is among them.
  • windows_guest_main_stack, windows_guest_main_stack_failure, windows_guest_main_stack_entry, guest_zero_finalizer, guest_module_args, windows_import_modules, windows_trace_imports, windows_kernel_variant_sys, windows_kernel_variant_web, entry_stub, windows_entry_stub_bounds, guest_kernel_is_stack and guest_pthread_stack pass in 3 of 3 runs. WindowsGuestMainStack.cpp now also checks that the argument pointer reaches the entry.
  • The 65 public_headers checks and linux_guest_stack pass, as on main.
  • Negative control: with WindowsEntryStubBuilder.cpp taken from the previous commit (entry in rcx) and only the relinker rebuilt, guest_zero_finalizer, windows_guest_main_stack_entry, windows_import_modules, windows_trace_imports and both windows_kernel_variant tests fail; restoring the file makes all 13 pass again.
  • python tools/check_conventions.py --base origin/main and git diff --check pass.
  • Castlevania Dominus Collection PPSA15645/01.003.000, converted with this head's relinker (--windows --to-intel --registry --module-dir .), NVIDIA GeForce RTX 3060 Laptop GPU, no input: runs for the 100 s limit at 600 presents per 10 s (median frame time 16.7 ms), and the dumped frames show the title's picture. main 439f320158, built and converted the same way, does the same (600 presents per 10 s from second 20 on in both runs). The converted app.exe contains the helper's name; the one made by a relinker without this change does not.
  • Linux and macOS not built or run here; the changed code is inside _WIN32 blocks, the Windows entry stub builder and Windows-only tests, except the one-byte fixture change in test_windows_import_modules.py, whose converted programs run only on Windows.

Earlier evidence, from heads before the signature change:

No other open PR found that implements this Windows main-stack transition; #7532 is the merged Linux counterpart. No menu, gameplay or frame-time claim.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: fix(threads): run Windows pthread and small fiber stacks in guest VA range #7149 after its reviewed corrections, for the main-thread exit integration
  • Fixes: none
  • Unblocks: PPSA15508 The Last of Us Part II Remastered (PPSA15508) #5468 (the stack-allocation stop in the documented integration; not standalone playability)
  • GPUs tested: n/a (Windows startup/libc change; the title runs used an NVIDIA GeForce RTX 3060 Laptop GPU, driver 621.01, Windows 11)
  • AI-assisted: yes

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Could you run a Windows title that already boots on main with this PR alone and post where it gets to before and after? Every title's main thread moves to the new stack, and the only title run so far is PPSA15508 on an integration branch with #3897 and #3925.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 12, 2026

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This changes the startup path of every Windows executable (the main thread moves to a GuestArena stack), and the only run so far is PPSA15508 on an integration branch that includes #3897 and #3925. Before this can merge:

  • Answer @oneandonlydean's request from 2026-10-11: run a Windows title that already boots on main with this PR alone and post where it gets to before and after. We can't run titles or Windows here, and the new tests only exist under if(WIN32).
  • Rebase onto main: it conflicts in core/libs/prx/libc/CMakeLists.txt (test block) and docs/dev/TechnicalDebt.md (line 395, adjacent to other entries).

Once both are done we can look at it again; the code itself needs no other change from what I read.

@EagleBearerYS

Copy link
Copy Markdown
Contributor

Resident Evil Village (PPSA01556, 01.210.000) needs this. On a local branch past its earlier stops, about 30 s in, it asks sceKernelIsStack for its main thread's stack and protects the whole range with CPU read/write. Without this PR, that call aborts:

[memory] protect 000000016ace0000+0x210000 prot=0xc2
what():  mprotect of uncommitted memory outside the guest arena
FATAL: abort()

That range is the host stack the relinker reserves in the PE header (0x210000). Windows commits it on demand, so below the guard page it is only reserved. On the console the whole main stack is mapped.

I checked this PR with a test that does what the title does: enter EnterGuestMainStack_nid_no_patch, call sceKernelIsStack, protect the whole range with 0xc2, then write to its lowest page. With this PR's GuestStacks change it passes, because the stack is arena memory and the arena path commits its lowest 64 KiB placeholder. Setup: Windows 11, WinLibs GCC 15.2.0 r7, Release, RTX 3070 Laptop.

@eliasbruno124-dev

Copy link
Copy Markdown
Contributor Author

Rebased onto 0aa4cb1c and resolved the libc test block, startup diagnostic and debt conflicts. At 4387c499, the full runtime build, nine focused stack/context tests and all 121 relinker tests pass on Windows 11 with WinLibs GCC 15.2.0 r7. The upstream tracing fixture needed the main-stack helper; its assertions and the explicit missing-helper regression remain intact. CTest ran noninteractively with unchanged timeouts.

I also ran Castlevania Dominus Collection PPSA15645/01.003.000 on pure main versus this PR alone, without #3897/#3925 or other unmerged changes:

Observation Main 0aa4cb1c PR 4387c499
Original ELF entry and 12 title modules Reached and verified Reached and verified
Stack pointer at entry 0x60fec8 0x20021ff48
Vulkan/swapchain Initialized, 1152x648 Initialized, 1152x648
Next stop scePadUnknown_n3kSX62fgNo not implemented Same stop
sceVideoOutSubmitFlip calls 0 0

The candidate's Windows stack bounds are 0x200010000..0x200220000. Inputs, other runtime libraries and settings were identical, and actual loaded module paths were checked. Both used the same readable SELF-to-ELF staging with original relative filenames and same-name resource mappings; the original dump stayed unchanged. No input or return-value substitution was used.

This supplies a main-versus-PR startup comparison through graphics initialization, but not a title reaching its menu on main. It does not establish gameplay or performance; the transfer running alongside the observations also rules out a clean performance comparison. The PR body distinguishes this run from the earlier TLOU integration evidence.

#4774 and #5406 add different operations at the same startup insertion point. Neither is stacked here; their merge order still needs coordination. The later main refresh at 8d98e8851 merges cleanly with this branch and does not change these entry/stack functions.

Prepared with AI assistance.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Rebased onto main; the only conflict was the docs/dev/debt/libc.md entry next to the new Windows direct-memory one.

@oneandonlydean
oneandonlydean force-pushed the fix/windows-guest-main-stack branch from 4387c49 to 49b51d2 Compare October 14, 2026 05:19
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 14, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

Thanks for the rebase and the Windows test run. adriadam10's review still needs one thing: a Windows title that boots on current main, run with this PR alone, showing where it gets to before and after (title ID, GPU/OS). @EagleBearerYS, could you run Resident Evil Village on this head on top of main?

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 14, 2026
@klosixgaming-arch

Copy link
Copy Markdown
Contributor

Test run (not a code review). I merged this PR onto current main (49d1f9b), built it on Windows (Release, winlibs), and ran Tekken Dark Resurrection (PPSA31371, PSPHD) for 112 s.

  • Merges cleanly, builds, and the game stays alive for the full run.
  • The run log differs from a baseline main run by only about 111 lines out of ~650, which is run-to-run noise, nothing new or removed in the errors.
  • I did not verify any visual change. My screenshots of this run did not capture the game window, so I cannot say whether the issue this PR targets is fixed.

So: no regression found, and no evidence of a fix either way.

@fogydes

fogydes commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Correction: The previous review comment (Oct 24) flagged an unticked checklist item, a stale head reference in the description, and an explanatory comment in test_windows_kernel_variant_imports.py. Commit 8029f87e58 resolved all three points: the comment was cleanly removed and moved to the description, the first checklist item is now ticked, and the description was updated.

Verdict: OK

Findings:

  1. check_conventions.py passes cleanly: ran python tools/check_conventions.py --base 309912635e83bd450ad30cb2bf02a559e9b67750 in a scratch worktree at head 8029f87e58; 0 findings. [verified]
  2. Public header declaration audit passes: ran python core/libs/tests/test_public_headers.py --audit-only in the worktree; verified 368 libraries, 12,194 exports with unique declarations. [verified]
  3. Clean merge-tree: git merge-tree --write-tree origin/main 8029f87e58 succeeds cleanly with exit code 0 (tree 16ed5859ea46549688adaa0be7c3bb5801beabd8), 4,092 commits behind current main. [verified]
  4. Code hygiene and checklist compliance:
    • Commit 8029f87e58 cleanly stripped the explanatory code comment from core/relinker/relinker/tests/test_windows_kernel_variant_imports.py:21, preserving strict zero-comment rules.
    • The PR description checklist strictly mirrors .github/pull_request_template.md with all 12 items ticked and explicit lines filled (Depends on: #7149 ..., Fixes: none, Unblocks: PPSA15508 #5468 ..., GPUs tested: n/a ..., AI-assisted: yes). [read-only]
  5. Implementation in GuestStacks.cpp and WindowsEntryStubBuilder.cpp cleanly isolates guest startup onto the committed GuestArena stack while retaining host stack execution for native module loading. TEB stack limits are correctly updated via ApplyBounds, failures roll back cleanly in catch (...), and the exception directory table is properly partitioned into dual RUNTIME_FUNCTION entries for host vs. guest stack unwinding. [read-only]
  6. Technical debt entry in docs/dev/debt/libc.md accurately records Windows main-stack capacity matching native reservation and unmeasured console stack accounting. [read-only]
  7. Title comparison evidence (TLOU Part II PPSA15508, ccleste PPSA59322, ScreenTester5 PPSA69420) and Windows CTest execution reports are [author-reported].

Freshness envelope:

  • Head SHA: 8029f87e5872277c330494a052a3d907052a3b7b
  • Base SHA: 309912635e83bd450ad30cb2bf02a559e9b67750
  • Behind count: 4,092 commits behind origin/main (bb04a4f1ea)
  • Merge-tree: exit code 0, clean tree 16ed5859ea46549688adaa0be7c3bb5801beabd8

Cross-PR ledger:

@github-actions github-actions Bot added the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 1, 2026

@BunnyFl BunnyFl 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.

Reads right. In EnterGuestMainStack_nid_no_patch (core/libs/prx/libc/src/GuestStacks.cpp), the new stack copies the host main stack's reservation capacity above a 64 KiB inaccessible bottom, and the entry frame is set up for the Windows x64 convention. Rsp = top - 40 with the 64 KiB-aligned top leaves rsp % 16 == 8 at entry with 32 bytes of shadow space above a zero return address, and Rbp = 0 gives the unwinder a clean root. A failure during setup releases the reservation and clears entered before rethrowing, on the original stack. The GuestArenaUnpinWritable in that path is safe when the commit failed before anything was pinned: WindowsMappings::Unpin only decrements pages whose pins is non-zero (core/libs/prx/libc/include/WindowsMappings.hpp).

Tested on Windows 11, WinLibs GCC 15.2.0, with this head merged onto current main, after building the windows_stdio_* fixture DLLs: windows_guest_main_stack, windows_guest_main_stack_entry, windows_guest_main_stack_failure, and the relinker tests this PR edits (windows_import_modules, windows_trace_imports, windows_kernel_variant_sys, windows_kernel_variant_web) pass, 7 of 7, nothing skipped. The four relinker tests also pass on plain main with the same fixtures.

@XairRrR XairRrR 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.

Reviewed — comments

The merge is clean, the build succeeds, the convention checks pass and the relinker tests that are registered on Linux pass. The new main-stack switch and every test that exercises it are Windows-only, so this Linux machine could not test the behaviour. I found nothing blocking.

What I ran

Head 8029f87e5872277c330494a052a3d907052a3b7b, main 9090972b7e91fd266819cbd77a8b058e177b5682, merged tree b944fb303a78e2f2d6db2ec234292c5b4501b05f. Machine: Debian 13 VM, GCC 14.2.0, Release, Ninja. The prepared build of the merged tree was used.

git diff --check 9090972b7e91fd266819cbd77a8b058e177b5682...8029f87e5872277c330494a052a3d907052a3b7b
python3 tools/check_conventions.py --base 9090972b7e91fd266819cbd77a8b058e177b5682
ctest --test-dir build -j8 --test-load 32 --output-on-failure -R "^(windows_trace_imports|windows_import_modules|entry_stub|windows_entry_stub_bounds|guest_kernel_is_stack|guest_pthread_stack)$"
# negative control
git show 9090972b7e91fd266819cbd77a8b058e177b5682:core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp > core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp
ninja -C build -j32 -l32 relinker
ctest --test-dir build -j8 --test-load 32 -R "^(windows_trace_imports|windows_import_modules|entry_stub|windows_entry_stub_bounds)$"
git show b944fb303a78e2f2d6db2ec234292c5b4501b05f:core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp > core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp
ninja -C build -j32 -l32 relinker
git status --porcelain

Results

Check Result
Merge into main Clean
git diff --check Clean
check_conventions.py All conventions checks passed.
Configure, build and libs OK (according to build.json)
Selected tests (build.json) No new failures and no timeouts. The 9 known failures also fail on main. guest_net_ctl was skipped for a reason that is not expected, which also happens on main.
windows_import_modules, windows_trace_imports, entry_stub, windows_entry_stub_bounds, guest_kernel_is_stack, guest_pthread_stack 6/6 passed
windows_guest_main_stack, windows_guest_main_stack_failure, windows_guest_main_stack_entry, windows_kernel_variant_* Not registered on Linux (if(WIN32))
Vulkan validation Skipped: the PR changes no file under the AGC driver, the shader recompiler or VideoOut

Negative control

I restored WindowsEntryStubBuilder.cpp from main and rebuilt relinker. windows_import_modules and windows_trace_imports still passed, so the control does not detect the change on Linux. Those tests only run the converted executable under os.name == 'nt', which includes the new missing-helper assertion. Here they only check the conversion. The three new libc tests are Windows-only and were not built. After the control I restored the merged file and rebuilt. git status --porcelain is empty.

BunnyFl's approval reports that the three new tests and the edited relinker tests pass on Windows on this head. screamm reported the same for an earlier head with identical changed lines. I could not reproduce either run.

Findings

Blocking

None.

Non-blocking

  • No stack-overflow guard semantics on the new main stack: core/libs/prx/libc/src/GuestStacks.cpp:114 commits the whole stack. Then core/libs/prx/libc/src/GuestStacks.cpp:131 sets StackLimit to its lowest committed byte, and the 64 KiB region below it is PAGE_NOACCESS, not a PAGE_GUARD page.
    • Why it matters: if the guest main thread overflows its stack, the kernel should report STATUS_ACCESS_VIOLATION instead of STATUS_STACK_OVERFLOW. Unlike the host stack, there is no reserved guard region left for the overflow handler. Both the host and the console abort in this case, so the effect is limited to diagnostics.
    • Suggested fix: mention this in the debt entry at docs/dev/debt/libc.md:141.
  • Debt entry style: the new entry at docs/dev/debt/libc.md:141 has no final period, unlike the entries around it.

Review of the stub code: the second RUNTIME_FUNCTION reuses unwindRva. That is valid because core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp:810 emits the same prologue bytes as the main entry at :503. The stack slots [rsp+0x20..0x58] that the post-switch code reads are all written after the switch, at :859-875. The exception-table bound at :925 is equivalent to the old >= 32 check when there is one entry. The reserved table still holds 32 entries (:134). On the new stack, rsp = top - 40 gives rsp % 16 == 8 with a zero return address, as BunnyFl's review says.

Not verified

  • Any Windows execution: the three new libc tests, the missing-helper regression in windows_import_modules, windows_kernel_variant_sys/web, and the generated-ELF exit code (42 versus 89). This machine is Linux-only, and these paths are guarded by WIN32 or os.name == 'nt'.
  • The title comparisons in the description and discussion: Castlevania PPSA15645, ccleste, ScreenTester5 and TLOU PPSA15508.
  • The declared dependency on corrected #7149. In the discussion, oneandonlydean notes that a main-thread scePthreadExit with workers still running would exit with the TEB pointing at the guest arena stack. That fix belongs in #7149, so the merge order #7149 before #3965 matters. I did not check whether #7149 has merged.

To get this to a good state

  • Have a maintainer confirm that the Windows CI run (Actions > Build with pr=3965) passes windows_guest_main_stack, windows_guest_main_stack_failure, windows_guest_main_stack_entry, windows_import_modules, windows_trace_imports and windows_kernel_variant_*.
  • Merge only after corrected #7149, as the Depends on line says.
  • Optionally, record the overflow-reporting difference in the debt entry and add its final period.

@Superseabas Superseabas 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.

Windows run of head 8029f87e58 merged onto current main 4741457fed (clean merge, local only). It covers the Windows-only tests @XairRrR couldn't run, and it finds one regression against a test that was added after this branch's base.

Windows 11 Home 10.0.26200, WinLibs GCC 16.2.0 (x86_64-ucrt-posix-seh, r3), Python 3.13, Release, BUILD_TESTING=ON.

The PR's Windows tests pass. windows_guest_main_stack, windows_guest_main_stack_failure, windows_guest_main_stack_entry, windows_kernel_variant_sys, windows_kernel_variant_web, windows_import_modules, windows_trace_imports, entry_stub, windows_entry_stub_bounds, guest_kernel_is_stack, guest_pthread_stack and public_headers pass, 3 runs each. windows_guest_main_stack_entry passes 3 of 3 from PowerShell; see the PATH note below for Git Bash. On main the 9 of them that exist pass.

Regression: guest_zero_finalizer fails on Windows with this PR.

Tree guest_zero_finalizer
main 3 of 3 pass
merged 0 of 3: AssertionError: ('windows', True, 3221225477, '', '', '')
merged, with main's WindowsEntryStubBuilder.cpp passes
  • 3221225477 is 0xC0000005. The converted program crashes before it records anything.
  • With the assertion turned into a print (a local copy of the test), all three Windows cases crash with this PR, zero, absent and nonzero. All three pass on main, and the Linux cases pass on both.
  • The guest module in that test is built with the THREAD_POINTER prefix (tls=True), so it reads the thread pointer, and it's loaded from sce_module.
  • The test came in with f5879c4ada (fix(relinker): preserve guest finalizers at address zero, 2026-10-24), which isn't in this branch, so it hasn't run against this change before.
  • In the full suite on the merge (RTX 5070 Ti, ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1), it is the only failure that main doesn't also have on this machine: 4,199 of 4,205 pass. The other five are known: test_registration and select_tests_MissingCommandTests (#15652), windows_crash_thread_name (#15578), agc_driver_direct_write_completion (#15564) and agc_driver_quad_pixel_mask (#14341).

Red check. The merged tree with only WindowsEntryStubBuilder.cpp taken back from main fails windows_guest_main_stack_entry and windows_import_modules, so the new tests do cover the stub change. With that one file back, guest_zero_finalizer passes again.

Overlap with #7532. Since this branch's base, #7532 (merged 2026-11-03) added extern "C" EnterGuestMainStack_nid_no_patch(void* arguments, void (*entry)(void*)) to libkernel (Pthread/src/Thread.cpp). It maps a main stack at the console's address range and isn't guarded to Linux. This PR adds a libc EnterGuestMainStack_nid_no_patch(void (*entry)()) with the same name, a different signature, and an arena stack sized from the host stack. The Windows stub takes it from libc.prx with GetProcAddress, so the two don't collide at load time, and public_headers passes. Still, that leaves two main-stack implementations under one exported name in two libraries. Whether Windows should use #7532's would be worth settling here.

Smaller: test_windows_guest_main_stack.py copies the compiler runtime DLLs from the first match on PATH.

  • Run from Git Bash, the first libstdc++-6.dll on PATH here is Git for Windows' (C:\Program Files\Git\mingw64\bin, an older GCC). The converted program then fails with Failed to load module: ...\libc.prx, GetLastError: 127.
  • From PowerShell, where the WinLibs copy comes first, it passes.
  • Taking them from the compiler's own directory (CMAKE_CXX_COMPILER) would avoid that. The 3-of-3 results above are from the PowerShell environment.

check_conventions.py --base main passes on the merge.

AI-assisted: yes (Claude Code)

@BunnyFl BunnyFl 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.

@eliasbruno124-dev changing my review to request changes: guest_zero_finalizer fails with this PR on Windows. cc @Superseabas, who found it. You're right, and my approval at this head missed it: the test came in with f5879c4ada (2026-10-24), which isn't in this branch, and I didn't run it.

I reproduced it. Head 8029f87e58 merged onto main 6a337633c6 (merge ba5963cf3b, clean), Windows 11 Pro 10.0.26300, WinLibs GCC, Release, one run of each:

Test the merge the merge with WindowsEntryStubBuilder.cpp taken from main
guest_zero_finalizer fails: AssertionError: ('windows', True, 3221225477, '', '', '') passes
windows_guest_main_stack_entry passes fails
windows_import_modules passes fails
windows_guest_main_stack, windows_guest_main_stack_failure, windows_trace_imports, windows_kernel_variant_sys, windows_kernel_variant_web, entry_stub, windows_entry_stub_bounds pass pass

3221225477 is 0xC0000005. So the change in core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp is what both the new tests and the guest_zero_finalizer result turn on. I haven't looked into why the converted program crashes there, so I can't point at a line.

Please merge main into the branch, which brings the test in, and make guest_zero_finalizer pass on Windows with the stub change. I'll rerun these ten tests on the new head.

AI-assisted: yes (Claude Code)

@github-actions github-actions Bot removed the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 5, 2026
@JJenkx

JJenkx commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Windows check of head 8029f87e58, merged onto main 49f3653632 (ddd024df78, clean merge).

Setup: Windows 11 Enterprise 22621, WinLibs GCC 15.2 UCRT, Release. The hosted Windows check does not run these tests on pull requests.

  • windows_guest_main_stack, windows_guest_main_stack_entry, windows_guest_main_stack_failure, windows_import_modules, windows_kernel_variant_sys, windows_kernel_variant_web, windows_trace_imports pass in 3 of 3 runs, none skipped.

AI-assisted: yes.

@oneandonlydean
oneandonlydean dismissed adriadam10’s stale review November 9, 2026 09:55

Met: Windows title runs with this PR alone were posted on 10-25 (ccleste, ScreenTester5, a PPSA title) and the branch is mergeable. BunnyFl's guest_zero_finalizer request still stands.

@relativespace2K

Copy link
Copy Markdown
Contributor

Checked on Windows (11 IoT Enterprise LTSC 26100, WinLibs GCC 15.2, Release), head 8029f87e58 merged with main 11673672d9 (289ffa8d42).

Reproduces the CR: ctest -R guest_zero_finalizer -> AssertionError: ('windows', True, 3221225477, '', '', '') on the zero case, no events.txt.

Cause: GuestModuleArgsHost.cpp is still built with the libkernel ABI, but the stub now calls the new libc export.

  • WindowsEntryStubBuilder.cpp resolves EnterGuestMainStack_nid_no_patch from libc.prx and emits lea rcx, <guest entry>; call rax (48 8d 0d + ff d0). That register is right: the export added in GuestStacks.hpp/GuestStacks.cpp has no APS5_VABI, so it uses the Microsoft x64 convention, the same as TraceImport_nid_no_patch, which the same stub also calls with RCX.
  • core/relinker/elfpatcher/tests/GuestModuleArgsHost.cpp:65, the stand-in that test_guest_zero_finalizer.py:66 copies in as libc.prx, still declares APS5_VABI EnterGuestMainStack_nid_no_patch(void* arguments, void (*entry)(void*)). On Windows APS5_VABI is __attribute__((sysv_abi)), so the callee takes both arguments from RDI/RSI and calls whatever RSI holds; the stub sets neither.
  • gdb at the fault: RIP 0x4233d0 (zero-filled image), RCX 0x43e51a = the guestEntryStart prologue (push rbx; push rbp; push rsi; push rdi; push r12; sub rsp,0x60), backtrace #0 0x4233d0, #1 EnterGuestMainStack_nid_no_patch.

Fixture-only fix makes it pass (the stub stays untouched):

-extern "C" [[noreturn]] void APS5_VABI EnterGuestMainStack_nid_no_patch(void* arguments, void (APS5_VABI* entry)(void*)) {
-    entry(arguments);
+extern "C" [[noreturn]] void EnterGuestMainStack_nid_no_patch(void (*entry)()) {
+    entry();
     Fail("The guest entry point returned");
 }

With it: ctest -R "windows_guest_main_stack|guest_zero_finalizer|windows_trace_imports|windows_kernel_variant" 7/7 pass, including windows_guest_main_stack_entry, which relinks and runs an executable against the real libc.prx and is the test that exercises the RCX call end to end. windows_import_modules did not run in my tree (it wants windows_stdio_host_ucrt.dll, which I did not build).

One thing to settle: the same symbol would have two ABIs inside one process - libc exports the 1-argument MS-x64 copy for the stub, while libkernel still exports the 2-argument APS5_VABI one (Pthread/src/Thread.cpp:245) for guest imports. Nothing here exercises the libkernel copy, so I would not block on it, but if you prefer one ABI, declare the libc copy APS5_VABI with two arguments as well and have the stub pass xor edi,edi; lea rsi,[rip+entry].

eliasbruno124-dev and others added 5 commits November 12, 2026 09:50
… guest main-stack entry

The Windows entry stub now requires the host libc to export EnterGuestMainStack_nid_no_patch. The kernel variant test installs a synthetic libc.prx (the runtime image, or the empty image in the failure cases) that did not, so every case that runs the converted executable stopped with 'host libc does not provide guest main-stack entry' before reaching the import it checks. Give both images the export, as test_windows_import_modules.py does for its providers.
@eliasbruno124-dev
eliasbruno124-dev force-pushed the fix/windows-guest-main-stack branch from 8029f87 to bc0ee29 Compare November 12, 2026 09:30
@eliasbruno124-dev

Copy link
Copy Markdown
Contributor Author

@BunnyFl @Superseabas @relativespace2K thank you for the reports and the trace. The branch is rebased onto main 439f320158, which brings guest_zero_finalizer in, and has one new commit; the head is bc0ee29e4c.

Cause, as @relativespace2K found: #7532 added EnterGuestMainStack_nid_no_patch for Linux as APS5_VABI (void* arguments, void (APS5_VABI* entry)(void*)), and GuestModuleArgsHost.cpp defines it that way, while this branch exported a one-argument Microsoft-convention function of the same name from libc and called it with the entry in rcx.

Fix: of the two options in that comment I took the second, one signature for the name. The libc export now has the Linux signature and passes arguments to the entry in rdi; the Windows stub calls it with xor edi, edi; lea rsi, [rip+entry]; call rax. GuestModuleArgsHost.cpp is untouched. The Python fixtures' helper is jmp rsi instead of jmp rcx, and WindowsGuestMainStack.cpp checks that the argument pointer arrives.

Tested on Windows 11 Pro 10.0.26300, MSYS2 UCRT64 GCC 16.2.0-6, Release, full build of bc0ee29e4c alone:

  • All 247 tests of the relinker directory pass, as on main 439f320158.
  • guest_zero_finalizer, guest_module_args, the three windows_guest_main_stack* tests, windows_import_modules, windows_trace_imports, both windows_kernel_variant tests, entry_stub, windows_entry_stub_bounds, guest_kernel_is_stack and guest_pthread_stack pass in 3 of 3 runs; the 65 public_headers checks pass.
  • Negative control: with the previous commit's WindowsEntryStubBuilder.cpp and only the relinker rebuilt, guest_zero_finalizer and five of the Windows tests fail; with the file restored all 13 pass.
  • Castlevania Dominus Collection PPSA15645 runs for 100 s at 600 presents per 10 s on this head and on main alike, each converted with its own relinker.

Not tested: Linux and macOS. The description is updated; the title evidence from earlier heads is marked as such.

AI-assisted: yes.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@eliasbruno124-dev, the code looks right to me on bc0ee29 and I am recording a PASS. The sysv signature now matches the GuestModuleArgsHost fixture that failed before, and the stub, unwind entry and tests are consistent. One question for the merger, not a request for a change: with this PR the main thread's TEB DeallocationStack points at the arena allocation, and main's scePthreadExit still calls ReleaseThread and _endthreadex(0) without restoring the host bounds (#7149 is open for that). If a title's main thread exits while workers are still running, Windows could free that region behind the arena. Can you say whether you tested that case, or whether it should wait for #7149?

@BunnyFl BunnyFl 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.

@eliasbruno124-dev thanks: bc0ee29e4c fixes what my change request asked for (the runs below), and I'm approving it. Thanks also to @relativespace2K for the trace that found the cause and @Superseabas for the original report.

I reran the ten tests from my 2026-11-05 request plus guest_module_args, on this head merged onto main 3b7f31fa70 (merge 6c11fc7412, clean), Windows 11 Pro 10.0.26300, WinLibs GCC 15.2, Release, with relinker, guest_module_args_host and both windows_guest_main_stack* executables rebuilt:

Test the merge the merge with WindowsEntryStubBuilder.cpp taken from main
guest_zero_finalizer passes passes
windows_guest_main_stack_entry passes fails: AssertionError: (89, 'Transferring control to ELF entry point\n', '')
windows_import_modules passes fails: AssertionError: (11, 'Transferring control to ELF entry point\n', '')
guest_module_args, windows_guest_main_stack, windows_guest_main_stack_failure, windows_trace_imports, windows_kernel_variant_sys, windows_kernel_variant_web, entry_stub, windows_entry_stub_bounds pass pass

So 11 of 11 pass on the merge, none Not Run; guest_zero_finalizer, which failed at 8029f87e58 with 0xC0000005 (my change request), passes now.

The new commit reads as you describe: EnterGuestMainStack_nid_no_patch in core/libs/prx/libc/src/GuestStacks.cpp now takes (void* arguments, void (APS5_VABI* entry)(void*)) and puts arguments in Rdi for the entry, and the stub in core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp emits xor edi, edi (31 ff) and loads the entry with lea rsi, [rip+...] (48 8d 35) where it used rcx before.

Overlap: tools/pr_overlap.py --branch on this head failed closed (exit 2). 50 open pull requests share a file but conflict with main; the tool printed "cannot confirm overlap" for each. Most share only core/libs/prx/libc/CMakeLists.txt or docs/dev/debt/libc.md. Six share code this PR changes: #7149 and #9938 (GuestStacks.hpp/GuestStacks.cpp), and #11628, #11661, #11689 and #11698 (WindowsEntryStubBuilder.cpp). I searched those six patches' changed lines for EnterGuestMainStack and for the stub's entry-load bytes; none of them touches either. I did not compare the other 44 line by line.

Not tested: Linux and macOS, a title, and the main-thread-exit case @oneandonlydean asked you about, which is yours to answer.

AI-assisted: yes (Claude Code)

@github-actions github-actions Bot added the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 12, 2026
@eliasbruno124-dev

Copy link
Copy Markdown
Contributor Author

@oneandonlydean thank you. I had not tested that case, so I measured it now. It is one scratch program on one machine, not a test in the PR.

What ran: a program linked against libc.prx and libkernel.prx of a build that contains bc0ee29e4c (main 439f320158 with this PR; #18116, #18119, #18085, #11630 and #17570 are merged in the same tree and touch neither library's stack code). The main thread enters EnterGuestMainStack_nid_no_patch, adopts itself with scePthreadSelf, starts a worker with scePthreadCreate and calls scePthreadExit. The worker waits for the main thread's handle, then walks the main thread's former stack range with VirtualQuery and writes to its top page. Windows 11 Pro 10.0.26300, MSYS2 UCRT64 GCC 16.2.0-6, 3 runs, identical each time.

On the arena stack (this PR), output abridged:

before the main thread exits: base=0x200210000 limit=0x200010000 deallocation=0x200000000
  [0x200000000, 0x200010000) allocationBase=0x7fff0000 state=0x2000 protect=0     (64 KiB reserved)
  [0x200010000, 0x200210000) 512 pages, state=0x1000 protect=0x4                  (2048 KiB committed read-write)
main thread wait=0 exit code=0
after the main thread exited: the same 64 KiB reserved and 512 committed read-write pages
  original host stack [0xbe40600000, 0xbe40800000): top page state=0x1000 allocationBase=0xbe40600000
  top page still writable: 1

Control, the same program without the stack switch (the main thread exits on its host stack): afterwards the whole host stack range is state=0x10000 (free).

So in this run Windows did not free the arena range when the main thread exited with a worker still running: the range stayed mapped and writable. DeallocationStack (0x200000000) lies inside the arena's reservation, whose allocation base is 0x7fff0000, so it is not the base of an allocation; I take that to be why the release has no effect, but I did not trace the call. What does change is that the original 2 MiB host stack is no longer released at thread exit and stays committed until the process ends.

Not covered: other Windows builds, a real title whose main thread exits this way, what the arena's own bookkeeping does with that range afterwards (nothing releases it; the PR keeps the stack until process termination by design), and the main-thread exit integration that #7149 changes. Whether this should wait for #7149 is your call; this branch does not touch scePthreadExit.

Program
#define _WIN32_WINNT 0x0602
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestStacks.hpp"
#include "prx/libkernel/include/Api.hpp"
#include "prx/libkernel/Pthread/include/Pthread.hpp"
#include "prx/libkernel/Pthread/include/ThreadLifecycle.hpp"
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <windows.h>

static std::uintptr_t stackBase;
static std::uintptr_t stackLimit;
static std::uintptr_t stackDeallocation;
static HANDLE mainThread;
static std::uintptr_t hostBase;
static std::uintptr_t hostDeallocation;

static void Report(const char* label) {
    std::printf("%s: base=%#zx limit=%#zx deallocation=%#zx\n", label, stackBase, stackLimit, stackDeallocation);
    for (auto cursor = stackDeallocation; cursor < stackBase;) {
        MEMORY_BASIC_INFORMATION memory{};
        if (VirtualQuery(reinterpret_cast<void*>(cursor), &memory, sizeof(memory)) != sizeof(memory)) {
            std::printf("  VirtualQuery failed at %#zx (%lu)\n", cursor, GetLastError());
            break;
        }
        const auto begin = reinterpret_cast<std::uintptr_t>(memory.BaseAddress);
        const auto end = begin + memory.RegionSize;
        std::printf("  [%#zx, %#zx) allocationBase=%#zx state=%#lx protect=%#lx type=%#lx\n", begin, end < stackBase ? end : stackBase,
                    reinterpret_cast<std::uintptr_t>(memory.AllocationBase), memory.State, memory.Protect, memory.Type);
        cursor = end;
    }
    std::printf("  arena contains the writable range: %d\n",
                static_cast<int>(GuestArena::GuestArenaContains_nid_postfix(reinterpret_cast<void*>(stackLimit), stackBase - stackLimit)));
    std::fflush(stdout);
}

static void* APS5_VABI Worker(void*) {
    const DWORD waited = WaitForSingleObject(mainThread, 10000);
    DWORD code = 0;
    GetExitCodeThread(mainThread, &code);
    std::printf("main thread wait=%lu exit code=%lu\n", waited, code);
    Report("after the main thread exited");
    MEMORY_BASIC_INFORMATION host{};
    VirtualQuery(reinterpret_cast<void*>(hostBase - 0x1000), &host, sizeof(host));
    std::printf("  original host stack [%#zx, %#zx): top page state=%#lx allocationBase=%#zx\n", hostDeallocation, hostBase, host.State, reinterpret_cast<std::uintptr_t>(host.AllocationBase));
    MEMORY_BASIC_INFORMATION memory{};
    VirtualQuery(reinterpret_cast<void*>(stackBase - 0x1000), &memory, sizeof(memory));
    if (memory.State == MEM_COMMIT && memory.Protect == PAGE_READWRITE) {
        volatile unsigned char* top = reinterpret_cast<volatile unsigned char*>(stackBase - 0x1000);
        top[0] = 0x5a;
        std::printf("  top page still writable: %d\n", top[0] == 0x5a);
    } else {
        std::printf("  top page is no longer committed read-write\n");
    }
    std::fflush(stdout);
    ExitProcess(0);
    return nullptr;
}

static void APS5_VABI OnStack(void*) {
    auto* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
    stackBase = reinterpret_cast<std::uintptr_t>(tib->StackBase);
    stackLimit = reinterpret_cast<std::uintptr_t>(tib->StackLimit);
    stackDeallocation = *reinterpret_cast<std::uintptr_t*>(reinterpret_cast<unsigned char*>(tib) + 0x1478);
    Report("before the main thread exits");
    if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &mainThread, 0, FALSE, DUPLICATE_SAME_ACCESS)) std::abort();
    if (scePthreadSelf() == nullptr) std::abort();
    Pthread worker = nullptr;
    if (scePthreadCreate(&worker, nullptr, Worker, nullptr, "worker") != 0) std::abort();
    scePthreadExit(nullptr);
    std::abort();
}

int main(int argc, char**) {
    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
    std::setvbuf(stdout, nullptr, _IONBF, 0);
    auto* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
    hostBase = reinterpret_cast<std::uintptr_t>(tib->StackBase);
    hostDeallocation = *reinterpret_cast<std::uintptr_t*>(reinterpret_cast<unsigned char*>(tib) + 0x1478);
    if (argc > 1) OnStack(nullptr);
    GuestStacks::EnterGuestMainStack_nid_no_patch(nullptr, OnStack);
}

AI-assisted: yes.

@oneandonlydean
oneandonlydean merged commit 27dae25 into boykopovar:main Nov 14, 2026
22 of 23 checks passed
@github-actions github-actions Bot removed the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

build docs libc relinker unblocks title Names a title ID on the Unblocks line

Projects

None yet

Development

Successfully merging this pull request may close these issues.