fix(libc): validate guest heap block headers before freeing #11468

Merged
valenciana-nc merged 5 commits from upstream-pr/11468 into main 2026-10-30 01:50:20 +00:00
valenciana-nc commented 2026-10-26 15:15:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by valenciana-nc on 2026-10-26T15:15:22Z.


What

Authenticate guest-writable heap headers against trusted host-owned records of the exact user pointer, raw block start and allocator-selected size. Free validates before removing registration, changing usage or mutating free lists; realloc/realign validate before replacement allocation, including zero-size requests. This rejects the reviewed in-arena interior-pointer forgery and registered non-heap memory.

Addressed the shutdown review: blocks() now has process lifetime, matching GuestAllocations::registry(). It is deliberately not destroyed while guest threads may still allocate/free. Added guest_heap_lifetime under UNIX: a child registers an exit callback before first allocation; the callback starts a worker during static finalization, checks a retained small allocation, performs 256 allocation/free pairs, then frees the retained block. The parent verifies callback success and normal child exit. This targets the new map's lifetime, not the pre-existing large-block cache lifetime gap.

Tested

Pinned main: 3ae8209b643be054ef09542f9e9e5e951b1ed73b. Tested head: 69667d35df0329efbbab3bc9e99c9d4e2d2519b1. Windows 11 x86-64 build 26300; Intel i7-13650HX; NVIDIA GeForce RTX 4060 Laptop GPU / NVIDIA 610.62; WinLibs GCC 15.2.0 r7; Release, BUILD_TESTING=ON.

  • Windows rebuilt libraries and common controls: main 12/12, heap PR 12/12. The ownership/corruption regressions remain in agc_driver_graphics.
  • Linux x86-64, Ubuntu under WSL2, GCC 13.3.0, -std=c++20 -pthread: the exact committed lifetime fixture and GuestHeap/GuestAllocations/GuestArena/GuestWriteWatch sources pass optimized and AddressSanitizer builds; the optimized fixed case also passes 20/20 repeats.
  • Negative control keeps the identical fixture and restores only the earlier destructible-map GuestHeap implementation: optimized test fails, and ASan reports heap-use-after-free in the unordered-map insertion path. Fixed ASan run is clean. ASAN_OPTIONS=detect_leaks=0 excludes intentionally process-lived state; no leak-clean claim.
  • Linux tests are standalone allocator-source builds, not the full linked Linux runtime/CTest target; macOS was not run. The earlier bounds-only forgery negative control remains historical evidence in heap-negative-tests.log, not a freshly repeated negative control on this base.

Requested allocation-heavy microbenchmark

Same Linux machine/compiler, -std=c++20 -O2 -pthread, main versus the final fixed allocator; no overlapping source build during timed execution. Warmed single-thread workloads: 32-byte allocate/write/free churn and batches of 1,024 simultaneous 32/96/256-byte allocations. Each timed sample is 524,288 allocation/free pairs; 21 samples per variant/workload, ordered main/fixed/fixed/main/main/fixed across processes. Wall time per pair, pooled sample medians:

Workload Main ns/pair PR ns/pair Observed difference
churn32 364.1 406.3 +42.2 ns (+11.6%)
batch1024-mixed 627.6 672.5 +44.9 ns (+7.2%)

Instrumentation of warmed ordinary C++ operator new calls sees 8 to 9 calls per guest allocation/free pair, and 384 to 416 requested host bytes: one extra 32-byte map node per live allocation on this libstdc++ implementation. This is requested allocation traffic, not RSS or a cross-platform node-size guarantee; startup/bucket growth is excluded. Freed nodes are reclaimed, but the intentionally process-lived map retains its bucket capacity until process exit.

Clocks/power/host load were uncontrolled and samples vary substantially; the table is a small synthetic overhead observation, not a statistically established game/frame/throughput result or a speedup claim. No title run, thread scaling, cold start or trace-digest performance comparison was made. Benchmark source, exact build/run script and raw samples are attached in the gist, not added to the repository.

Exact GPU environment on baseline and candidates:

export ANYPS5_GPU='NVIDIA GeForce RTX 4060 Laptop GPU'
export ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1
export VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation
export VK_LAYER_PATH='C:/Users/abelv/AppData/Local/Temp/anyps5-priority-work/validation/windows-x64'
export VK_LOADER_DEBUG=layer
cmake --build build --target libs agc_driver_graphics_tests agc_driver_draw_shader_failure_tests request_serializer_tests agc_shader_memory_tests guest_allocator_failures_tests application_heap_tests -j 6
ctest --test-dir build -R '^(request_serializer|agc_shader_memory|agc_driver_graphics|agc_driver_draw_shader_failure.*|guest_allocator_failures|application_heap_default|application_heap_exit_order)$' -V

The 12 common controls pass on main and every candidate: request serializer, shader memory, driver graphics, six draw-shader-failure modes, allocator failures and two application-heap modes. Actual libs and affected test binaries rebuilt at each pinned head. Every GPU-bearing log confirms actual Khronos layer insertion, with no skips, VUID-, synchronization hazards, validation errors/warnings or missing-requested-layer diagnostics. This is not inferred from CTest's exit status alone.

git diff --check, current-main conventions and the required python tools/check_conventions.py --base origin/main pass. The latter retains inherited debt-length warnings from the stale fork-main comparison. Hosted path-skipped product jobs are not runtime evidence. Exact commands, raw logs and source/binary hashes are in the evidence gist (resume-* files and resume-provenance.json); older prefixes describe older heads. AI-assisted.

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: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: NVIDIA GeForce RTX 4060 Laptop GPU, NVIDIA 610.62, Windows 11 x86-64 26300 (existing GPU-bearing controls; production change is libc)
  • AI-assisted: yes

Local validation logs and scope.

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5019874622 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11468). Originally posted by [valenciana-nc](https://github.com/valenciana-nc) on 2026-10-26T15:15:22Z. --- ### What Authenticate guest-writable heap headers against trusted host-owned records of the exact user pointer, raw block start and allocator-selected size. Free validates before removing registration, changing usage or mutating free lists; realloc/realign validate before replacement allocation, including zero-size requests. This rejects the reviewed in-arena interior-pointer forgery and registered non-heap memory. Addressed the shutdown review: `blocks()` now has process lifetime, matching `GuestAllocations::registry()`. It is deliberately not destroyed while guest threads may still allocate/free. Added `guest_heap_lifetime` under UNIX: a child registers an exit callback before first allocation; the callback starts a worker during static finalization, checks a retained small allocation, performs 256 allocation/free pairs, then frees the retained block. The parent verifies callback success and normal child exit. This targets the new map's lifetime, not the pre-existing large-block cache lifetime gap. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> Pinned main: `3ae8209b643be054ef09542f9e9e5e951b1ed73b`. Tested head: `69667d35df0329efbbab3bc9e99c9d4e2d2519b1`. Windows 11 x86-64 build 26300; Intel i7-13650HX; NVIDIA GeForce RTX 4060 Laptop GPU / NVIDIA 610.62; WinLibs GCC 15.2.0 r7; Release, `BUILD_TESTING=ON`. - Windows rebuilt libraries and common controls: **main 12/12, heap PR 12/12**. The ownership/corruption regressions remain in `agc_driver_graphics`. - Linux x86-64, Ubuntu under WSL2, GCC 13.3.0, `-std=c++20 -pthread`: the exact committed lifetime fixture and GuestHeap/GuestAllocations/GuestArena/GuestWriteWatch sources pass optimized and AddressSanitizer builds; the optimized fixed case also passes **20/20 repeats**. - Negative control keeps the identical fixture and restores only the earlier destructible-map GuestHeap implementation: optimized test fails, and ASan reports **heap-use-after-free** in the unordered-map insertion path. Fixed ASan run is clean. `ASAN_OPTIONS=detect_leaks=0` excludes intentionally process-lived state; no leak-clean claim. - Linux tests are standalone allocator-source builds, not the full linked Linux runtime/CTest target; macOS was not run. The earlier bounds-only forgery negative control remains historical evidence in `heap-negative-tests.log`, not a freshly repeated negative control on this base. #### Requested allocation-heavy microbenchmark Same Linux machine/compiler, `-std=c++20 -O2 -pthread`, main versus the final fixed allocator; no overlapping source build during timed execution. Warmed single-thread workloads: 32-byte allocate/write/free churn and batches of 1,024 simultaneous 32/96/256-byte allocations. Each timed sample is 524,288 allocation/free pairs; 21 samples per variant/workload, ordered main/fixed/fixed/main/main/fixed across processes. Wall time per pair, pooled sample medians: | Workload | Main ns/pair | PR ns/pair | Observed difference | |---|---:|---:|---:| | churn32 | 364.1 | 406.3 | +42.2 ns (+11.6%) | | batch1024-mixed | 627.6 | 672.5 | +44.9 ns (+7.2%) | Instrumentation of warmed ordinary C++ `operator new` calls sees **8 to 9 calls per guest allocation/free pair**, and **384 to 416 requested host bytes**: one extra 32-byte map node per live allocation on this libstdc++ implementation. This is requested allocation traffic, not RSS or a cross-platform node-size guarantee; startup/bucket growth is excluded. Freed nodes are reclaimed, but the intentionally process-lived map retains its bucket capacity until process exit. Clocks/power/host load were uncontrolled and samples vary substantially; the table is a small synthetic overhead observation, not a statistically established game/frame/throughput result or a speedup claim. No title run, thread scaling, cold start or trace-digest performance comparison was made. Benchmark source, exact build/run script and raw samples are attached in the gist, not added to the repository. Exact GPU environment on baseline and candidates: ```bash export ANYPS5_GPU='NVIDIA GeForce RTX 4060 Laptop GPU' export ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 export VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation export VK_LAYER_PATH='C:/Users/abelv/AppData/Local/Temp/anyps5-priority-work/validation/windows-x64' export VK_LOADER_DEBUG=layer cmake --build build --target libs agc_driver_graphics_tests agc_driver_draw_shader_failure_tests request_serializer_tests agc_shader_memory_tests guest_allocator_failures_tests application_heap_tests -j 6 ctest --test-dir build -R '^(request_serializer|agc_shader_memory|agc_driver_graphics|agc_driver_draw_shader_failure.*|guest_allocator_failures|application_heap_default|application_heap_exit_order)$' -V ``` The 12 common controls pass on main and every candidate: request serializer, shader memory, driver graphics, six draw-shader-failure modes, allocator failures and two application-heap modes. Actual `libs` and affected test binaries rebuilt at each pinned head. Every GPU-bearing log confirms actual Khronos layer insertion, with no skips, `VUID-`, synchronization hazards, validation errors/warnings or missing-requested-layer diagnostics. This is not inferred from CTest's exit status alone. `git diff --check`, current-main conventions and the required `python tools/check_conventions.py --base origin/main` pass. The latter retains inherited debt-length warnings from the stale fork-main comparison. Hosted path-skipped product jobs are not runtime evidence. Exact commands, raw logs and source/binary hashes are in the evidence gist (`resume-*` files and `resume-provenance.json`); older prefixes describe older heads. AI-assisted. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: <!-- #PR, or none --> none - [x] Fixes: <!-- issue it closes as Fixes #N, or none --> none - [x] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> none - [x] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> NVIDIA GeForce RTX 4060 Laptop GPU, NVIDIA 610.62, Windows 11 x86-64 26300 (existing GPU-bearing controls; production change is libc) - [x] AI-assisted: <!-- yes / no --> yes [Local validation logs and scope](https://gist.github.com/valenciana-nc/535e87d2d74acfde062effdf1dd26c37).
MarcZX10 commented 2026-10-26 15:17:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-26T15:17:16Z.

Review: CHANGES_REQUESTED


I found a remaining allocator-integrity gap in the new validation on head c7bfe92aa55b5ba3e3548d8b412f5d5b8b8c328c.

The check proves that the guest-writable raw and blockBytes cover the registered user range and lie inside the reserved arena, but it does not prove that raw is the actual block start returned by ArenaHeap or that the block size matches that allocation. GuestArenaContains only checks the arena's overall address bounds. For a 32-byte allocation, the allocator requests 80 bytes and uses the 96-byte size class. If the header is changed to raw = pointer - 16 and blockBytes = 96, the current preceding-header, coverage and arena checks all pass for an ordinary in-arena allocation. ArenaHeap::Free then inserts that interior pointer into the 96-byte free list; the next 32-byte allocation can reuse an overlapping block and extend 16 bytes past the original class block into its neighbor.

Please validate raw/blockBytes against trusted host-side allocation metadata (or an equivalent allocator-owned block-boundary check) before removing the registered allocation or mutating the free list. Add a regression that forges an in-arena interior raw with a plausible valid class size, verifies free is rejected and the allocation remains registered, then proves a same-class allocation cannot receive the forged overlapping block. The existing zero-size corruption test does not exercise this case.

The current diff passes git diff --check, current-main conventions and a clean merge-tree preview. I did not independently run the AGC test suite; hosted relinker/registration jobs are still running, and AGC product jobs are path-skipped.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5654399360 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11468#pullrequestreview-5654399360). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-26T15:17:16Z. **Review:** CHANGES_REQUESTED --- I found a remaining allocator-integrity gap in the new validation on head `c7bfe92aa55b5ba3e3548d8b412f5d5b8b8c328c`. The check proves that the guest-writable `raw` and `blockBytes` cover the registered user range and lie inside the reserved arena, but it does not prove that `raw` is the actual block start returned by `ArenaHeap` or that the block size matches that allocation. `GuestArenaContains` only checks the arena's overall address bounds. For a 32-byte allocation, the allocator requests 80 bytes and uses the 96-byte size class. If the header is changed to `raw = pointer - 16` and `blockBytes = 96`, the current preceding-header, coverage and arena checks all pass for an ordinary in-arena allocation. `ArenaHeap::Free` then inserts that interior pointer into the 96-byte free list; the next 32-byte allocation can reuse an overlapping block and extend 16 bytes past the original class block into its neighbor. Please validate `raw`/`blockBytes` against trusted host-side allocation metadata (or an equivalent allocator-owned block-boundary check) before removing the registered allocation or mutating the free list. Add a regression that forges an in-arena interior `raw` with a plausible valid class size, verifies free is rejected and the allocation remains registered, then proves a same-class allocation cannot receive the forged overlapping block. The existing zero-size corruption test does not exercise this case. The current diff passes `git diff --check`, current-main conventions and a clean merge-tree preview. I did not independently run the AGC test suite; hosted relinker/registration jobs are still running, and AGC product jobs are path-skipped.
MarcZX10 commented 2026-10-29 07:57:48 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T07:57:48Z.

Review: CHANGES_REQUESTED


Re-review — changes requested

The two earlier code findings appear addressed on exact head 69667d35df0329efbbab3bc9e99c9d4e2d2519b1: the free/realloc validation now checks the guest header against host-owned block metadata, and the block map has process lifetime. The author reports an exit-time ASan regression/control, Windows controls, and a microbenchmark with its limitations documented. I found no new allocator-integrity defect in this re-review.

Findings

[P2] Agree on the overlapping heap changes

This PR and open #12239 both change core/libs/prx/libc/src/GuestHeap.cpp; a pairwise merge preview reports a content conflict. CONTRIBUTING requires the authors to agree on landing order and record the prerequisite on the later PR. Please coordinate the order with #12239's author and update the relevant Depends on checklist line. The current none entry does not record that conflict.

[P2] Integrate current main and rerun the heap tests

Current main is 4c7d275bef89d309313d16bc2bc05d37a1b50be2; this head is based on 3ae8209b643be054ef09542f9e9e5e951b1ed73b. The current merge preview is clean, but main has changed the libc CMake file and GuestAllocations.cpp test path, both touched by this PR. Please keep the branch current and rerun the heap lifetime/integrity tests and relevant allocator suite on the integrated tree.

Checks

  • Current-main merge preview: clean.
  • git diff --check: clean.
  • tools/check_conventions.py: passed against current main.
  • Existing author-reported Linux ASan and Windows results predate current main; hosted product jobs are not current-main validation.
  • I did not run a local build or allocator tests.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5694471603 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11468#pullrequestreview-5694471603). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-29T07:57:48Z. **Review:** CHANGES_REQUESTED --- # Re-review — changes requested The two earlier code findings appear addressed on exact head `69667d35df0329efbbab3bc9e99c9d4e2d2519b1`: the free/realloc validation now checks the guest header against host-owned block metadata, and the block map has process lifetime. The author reports an exit-time ASan regression/control, Windows controls, and a microbenchmark with its limitations documented. I found no new allocator-integrity defect in this re-review. ## Findings ### [P2] Agree on the overlapping heap changes This PR and open #12239 both change `core/libs/prx/libc/src/GuestHeap.cpp`; a pairwise merge preview reports a content conflict. CONTRIBUTING requires the authors to agree on landing order and record the prerequisite on the later PR. Please coordinate the order with #12239's author and update the relevant `Depends on` checklist line. The current `none` entry does not record that conflict. ### [P2] Integrate current main and rerun the heap tests Current `main` is `4c7d275bef89d309313d16bc2bc05d37a1b50be2`; this head is based on `3ae8209b643be054ef09542f9e9e5e951b1ed73b`. The current merge preview is clean, but `main` has changed the libc CMake file and `GuestAllocations.cpp` test path, both touched by this PR. Please keep the branch current and rerun the heap lifetime/integrity tests and relevant allocator suite on the integrated tree. ## Checks - Current-main merge preview: clean. - `git diff --check`: clean. - `tools/check_conventions.py`: passed against current `main`. - Existing author-reported Linux ASan and Windows results predate current `main`; hosted product jobs are not current-main validation. - I did not run a local build or allocator tests.
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!11468
No description provided.