fix(ajm, apr): keep AJM and APR state alive through static teardown #1926

Merged
fisherjoey merged 2 commits from upstream-pr/1926 into main 2026-10-10 04:42:42 +00:00
fisherjoey commented 2026-10-09 00:07:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fisherjoey on 2026-10-09T00:07:27Z.


What

A window close ends in std::exit on a helper thread (LibcRequestExit_nid_postfix), and std::exit destroys the host libraries' statics while the title's threads are still running. AJM and APR keep their state in namespace-scope statics, so a title thread that calls them during exit reads freed memory:

  • libSceAjm.native: g_instances and g_batches (and their mutexes). A job on a freed Instance decodes a garbage codec, sceAjmBatchWait returns SCE_AJM_ERROR_INVALID_BATCH for a batch it just started, and sceAjmInstanceDestroy frees an instance twice.
  • libkernel APR: g_files, g_idsByPath, g_directories, g_counterWrites and the AMM state from _amm(). A read resolves its file id through the freed vector.

All of these are now allocated once and never destroyed, the same approach #1197 took for NGS2. Callers don't change: the namespace-scope names are now references to the heap objects.

Closes #1925

Tested

Nobara 44 x86-64 (Linux 7.2), GCC 16.2, RTX 5070 Ti, driver 595.91.07. Base: main f1451396.

  • New test guest_ajm_teardown (UNIX only, it needs dlopen). It registers an atexit handler, then dlopens libSceAjm.native and creates an instance. Because the library is loaded after the handler is registered, its statics are destroyed before the handler runs. The handler then runs a batch on the instance, waits for the batch and destroys the instance. With main's Ajm.cpp it aborts 3 of 3 times (free(): double free detected in tcache 2). With this change it passes.
  • ctest -j1 --timeout 60: 494 of 495 pass. The one failure, guest_dynamic_loader, also fails here without this change. tools/check_conventions.py and tools/check_test_registration.py pass.
  • Demon's Souls PPSA01341 v1.07, closed with the window's close button at the attract movie after 150 s. These runs used our test stack (main from 10-07 with #1071, #1202, #1184 and local performance changes) with this commit on top. Before: 15 of 15 closes crashed (SIGABRT on AJM: decoding codec 4026830656 is not implemented, APR: cannot open <garbage> or double free or corruption, or SIGSEGV after NCA DecoderManager: sceAjmBatchWait() failed with error code 0x80930004), and 3 of 3 with #1658. After: 5 of 5 closes exit 0 with no core. One more run aborted at boot, before any close, on an X RandR error (BadRROutput) and VideoOut: presentation thread cannot stop itself. That is unrelated to this change.
  • Windows: not built. The change is plain C++.

Other libkernel state lives in namespace-scope statics too (Equeue.cpp, SyncOnAddress.cpp, DirectMemory.cpp). Demon's Souls didn't hit those in these runs, so they are left as they are.

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 in TechnicalDebt
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4794279404 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1926). Originally posted by [fisherjoey](https://github.com/fisherjoey) on 2026-10-09T00:07:27Z. --- ### What A window close ends in `std::exit` on a helper thread (`LibcRequestExit_nid_postfix`), and `std::exit` destroys the host libraries' statics while the title's threads are still running. AJM and APR keep their state in namespace-scope statics, so a title thread that calls them during exit reads freed memory: - `libSceAjm.native`: `g_instances` and `g_batches` (and their mutexes). A job on a freed `Instance` decodes a garbage codec, `sceAjmBatchWait` returns `SCE_AJM_ERROR_INVALID_BATCH` for a batch it just started, and `sceAjmInstanceDestroy` frees an instance twice. - `libkernel` APR: `g_files`, `g_idsByPath`, `g_directories`, `g_counterWrites` and the AMM state from `_amm()`. A read resolves its file id through the freed vector. All of these are now allocated once and never destroyed, the same approach #1197 took for NGS2. Callers don't change: the namespace-scope names are now references to the heap objects. Closes #1925 ### Tested Nobara 44 x86-64 (Linux 7.2), GCC 16.2, RTX 5070 Ti, driver 595.91.07. Base: `main` f1451396. - New test `guest_ajm_teardown` (UNIX only, it needs `dlopen`). It registers an `atexit` handler, then `dlopen`s `libSceAjm.native` and creates an instance. Because the library is loaded after the handler is registered, its statics are destroyed before the handler runs. The handler then runs a batch on the instance, waits for the batch and destroys the instance. With `main`'s `Ajm.cpp` it aborts 3 of 3 times (`free(): double free detected in tcache 2`). With this change it passes. - `ctest -j1 --timeout 60`: 494 of 495 pass. The one failure, `guest_dynamic_loader`, also fails here without this change. `tools/check_conventions.py` and `tools/check_test_registration.py` pass. - Demon's Souls PPSA01341 v1.07, closed with the window's close button at the attract movie after 150 s. These runs used our test stack (`main` from 10-07 with #1071, #1202, #1184 and local performance changes) with this commit on top. Before: 15 of 15 closes crashed (SIGABRT on `AJM: decoding codec 4026830656 is not implemented`, `APR: cannot open <garbage>` or `double free or corruption`, or SIGSEGV after `NCA DecoderManager: sceAjmBatchWait() failed with error code 0x80930004`), and 3 of 3 with #1658. After: 5 of 5 closes exit 0 with no core. One more run aborted at boot, before any close, on an X RandR error (`BadRROutput`) and `VideoOut: presentation thread cannot stop itself`. That is unrelated to this change. - Windows: not built. The change is plain C++. Other libkernel state lives in namespace-scope statics too (`Equeue.cpp`, `SyncOnAddress.cpp`, `DirectMemory.cpp`). Demon's Souls didn't hit those in these runs, so they are left as they are. ### Checklist - [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 - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in TechnicalDebt - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes
klosixgaming-arch commented 2026-10-09 00:46:21 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-09T00:46:21Z.

Review: APPROVED


I can approve this.

  • The *new T idiom to make these statics immortal is the established pattern here (you cite #1197 for NGS2), so it's not a novel hack — it's the project's chosen remedy for "title thread reads freed statics during std::exit". Consistent.
  • Callers are unchanged because the namespace-scope names become references to heap objects — correct, and the smallest possible surface for the change.
  • The test is excellent: it dlopens the library after registering the atexit handler so the library's statics are destroyed before the handler runs, then exercises AJM from the handler. main aborts 3/3 (double free in tcache 2), this branch passes. That's a genuine regression test for the exact failure class, not a symbol check.
  • You correctly scope it to AJM+APR and explicitly note the other libkernel namespace statics (Equeue.cpp, SyncOnAddress.cpp, DirectMemory.cpp) that weren't hit — honest boundary, not silent.

Non-blocking note: the deliberate leak is the whole point, but a reader glancing at std::mutex& g_lock = *new std::mutex(); might not know it's intentional project policy. A one-line debt/CONVENTIONS pointer (or a shared helper Immortal<T>) would stop a future reviewer from "fixing" it back to a normal static. Worth it given it's now in at least three files.

Written with AI assistance.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5464516569 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1926#pullrequestreview-5464516569). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-09T00:46:21Z. **Review:** APPROVED --- I can approve this. - The `*new T` idiom to make these statics immortal is the established pattern here (you cite #1197 for NGS2), so it's not a novel hack — it's the project's chosen remedy for "title thread reads freed statics during `std::exit`". Consistent. - Callers are unchanged because the namespace-scope names become references to heap objects — correct, and the smallest possible surface for the change. - The test is excellent: it `dlopen`s the library *after* registering the `atexit` handler so the library's statics are destroyed before the handler runs, then exercises AJM from the handler. `main` aborts 3/3 (`double free in tcache 2`), this branch passes. That's a genuine regression test for the exact failure class, not a symbol check. - You correctly scope it to AJM+APR and explicitly note the other `libkernel` namespace statics (`Equeue.cpp`, `SyncOnAddress.cpp`, `DirectMemory.cpp`) that weren't hit — honest boundary, not silent. Non-blocking note: the deliberate leak is the whole point, but a reader glancing at `std::mutex& g_lock = *new std::mutex();` might not know it's intentional project policy. A one-line debt/`CONVENTIONS` pointer (or a shared helper `Immortal<T>`) would stop a future reviewer from "fixing" it back to a normal static. Worth it given it's now in at least three files. Written with AI assistance.
popcoder565 commented 2026-10-09 10:25:53 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by popcoder565 on 2026-10-09T10:25:53Z.


Windows build check, since the description says Windows wasn't built. Setup: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release. Merged onto main 745b775e together with #1926, #1950, #1260 and #1988. Full ctest: 507/507.

  • It builds.
  • The existing guest_ajm and APR tests pass.
  • The new guest_ajm_teardown is registered under if(UNIX), so it didn't run here.

🤖 Addressed by Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6079043704 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1926#issuecomment-6079043704). Originally posted by [popcoder565](https://github.com/popcoder565) on 2026-10-09T10:25:53Z. --- Windows build check, since the description says Windows wasn't built. Setup: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release. Merged onto `main` 745b775e together with #1926, #1950, #1260 and #1988. Full ctest: 507/507. - It builds. - The existing `guest_ajm` and APR tests pass. - The new `guest_ajm_teardown` is registered under `if(UNIX)`, so it didn't run here. _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
fisherjoey commented 2026-10-09 15:14:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fisherjoey on 2026-10-09T15:14:30Z.


@klosixgaming-arch thanks. I added a TechnicalDebt entry for the leaked statics (NGS2, AJM, APR) in f79d69cc, since code comments aren't allowed here. A shared helper would also change NGS2, so I'd leave it for another PR.

@popcoder565 thanks for the Windows build. The teardown test is Unix-only on purpose. It depends on the ELF order in which a dlopen'd library's statics are destroyed relative to atexit handlers. On Windows a DLL's own atexit handlers and static destructors run when that DLL detaches (DLL_PROCESS_DETACH), so the same setup doesn't reproduce the ordering there.

AI-assisted: yes

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6083734865 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1926#issuecomment-6083734865). Originally posted by [fisherjoey](https://github.com/fisherjoey) on 2026-10-09T15:14:30Z. --- @klosixgaming-arch thanks. I added a TechnicalDebt entry for the leaked statics (NGS2, AJM, APR) in f79d69cc, since code comments aren't allowed here. A shared helper would also change NGS2, so I'd leave it for another PR. @popcoder565 thanks for the Windows build. The teardown test is Unix-only on purpose. It depends on the ELF order in which a `dlopen`'d library's statics are destroyed relative to `atexit` handlers. On Windows a DLL's own `atexit` handlers and static destructors run when that DLL detaches (`DLL_PROCESS_DETACH`), so the same setup doesn't reproduce the ordering there. AI-assisted: yes
github-actions[bot] commented 2026-10-10 02:45:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-10T02:45:01Z.


Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#1969 docs/dev/TechnicalDebt.md L398
#2142 docs/dev/TechnicalDebt.md L398
#2545 core/libs/tests/GuestAjmTeardown.cpp
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6092936532 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1926#issuecomment-6092936532). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-10T02:45:01Z. --- <!-- pr-overlap --> Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in **Depends on**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | #1969 | `docs/dev/TechnicalDebt.md` [L398](https://github.com/boykopovar/AnyPS5/blob/80d539abcbd0f90a7b6e64f7ab4868556671f241/docs/dev/TechnicalDebt.md#L398) | | | | #2142 | `docs/dev/TechnicalDebt.md` [L398](https://github.com/boykopovar/AnyPS5/blob/80d539abcbd0f90a7b6e64f7ab4868556671f241/docs/dev/TechnicalDebt.md#L398) | | | | #2545 | | | `core/libs/tests/GuestAjmTeardown.cpp` |
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!1926
No description provided.