Skip to content

fix(libSceJxr): validate guest memory pointers in WMPAlloc and WMPFree - #18247

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
amazedturnip:fix/libSceJxr-validate-alloc-free-pointers
Nov 26, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
amazedturnip:fix/libSceJxr-validate-alloc-free-pointers

Conversation

@amazedturnip

@amazedturnip amazedturnip commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What

  • Validates the memory double pointer in WMPAlloc_nid_postfix and WMPFree_nid_postfix (core/libs/prx/libSceJxr/Export.cpp):
    • WMPAlloc_nid_postfix allocates into a temporary allocated pointer and commits it via GuestCopyOut_nid_no_patch(memory, &allocated, sizeof(allocated)); if GuestCopyOut_nid_no_patch fails, it frees allocated (when non-null) before throwing std::invalid_argument via APS5_INVALID_ARG_EX so no host block leaks.
    • WMPFree_nid_postfix reads *memory via GuestCopyIn_nid_no_patch, and when non-null, writes nullptr back to memory via GuestCopyOut_nid_no_patch before calling free_nid_postfix(ptr) so unwritable guest pointer slots throw std::invalid_argument without freeing the host block.
  • Extends core/libs/tests/JxrStream.cpp (Allocation()) to verify that unmapped pointers (0x10) throw std::invalid_argument in both WMPAlloc_nid_postfix and WMPFree_nid_postfix, and that a read-only direct-memory slot (sceKernelMprotect(..., 1)) causes WMPFree_nid_postfix to throw std::invalid_argument, leaves slotPtr[0] untouched, and succeeds once writability is restored.

Tested

  • Linux (WSL2, Release, Ninja) on head 85b345eb9a: built guest_jxr_stream_tests and ran ctest (guest_jxr_stream) covering the unmapped (0x10) and read-only direct-memory slot regression tests (100% passed).
  • python3 tools/check_conventions.py --base upstream/main --head HEAD: passed (0 violations).
  • Negative control: verified that unpatched code segfaulted on unmapped pointer 0x10, whereas patched code safely throws std::invalid_argument.

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: n/a
  • AI-assisted: yes

@MarcZX10 MarcZX10 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 — changes requested

WMPFree_nid_postfix can free an allocation before discovering that the guest pointer slot is not writable, leaving the caller with a dangling pointer after the function throws.

What I ran

Reviewed head cfd85e3edb7bc50d37114dd3e07dab097f8f2765 against base bc94a8e423ea026aadbb29165fed1ad2db471154; the merge preview was clean. I read both changed files and inspected the checked guest-copy helpers.

Environment: Linux 6.1, Python 3.11.2, GCC 12.2.0. I ran:

python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 18247 --output-dir /tmp/anyps5-pr-precheck-18247
gh pr checks 18247 -R boykopovar/AnyPS5

I did not build or run CTest. The author reports that guest_jxr_stream_tests passed and that the unpatched invalid-pointer case segfaulted; I did not reproduce those runs.

Results

Check Result Note
No-build precheck passed Applicable static checks passed; build-dependent checks were not run.
Merge preview passed Clean against the stated base.
Source review failed WMPFree_nid_postfix frees before validating the output write.
Local C++ tests not run No build or CTest run by me.
Hosted Windows build not run GitHub job was pending at review time.
Precheck results and command output
Check Status Reason
build_and_compile not run Builds are excluded from the no-build precheck.
diff_check passed git diff --check on the pinned base and head.
conventions_and_pr_template passed Repository conventions and PR template passed.
changed_export_abi_audit passed Audit completed without findings.
python_syntax not applicable No Python implementation changed.
related_python_unit_tests not applicable No Python tool module changed.
python_test_registration not applicable No Python tests changed.
live_dependency_and_mergeability_check passed Clean merge preview; no declared dependency found.
build_dependent_cpp_tests not run This no-build pass does not build changed C++ code.
test_quality_heuristics passed Heuristics completed; source and test registration were reviewed manually.
negative_controls not applicable No eligible Python-tool negative control.

Commands and captured output:

$ git diff --check bc94a8e423ea026aadbb29165fed1ad2db471154...cfd85e3edb7bc50d37114dd3e07dab097f8f2765
(no output; exit 0)

$ /usr/bin/python3 tools/check_conventions.py --base bc94a8e423ea026aadbb29165fed1ad2db471154 --head cfd85e3edb7bc50d37114dd3e07dab097f8f2765 --title 'fix(libSceJxr): validate guest memory pointers in WMPAlloc and WMPFree' --body /tmp/anyps5-pr-precheck-18247/pr-body.md
All conventions checks passed.

Negative control

The author reports that the unpatched 0x10 pointer case segfaulted and the patched version throws. I did not run this control; it does not exercise a readable but read-only pointer slot.

Findings

Blocking

  • In WMPFree_nid_postfix, the function reads the pointer, frees its pointee, then checks whether it can write null back through the guest slot. A readable, read-only slot passes GuestCopyIn_nid_no_patch, but the later GuestCopyOut_nid_no_patch fails after the allocation has already been freed. The function throws while the slot still contains the freed address, so retrying can free it again. Validate that the output slot is writable before releasing the allocation, and add a regression test proving a rejected read-only slot leaves the allocation valid.

Non-blocking

None.

Sources

Not verified

  • A local build, CTest, and the reported negative control were not run by me.
  • The hosted Windows build was pending; no hardware or console behavior was checked.

To get this to a good state

Validate the output slot before freeing its pointee and add the read-only-slot regression test. I’ll rerun the same precheck and review the complete diff on the updated head.

@JJenkx

JJenkx commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Windows check of head cfd85e3edb, merged onto main bc94a8e423 (7795d8a985, 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.

  • guest_jxr_stream passes in 3 of 3 runs, none skipped.

AI-assisted: yes.

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

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against cfd85e3edb:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_jxr_stream_tests built cleanly.
  • CTest (guest_jxr_stream):
    1/1 Test #3394: guest_jxr_stream .................   Passed    0.01 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libSceJxr/Export.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #3394: guest_jxr_stream .................***Exception: SegFault  0.12 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/libs/prx/libSceJxr/Export.cpp: Checked WMPAlloc_nid_postfix return values on allocation failure (returning WmpErrOutOfMemory / -101) and success (WmpErrSuccess / 0), confirming that failed allocations clear *memory to nullptr.
    • core/libs/prx/libSceJxr/Export.cpp: Verified null-pointer argument validation in WMPAlloc_nid_postfix and WMPFree_nid_postfix against APS5_INVALID_ARG_EX throwing std::invalid_argument.
    • core/libs/prx/libSceJxr/Export.cpp: Verified resource cleanup in WMPAlloc_nid_postfix, confirming allocated heap memory is freed via free_nid_postfix if GuestCopyOut_nid_no_patch fails.
    • core/libs/prx/libSceJxr/Export.cpp: Evaluated exception safety and resource lifetimes in WMPFree_nid_postfix (lines 358-361) when memory points to readable but read-only memory, checking for premature deallocation before copy-out.
    • core/libs/tests/JxrStream.cpp: Verified unit test coverage in Allocation() for unmapped pointers (0x10) using RequireInvalidArgument on WMPAlloc_nid_postfix and WMPFree_nid_postfix.
    • core/libs/prx/libSceJxr/Export.cpp & core/libs/tests/JxrStream.cpp: Verified AGENTS.md rule compliance, confirming zero forbidden code comments were introduced and conventional commit formatting was followed.
  • Concerns:
    • core/libs/prx/libSceJxr/Export.cpp:358-361: In WMPFree_nid_postfix, free_nid_postfix(ptr) is called before verifying that memory is writable via GuestCopyOut_nid_no_patch. If memory is mapped read-only (or write-protected), GuestCopyIn_nid_no_patch succeeds, the memory at ptr is freed, and then GuestCopyOut_nid_no_patch fails, throwing APS5_INVALID_ARG_EX. This leaves *memory containing a dangling pointer to freed memory while reporting failure via an exception, creating use-after-free and double-free hazards upon subsequent error handling or cleanup. The null pointer must be written to memory via GuestCopyOut_nid_no_patch before deallocating ptr.
  • Note: the AI-assisted checkbox can stay.

Requesting changes for the points above.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 15646 core/libs/prx/libSceJxr/Export.cpp

@Kikoarl

Kikoarl commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Linux check of head cfd85e3edb, merged onto main 233c1606c4 (fe79a2af4e, clean merge).

Setup: Linux x86_64, 13th Gen Intel(R) Core(TM) i7-13700T, GCC 16.2.1, Release.

  • python3 tools/check_conventions.py passes cleanly (no violations).
  • guest_jxr_stream passes in 3 of 3 runs, none skipped (all 20 guest_jxr* tests also pass 3 of 3 runs).

AI-assisted: yes.

@github-actions github-actions Bot added the prx label Nov 11, 2026
@amazedturnip
amazedturnip force-pushed the fix/libSceJxr-validate-alloc-free-pointers branch from cfd85e3 to 85b345e Compare November 11, 2026 02:54
@amazedturnip

amazedturnip commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated in head 85b345eb9a:

  1. Reordered slot mutation and host deallocation in WMPFree_nid_postfix:
    GuestCopyOut_nid_no_patch(memory, &nullPtr, sizeof(nullPtr)) is now validated and executed before invoking free_nid_postfix(ptr). If the guest pointer slot is write-protected (e.g., mapped read-only), GuestCopyOut_nid_no_patch fails and throws APS5_INVALID_ARG_EX immediately without deallocating ptr, preventing use-after-free and dangling pointer states.
  2. Added read-only slot regression test in core/libs/tests/JxrStream.cpp:
    Allocates direct memory mapped with read-write protection, sets the buffer pointer into the slot, protects the slot read-only via sceKernelMprotect, confirms WMPFree_nid_postfix is rejected with invalid_argument while the pointer in the slot remains intact and un-freed, restores write protection, and verifies successful deallocation and nulling of the slot.
  3. Verification:
    • python3 tools/check_conventions.py --base upstream/main --head HEAD: passed.
    • Built and ran guest_jxr_stream_tests via CTest (guest_jxr_stream): 100% passed.

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

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 85b345eb9a:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_jxr_stream_tests built cleanly.
  • CTest (guest_jxr_stream):
    1/1 Test #3394: guest_jxr_stream .................   Passed    0.01 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libSceJxr/Export.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #3394: guest_jxr_stream .................***Exception: SegFault  0.12 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/libs/prx/libSceJxr/Export.cpp: Verified that WMPAlloc_nid_postfix validates that memory is non-null, allocates zeroed memory via calloc_nid_postfix(1, size), and writes the pointer to guest memory via GuestCopyOut_nid_no_patch; if the copy fails on unmapped/read-only memory, any allocated buffer is promptly freed via free_nid_postfix before throwing std::invalid_argument via APS5_INVALID_ARG_EX.
    • core/libs/prx/libSceJxr/Export.cpp: Verified that WMPAlloc_nid_postfix properly handles allocation failure (e.g. size == Max): calloc_nid_postfix returns nullptr, GuestCopyOut_nid_no_patch commits nullptr to guest memory, and WmpErrOutOfMemory (-101) is returned.
    • core/libs/prx/libSceJxr/Export.cpp: Verified that WMPFree_nid_postfix validates memory via GuestCopyIn_nid_no_patch before reading the target pointer; when ptr is non-null, it verifies writability and clears the guest slot to nullptr with GuestCopyOut_nid_no_patch before invoking free_nid_postfix(ptr), ensuring that a write failure (e.g. read-only memory) aborts via APS5_INVALID_ARG_EX without freeing the buffer.
    • core/libs/prx/libSceJxr/Export.cpp: Verified that WMPFree_nid_postfix handles a valid guest pointer holding nullptr cleanly without attempting redundant writes, returning WmpErrSuccess (0).
    • core/libs/tests/JxrStream.cpp: Verified that Allocation() exercises unmapped pointers (0x10) for both allocation and deallocation, validates read-only direct memory behavior using sceKernelAllocateDirectMemory, sceKernelMapDirectMemory, and sceKernelMprotect, and ensures complete cleanup with sceKernelMunmap and sceKernelReleaseDirectMemory.
    • AGENTS.md & Repository Conventions: Verified that no comments were added to code, Conventional Commit guidelines were adhered to, and no unexpected files or title-specific workarounds were introduced.
  • Note: the AI-assisted checkbox can stay.

Looks Good To Me

@amazedturnip

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Fixed in head 85b345eb9a: WMPFree_nid_postfix now validates and performs the guest pointer slot write (GuestCopyOut_nid_no_patch) before calling free_nid_postfix, so a non-writable slot throws without freeing, leaving no dangling pointer. PrivacyOnion has verified this head on Linux (conventions, build, CTest all pass).

@MarcZX10 MarcZX10 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 WMPAlloc and WMPFree guest pointer checks — no blocking findings

Nothing blocks this; the points below are optional.

What I ran

  • Head reviewed: 85b345eb9ae4398eb2aa40a027e9162264db013c (base main).
  • Read the diff of core/libs/prx/libSceJxr/Export.cpp and core/libs/tests/JxrStream.cpp, then the helpers they call at the head: GuestCopyOut_nid_no_patch (core/libs/prx/libc/src/General.cpp), the kernel declarations in core/libs/prx/libkernel/include/Api.hpp, and the Require and RequireInvalidArgument helpers in the test file.
  • Reader commands, run against the pinned head:
repo_read.py search GuestCopyOut_nid_no_patch
repo_read.py search calloc_nid_postfix
repo_read.py search GuestCopyIn_nid_no_patch(void
repo_read.py cat core/libs/prx/libc/src/General.cpp 820 862
repo_read.py cat core/libs/tests/JxrStream.cpp 1 60
repo_read.py cat core/libs/prx/libkernel/include/Api.hpp 205 230
repo_read.py cat core/libs/prx/libSceJxr/Export.cpp 50 64
  • No build and no test run: this review does not compile the code.

Results

Check Result Note
Diff read, both files passed Two hunks, one per file
Kernel calls used by the new test passed Signatures match Api.hpp
Guest copy-out on read-only pages (Linux) passed process_vm_writev path returns false on EFAULT
Build and unit test not run No builds in this review
Author-reported checks
  • Author: ninja -C build guest_jxr_stream_tests && ./build/tests/guest_jxr_stream_tests passes (Linux, WSL2, Release).
  • Author: negative control, unpatched code segfaults on 0x10; patched code throws std::invalid_argument.

These are the author's runs, not runs I performed.

Findings

Blocking

None. The guarded reads and writes in WMPAlloc_nid_postfix and WMPFree_nid_postfix do what the description says, and the new assertions in core/libs/tests/JxrStream.cpp exercise both the unmapped pointer and the read-only slot paths.

Non-blocking

  • core/libs/prx/libSceJxr/Export.cpp:345 — WMPAlloc_nid_postfix allocates before it checks that the memory destination is writable. A bad pointer therefore costs one calloc and one free_nid_postfix before the throw. This is harmless. Checking the destination first would read more clearly, but this is a style choice, not a defect.

Not verified

  • The test suite passing on Linux and the unpatched-segfault negative control: author-reported only; not reproduced here.
  • GuestCopyIn_nid_no_patch: I saw its callers but did not read its definition at the head. The WMPFree path depends on it.
  • The Windows branch of GuestCopyOut_nid_no_patch (VirtualQuery checks): not read in this review.
  • AllocateZeroed at core/libs/prx/libSceJxr/Export.cpp:58 is not part of this diff and its callers were not checked.
  • The full text of the two changed files was not read; only the changed hunks and the helpers listed above.
  • The review-body structure validator was not run: it sits outside the directories this session can read.

To get this to a good state

Nothing is required.

@amazedturnip

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Thanks for re-reviewing 85b345eb9a. On the non-blocking WMPAlloc_nid_postfix note (Export.cpp:345), checking writability through GuestCopyOut_nid_no_patch and rolling back with free_nid_postfix on failure avoids adding a GuestWritable_nid_no_patch syscall on every valid allocation path while still leaving no leaked block on a bad guest pointer. Also refreshed the PR description to match 85b345eb9a (including the WMPFree rollback order and read-only slot test), and confirmed #15646 only touches PKFormatConverter_EnumConversions (L172-174) with no overlap on WMPAlloc/WMPFree. Could you dismiss the stale change-request review from cfd85e3edb when you get a chance?

@kiwe147

kiwe147 commented Nov 21, 2026

Copy link
Copy Markdown

Tested head 85b345eb9a, applied with git apply on main fd4aeed483 together with the other 28 PRs of one batch (#19470, #20317, #21336, #22189, #22888, #23474, #24467, #24489, #20216, #22048, #22111, #22319, #22422, #22841, #23127, #9547, #21720, #22375, #23405, #24134, #14851, #18324, #19650, #19986, #20447, #21078, #22362, #22702). All applied without conflicts and the whole tree built.

Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. GPUs: NVIDIA GeForce RTX 3080 (driver 621.24) and the AMD Radeon iGPU of the CPU (gfx1036, driver 32.0.21036.18). No validation layer. iGPU run: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ANYPS5_GPU="AMD Radeon", agc_/video tests only.

tests RTX 3080 iGPU
guest_jxr_stream (1 test, matched by name to the test file this PR changes) all pass outside the iGPU subset

Whole batch: the full ctest -j 12 (6526 tests) on the RTX 3080 has 9 failing tests; the 4 that also fail on main fd4aeed483 are agc_driver_stencil_plane_memory, agc_driver_msaa_dcc_unwatch, agc_storage_write_back_host_retile, and pr_overlap_names, which needs a newer Python than my 3.10. Intermittent in this run (pass when rerun alone, or known flaky): agc_driver_store_over_untracked, guest_raise_short_sleep_without_wake, agc_driver_store_over_untracked. Failing tests I could not trace to a single PR (reverting the likely candidates did not clear them): guest_agc_driver_unknown, guest_load_ranges, tool_script_modes. The 2127 agc_/video tests on the iGPU have 2 failing: agc_driver_stencil_plane_memory, agc_driver_store_over_untracked (agc_driver_stencil_plane_memory also fails on main).

This is one combined tree, not a run of this PR alone.

AI-assisted: yes (Claude Code)

@oneandonlydean
oneandonlydean dismissed MarcZX10’s stale review November 26, 2026 03:41

18247 MarcZX10 CR 5851320762 (10 Nov 23:48Z on cfd85e3): met

Claim: WMPFree frees the pointee before checking the slot is writable, so a read-only slot keeps the freed address.
Live head 85b345e, core/libs/prx/libSceJxr/Export.cpp:358-360 writes null to the slot first and frees only after that write succeeds.
PASS LOW NO by pr-review3 on 85b345e at 11 Nov 23:14Z, after the CR. Checked at source by pr-review1.

@oneandonlydean
oneandonlydean merged commit effab78 into boykopovar:main Nov 26, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants