fix(libkernel): harden DirectMemory validation and tests #3870
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3870"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-11T18:18:52Z.
What
Hardens
PhysicalMemoryPoolagainst out-of-range and overflowing inputs and makes its mutating paths roll back:_used[]; out-of-pool or overflowing ranges are ignored (Free,CheckedFree,Retype) or returnEAGAIN(Alloc).Alloc,Free/CheckedFreeandRetyperoll back_blocksand_used[]when node allocation, backing creation or backing cleanup throws. Blocks are split first; the erase and flag updates that follow cannot throw.DirectMemoryLargestFree.DirectMemoryAllocmapsstd::bad_alloctoSCE_KERNEL_ERROR_ENOMEM. A mismatch between_blocksand_used[]throwsstd::logic_errorinstead of being silently overwritten.MemoryPoolTest(15 cases), registered in ctest. It is a host-only test, so on MinGW it is built with-fasynchronous-unwind-tables.Validation that
Export.cppalready does (unaligned or zero lengths, out-of-pool ranges) is not repeated, apart fromlen == 0inAlloc. Existing behaviour is otherwise kept, includingEAGAINforsearchStart >= searchEnd, partial and multi-allocationFree, andRetypeskipping gaps. Choices that are not checked against a reference (alignment normalisation,EINVALforlen == 0, rounding unaligned ranges to whole pages) are listed indocs/dev/debt/libkernel.md.Why
Free,Retype, and the page-marking helpers previously lacked sufficient range checks. Expressions such ascur + len,start + align - 1, andstart + lencould overflow, allowing guest input to write beyond_used[]or create overlapping allocations.Alloc,Free, andRetypecould throw partway through an operation, leaving_used[]and_blocksout of sync.Behaviour changes
Free/CheckedFree/Retype_used[]Allocrequest that can never fit, or negativesearchStartEAGAINAllocwithlen == 0EINVALlenorstartinAlloc/Free/CheckedFree/RetypephysOut/ output pointersEFAULT/ falsestd::bad_allocinAlloc(block node or backing creation)ENOMEMstd::bad_allocwhile splitting blocks inFree/RetypeKnown limitation
The rollback covers the pool's own metadata only.
ForgetDirectMemoryerasesg_physPagesbeforeErasePhysMappings, andErasePhysMappingscan throw while inserting the surviving pieces of a partially overlapped mapping. In that case, the pool restores its splits, but the already-erased physical pages and mapping nodes are not restored, so a retry may failValidatePhysicalRange. Making these updates transactional is tracked indocs/dev/debt/libkernel.mdand is outside the scope of this PR.Tested
New tests (
MemoryPoolTest): 15 cases covering argument validation, rounding/alignment/clamping, partial and spanningFree,Retypesplitting, and rollback of_blocks/_used[]after injectedstd::bad_allocand backing/forget failures.Environment: Windows 11 Home (26100), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release.
MemoryPoolTestbuilds and passes on MinGW with the unwind fix: <yes/no, from your run on the final commit>main, only if they still apply>CTestTestfile.cmakecommands because local antivirus blocksctest.exe.tools/check_conventions.py:Checklist
main; no other open PR implements the same functions.mdfiles, or images added to the repositoryImported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T18:23:18Z.
Review: CHANGES_REQUESTED
Thanks for the PR. The rollback logic and the test look right (MemoryPoolTest passes on the PR merged onto main and fails with
MemoryPool.cppreverted), but these need fixing first:MemoryPool.cpp:13-27: the#ifndef … #define SCE_KERNEL_ERROR_*block redefines constants thatprx/libkernel/KernelErrors.hppalready provides asconstexpr; the#ifndefcan never see them. Include that header and drop the macros.EINVAL(sceKernelAllocateDirectMemorycurrently accepts any multiple of the page size),searchStart == searchEndchanges fromEAGAINtoEINVAL,Free/Retypesilently ignore an unaligned start,lenis rounded up. Please say which reference each follows (FreeBSDsys/vm, KytyPS5, shadPS4) or keep the old behaviour.Export.cpp(sceKernelAllocateDirectMemory,sceKernelReleaseDirectMemory,sceKernelCheckedReleaseDirectMemoryalready reject unaligned or zero lengths and out-of-pool ranges). Keep only the checks the exports don't do.false/0/EFAULT; the originalMemoryPool.cpphas notry/catch. Please correct the description, since "exceptions propagate" is not a change for those paths.docs/dev/TechnicalDebt.md: the new line under "Unknown function info" names no sources and does not list the behaviour changes above; each unverified choice needs its own statement. The diff also adds a blank line before the "Comparison-sampled R32" entry and rewrites the last line (sceSharePlayGetCurrentConnectionInfoA) without changing it; please drop both.core/libs/CMakeLists.txt: one extra blank line beforeadd_test_executable(MemoryPoolTest.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-11T18:28:08Z.
I independently built and ran the new
MemoryPoolTesttarget from headdd01acd4499de57a89ac365ad8d4f9eed004d75bon Linux (GCC 12.2.0, Release).ctest --test-dir /tmp/AnyPS5-pr-3870-build -R "^MemoryPoolTest$" --output-on-failurepassed: 1/1 test. This is the focused pool test only; I did not run the full suite.Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-11T18:44:54Z.
Thanks for independently building and testing
MemoryPoolTeston Linux! I really appreciate you taking the time to verify it on a different environment and share the results. Glad to see the focused test passing. Thanks for the help!Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T18:54:39Z.
Review: CHANGES_REQUESTED
Thanks for the update. Build and ctest are green on the PR merged onto main, and
MemoryPoolTestfails withMemoryPool.cppreverted. The points from the previous review aboutKernelErrors.hpp,searchStart == searchEnd, non-power-of-two alignment and the CMake blank line are fixed. Still open:false,0, orEFAULT", but the originalMemoryPool.cpphas notry/catch, so "exceptions propagate" is not a change for those paths. The behaviour table also says an unalignedstartinFree/CheckedFree/Retypeis "Rejected";PageSpanfloorsstartand ceils the end to whole pages instead. The checklist says a single-commit history, but the branch has 4 commits; please squash.sys/vm, KytyPS5, shadPS4) or aTechnicalDebt.mdstatement:DirectMemoryAllocmappingstd::bad_alloctoENOMEM(previously it propagated),LargestFreetreating a negativesearchEndas unbounded (previouslyfalse), andlenrounded up to whole pages. Either cite where each comes from or keep the old behaviour.docs/dev/TechnicalDebt.md: the new "Unknown function info" line says invalid ranges are "rejected withEINVALorEFAULT", butFree/Retypereturn aboolthatDirectMemoryFree/DirectMemoryRetypediscard. Describe what the code does, one statement per unverified choice. The diff also still adds a blank line before the "Comparison-sampled R32" entry and rewrites the last line (sceSharePlayGetCurrentConnectionInfoA) without changing it; please drop both.Export.cpp(sceKernelAllocateDirectMemory,sceKernelReleaseDirectMemory,sceKernelCheckedReleaseDirectMemory) already rejects unaligned or zero lengths and out-of-pool ranges; keep only the checks the exports don't do, or say which guest path reaches the extra ones.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T22:12:33Z.
Review: APPROVED
Checked the PR merged onto main: build and ctest (113 tests in core/libs and libkernel, including
guest_kernel_sysandMemoryPoolTest) are green, andMemoryPoolTestfails withMemoryPool.cppreverted. The earlier points (KernelErrors.hpp, alignment,searchStart == searchEnd, TechnicalDebt statements) are fixed.Added on your branch:
FunctionalTechnicalDebt line off the top of the section; it conflicted with #3669 and #3691, which add there too.Left as is, please keep in mind (the description is not part of the code, so we are not editing it):
false/0/EFAULT; the original had notry/catch, so that is not a change.Merging once CI is green.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-12T03:06:51Z.
Passed our title check together with the other queued PRs. It conflicts with main in
core/libs/CMakeLists.txtonly (main added theguest_acmblock where this addsMemoryPoolTest; keep both); please rebase so the full build can run, then it can go in.Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-12T06:33:36Z.
Thanks for the review and for resolving the CMake conflict. I've merged the latest
mainchanges into my branch, and the rebase label is now cleared. I'll wait for the remaining workflows to be approved and completed.Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-12T06:34:42Z.
Thanks, oneandonlydean, for pointing out the CMake conflict. I've merged the latest
mainchanges into my branch, and the rebase label has been cleared. I appreciate your help buddy!Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-12T09:27:03Z.
Hi oneandonlydean, thanks for your help with the rebase and CMake conflict. The PR already has an approval, and I've merged the latest
mainchanges into my branch. Is anything else needed from my side to get the full build running? I'm happy to address any remaining issues. Thanks once agaiin!Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-12T13:06:16Z.
Resolved the
TechnicalDebt.mdconflict with main and corrected the description (15 test cases, removed the inaccurate exception bullet, fixed the history line in the checklist). The branch has merge commits from updating through the web UI, so a squash merge would be ideal. Thanks again for the reviews.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-12T20:34:37Z.
The Windows build of this branch does not link, and 0d859c27 still has the same target (https://github.com/boykopovar/AnyPS5/actions/runs/38239471765):
core/libscompiles everything with-fno-asynchronous-unwind-tableson MinGW, and that symbol then comes from the guestlibc, whichMemoryPoolTestdoes not link. It is a host-only test, so incore/libs/CMakeLists.txtdo whatpatched_libraries_testsandhost_thread_local_testsdo, in place ofconfigure_windows_unwind(MemoryPoolTest):Please also rebase onto main as one commit and force-push instead of merging main again; the branch has 11 merge commits.
Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-13T05:40:17Z.
oneandonlydean You all just sexually harassing me now 😭, But Ok I'll Rebase it. Thanks for supporting me.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-13T10:31:59Z.
The CMake fix is in. The branch still merges main instead of rebasing (18 merge commits now); please squash it into one commit on top of main and force-push.
docs/dev/debt/libkernel.mdalso lost its final newline.Imported from boykopovar/AnyPS5. Originally posted by yash27git on 2026-10-13T11:44:14Z.
Dear oneandonlydean,
Squashed into one commit on top of main and force-pushed; no merge commits remain. docs/dev/debt/libkernel.md ends with a newline again, and the CMake fix (-fasynchronous-unwind-tables under if(MINGW)) is included.