fix(libkernel): measure the Apple guest stack at the call #16790

Open
wanderingbug wants to merge 1 commit from upstream-pr/16790 into main
wanderingbug commented 2026-11-07 16:41:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by wanderingbug on 2026-11-07T16:41:25Z.


What

Open #16801 (fix/macos-test-compile, 38bddbff44) edits only ResourceRequest.cpp, RtcpTransportFeedback.cpp, and GuestCesGbSetters.cpp: <initializer_list> and ResourceRequestBase value initialization. None of those symbols are in this pull request.

Darwin has no pthread_getattr_np. CallGuestOnMeasuredStack samples the stack pointer, reads the existing HostStackLimits window, and calls the guest from that window. The extra host margin is Apple-only. The test is MeasuredGuestStack, with its own header and CMake entry.

This replaces closed #12112. That patch edited GuestThreadSelf.cpp. This one does not. Open #7804 also queries the Apple stack limits and is not in this branch. HostStackLimits is already on main, so this is not a code dependency on #7804. The Mac integration build did include test-only #7804 (5e944037) and #4630 (5f4bbc87).

Tested

measured_guest_stack exited 0 in one cache-reuse run on an Apple M2 Max, macOS 27.2, x86_64 under Rosetta. The tree was snapshot 7a6e44ece4 plus overlays 671d12cf, 5f4bbc87, 42f65a4b, e074d9c7, 203b4744, and e72d276e. This head was not rebuilt by itself on current main. Not tested on a second machine; no game tested.

Checklist

  • Based on current main; no other open PR implements the same functions. Unchecked: parent is 30a863d12d, and upstream main is now daad891ea6. #16801 does not implement these functions. Other open pull requests were not fully scanned.
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt. The diff adds no // comments. The debt note is in docs/dev/debt/libkernel.md.
  • Unimplemented paths throw. Unchecked: the new call path was not re-audited line by line in this pass.
  • No notes, investigation .md files or images added to the repository. Existing development documentation is edited; maintainer confirmation of this rule is still needed
  • New third-party code is a submodule built from source. No 3rdparty/ change.
  • Generic behaviour, not specific to one title
  • Depends on: none. Test-only #7804 and #4630 were in the Mac tree and are not in this branch.
  • Fixes: none found in this pass. No issue search.
  • Unblocks: none claimed. No title bring-up check.
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5203757930 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/16790). Originally posted by [wanderingbug](https://github.com/wanderingbug) on 2026-11-07T16:41:25Z. --- ### What Open #16801 (`fix/macos-test-compile`, `38bddbff44`) edits only `ResourceRequest.cpp`, `RtcpTransportFeedback.cpp`, and `GuestCesGbSetters.cpp`: `<initializer_list>` and `ResourceRequestBase` value initialization. None of those symbols are in this pull request. Darwin has no `pthread_getattr_np`. `CallGuestOnMeasuredStack` samples the stack pointer, reads the existing `HostStackLimits` window, and calls the guest from that window. The extra host margin is Apple-only. The test is `MeasuredGuestStack`, with its own header and CMake entry. This replaces closed #12112. That patch edited `GuestThreadSelf.cpp`. This one does not. Open #7804 also queries the Apple stack limits and is not in this branch. `HostStackLimits` is already on `main`, so this is not a code dependency on #7804. The Mac integration build did include test-only #7804 (`5e944037`) and #4630 (`5f4bbc87`). ### Tested `measured_guest_stack` exited 0 in one cache-reuse run on an Apple M2 Max, macOS 27.2, x86_64 under Rosetta. The tree was snapshot `7a6e44ece4` plus overlays `671d12cf`, `5f4bbc87`, `42f65a4b`, `e074d9c7`, `203b4744`, and `e72d276e`. This head was not rebuilt by itself on current `main`. Not tested on a second machine; no game tested. ### Checklist - [ ] Based on current `main`; no other open PR implements the same functions. Unchecked: parent is `30a863d12d`, and upstream `main` is now `daad891ea6`. #16801 does not implement these functions. Other open pull requests were not fully scanned. - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except technical debt. The diff adds no `//` comments. The debt note is in `docs/dev/debt/libkernel.md`. - [ ] Unimplemented paths throw. Unchecked: the new call path was not re-audited line by line in this pass. - [ ] No notes, investigation `.md` files or images added to the repository. Existing development documentation is edited; maintainer confirmation of this rule is still needed - [x] New third-party code is a submodule built from source. No `3rdparty/` change. - [x] Generic behaviour, not specific to one title - [x] Depends on: none. Test-only #7804 and #4630 were in the Mac tree and are not in this branch. - [ ] Fixes: none found in this pass. No issue search. - [ ] Unblocks: none claimed. No title bring-up check. - [x] GPUs tested: n/a - [x] AI-assisted: yes
gabichuuuuu commented 2026-11-07 17:07:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gabichuuuuu on 2026-11-07T17:07:46Z.

Review: COMMENTED


Two points from reading bd60dd0d5b; not run here, since I have no Mac.

  • stackAddress and stackSize change after the thread is published. StartNativeThread sets stackAddress before initialized.set_value(), and the creator gets the handle from there. On Apple, CallGuestOnMeasuredStack then writes both fields again from the new thread, without a lock. scePthreadAttrGet (Pthread/src/Attr.cpp) and pthread_attr_get_np (Pthread/Posix/Attr.cpp) read them under CpuClocks().lock through LockLiveGuestThread, so those reads and this write race. It is also visible without any race: for a thread created suspended, scePthreadAttrGet before scePthreadResume returns the old window, the one the test shows does not hold the guest frames, and after the resume it returns another one. Writing the two fields under LockRegisteredGuestThread(self) would fix the race. The suspended case would still need a debt note, or the window chosen before initialized.set_value(). Also, with RegisterStack moved into CallGuestOnMeasuredStack on Apple, a suspended thread is not in liveStacks until it resumes.
  • The overrun case in MeasuredGuestStack.cpp passes without the reserve check. Require(overrun.low < shortHostLow + hostMargin || overrun.high == 0) is also true for a window that runs into the host margin, which is exactly the result the check exists to prevent. With the if (low < hostLow + hostReserve) return window; line removed from MeasureGuestStackWindow, all four checks still pass in a Python model of the function, and the overrun case returns a window inside the margin. Require(overrun.high == 0 && overrun.low == 0) would catch that.

A smaller one: HostCallDepth measures high - rsp in a probe thread's start routine, which is about what MeasureStackReserve measures, plus a page. It is not measured at the call in CallGuestOnMeasuredStack, below StartNativeThread (with its jmp_buf) and RunThread. The debt note's "the measured depth of a host probe at that call" overstates it: the extra page is an assumption.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5813908860 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/16790#pullrequestreview-5813908860). Originally posted by [gabichuuuuu](https://github.com/gabichuuuuu) on 2026-11-07T17:07:46Z. **Review:** COMMENTED --- Two points from reading `bd60dd0d5b`; not run here, since I have no Mac. - **`stackAddress` and `stackSize` change after the thread is published.** `StartNativeThread` sets `stackAddress` before `initialized.set_value()`, and the creator gets the handle from there. On Apple, `CallGuestOnMeasuredStack` then writes both fields again from the new thread, without a lock. `scePthreadAttrGet` (`Pthread/src/Attr.cpp`) and `pthread_attr_get_np` (`Pthread/Posix/Attr.cpp`) read them under `CpuClocks().lock` through `LockLiveGuestThread`, so those reads and this write race. It is also visible without any race: for a thread created suspended, `scePthreadAttrGet` before `scePthreadResume` returns the old window, the one the test shows does not hold the guest frames, and after the resume it returns another one. Writing the two fields under `LockRegisteredGuestThread(self)` would fix the race. The suspended case would still need a debt note, or the window chosen before `initialized.set_value()`. Also, with `RegisterStack` moved into `CallGuestOnMeasuredStack` on Apple, a suspended thread is not in `liveStacks` until it resumes. - **The overrun case in `MeasuredGuestStack.cpp` passes without the reserve check.** `Require(overrun.low < shortHostLow + hostMargin || overrun.high == 0)` is also true for a window that runs into the host margin, which is exactly the result the check exists to prevent. With the `if (low < hostLow + hostReserve) return window;` line removed from `MeasureGuestStackWindow`, all four checks still pass in a Python model of the function, and the overrun case returns a window inside the margin. `Require(overrun.high == 0 && overrun.low == 0)` would catch that. A smaller one: `HostCallDepth` measures `high - rsp` in a probe thread's start routine, which is about what `MeasureStackReserve` measures, plus a page. It is not measured at the call in `CallGuestOnMeasuredStack`, below `StartNativeThread` (with its `jmp_buf`) and `RunThread`. The debt note's "the measured depth of a host probe at that call" overstates it: the extra page is an assumption. AI-assisted: yes.
adriadam10 commented 2026-11-11 10:17:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-11-11T10:17:43Z.

Review: CHANGES_REQUESTED


Read through the diff; nothing was run (no Mac here, and the Apple path is #ifdef __APPLE__). Points to fix:

  • core/libs/prx/libkernel/Pthread/src/Thread.cpp:988-990: stackAddress/stackSize are rewritten from the new thread after StartNativeThread already published them, without a lock. scePthreadAttrGet and pthread_attr_get_np read them under LockLiveGuestThread, so this races. Write both under LockRegisteredGuestThread(self), or choose the window before initialized.set_value().
  • Thread.cpp:990 / :1006: moving RegisterStack into CallGuestOnMeasuredStack leaves a thread created suspended out of liveStacks until it is resumed, and scePthreadAttrGet before the resume returns the old window. Fix it or record it in the debt file.
  • core/libs/tests/MeasuredGuestStack.cpp:44: overrun.low < shortHostLow + hostMargin || overrun.high == 0 is also true for a window that runs into the host margin, which is what the reserve check prevents. With the low < hostLow + hostReserve line removed from MeasureGuestStackWindow all checks still pass. Use Require(overrun.high == 0 && overrun.low == 0).
  • The test only exercises the pure helper, not CallGuestOnMeasuredStack/HostCallDepth; please say in Tested how the Apple path itself was verified on this head (the reported run was a different tree).
  • docs/dev/debt/libkernel.md:267: "the measured depth of a host probe at that call" is not accurate: HostCallDepth (Thread.cpp:861-875) measures in a probe thread's start routine, not below StartNativeThread/RunThread, and the extra page is an assumption. Say so.
  • Conventions is failing and the body has unchecked boxes. Please rebase on current main, tick the checklist, and fill Fixes/Unblocks.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5857174383 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/16790#pullrequestreview-5857174383). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-11-11T10:17:43Z. **Review:** CHANGES_REQUESTED --- Read through the diff; nothing was run (no Mac here, and the Apple path is `#ifdef __APPLE__`). Points to fix: - `core/libs/prx/libkernel/Pthread/src/Thread.cpp:988-990`: `stackAddress`/`stackSize` are rewritten from the new thread after `StartNativeThread` already published them, without a lock. `scePthreadAttrGet` and `pthread_attr_get_np` read them under `LockLiveGuestThread`, so this races. Write both under `LockRegisteredGuestThread(self)`, or choose the window before `initialized.set_value()`. - `Thread.cpp:990` / `:1006`: moving `RegisterStack` into `CallGuestOnMeasuredStack` leaves a thread created suspended out of `liveStacks` until it is resumed, and `scePthreadAttrGet` before the resume returns the old window. Fix it or record it in the debt file. - `core/libs/tests/MeasuredGuestStack.cpp:44`: `overrun.low < shortHostLow + hostMargin || overrun.high == 0` is also true for a window that runs into the host margin, which is what the reserve check prevents. With the `low < hostLow + hostReserve` line removed from `MeasureGuestStackWindow` all checks still pass. Use `Require(overrun.high == 0 && overrun.low == 0)`. - The test only exercises the pure helper, not `CallGuestOnMeasuredStack`/`HostCallDepth`; please say in Tested how the Apple path itself was verified on this head (the reported run was a different tree). - `docs/dev/debt/libkernel.md:267`: "the measured depth of a host probe at that call" is not accurate: `HostCallDepth` (`Thread.cpp:861-875`) measures in a probe thread's start routine, not below `StartNativeThread`/`RunThread`, and the extra page is an assumption. Say so. - Conventions is failing and the body has unchecked boxes. Please rebase on current `main`, tick the checklist, and fill `Fixes`/`Unblocks`.
MarcZX10 commented 2026-11-21 05:02:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-21T05:02:58Z.

Review: COMMENTED


Reviewed — no blocking findings

The Apple-specific stack placement and its focused unit test are present in the reviewed head; the source and test code were read, but no build or test was run in this review.

What I ran

Reviewed head bd60dd0d5b5ef909a00bbc1da9e62ad93b9fc336 against base main. Used repo_read.py to inspect the prepared diff and changed-file source ranges; no commands or tests were run.

Results

Check Result Note
Diff and changed lines passed All five changed files read
Build and tests not run No local run performed
Apple host behavior not run No console or host runtime run

Findings

Blocking

None.

Non-blocking

  • The description reports one cache-reuse test run on an Apple M2 Max, macOS 27.2, x86_64 under Rosetta, on an overlay tree rather than this exact head. This review did not independently verify that run.
  • The debt note says the Apple stack query still depends on open pull request #7804, while the description says HostStackLimits is already on main. The reviewed diff calls HostStackLimits on the Apple path, but this review did not verify the base history or #7804's status.

Not verified

No build, automated test, or runtime behavior was verified. description.md and commits.md were read. All five changed files listed in manifest.json were read at the relevant changed lines, including the stack helper, the changed thread functions, the new test, the CMake test registration, and the debt note. No changed files were excluded.

To get this to a good state

Nothing is required. Optional: reconcile the debt note's #7804 dependency statement with the current base and clarify the reported test tree's relationship to this head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6002964801 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/16790#pullrequestreview-6002964801). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-21T05:02:58Z. **Review:** COMMENTED --- # Reviewed — no blocking findings The Apple-specific stack placement and its focused unit test are present in the reviewed head; the source and test code were read, but no build or test was run in this review. ## What I ran Reviewed head `bd60dd0d5b5ef909a00bbc1da9e62ad93b9fc336` against base `main`. Used `repo_read.py` to inspect the prepared diff and changed-file source ranges; no commands or tests were run. ## Results | Check | Result | Note | |---|---|---| | Diff and changed lines | passed | All five changed files read | | Build and tests | not run | No local run performed | | Apple host behavior | not run | No console or host runtime run | ## Findings ### Blocking None. ### Non-blocking - The description reports one cache-reuse test run on an Apple M2 Max, macOS 27.2, x86_64 under Rosetta, on an overlay tree rather than this exact head. This review did not independently verify that run. - The debt note says the Apple stack query still depends on open pull request #7804, while the description says `HostStackLimits` is already on `main`. The reviewed diff calls `HostStackLimits` on the Apple path, but this review did not verify the base history or #7804's status. ## Not verified No build, automated test, or runtime behavior was verified. `description.md` and `commits.md` were read. All five changed files listed in `manifest.json` were read at the relevant changed lines, including the stack helper, the changed thread functions, the new test, the CMake test registration, and the debt note. No changed files were excluded. ## To get this to a good state Nothing is required. Optional: reconcile the debt note's #7804 dependency statement with the current base and clarify the reported test tree's relationship to this head.
ligmaSec commented 2026-12-03 16:20:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T16:20:33Z.

Review: COMMENTED


I compiled and ran the branch's MeasuredGuestStack fixture on Linux. It passed the standalone window arithmetic checks. The branch conflicts with main, and the actual pthread stack measurement at the call site still needs macOS coverage.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6173793327 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/16790#pullrequestreview-6173793327). Originally posted by [ligmaSec](https://github.com/ligmaSec) on 2026-12-03T16:20:33Z. **Review:** COMMENTED --- I compiled and ran the branch's `MeasuredGuestStack` fixture on Linux. It passed the standalone window arithmetic checks. The branch conflicts with main, and the actual pthread stack measurement at the call site still needs macOS coverage. AI-assisted: yes.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/16790:upstream-pr/16790'
git switch 'upstream-pr/16790'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/16790'
git switch 'upstream-pr/16790'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/16790'
git switch 'upstream-pr/16790'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/16790'
git switch 'main'
git merge --squash 'upstream-pr/16790'
git switch 'main'
git merge --ff-only 'upstream-pr/16790'
git switch 'main'
git merge 'upstream-pr/16790'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!16790
No description provided.