fix(libkernel): round sceKernelMunmap ranges to guest pages #24743

Merged
nodex0 merged 1 commit from upstream-pr/24743 into main 2026-11-29 10:13:56 +00:00
nodex0 commented 2026-11-21 00:58:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by nodex0 on 2026-11-21T00:58:55Z.


What

Round the start of sceKernelMunmap down and the end up to 16 KiB boundaries, with the arithmetic and bounds the console showed: the offset in the page is added to the length modulo 2^64, a sum that rounds to 0 returns 0 without unmapping, and a start in the first page, a wrapping range or a range that ends above 0x800000000000 returns EINVAL. The rounded range is used for unmapping, flexible-memory accounting, locked ranges and names. The POSIX munmap wrapper now shares this path. This resolves the hardware question recorded by #13866.

Tested

Measured on 2026-11-20 and 2026-11-21 in a PS5 homebrew payload process (firmware 13.40, SDK 0x13400002, elfldr). A title process may differ. Six ranges on anonymous, flexible and direct read/write mappings of four pages all returned 0: at a page boundary, lengths 1, 16384 and 16385 removed 1, 1 and 2 pages; one byte into a page, lengths 1 and 16384 removed 1 and 2 pages; two bytes straddling a boundary removed both. Adjacent pages stayed mapped with their protection and contents. Lengths near 2^64, the error cases, and the lowest and highest accepted addresses (0x4000, and a range that ends at 0x800000000000) were measured as well. The tables, payload sources and raw output are in the first comment.

On Windows (WinLibs GCC 15.2.0, Release) a harness printing the same lines as console probes 2 to 5 (probe 1 is six ranges that probe 2 repeats) differs from the console on none of 263 lines with this change (e4485b9b1c); on main fc973e0189 46 of the first 164 differ, and a length that rounds to 0 throws. guest_memory, guest_mmap_fixed_anonymous and 13 other memory tests pass. The first version of the regression failed at the one-byte unmap with the original implementation.

Branch base fc973e0189. The conventions check, debt_fold.py --check and git diff --check passed. Linux and macOS were not tested. Not measured on the PS5: the flexible budget, because a payload process has none; the host test checks its accounting.

pr_overlap.py --branch (2299 open pull requests) could not compare #18190, #18571 and #21569, which conflict with main on their own, so I read their diffs: #18190 forwards sceKernelMunmap and munmap through _nid_no_patch wrappers and renames the munmap definition this change edits, so whichever merges second needs a rebase; #18571 (madvise tests) and #21569 (range names) do not touch sceKernelMunmap or the new test.

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • 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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5422636179 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24743). Originally posted by [nodex0](https://github.com/nodex0) on 2026-11-21T00:58:55Z. --- ### What Round the start of `sceKernelMunmap` down and the end up to 16 KiB boundaries, with the arithmetic and bounds the console showed: the offset in the page is added to the length modulo 2^64, a sum that rounds to 0 returns 0 without unmapping, and a start in the first page, a wrapping range or a range that ends above 0x800000000000 returns `EINVAL`. The rounded range is used for unmapping, flexible-memory accounting, locked ranges and names. The POSIX `munmap` wrapper now shares this path. This resolves the hardware question recorded by #13866. ### 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. --> Measured on 2026-11-20 and 2026-11-21 in a PS5 homebrew payload process (firmware 13.40, SDK `0x13400002`, elfldr). A title process may differ. Six ranges on anonymous, flexible and direct read/write mappings of four pages all returned 0: at a page boundary, lengths 1, 16384 and 16385 removed 1, 1 and 2 pages; one byte into a page, lengths 1 and 16384 removed 1 and 2 pages; two bytes straddling a boundary removed both. Adjacent pages stayed mapped with their protection and contents. Lengths near 2^64, the error cases, and the lowest and highest accepted addresses (0x4000, and a range that ends at 0x800000000000) were measured as well. The tables, payload sources and raw output are in the first comment. On Windows (WinLibs GCC 15.2.0, Release) a harness printing the same lines as console probes 2 to 5 (probe 1 is six ranges that probe 2 repeats) differs from the console on none of 263 lines with this change (`e4485b9b1c`); on `main` `fc973e0189` 46 of the first 164 differ, and a length that rounds to 0 throws. `guest_memory`, `guest_mmap_fixed_anonymous` and 13 other memory tests pass. The first version of the regression failed at the one-byte unmap with the original implementation. Branch base `fc973e0189`. The conventions check, `debt_fold.py --check` and `git diff --check` passed. Linux and macOS were not tested. Not measured on the PS5: the flexible budget, because a payload process has none; the host test checks its accounting. `pr_overlap.py --branch` (2299 open pull requests) could not compare #18190, #18571 and #21569, which conflict with `main` on their own, so I read their diffs: #18190 forwards `sceKernelMunmap` and `munmap` through `_nid_no_patch` wrappers and renames the `munmap` definition this change edits, so whichever merges second needs a rebase; #18571 (madvise tests) and #21569 (range names) do not touch `sceKernelMunmap` or the new test. ### 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) and the licence notice of code adapted from upstream (see AGENTS.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: none <!-- #PR, or none --> - [x] Fixes: none <!-- issue it closes as Fixes #N, or none --> - [x] Unblocks: none <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> - [x] GPUs tested: n/a <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> - [x] AI-assisted: yes <!-- yes / no -->
MarcZX10 commented 2026-11-21 01:19:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-21T01:19:27Z.

Review: DISMISSED


Reviewed — changes requested

Changes are required before merge: guard the page-rounding arithmetic against unsigned overflow before using the rounded range.

What I ran

Reviewed head e4485b9b1c9b6a03e9dab17ef602224ccaf1043d and its prepared diff. No commands or tests were run.

Results

Check Result Note
Changed code review failed Rounding arithmetic can overflow
Tests not run Author-reported runs only

Findings

Blocking

  • core/libs/prx/libkernel/DirectMemory/Export.cpp:417: len + offset + mask is calculated in size_t before the code checks for wrapping. If it wraps to a small page-aligned value, the later end check may accept it and unmap a range much smaller than requested. For example, an aligned vaddr and len == SIZE_MAX - mask + 1 make the addition wrap to zero, after which the function returns success without unmapping; other overflow values can round to a nonzero range. Detect overflow in the additions before rounding, while preserving the specifically described modulo-2^64 zero case if that is confirmed behavior.

Non-blocking

None.

Not verified

No test suite or hardware probe was run. The Windows harness and PS5 measurements in the description are author-reported. Reviewed all changed files listed in the manifest: Export.cpp, PosixMemory.cpp, GuestMemory.cpp, and fix-libkernel-munmap-page-range.md. No excluded changed files were listed.

To get this to a good state

Add explicit, well-defined checks for overflow in the page-rounding calculation and regression tests for values that currently wrap to a nonzero rounded length; rerun the relevant memory tests.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6001720747 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24743#pullrequestreview-6001720747). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-21T01:19:27Z. **Review:** DISMISSED --- # Reviewed — changes requested Changes are required before merge: guard the page-rounding arithmetic against unsigned overflow before using the rounded range. ## What I ran Reviewed head `e4485b9b1c9b6a03e9dab17ef602224ccaf1043d` and its prepared diff. No commands or tests were run. ## Results | Check | Result | Note | |---|---|---| | Changed code review | failed | Rounding arithmetic can overflow | | Tests | not run | Author-reported runs only | ## Findings ### Blocking - `core/libs/prx/libkernel/DirectMemory/Export.cpp:417`: `len + offset + mask` is calculated in `size_t` before the code checks for wrapping. If it wraps to a small page-aligned value, the later `end` check may accept it and unmap a range much smaller than requested. For example, an aligned `vaddr` and `len == SIZE_MAX - mask + 1` make the addition wrap to zero, after which the function returns success without unmapping; other overflow values can round to a nonzero range. Detect overflow in the additions before rounding, while preserving the specifically described modulo-2^64 zero case if that is confirmed behavior. ### Non-blocking None. ## Not verified No test suite or hardware probe was run. The Windows harness and PS5 measurements in the description are author-reported. Reviewed all changed files listed in the manifest: `Export.cpp`, `PosixMemory.cpp`, `GuestMemory.cpp`, and `fix-libkernel-munmap-page-range.md`. No excluded changed files were listed. ## To get this to a good state Add explicit, well-defined checks for overflow in the page-rounding calculation and regression tests for values that currently wrap to a nonzero rounded length; rerun the relevant memory tests.
PrivacyOnion commented 2026-11-21 01:34:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-21T01:34:05Z.

Review: APPROVED


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

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_memory_tests built cleanly.
  • CTest (guest_memory, guest_mmap_fixed_anonymous, guest_mmap_executable):
    1/3 Test #5916: guest_mmap_executable ............   Passed    0.04 sec
    2/3 Test #5915: guest_mmap_fixed_anonymous .......   Passed    0.03 sec
    3/3 Test #5914: guest_memory .....................   Passed    6.83 sec
    100% tests passed, 0 tests failed out of 3
    
  • Negative control: with core/libs/prx/libkernel/DirectMemory/Export.cpp, core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp reverted to main and the new tests kept, the suite fails:
    1/3 Test #5916: guest_mmap_executable ............   Passed    0.03 sec
    2/3 Test #5915: guest_mmap_fixed_anonymous .......   Passed    0.03 sec
    3/3 Test #5914: guest_memory .....................Subprocess aborted***Exception:   0.45 sec
    67% tests passed, 1 tests failed out of 3
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified Export.cpp:413-421 rounding logic against FreeBSD 11.4 vm_mmap.c kern_munmap semantics and tested edge cases including modulo-2^64 wrap and 0x800000000000 user address limit
    • Verified MarcZX10's review objection and proved it invalid: FreeBSD kern_munmap intentionally allows (len + offset + mask) modulo-2^64 to wrap to 0, returning 0 without unmapping, matching PS5 hardware hardware probe results
    • Checked PosixMemory.cpp munmap_nid_postfix wrapper delegation to sceKernelMunmap and verified proper error handling and errno mapping to GuestInvalid/GuestNoMemory
    • Audited 64-bit integer width and sign consistency between uint64_t vaddr, size_t len, and uintptr_t for both LP64 Linux and LLP64 Windows targets
    • Inspected locking and unmapping order in sceKernelMunmap for _releaseFlexible, ForgetLockedRange, and EraseRangeNames with g_rangeNameLock
    • Validated GuestMemory.cpp test coverage for unaligned offsets, boundary crossings, wrapping lengths, upper memory bounds, and flexible memory tracking

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6001834668 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24743#pullrequestreview-6001834668). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-21T01:34:05Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `e4485b9b1c`: - **Conventions**: `tools/check_conventions.py` passed. - **Build**: `guest_memory_tests` built cleanly. - **CTest** (`guest_memory`, `guest_mmap_fixed_anonymous`, `guest_mmap_executable`): ``` 1/3 Test #5916: guest_mmap_executable ............ Passed 0.04 sec 2/3 Test #5915: guest_mmap_fixed_anonymous ....... Passed 0.03 sec 3/3 Test #5914: guest_memory ..................... Passed 6.83 sec 100% tests passed, 0 tests failed out of 3 ``` - **Negative control**: with `core/libs/prx/libkernel/DirectMemory/Export.cpp`, `core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/3 Test #5916: guest_mmap_executable ............ Passed 0.03 sec 2/3 Test #5915: guest_mmap_fixed_anonymous ....... Passed 0.03 sec 3/3 Test #5914: guest_memory .....................Subprocess aborted***Exception: 0.45 sec 67% tests passed, 1 tests failed out of 3 ``` Restoring the change makes it pass again. - **Code reading**: - Verified Export.cpp:413-421 rounding logic against FreeBSD 11.4 vm_mmap.c kern_munmap semantics and tested edge cases including modulo-2^64 wrap and 0x800000000000 user address limit - Verified MarcZX10's review objection and proved it invalid: FreeBSD kern_munmap intentionally allows (len + offset + mask) modulo-2^64 to wrap to 0, returning 0 without unmapping, matching PS5 hardware hardware probe results - Checked PosixMemory.cpp munmap_nid_postfix wrapper delegation to sceKernelMunmap and verified proper error handling and errno mapping to GuestInvalid/GuestNoMemory - Audited 64-bit integer width and sign consistency between uint64_t vaddr, size_t len, and uintptr_t for both LP64 Linux and LLP64 Windows targets - Inspected locking and unmapping order in sceKernelMunmap for _releaseFlexible, ForgetLockedRange, and EraseRangeNames with g_rangeNameLock - Validated GuestMemory.cpp test coverage for unaligned offsets, boundary crossings, wrapping lengths, upper memory bounds, and flexible memory tracking Looks Good To Me
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!24743
No description provided.