fix(libkernel): place a fixed mapping at any page-aligned address whatever its alignment #20349

Merged
Gag21 merged 1 commit from upstream-pr/20349 into main 2026-11-29 12:28:25 +00:00
Gag21 commented 2026-11-15 02:37:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Gag21 on 2026-11-15T02:37:17Z.


What

With MAP_FIXED, MapPlaced checked the requested address against the alignment argument, so a fixed mapping at a page-aligned address that is not a multiple of that alignment threw:

terminate called after throwing an instance of 'std::invalid_argument'
  what():  Invalid memory address, alignment or range

A PS4 title (CUSA01709) hits this during its first heap setup. With APS5_TRACE_MEMORY=1 the run shows an anonymous mapping of 0x17d98000 bytes at 0x5000000000 and an allocation of 0x22268000 bytes of direct memory; the title then maps 0x22268000 bytes at the fixed address right after the first mapping, 0x5017d98000, with an alignment of 0x200000. That address is aligned to 0x8000, not to 0x200000.

Both references agree that the alignment only matters when the kernel picks the address:

  • FreeBSD 11.4 vm_mmap, the baseline docs/dev/REVERSE_ENGINEERING.md gives for libkernel: with MAP_FIXED, sys_mmap checks only that the address is page-aligned (if (addr & PAGE_MASK) return (EINVAL);), and vm_mmap_object turns MAP_ALIGNED into a search constraint only in the fitit (not fixed) branch.
  • shadPS4 MemoryManager::MapMemory, at the commit the GNM and kernel debt entries already cite: the alignment goes to SearchFree only when Fixed is not set.

So a fixed mapping now needs only a page-aligned address. The alignment value itself is still validated (a power of two no smaller than a page), as before and as shadPS4 does. MapPlaced used the alignment for nothing else on the fixed path, so this covers every caller that reaches it with MAP_FIXED: the direct, flexible, anonymous and file-backed maps and sceKernelReserveVirtualRange.

docs/dev/debt/libkernel.md gets an entry: this follows FreeBSD and shadPS4 and is not measured on a console.

Tested

Windows 11 Pro 10.0.26300, i5-6600K, NVIDIA GeForce RTX 3070, WinLibs GCC 16.2.0, CMake 4.4.4, Ninja, Release, BUILD_TESTING=ON, on main 61f33fc26c.

  • New check CheckFixedDirectMapIgnoresAlignment in guest_memory (core/libs/tests/GuestMemory.cpp): maps two 2 MiB pages of direct memory with an alignment of 0x200000, unmaps them, then maps 2 MiB with MAP_FIXED at that base plus one page, with the same alignment. It checks the mapping lands at the requested address, that sceKernelVirtualQuery reports it as direct memory at the right offset with read/write protection, and that its last byte holds a write.
  • Does it fail without the change? With only the DirectMemory.cpp line reverted and the test kept, guest_memory fails with Invalid memory address, alignment or range; with the change it passes.
  • Related tests: the 230 tests matching memory|mmap|mprotect|munmap|direct|flexible|protection|page_table|arena|reserve|virtual|write_watch|ampr|apr_. With ctest -j 3, 13 graphics tests failed; run one at a time, 12 of them pass. The last, agc_image_memory_accounting, fails the same way on main 61f33fc26c on this machine (a Vulkan allocation returning -2 in its test image), twice on main and once on this branch, so it is not caused by this change.
  • The title: with this change and other local changes that are not in this PR, CUSA01709 gets past this mapping, prints its heap setup (Ebony Heap : 0x5000000000 381+546MBytes), starts its worker threads and opens its Vulkan device. Without it, it stops at the mapping with the message above.
  • python tools/check_conventions.py --base origin/main passes. python tools/pr_overlap.py --branch failed closed (exit 2) on 34 open pull requests that conflict with main. Three of them change DirectMemory.cpp or GuestMemory.cpp (#7149, #16372, #18293); none of their patches to those files changes the fixed-mapping check. The other 31 share only docs/dev/debt/libkernel.md.

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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5318745150 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/20349). Originally posted by [Gag21](https://github.com/Gag21) on 2026-11-15T02:37:17Z. --- ### What With `MAP_FIXED`, `MapPlaced` checked the requested address against the alignment argument, so a fixed mapping at a page-aligned address that is not a multiple of that alignment threw: ``` terminate called after throwing an instance of 'std::invalid_argument' what(): Invalid memory address, alignment or range ``` A PS4 title (CUSA01709) hits this during its first heap setup. With `APS5_TRACE_MEMORY=1` the run shows an anonymous mapping of 0x17d98000 bytes at 0x5000000000 and an allocation of 0x22268000 bytes of direct memory; the title then maps 0x22268000 bytes at the fixed address right after the first mapping, 0x5017d98000, with an alignment of 0x200000. That address is aligned to 0x8000, not to 0x200000. Both references agree that the alignment only matters when the kernel picks the address: - [FreeBSD 11.4 `vm_mmap`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/vm/vm_mmap.c), the baseline `docs/dev/REVERSE_ENGINEERING.md` gives for libkernel: with `MAP_FIXED`, `sys_mmap` checks only that the address is page-aligned (`if (addr & PAGE_MASK) return (EINVAL);`), and `vm_mmap_object` turns `MAP_ALIGNED` into a search constraint only in the `fitit` (not fixed) branch. - [shadPS4 `MemoryManager::MapMemory`](https://github.com/shadps4-emu/shadPS4/blob/a808e7626e3c7de8d0f0fda6a91f620b42f6c762/src/core/memory.cpp), at the commit the GNM and kernel debt entries already cite: the alignment goes to `SearchFree` only when `Fixed` is not set. So a fixed mapping now needs only a page-aligned address. The alignment value itself is still validated (a power of two no smaller than a page), as before and as shadPS4 does. `MapPlaced` used the alignment for nothing else on the fixed path, so this covers every caller that reaches it with `MAP_FIXED`: the direct, flexible, anonymous and file-backed maps and `sceKernelReserveVirtualRange`. `docs/dev/debt/libkernel.md` gets an entry: this follows FreeBSD and shadPS4 and is not measured on a console. ### 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. --> Windows 11 Pro 10.0.26300, i5-6600K, NVIDIA GeForce RTX 3070, WinLibs GCC 16.2.0, CMake 4.4.4, Ninja, Release, `BUILD_TESTING=ON`, on `main` `61f33fc26c`. - **New check** `CheckFixedDirectMapIgnoresAlignment` in `guest_memory` (`core/libs/tests/GuestMemory.cpp`): maps two 2 MiB pages of direct memory with an alignment of 0x200000, unmaps them, then maps 2 MiB with `MAP_FIXED` at that base plus one page, with the same alignment. It checks the mapping lands at the requested address, that `sceKernelVirtualQuery` reports it as direct memory at the right offset with read/write protection, and that its last byte holds a write. - **Does it fail without the change?** With only the `DirectMemory.cpp` line reverted and the test kept, `guest_memory` fails with `Invalid memory address, alignment or range`; with the change it passes. - **Related tests:** the 230 tests matching `memory|mmap|mprotect|munmap|direct|flexible|protection|page_table|arena|reserve|virtual|write_watch|ampr|apr_`. With `ctest -j 3`, 13 graphics tests failed; run one at a time, 12 of them pass. The last, `agc_image_memory_accounting`, fails the same way on `main` `61f33fc26c` on this machine (a Vulkan allocation returning -2 in its test image), twice on `main` and once on this branch, so it is not caused by this change. - **The title:** with this change and other local changes that are not in this PR, CUSA01709 gets past this mapping, prints its heap setup (`Ebony Heap : 0x5000000000 381+546MBytes`), starts its worker threads and opens its Vulkan device. Without it, it stops at the mapping with the message above. - `python tools/check_conventions.py --base origin/main` passes. `python tools/pr_overlap.py --branch` failed closed (exit 2) on 34 open pull requests that conflict with `main`. Three of them change `DirectMemory.cpp` or `GuestMemory.cpp` (#7149, #16372, #18293); none of their patches to those files changes the fixed-mapping check. The other 31 share only `docs/dev/debt/libkernel.md`. ### 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: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
MarcZX10 commented 2026-11-15 03:07:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-15T03:07:24Z.

Review: APPROVED


Reviewed — looks good

Nothing blocks this change; the fixed path validates the requested range at page alignment while retaining the existing alignment-argument validation.

What I ran

Reviewed head 3a56f1ce6b5ea623ff37c0411be27f32f48bd67a using the prepared patch and pinned repository reader. No tests or builds were run.

Results

Check Result Note
Patch and changed code review passed Three changed files read
Tests and build not run Author-reported results were not independently run

Findings

Blocking

None.

Non-blocking

None.

Not verified

No programmatic checks or console behavior were independently verified. Read: core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp, core/libs/tests/GuestMemory.cpp, and docs/dev/debt/libkernel.md; all three files listed in the manifest as reviewed were read. files.json was unavailable through the reader. No changed files were excluded in the manifest.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5908786536 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/20349#pullrequestreview-5908786536). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-15T03:07:24Z. **Review:** APPROVED --- # Reviewed — looks good Nothing blocks this change; the fixed path validates the requested range at page alignment while retaining the existing alignment-argument validation. ## What I ran Reviewed head `3a56f1ce6b5ea623ff37c0411be27f32f48bd67a` using the prepared patch and pinned repository reader. No tests or builds were run. ## Results | Check | Result | Note | |---|---|---| | Patch and changed code review | passed | Three changed files read | | Tests and build | not run | Author-reported results were not independently run | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified No programmatic checks or console behavior were independently verified. Read: `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp`, `core/libs/tests/GuestMemory.cpp`, and `docs/dev/debt/libkernel.md`; all three files listed in the manifest as reviewed were read. `files.json` was unavailable through the reader. No changed files were excluded in the manifest. ## To get this to a good state Nothing is required.
PrivacyOnion commented 2026-11-15 03:07:34 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-15T03:07:34Z.

Review: APPROVED


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

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_memory_tests built cleanly.
  • CTest (guest_memory_pool_stats, guest_memory_resource, guest_memory_lifetime, guest_memory, guest_mmap_fixed_anonymous, guest_mmap_executable):
    1/6 Test #4747: guest_memory_lifetime ............   Passed    0.04 sec
    2/6 Test #5006: guest_mmap_executable ............   Passed    0.04 sec
    3/6 Test  #879: guest_memory_pool_stats ..........   Passed    0.04 sec
    4/6 Test  #980: guest_memory_resource ............   Passed    0.02 sec
    5/6 Test #5005: guest_mmap_fixed_anonymous .......   Passed    0.01 sec
    6/6 Test #5004: guest_memory .....................   Passed    2.15 sec
    100% tests passed, 0 tests failed out of 6
    
  • Negative control: with core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp reverted to main and the new tests kept, the suite fails:
    1/6 Test #4747: guest_memory_lifetime ............   Passed    0.25 sec
    2/6 Test #5006: guest_mmap_executable ............   Passed    0.25 sec
    3/6 Test  #879: guest_memory_pool_stats ..........   Passed    0.17 sec
    4/6 Test  #980: guest_memory_resource ............   Passed    0.11 sec
    5/6 Test #5005: guest_mmap_fixed_anonymous .......   Passed    0.19 sec
    6/6 Test #5004: guest_memory .....................Subprocess aborted***Exception:   2.82 sec
    83% tests passed, 1 tests failed out of 6
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (MapPlaced): Verified that replacing ValidateRange(addr, len, alignment) with ValidateRange(addr, len, PS5_PAGE_SIZE) on the GuestMapFixed branch properly enforces null checks, positive page-multiple lengths, and non-overflowing page-aligned addresses without rejecting unaligned fixed offsets.
    • core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (ValidateAlignment): Verified that the alignment parameter remains validated upfront via ValidateAlignment(alignment), ensuring non-power-of-two values and alignments smaller than PS5_PAGE_SIZE continue to throw std::invalid_argument / return SCE_KERNEL_ERROR_EINVAL.
    • core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (DoMapDirect, DoMapAnon, DoReserveVirtual, DoMapFileBacked_nid_no_patch): Verified all callers reaching MapPlaced with GuestMapFixed (0x10) uniformly benefit from page-aligned fixed placement across Linux, macOS, and Windows without affecting non-fixed hint and search placement.
    • core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp: Verified that non-fixed mappings (without GuestMapFixed) continue using alignment for GuestArenaAllocateFromHint_nid_postfix, MapAtOrAbove, mmap_aligned, and GuestArenaAllocate_nid_postfix.
    • core/libs/tests/GuestMemory.cpp (CheckFixedDirectMapIgnoresAlignment): Verified that the unit test exercises direct memory allocation, maps at a 0x4000 page-aligned but 0x200000 unaligned fixed target, verifies memory write integrity and sceKernelVirtualQuery metadata, and releases all virtual and physical resources without leaks.
    • docs/dev/debt/libkernel.md and AGENTS.md rules: Verified zero comments were introduced in source/test files, no title-specific hardcoding was added, and the technical debt entry was correctly formatted with a relative file link.
  • Minor: please drop the Generated with footer from the description; the AI-assisted checkbox can stay.

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5908786970 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/20349#pullrequestreview-5908786970). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-15T03:07:34Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `3a56f1ce6b`: - **Conventions**: `tools/check_conventions.py` passed; `git diff --check` clean. - **Build**: `guest_memory_tests` built cleanly. - **CTest** (`guest_memory_pool_stats`, `guest_memory_resource`, `guest_memory_lifetime`, `guest_memory`, `guest_mmap_fixed_anonymous`, `guest_mmap_executable`): ``` 1/6 Test #4747: guest_memory_lifetime ............ Passed 0.04 sec 2/6 Test #5006: guest_mmap_executable ............ Passed 0.04 sec 3/6 Test #879: guest_memory_pool_stats .......... Passed 0.04 sec 4/6 Test #980: guest_memory_resource ............ Passed 0.02 sec 5/6 Test #5005: guest_mmap_fixed_anonymous ....... Passed 0.01 sec 6/6 Test #5004: guest_memory ..................... Passed 2.15 sec 100% tests passed, 0 tests failed out of 6 ``` - **Negative control**: with `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/6 Test #4747: guest_memory_lifetime ............ Passed 0.25 sec 2/6 Test #5006: guest_mmap_executable ............ Passed 0.25 sec 3/6 Test #879: guest_memory_pool_stats .......... Passed 0.17 sec 4/6 Test #980: guest_memory_resource ............ Passed 0.11 sec 5/6 Test #5005: guest_mmap_fixed_anonymous ....... Passed 0.19 sec 6/6 Test #5004: guest_memory .....................Subprocess aborted***Exception: 2.82 sec 83% tests passed, 1 tests failed out of 6 ``` Restoring the change makes it pass again. - **Code reading**: - core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (MapPlaced): Verified that replacing ValidateRange(addr, len, alignment) with ValidateRange(addr, len, PS5_PAGE_SIZE) on the GuestMapFixed branch properly enforces null checks, positive page-multiple lengths, and non-overflowing page-aligned addresses without rejecting unaligned fixed offsets. - core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (ValidateAlignment): Verified that the alignment parameter remains validated upfront via ValidateAlignment(alignment), ensuring non-power-of-two values and alignments smaller than PS5_PAGE_SIZE continue to throw std::invalid_argument / return SCE_KERNEL_ERROR_EINVAL. - core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp (DoMapDirect, DoMapAnon, DoReserveVirtual, DoMapFileBacked_nid_no_patch): Verified all callers reaching MapPlaced with GuestMapFixed (0x10) uniformly benefit from page-aligned fixed placement across Linux, macOS, and Windows without affecting non-fixed hint and search placement. - core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp: Verified that non-fixed mappings (without GuestMapFixed) continue using alignment for GuestArenaAllocateFromHint_nid_postfix, MapAtOrAbove, mmap_aligned, and GuestArenaAllocate_nid_postfix. - core/libs/tests/GuestMemory.cpp (CheckFixedDirectMapIgnoresAlignment): Verified that the unit test exercises direct memory allocation, maps at a 0x4000 page-aligned but 0x200000 unaligned fixed target, verifies memory write integrity and sceKernelVirtualQuery metadata, and releases all virtual and physical resources without leaks. - docs/dev/debt/libkernel.md and AGENTS.md rules: Verified zero comments were introduced in source/test files, no title-specific hardcoding was added, and the technical debt entry was correctly formatted with a relative file link. - Minor: please drop the `Generated with` footer from the description; the AI-assisted checkbox can stay. 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!20349
No description provided.