fix(libkernel): return EACCES for unknown ranges on direct-memory release paths #7105

Closed
Pouare514 wants to merge 1 commit from upstream-pr/7105 into main
Pouare514 commented 2026-10-17 11:51:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-17T11:51:41Z.


What

  • Release-path error behavior only (no locking/race claims): ForgetDirectMemory throws EACCES (system_error) for unknown but well-formed ranges (invalid_argument for malformed preserved); new non-throwing TryForgetDirectMemory pre-check; sceKernelReleaseDirectMemory returns EACCES for unknown/double-free (EINVAL for malformed preserved); DirectMemoryFree returns bool (false for unknown/misaligned); MemoryPool::_release early false for misaligned plus existing lenient spanning walk retained for current tests; PoolCommit saturate plus torn-len EINVAL; one debt line.
  • Dropped from prior revision: _mapFlexible check/unlock/map/relock split (kept single-lock), AddMapping snapshot-Map-outside/rollback/re-validate (kept under g_directLock), 64MiB torn-descriptor guard, DoMapDirect lock narrowing, TryValidatePhysicalRange (only TryForget kept).
  • Motivation: sane error behavior on release paths (Deathloop triage context only; no use-after-free claim).

Tested

  • New CheckReleaseUnknownRangeReturnsAccessError (single-threaded pin, no concurrency claims): double-release->EACCES, misaligned CheckedFree->false, bad-map still throws invalid_argument, Query(-1)->false. FAILS on main (throws invalid_argument, aborts) and PASSES with fix (verified both directions via stash; Windows Release).
  • ctest -R "guest_memory|guest_mmap|MemoryPoolTest|guest_memory_pool_stats": 4/4 pass on Windows (winlibs gcc15, Release). Linux left to PR CI.
  • git diff --check clean, python tools/check_conventions.py --base origin/main --head HEAD clean. No title run.

Checklist

  • Based on current main (c9e6c45de); no other open PR implements the same change
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • No new unimplemented paths or silent stubs
  • No notes, investigation files or images added to the repository
  • New third-party code: none
  • Generic behaviour, not specific to one title
  • Depends on: none (overlaps audited: #4449 REBASE-ONLY, #5021 REBASE-ONLY, #6044 REBASE-ONLY, #6222 REBASE-ONLY, #6542 REBASE-ONLY, #6565 REBASE-ONLY; #6491 no overlap, #6879 no overlap)
  • Unblocks: none
  • GPUs tested: n/a for this libkernel error-path change
  • AI-assisted: yes; I am responsible for this change
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4899811788 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7105). Originally posted by [Pouare514](https://github.com/Pouare514) on 2026-10-17T11:51:41Z. --- ### What - Release-path error behavior only (no locking/race claims): `ForgetDirectMemory` throws `EACCES` (`system_error`) for unknown but well-formed ranges (`invalid_argument` for malformed preserved); new non-throwing `TryForgetDirectMemory` pre-check; `sceKernelReleaseDirectMemory` returns `EACCES` for unknown/double-free (`EINVAL` for malformed preserved); `DirectMemoryFree` returns `bool` (`false` for unknown/misaligned); `MemoryPool::_release` early `false` for misaligned plus existing lenient spanning walk retained for current tests; `PoolCommit` saturate plus torn-len `EINVAL`; one debt line. - Dropped from prior revision: `_mapFlexible` check/unlock/map/relock split (kept single-lock), `AddMapping` snapshot-Map-outside/rollback/re-validate (kept under `g_directLock`), 64MiB torn-descriptor guard, `DoMapDirect` lock narrowing, `TryValidatePhysicalRange` (only `TryForget` kept). - Motivation: sane error behavior on release paths (Deathloop triage context only; no use-after-free claim). ### Tested - New `CheckReleaseUnknownRangeReturnsAccessError` (single-threaded pin, no concurrency claims): double-release->`EACCES`, misaligned `CheckedFree`->`false`, bad-map still throws `invalid_argument`, `Query(-1)`->`false`. FAILS on main (throws `invalid_argument`, aborts) and PASSES with fix (verified both directions via stash; Windows Release). - `ctest -R "guest_memory|guest_mmap|MemoryPoolTest|guest_memory_pool_stats"`: 4/4 pass on Windows (winlibs gcc15, Release). Linux left to PR CI. - `git diff --check` clean, `python tools/check_conventions.py --base origin/main --head HEAD` clean. No title run. ### Checklist - [x] Based on current main (c9e6c45de); no other open PR implements the same change - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except technical debt - [x] No new unimplemented paths or silent stubs - [x] No notes, investigation files or images added to the repository - [x] New third-party code: none - [x] Generic behaviour, not specific to one title - [x] Depends on: none (overlaps audited: #4449 REBASE-ONLY, #5021 REBASE-ONLY, #6044 REBASE-ONLY, #6222 REBASE-ONLY, #6542 REBASE-ONLY, #6565 REBASE-ONLY; #6491 no overlap, #6879 no overlap) - [x] Unblocks: none - [x] GPUs tested: n/a for this libkernel error-path change - [x] AI-assisted: yes; I am responsible for this change
Pouare514 commented 2026-10-17 11:52:18 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-17T11:52:18Z.


Manual overlap check for ITS files (DirectMemory.cpp/hpp, MemoryPool.cpp/hpp, MemoryPoolExport.cpp, Export.cpp, GuestMemory.cpp, debt/libkernel.md) against open PRs (via gh search prs --state open for DirectMemory/MemoryPool/GuestMemory/flexible + gh pr view --json files):

  • #6491 (open, account for fixed flexible memory replacements) — shares Export.cpp: semantic, flexible-budget accounting in the same _mapFlexible/remap area; this PR keeps their math and only narrows g_flexibleLock, so complementary.
  • #6515 (open, release flexible budget after direct replacements) — shares Export.cpp: semantic, budget release after direct replacements in the same file; keep their math, keep this PR's locking/validation on merge.
  • #6311 (open, release flexible memory budget through munmap) — no ITS file overlap (PosixMemory.cpp + GuestFlexibleMemoryBudget.cpp only): rebase-only, budget-theme adjacency, no action.
  • #6542 (open, map regular files with mmap on Windows) — shares DirectMemory.cpp, GuestMemory.cpp, debt/libkernel.md: semantic, mapping-path changes in the same files; rebase coordination needed, guards must be preserved.
  • #6534 (open, replace anonymous Windows stack mappings) — shares DirectMemory.cpp/hpp, debt/libkernel.md: semantic, stack-mapping work touches the same mapping API.
  • #6443 (open, protected host stack guard page / Linux main stack) — shares DirectMemory.cpp, debt/libkernel.md: semantic, adjacent stack-protection hunks in the mapping paths.
  • #6825 (open, report the read bit of every write bit) — shares DirectMemory.cpp, debt/libkernel.md: semantic, prot-reporting hunks adjacent to lifetime guards; no logic conflict expected.
  • #6469 (open, honor low guest mapping hints) — shares GuestMemory.cpp test + debt/libkernel.md only (PosixMemory.cpp otherwise): rebase-only, different area.
  • #5918 (open, precommitted stack of adopted thread) — shares debt/libkernel.md only: rebase-only.
  • #6928 (open, macOS JIT backing) — no ITS overlap (Jit.cpp only): no action.

MemoryPool.cpp/hpp and MemoryPoolExport.cpp are touched by no other open PR. Neither #6491 nor #6311 has landed (both still open), so no landed-budget reconciliation was needed; this PR changes no budget math.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6233559346 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7105#issuecomment-6233559346). Originally posted by [Pouare514](https://github.com/Pouare514) on 2026-10-17T11:52:18Z. --- Manual overlap check for ITS files (`DirectMemory.cpp/hpp`, `MemoryPool.cpp/hpp`, `MemoryPoolExport.cpp`, `Export.cpp`, `GuestMemory.cpp`, `debt/libkernel.md`) against open PRs (via `gh search prs --state open` for DirectMemory/MemoryPool/GuestMemory/flexible + `gh pr view --json files`): - #6491 (open, `account for fixed flexible memory replacements`) — shares `Export.cpp`: semantic, flexible-budget accounting in the same `_mapFlexible`/remap area; this PR keeps their math and only narrows `g_flexibleLock`, so complementary. - #6515 (open, `release flexible budget after direct replacements`) — shares `Export.cpp`: semantic, budget release after direct replacements in the same file; keep their math, keep this PR's locking/validation on merge. - #6311 (open, `release flexible memory budget through munmap`) — no ITS file overlap (`PosixMemory.cpp` + `GuestFlexibleMemoryBudget.cpp` only): rebase-only, budget-theme adjacency, no action. - #6542 (open, `map regular files with mmap on Windows`) — shares `DirectMemory.cpp`, `GuestMemory.cpp`, `debt/libkernel.md`: semantic, mapping-path changes in the same files; rebase coordination needed, guards must be preserved. - #6534 (open, `replace anonymous Windows stack mappings`) — shares `DirectMemory.cpp/hpp`, `debt/libkernel.md`: semantic, stack-mapping work touches the same mapping API. - #6443 (open, `protected host stack guard page / Linux main stack`) — shares `DirectMemory.cpp`, `debt/libkernel.md`: semantic, adjacent stack-protection hunks in the mapping paths. - #6825 (open, `report the read bit of every write bit`) — shares `DirectMemory.cpp`, `debt/libkernel.md`: semantic, prot-reporting hunks adjacent to lifetime guards; no logic conflict expected. - #6469 (open, `honor low guest mapping hints`) — shares `GuestMemory.cpp` test + `debt/libkernel.md` only (`PosixMemory.cpp` otherwise): rebase-only, different area. - #5918 (open, `precommitted stack of adopted thread`) — shares `debt/libkernel.md` only: rebase-only. - #6928 (open, macOS JIT backing) — no ITS overlap (`Jit.cpp` only): no action. `MemoryPool.cpp/hpp` and `MemoryPoolExport.cpp` are touched by no other open PR. Neither #6491 nor #6311 has landed (both still open), so no landed-budget reconciliation was needed; this PR changes no budget math.
oneandonlydean commented 2026-10-17 12:00:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T12:00:42Z.


Thanks @Pouare514 for chasing the Deathloop crash. We reviewed this at cfa5a5ee6 and can't merge it as it stands.

1. The use-after-free isn't visible on main. Every g_physPages access on main already holds g_directLock:

  • SharedBacking, WriteSharedBacking, CreateDirectMemoryBacking and ForgetDirectMemory take it themselves.
  • AddMapping and ValidatePhysicalRange are only called from RemapFixedIntoRegistered and DoMapDirect, both under the lock.

A bad phys/len makes ValidatePhysicalRange throw invalid_argument ("references unallocated physical page"); it doesn't walk freed nodes. The run26 FATAL in that function is most likely that throw, reached when the title maps a page it has already released. This PR keeps the throw in DoMapDirect, so the Deathloop stop is probably unchanged. Could you attach run26's backtrace/log and point to the unlocked access? If there isn't one, please retitle this as a release-path error change.

2. New race in _mapFlexible (blocker). On main, the budget check, DoMapAnon and the g_flexibleRanges insert all run under g_flexibleLock. The PR checks, unlocks, maps, then relocks, so two threads can both pass the check and go over the flexible size. The lock-order reason given doesn't apply: nothing takes g_flexibleLock while holding g_directLock. Please drop this hunk.

3. AddMapping maps outside the lock with no rollback. On main, validate, Map and the bookkeeping all run under g_directLock. Now the host Map (MAP_FIXED) runs unlocked, and if the second validation throws "range changed during mapping", the host mapping stays installed. In RemapFixedIntoRegistered, that leaves new pages at addr while g_directMappings still describes the old mapping. Please keep Map under the lock.

Smaller points:

  • The 64 MiB "torn-descriptor guard" in RemapFixedIntoRegistered is arbitrary, and AddMapping validates every length anyway. Please drop it.
  • sceKernelReleaseDirectMemory now returns EACCES for holes. That's fine instead of throwing, but it now matches the checked variant. It also makes the !requireAllocated walk in MemoryPool::_release unreachable. Please delete the dead branch and add a debt line for the console's unknown behaviour.

Test: CheckDeathloopPhysLifetime is single-threaded. On main it fails only because the double release throws instead of returning EACCES, so it doesn't exercise a race.

Suggested split:

  • (a) A small PR that makes release-path validation return EACCES, with a debt entry.
  • (b) Locking changes only with a reproduced race and a test with concurrent map/release threads that fails on main.

Direct memory runs in our game gates, so (b) would also need a gate run.

On any new head, CI must show guest_memory, guest_mmap, MemoryPoolTest and guest_memory_pool_stats passing on Linux and Windows.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6233635647 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7105#issuecomment-6233635647). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-17T12:00:42Z. --- Thanks @Pouare514 for chasing the Deathloop crash. We reviewed this at cfa5a5ee6 and can't merge it as it stands. **1. The use-after-free isn't visible on main.** Every `g_physPages` access on main already holds `g_directLock`: - `SharedBacking`, `WriteSharedBacking`, `CreateDirectMemoryBacking` and `ForgetDirectMemory` take it themselves. - `AddMapping` and `ValidatePhysicalRange` are only called from `RemapFixedIntoRegistered` and `DoMapDirect`, both under the lock. A bad `phys/len` makes `ValidatePhysicalRange` throw `invalid_argument` ("references unallocated physical page"); it doesn't walk freed nodes. The run26 FATAL in that function is most likely that throw, reached when the title maps a page it has already released. This PR keeps the throw in `DoMapDirect`, so the Deathloop stop is probably unchanged. Could you attach run26's backtrace/log and point to the unlocked access? If there isn't one, please retitle this as a release-path error change. **2. New race in `_mapFlexible` (blocker).** On main, the budget check, `DoMapAnon` and the `g_flexibleRanges` insert all run under `g_flexibleLock`. The PR checks, unlocks, maps, then relocks, so two threads can both pass the check and go over the flexible size. The lock-order reason given doesn't apply: nothing takes `g_flexibleLock` while holding `g_directLock`. Please drop this hunk. **3. `AddMapping` maps outside the lock with no rollback.** On main, validate, `Map` and the bookkeeping all run under `g_directLock`. Now the host `Map` (MAP_FIXED) runs unlocked, and if the second validation throws "range changed during mapping", the host mapping stays installed. In `RemapFixedIntoRegistered`, that leaves new pages at `addr` while `g_directMappings` still describes the old mapping. Please keep `Map` under the lock. **Smaller points:** - The 64 MiB "torn-descriptor guard" in `RemapFixedIntoRegistered` is arbitrary, and `AddMapping` validates every length anyway. Please drop it. - `sceKernelReleaseDirectMemory` now returns `EACCES` for holes. That's fine instead of throwing, but it now matches the checked variant. It also makes the `!requireAllocated` walk in `MemoryPool::_release` unreachable. Please delete the dead branch and add a debt line for the console's unknown behaviour. **Test:** `CheckDeathloopPhysLifetime` is single-threaded. On main it fails only because the double release throws instead of returning `EACCES`, so it doesn't exercise a race. **Suggested split:** - (a) A small PR that makes release-path validation return `EACCES`, with a debt entry. - (b) Locking changes only with a reproduced race and a test with concurrent map/release threads that fails on main. Direct memory runs in our game gates, so (b) would also need a gate run. On any new head, CI must show `guest_memory`, `guest_mmap`, `MemoryPoolTest` and `guest_memory_pool_stats` passing on Linux and Windows.
Pouare514 commented 2026-10-17 12:32:26 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-17T12:32:26Z.


Concede no unlocked access on main per re-audit: ValidatePhysicalRange DirectMemory.cpp:494, AddMapping :582, ForgetDirectMemory :1223 all run under g_directLock; _mapFlexible Export.cpp:108 is single-lock. run26 log is unavailable (run dirs cleaned, binaries only) so no backtrace can be attached; contemporaneous notes indicated AV read of -1 with rax=-1, inconsistent with a clean throw which aborts with a message, but without the log propose settling it in split (b) with a concurrent stress plus gate run rather than claiming it here; retitled as release-path error change. _mapFlexible split dropped (race acknowledged, no lock-order issue). AddMapping-outside-lock dropped, Map stays under g_directLock. 64MiB guard dropped; _release lenient walk retained (strict requires-all-used breaks 11 MemoryPoolTest cases) plus debt line added. Test reworked to honest single-threaded EACCES pin. CI: guest_memory, guest_mmap, MemoryPoolTest, guest_memory_pool_stats green on Windows; Linux left to PR CI.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6233915132 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7105#issuecomment-6233915132). Originally posted by [Pouare514](https://github.com/Pouare514) on 2026-10-17T12:32:26Z. --- Concede no unlocked access on main per re-audit: ValidatePhysicalRange DirectMemory.cpp:494, AddMapping :582, ForgetDirectMemory :1223 all run under g_directLock; _mapFlexible Export.cpp:108 is single-lock. run26 log is unavailable (run dirs cleaned, binaries only) so no backtrace can be attached; contemporaneous notes indicated AV read of -1 with rax=-1, inconsistent with a clean throw which aborts with a message, but without the log propose settling it in split (b) with a concurrent stress plus gate run rather than claiming it here; retitled as release-path error change. _mapFlexible split dropped (race acknowledged, no lock-order issue). AddMapping-outside-lock dropped, Map stays under g_directLock. 64MiB guard dropped; _release lenient walk retained (strict requires-all-used breaks 11 MemoryPoolTest cases) plus debt line added. Test reworked to honest single-threaded EACCES pin. CI: guest_memory, guest_mmap, MemoryPoolTest, guest_memory_pool_stats green on Windows; Linux left to PR CI.
Pouare514 commented 2026-10-17 12:33:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Pouare514 on 2026-10-17T12:33:05Z.


CI note on the 4 requested tests (guest_memory, guest_mmap, MemoryPoolTest, guest_memory_pool_stats): verified 4/4 green on Windows locally (WinLibs GCC 15.2, Release; run recorded in the body). The hosted Linux + Windows full builds can't run automatically for PRs - build.yml enables them only on push to main or manual workflow_dispatch ('Automatic full builds only run on main'). Requesting a collaborator dispatch the full build when the reduced scope looks good.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6233921328 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7105#issuecomment-6233921328). Originally posted by [Pouare514](https://github.com/Pouare514) on 2026-10-17T12:33:05Z. --- CI note on the 4 requested tests (guest_memory, guest_mmap, MemoryPoolTest, guest_memory_pool_stats): verified 4/4 green on Windows locally (WinLibs GCC 15.2, Release; run recorded in the body). The hosted Linux + Windows full builds can't run automatically for PRs - build.yml enables them only on push to main or manual workflow_dispatch ('Automatic full builds only run on main'). Requesting a collaborator dispatch the full build when the reduced scope looks good.
CnRJay commented 2026-11-01 19:52:35 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T19:52:35Z.

Review: COMMENTED


Points on 7105:

  1. Comments in code. core/libs/tests/GuestMemory.cpp adds a three-line comment ("Single-threaded error-behavior pin: releasing an unknown range reports EACCES..."). The rule is no comments except #endif and namespace ends.

  2. Evidence for EACCES. The description should say where the errno comes from (a measurement on a console, or the FreeBSD source for the specific release path) for each of the release paths changed, and which title hits an unknown range on main with a log line. Without it this is a guess at an errno.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5729932400 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7105#pullrequestreview-5729932400). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-11-01T19:52:35Z. **Review:** COMMENTED --- Points on 7105: 1. **Comments in code.** `core/libs/tests/GuestMemory.cpp` adds a three-line comment ("Single-threaded error-behavior pin: releasing an unknown range reports EACCES..."). The rule is no comments except `#endif` and namespace ends. 2. **Evidence for EACCES.** The description should say where the errno comes from (a measurement on a console, or the FreeBSD source for the specific release path) for each of the release paths changed, and which title hits an unknown range on main with a log line. Without it this is a guess at an errno.

Pull request closed

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!7105
No description provided.