fix(libkernel): model direct-memory initialization #24063

Closed
malekaifa wants to merge 3 commits from upstream-pr/24063 into main
malekaifa commented 2026-11-20 03:44:00 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by malekaifa on 2026-11-20T03:44:00Z.


What

Model the firmware 13.60 direct-memory initialization state while matching title startup: sceKernelAvailableDirectMemorySize still reports EBADF before direct memory is initialized, but libkernel now calls DirectMemoryTouch() during ProgramNameRegistration, before libc program-name registration and before guest module entry. Titles therefore enter guest code with direct memory initialized, matching the console startup path noted by @oneandonlydean.

The availability query itself still does not initialize the state. Invalid non-power-of-two alignment remains EINVAL before the initialization check, and the existing largest-free-range/output behavior is retained after initialization.

The overlap scan reports #18112 and #18190 because they mirror the same NIDs through libkernel_web and libkernel_sys; neither implements this libkernel behavior.

Tested

Machine main, Windows 11, MinGW-w64 GCC 16.2.0, Release, BUILD_TESTING=ON, exact head 3ac4d05336c9:

  • Built guest_direct_memory_initialization_tests, guest_direct_memory_for_app_tests, and MemoryPoolTest.
  • guest_direct_memory_initialization: 5/5 passed; the first valid availability query succeeds without a prior guest direct-memory API call.
  • guest_direct_memory_for_app: 5/5 passed.
  • MemoryPoolTest: 5/5 passed.
  • Invalid alignment still returns EINVAL and preserves output values.
  • tools/check_conventions.py: passed.
  • tools/debt_fold.py --check: passed.
  • git diff --check: passed.

Independent Linux validation on the earlier source head also built and passed the direct-memory tests and negative control; the final follow-up changes only startup initialization and the matching initialization test.

Checklist

  • Based on current main; no other open PR implements this behavior (#18112 and #18190 mirror the NIDs through other modules only)
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw; no unimplemented paths added
  • No notes or investigation files added; the debt fragment is the required technical-debt entry
  • No third-party code added
  • Generic behavior, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5407326656 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063). Originally posted by [malekaifa](https://github.com/malekaifa) on 2026-11-20T03:44:00Z. --- ### What Model the firmware 13.60 direct-memory initialization state while matching title startup: `sceKernelAvailableDirectMemorySize` still reports `EBADF` before direct memory is initialized, but libkernel now calls `DirectMemoryTouch()` during `ProgramNameRegistration`, before libc program-name registration and before guest module entry. Titles therefore enter guest code with direct memory initialized, matching the console startup path noted by @oneandonlydean. The availability query itself still does not initialize the state. Invalid non-power-of-two alignment remains `EINVAL` before the initialization check, and the existing largest-free-range/output behavior is retained after initialization. The overlap scan reports #18112 and #18190 because they mirror the same NIDs through `libkernel_web` and `libkernel_sys`; neither implements this `libkernel` behavior. ### Tested Machine `main`, Windows 11, MinGW-w64 GCC 16.2.0, Release, `BUILD_TESTING=ON`, exact head `3ac4d05336c9`: - Built `guest_direct_memory_initialization_tests`, `guest_direct_memory_for_app_tests`, and `MemoryPoolTest`. - `guest_direct_memory_initialization`: 5/5 passed; the first valid availability query succeeds without a prior guest direct-memory API call. - `guest_direct_memory_for_app`: 5/5 passed. - `MemoryPoolTest`: 5/5 passed. - Invalid alignment still returns `EINVAL` and preserves output values. - `tools/check_conventions.py`: passed. - `tools/debt_fold.py --check`: passed. - `git diff --check`: passed. Independent Linux validation on the earlier source head also built and passed the direct-memory tests and negative control; the final follow-up changes only startup initialization and the matching initialization test. ### Checklist - [x] Based on current `main`; no other open PR implements this behavior (#18112 and #18190 mirror the NIDs through other modules only) - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except technical debt - [x] Unimplemented paths throw; no unimplemented paths added - [x] No notes or investigation files added; the debt fragment is the required technical-debt entry - [x] No third-party code added - [x] Generic behavior, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
copilot-pull-request-reviewer[bot] commented 2026-11-20 03:44:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-20T03:44:09Z.

Review: COMMENTED


Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5987166816 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063#pullrequestreview-5987166816). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-20T03:44:09Z. **Review:** COMMENTED --- Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
PrivacyOnion commented 2026-11-20 03:46:02 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-20T03:46:02Z.

Review: APPROVED


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

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_direct_memory_for_app_tests, guest_direct_memory_initialization_tests built cleanly.
  • CTest (guest_direct_memory_for_app, guest_direct_memory_initialization):
    1/2 Test #5549: guest_direct_memory_initialization ...   Passed    0.01 sec
    2/2 Test #5548: guest_direct_memory_for_app ..........   Passed    0.01 sec
    100% tests passed, 0 tests failed out of 2
    
  • Negative control: with core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp, core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp, core/libs/prx/libkernel/DirectMemory/Export.cpp, core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp reverted to main and the new tests kept, the suite fails:
    1/2 Test #5548: guest_direct_memory_for_app ..........   Passed    0.01 sec
    2/2 Test #5549: guest_direct_memory_initialization ...Subprocess aborted***Exception:   0.12 sec
    50% tests passed, 1 tests failed out of 2
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified validation ordering in sceKernelAvailableDirectMemorySize: alignment power-of-two check ((alignment & (alignment - 1)) != 0) precedes DirectMemoryIsInitialized() in DirectMemoryLargestFree, returning SCE_KERNEL_ERROR_EINVAL before SCE_KERNEL_ERROR_EBADF.
    • Verified DirectMemoryTouch() is invoked across direct memory lifecycle operations in DirectMemory.cpp, Export.cpp, and MemoryPool.cpp (allocation, deallocation, mapping, retyping, queries, locking).
    • Verified thread-safety and memory ordering of DirectMemoryState::initialized using std::atomic_bool with memory_order_release on store and memory_order_acquire on load.
    • Verified guest memory safety, guest pointer handling (GuestCopyOut_nid_no_patch), and absence of TOCTOU vulnerabilities or lock deadlocks in the touch/query logic.
    • Verified AGENTS.md technical debt fragment syntax and rules in docs/dev/debt/changes/fix-libkernel-available-direct-memory-size-ebadf.md.

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5987183042 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063#pullrequestreview-5987183042). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-20T03:46:02Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `b36322c46c`: - **Conventions**: `tools/check_conventions.py` passed. - **Build**: `guest_direct_memory_for_app_tests`, `guest_direct_memory_initialization_tests` built cleanly. - **CTest** (`guest_direct_memory_for_app`, `guest_direct_memory_initialization`): ``` 1/2 Test #5549: guest_direct_memory_initialization ... Passed 0.01 sec 2/2 Test #5548: guest_direct_memory_for_app .......... Passed 0.01 sec 100% tests passed, 0 tests failed out of 2 ``` - **Negative control**: with `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp`, `core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp`, `core/libs/prx/libkernel/DirectMemory/Export.cpp`, `core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/2 Test #5548: guest_direct_memory_for_app .......... Passed 0.01 sec 2/2 Test #5549: guest_direct_memory_initialization ...Subprocess aborted***Exception: 0.12 sec 50% tests passed, 1 tests failed out of 2 ``` Restoring the change makes it pass again. - **Code reading**: - Verified validation ordering in sceKernelAvailableDirectMemorySize: alignment power-of-two check ((alignment & (alignment - 1)) != 0) precedes DirectMemoryIsInitialized() in DirectMemoryLargestFree, returning SCE_KERNEL_ERROR_EINVAL before SCE_KERNEL_ERROR_EBADF. - Verified DirectMemoryTouch() is invoked across direct memory lifecycle operations in DirectMemory.cpp, Export.cpp, and MemoryPool.cpp (allocation, deallocation, mapping, retyping, queries, locking). - Verified thread-safety and memory ordering of DirectMemoryState::initialized using std::atomic_bool with memory_order_release on store and memory_order_acquire on load. - Verified guest memory safety, guest pointer handling (GuestCopyOut_nid_no_patch), and absence of TOCTOU vulnerabilities or lock deadlocks in the touch/query logic. - Verified AGENTS.md technical debt fragment syntax and rules in docs/dev/debt/changes/fix-libkernel-available-direct-memory-size-ebadf.md. Looks Good To Me
MarcZX10 commented 2026-11-20 05:19:21 +00:00 (Migrated from github.com)

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

Review: APPROVED


Reviewed — looks good

The change models the reported pre-initialization error and retains the existing availability search after direct memory is touched; I found no verified blocking defect in the changed code.

What I ran

Reviewed head b36322c46c314fec9a6af008ec5362c3f8894f4b. I read the prepared description, commit list, manifest, diff, and all eight changed files listed in the manifest. I also read the availability-query caller, test call sites, and direct-memory initialization code through repo_read.py. No commands or tests were run in this review.

Results

Check Result Note
Changed lines read passed All manifest-listed added lines inspected
Targeted source context passed Query and initialization paths inspected
Tests in this review not run Author-reported results are not independent runs

Findings

Blocking

None.

Non-blocking

None.

Not verified

I did not run the test suite, reproduce the firmware probe, or independently verify the author-reported Windows and Linux results. The changed files were all included and read; no changed file was excluded by the manifest.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5987892727 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063#pullrequestreview-5987892727). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-20T05:19:21Z. **Review:** APPROVED --- # Reviewed — looks good The change models the reported pre-initialization error and retains the existing availability search after direct memory is touched; I found no verified blocking defect in the changed code. ## What I ran Reviewed head `b36322c46c314fec9a6af008ec5362c3f8894f4b`. I read the prepared description, commit list, manifest, diff, and all eight changed files listed in the manifest. I also read the availability-query caller, test call sites, and direct-memory initialization code through `repo_read.py`. No commands or tests were run in this review. ## Results | Check | Result | Note | |---|---|---| | Changed lines read | passed | All manifest-listed added lines inspected | | Targeted source context | passed | Query and initialization paths inspected | | Tests in this review | not run | Author-reported results are not independent runs | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified I did not run the test suite, reproduce the firmware probe, or independently verify the author-reported Windows and Linux results. The changed files were all included and read; no changed file was excluded by the manifest. ## To get this to a good state Nothing is required.
MarcZX10 commented 2026-11-22 13:11:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-22T13:11:47Z.

Review: APPROVED


Reviewed — looks good

Nothing blocks this change; the optional documentation point below can be addressed separately.

What I ran

Reviewed head 37442eeaf1e51b093d6fcbdf2ae4d77141246b6e using repo_read.py through the supplied reader. No build or tests were run in this review; the description reports Windows and Linux test runs.

Results

Check Result Note
Changed code and tests passed Read all changed files
Build and test execution not run Author-reported results only

Findings

Blocking

None.

Non-blocking

  • The existing docs/dev/debt/libkernel.md entry for sceKernelAvailableDirectMemorySize still says the call “always searches the pool.” The new behavior changes that before initialization. Consider updating the existing entry so it does not contradict the new debt note. Changed line: docs/dev/debt/changes/fix-libkernel-available-direct-memory-size-ebadf.md:7.

Not verified

No checks were executed. The broader guest_memory suite and console behavior were not verified in this review. The author reports that the broader suite was not tested. Read all nine changed files listed as reviewed in manifest.json; no changed files were excluded by files.json.

To get this to a good state

Nothing is required. Optionally update the existing sceKernelAvailableDirectMemorySize description in docs/dev/debt/libkernel.md to reflect the initialization behavior.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6012430481 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063#pullrequestreview-6012430481). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-22T13:11:47Z. **Review:** APPROVED --- # Reviewed — looks good Nothing blocks this change; the optional documentation point below can be addressed separately. ## What I ran Reviewed head `37442eeaf1e51b093d6fcbdf2ae4d77141246b6e` using `repo_read.py` through the supplied reader. No build or tests were run in this review; the description reports Windows and Linux test runs. ## Results | Check | Result | Note | |---|---|---| | Changed code and tests | passed | Read all changed files | | Build and test execution | not run | Author-reported results only | ## Findings ### Blocking None. ### Non-blocking - The existing `docs/dev/debt/libkernel.md` entry for `sceKernelAvailableDirectMemorySize` still says the call “always searches the pool.” The new behavior changes that before initialization. Consider updating the existing entry so it does not contradict the new debt note. Changed line: `docs/dev/debt/changes/fix-libkernel-available-direct-memory-size-ebadf.md:7`. ## Not verified No checks were executed. The broader `guest_memory` suite and console behavior were not verified in this review. The author reports that the broader suite was not tested. Read all nine changed files listed as reviewed in `manifest.json`; no changed files were excluded by `files.json`. ## To get this to a good state Nothing is required. Optionally update the existing `sceKernelAvailableDirectMemorySize` description in `docs/dev/debt/libkernel.md` to reflect the initialization behavior.
PrivacyOnion commented 2026-11-23 01:07:53 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-23T01:07:53Z.

Review: APPROVED


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

  • Conventions: tools/check_conventions.py passed.
  • Build: MemoryPoolTest, guest_direct_memory_for_app_tests, guest_direct_memory_initialization_tests built cleanly.
  • CTest (MemoryPoolTest, guest_direct_memory_for_app, guest_direct_memory_initialization):
    1/3 Test #5825: guest_direct_memory_for_app ..........   Passed    0.01 sec
    2/3 Test #5826: guest_direct_memory_initialization ...   Passed    0.01 sec
    3/3 Test #1096: MemoryPoolTest .......................   Passed    0.20 sec
    100% tests passed, 0 tests failed out of 3
    
  • Negative control: with core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp, core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp, core/libs/prx/libkernel/DirectMemory/Export.cpp, core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp, core/libs/prx/libkernel/System/src/Process.cpp reverted to main and the new tests kept, the suite fails:
    1/3 Test #5825: guest_direct_memory_for_app ..........   Passed    0.01 sec
    2/3 Test #5826: guest_direct_memory_initialization ...   Passed    0.01 sec
    3/3 Test #1096: MemoryPoolTest .......................   Passed    0.20 sec
    100% tests passed, 0 tests failed out of 3
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified memory ordering and concurrency: DirectMemoryTouch uses store(release) and DirectMemoryIsInitialized uses load(acquire) on atomic_bool, preventing data races.
    • Checked error code ordering in DirectMemoryLargestFree: invalid non-power-of-two alignment checks SCE_KERNEL_ERROR_EINVAL before verifying DirectMemoryIsInitialized() returning SCE_KERNEL_ERROR_EBADF.
    • Checked pointer handling in Export.cpp: sceKernelAvailableDirectMemorySize validates outputs using GuestCopyOut_nid_no_patch to prevent illegal guest memory access.
    • Verified test coverage in GuestDirectMemoryInitialization.cpp and GuestDirectMemoryForApp.cpp: tests exercise startup state, EINVAL checks, valid query, and allocation-first touch sequences.
    • Verified PR startup touch in Process.cpp: ProgramNameRegistration calls DirectMemoryTouch() at startup as requested by maintainer oneandonlydean so titles do not unexpectedly encounter EBADF.
    • Verified AGENTS.md rules and Technical Debt entry: fragment added under docs/dev/debt/changes/ with matching functional description, no forbidden code comments added, clean conventions.

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6015536008 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063#pullrequestreview-6015536008). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-23T01:07:53Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `3ac4d05336`: - **Conventions**: `tools/check_conventions.py` passed. - **Build**: `MemoryPoolTest`, `guest_direct_memory_for_app_tests`, `guest_direct_memory_initialization_tests` built cleanly. - **CTest** (`MemoryPoolTest`, `guest_direct_memory_for_app`, `guest_direct_memory_initialization`): ``` 1/3 Test #5825: guest_direct_memory_for_app .......... Passed 0.01 sec 2/3 Test #5826: guest_direct_memory_initialization ... Passed 0.01 sec 3/3 Test #1096: MemoryPoolTest ....................... Passed 0.20 sec 100% tests passed, 0 tests failed out of 3 ``` - **Negative control**: with `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp`, `core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp`, `core/libs/prx/libkernel/DirectMemory/Export.cpp`, `core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp`, `core/libs/prx/libkernel/System/src/Process.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/3 Test #5825: guest_direct_memory_for_app .......... Passed 0.01 sec 2/3 Test #5826: guest_direct_memory_initialization ... Passed 0.01 sec 3/3 Test #1096: MemoryPoolTest ....................... Passed 0.20 sec 100% tests passed, 0 tests failed out of 3 ``` Restoring the change makes it pass again. - **Code reading**: - Verified memory ordering and concurrency: DirectMemoryTouch uses store(release) and DirectMemoryIsInitialized uses load(acquire) on atomic_bool, preventing data races. - Checked error code ordering in DirectMemoryLargestFree: invalid non-power-of-two alignment checks SCE_KERNEL_ERROR_EINVAL before verifying DirectMemoryIsInitialized() returning SCE_KERNEL_ERROR_EBADF. - Checked pointer handling in Export.cpp: sceKernelAvailableDirectMemorySize validates outputs using GuestCopyOut_nid_no_patch to prevent illegal guest memory access. - Verified test coverage in GuestDirectMemoryInitialization.cpp and GuestDirectMemoryForApp.cpp: tests exercise startup state, EINVAL checks, valid query, and allocation-first touch sequences. - Verified PR startup touch in Process.cpp: ProgramNameRegistration calls DirectMemoryTouch() at startup as requested by maintainer oneandonlydean so titles do not unexpectedly encounter EBADF. - Verified AGENTS.md rules and Technical Debt entry: fragment added under docs/dev/debt/changes/ with matching functional description, no forbidden code comments added, clean conventions. Looks Good To Me
MarcZX10 commented 2026-11-23 01:20:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T01:20:06Z.

Review: APPROVED


Reviewed — looks good

Nothing blocks this change; the reviewed code supports the described startup initialization and query behavior.

What I ran

Reviewed head 3ac4d05336c92e269db715ac8bce16b07e51873d. No commands or tests were run. The author reports Windows 11/MinGW test and convention checks in description.md; these were not independently run.

Results

Check Result Note
Diff and changed sources passed All changed files were included and read.
Tests not run Author-reported results only.

Findings

Blocking

None.

Non-blocking

None.

Not verified

No test suite, build, or convention checks were run. The reported console behavior and author-reported Windows and Linux results were not independently confirmed. files.json was not available to read; manifest lists nine changed files, all marked included, and each was read. No files were excluded according to the supplied manifest.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6015592189 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/24063#pullrequestreview-6015592189). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-23T01:20:06Z. **Review:** APPROVED --- # Reviewed — looks good Nothing blocks this change; the reviewed code supports the described startup initialization and query behavior. ## What I ran Reviewed head `3ac4d05336c92e269db715ac8bce16b07e51873d`. No commands or tests were run. The author reports Windows 11/MinGW test and convention checks in `description.md`; these were not independently run. ## Results | Check | Result | Note | |---|---|---| | Diff and changed sources | passed | All changed files were included and read. | | Tests | not run | Author-reported results only. | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified No test suite, build, or convention checks were run. The reported console behavior and author-reported Windows and Linux results were not independently confirmed. `files.json` was not available to read; manifest lists nine changed files, all marked included, and each was read. No files were excluded according to the supplied manifest. ## To get this to a good state Nothing is required.

Pull request closed

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!24063
No description provided.