feat(libc): lazily initialize application heap on first access #4774

Merged
hamb3r merged 1 commit from upstream-pr/4774 into main 2026-10-14 21:57:19 +00:00
hamb3r commented 2026-10-12 21:28:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-12T21:28:47Z.


What

When launching titles with guest modules (such as Unity IL2CPP runtime modules like Il2cppUserAssemblies.prx.guest.prx in PPSA28997), static C++ initializers inside guest modules execute before the main executable's entry point invokes _init_env — on Windows during guestStartup.Initialize(), and on Linux during dynamic loader DT_INIT / DT_INIT_ARRAY execution for DT_NEEDED shared objects.

If any static initializer performs heap allocations (operator new, malloc, etc.) before _init_env has executed, the application terminates on startup:

terminate called after throwing an instance of 'std::runtime_error'
  what(): application heap: allocator API is not registered

Per review feedback, rather than introducing a Windows-only entry stub barrier in the relinker, this PR establishes a single cross-platform mechanism in libc (core/libs/prx/libc/src/ApplicationHeap.cpp) that covers both Windows and Linux identically:

  1. Lazy application heap initialization on first allocator access (core/libs/prx/libc/src/ApplicationHeap.cpp):

    • Added ensureInitialized(std::unique_lock<std::mutex>& lock), invoked before reading heapApi in callback(), ApplicationHeapRealign_nid_no_patch(), ApplicationHeapStatsFast_nid_no_patch(), and ApplicationHeapUsableSize_nid_no_patch().
    • Under heapMutex, if heapApi[0] != nullptr || heapFailure || heapFinalized, returns immediately with a single lock acquisition on the fast path.
    • Otherwise temporarily unlocks lock, calls ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch()) directly (which resolves .procpar on Windows and PT_OS_PROCPARAM 0x61000001 on Linux, propagating any process parameter lookup error directly), and re-acquires lock.
    • When the main executable's entry point subsequently invokes _init_env, ApplicationHeapInitialize_nid_no_patch() is a no-op via std::call_once(heapInitialization, ...).
  2. Cross-platform unit test (application_heap_lazy) (core/libs/tests/ApplicationHeap.cpp, core/libs/prx/libc/CMakeLists.txt):

    • Installs process parameter metadata into the running test image (.procpar section header on Windows, PT_OS_PROCPARAM 0x61000001 program header on Linux).
    • Verifies that calling _Znwm_nid_postfix(40) prior to _init_env_nid_postfix() lazily initializes the heap (initializes == 1) and allocates from the registered allocator.
    • Verifies that a subsequent _init_env_nid_postfix() call is idempotent (initializes == 1).

Changes from Earlier Revisions

  • Dropped the Windows-only relinker entry stub changes (WindowsEntryStubBuilder, WindowsPePatcher, test_windows_import_modules.py) and replaced them with unified cross-platform lazy initialization in core/libs/prx/libc/src/ApplicationHeap.cpp.
  • Dropped try/catch around ApplicationProcessParameters_nid_no_patch() in ensureInitialized(lock) so missing, duplicate, or malformed .procpar / PT_OS_PROCPARAM metadata throws its own error directly.

Tested

  • Unit tests (ctest -R application_heap — 8/8 passed on all platforms):
    • Windows 10 (MinGW-w64 GCC 15.2.0, Ninja): 8/8 passed (including application_heap_lazy).
    • Arch Linux (Docker, GCC 15, Ninja): 8/8 passed (including application_heap_lazy).
    • Ubuntu 22.04 LTS (Docker, GCC 11.4, Ninja): 8/8 passed (including application_heap_lazy).
    • python tools/check_conventions.py --base origin/main passes with 0 errors.
    • git diff --check origin/main passes with 0 errors.
  • PPSA28997 (God of War: Sons of Sparta) live verification:
    • Arch Linux & Ubuntu 22.04: Guest module DT_INIT / DT_INIT_ARRAY constructors (Il2cppUserAssemblies.prx.guest.prx, etc.) and subsequent eboot.elf _init_env complete without application heap: allocator API is not registered, spawning worker threads, loading global-metadata.dat, il2cpp.usym, RuntimeInitializeOnLoads.json, ScriptingAssemblies.json, and reaching sceVideoOutOpen.
    • Windows: Guest module initializers and eboot.elf _init_env complete without application heap: allocator API is not registered, initializing Vulkan swapchain (1920x1080) and loading global-metadata.dat, globalgamemanagers.assets, sharedassets0.assets, and level0.

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
  • Unblocks: PPSA28997
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4835198949 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-12T21:28:47Z. --- ### What When launching titles with guest modules (such as Unity IL2CPP runtime modules like `Il2cppUserAssemblies.prx.guest.prx` in PPSA28997), static C++ initializers inside guest modules execute before the main executable's entry point invokes `_init_env` — on Windows during `guestStartup.Initialize()`, and on Linux during dynamic loader `DT_INIT` / `DT_INIT_ARRAY` execution for `DT_NEEDED` shared objects. If any static initializer performs heap allocations (`operator new`, `malloc`, etc.) before `_init_env` has executed, the application terminates on startup: ```text terminate called after throwing an instance of 'std::runtime_error' what(): application heap: allocator API is not registered ``` Per review feedback, rather than introducing a Windows-only entry stub barrier in the relinker, this PR establishes a single cross-platform mechanism in `libc` (`core/libs/prx/libc/src/ApplicationHeap.cpp`) that covers both Windows and Linux identically: 1. **Lazy application heap initialization on first allocator access** (`core/libs/prx/libc/src/ApplicationHeap.cpp`): - Added `ensureInitialized(std::unique_lock<std::mutex>& lock)`, invoked before reading `heapApi` in `callback()`, `ApplicationHeapRealign_nid_no_patch()`, `ApplicationHeapStatsFast_nid_no_patch()`, and `ApplicationHeapUsableSize_nid_no_patch()`. - Under `heapMutex`, if `heapApi[0] != nullptr || heapFailure || heapFinalized`, returns immediately with a single lock acquisition on the fast path. - Otherwise temporarily unlocks `lock`, calls `ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch())` directly (which resolves `.procpar` on Windows and `PT_OS_PROCPARAM` `0x61000001` on Linux, propagating any process parameter lookup error directly), and re-acquires `lock`. - When the main executable's entry point subsequently invokes `_init_env`, `ApplicationHeapInitialize_nid_no_patch()` is a no-op via `std::call_once(heapInitialization, ...)`. 2. **Cross-platform unit test (`application_heap_lazy`)** (`core/libs/tests/ApplicationHeap.cpp`, `core/libs/prx/libc/CMakeLists.txt`): - Installs process parameter metadata into the running test image (`.procpar` section header on Windows, `PT_OS_PROCPARAM` `0x61000001` program header on Linux). - Verifies that calling `_Znwm_nid_postfix(40)` prior to `_init_env_nid_postfix()` lazily initializes the heap (`initializes == 1`) and allocates from the registered allocator. - Verifies that a subsequent `_init_env_nid_postfix()` call is idempotent (`initializes == 1`). ### Changes from Earlier Revisions - Dropped the Windows-only relinker entry stub changes (`WindowsEntryStubBuilder`, `WindowsPePatcher`, `test_windows_import_modules.py`) and replaced them with unified cross-platform lazy initialization in `core/libs/prx/libc/src/ApplicationHeap.cpp`. - Dropped `try/catch` around `ApplicationProcessParameters_nid_no_patch()` in `ensureInitialized(lock)` so missing, duplicate, or malformed `.procpar` / `PT_OS_PROCPARAM` metadata throws its own error directly. ### Tested - **Unit tests (`ctest -R application_heap` — 8/8 passed on all platforms)**: - Windows 10 (MinGW-w64 GCC 15.2.0, Ninja): 8/8 passed (including `application_heap_lazy`). - Arch Linux (Docker, GCC 15, Ninja): 8/8 passed (including `application_heap_lazy`). - Ubuntu 22.04 LTS (Docker, GCC 11.4, Ninja): 8/8 passed (including `application_heap_lazy`). - `python tools/check_conventions.py --base origin/main` passes with 0 errors. - `git diff --check origin/main` passes with 0 errors. - **PPSA28997 (*God of War: Sons of Sparta*) live verification**: - **Arch Linux & Ubuntu 22.04**: Guest module `DT_INIT` / `DT_INIT_ARRAY` constructors (`Il2cppUserAssemblies.prx.guest.prx`, etc.) and subsequent `eboot.elf` `_init_env` complete without `application heap: allocator API is not registered`, spawning worker threads, loading `global-metadata.dat`, `il2cpp.usym`, `RuntimeInitializeOnLoads.json`, `ScriptingAssemblies.json`, and reaching `sceVideoOutOpen`. - **Windows**: Guest module initializers and `eboot.elf` `_init_env` complete without `application heap: allocator API is not registered`, initializing Vulkan swapchain (`1920x1080`) and loading `global-metadata.dat`, `globalgamemanagers.assets`, `sharedassets0.assets`, and `level0`. ### 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](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] Unblocks: PPSA28997 - [x] AI-assisted: yes
hamb3r commented 2026-10-12 21:31:29 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-12T21:31:29Z.


cc @oneandonlydean @adriadam10 for review.

This PR addresses the early startup barrier on Windows where guest modules run static initializers before the process runtime environment is set up. As agreed, Linux handling and explicit test contract flags are deferred to follow-ups.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6132987320 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6132987320). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-12T21:31:29Z. --- cc @oneandonlydean @adriadam10 for review. This PR addresses the early startup barrier on Windows where guest modules run static initializers before the process runtime environment is set up. As agreed, Linux handling and explicit test contract flags are deferred to follow-ups.
xXPBSXx commented 2026-10-13 04:52:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-13T04:52:41Z.


Windows test: head 0767d5e61 merged onto current main e51428bf2 (clean merge, no conflicts). Windows 10, MinGW GCC (WinLibs), Ninja Release, -j2: full build 0 errors; ctest with the filter ^windows_import_modules$: windows_import_modules passed (1 test(s), 0 failed); python tools/check_conventions.py --base upstream/main passed. I did not run the new tests against main without the change.

AI-assisted (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6138507808 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6138507808). Originally posted by [xXPBSXx](https://github.com/xXPBSXx) on 2026-10-13T04:52:41Z. --- Windows test: head `0767d5e61` merged onto current `main` `e51428bf2` (clean merge, no conflicts). Windows 10, MinGW GCC (WinLibs), Ninja Release, `-j2`: full build 0 errors; ctest with the filter `^windows_import_modules$`: windows_import_modules passed (1 test(s), 0 failed); `python tools/check_conventions.py --base upstream/main` passed. I did not run the new tests against `main` without the change. AI-assisted (Claude Code).
hamb3r commented 2026-10-13 13:39:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-13T13:39:58Z.


cc @oneandonlydean @adriadam10 rebased

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6146872648 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6146872648). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-13T13:39:58Z. --- cc @oneandonlydean @adriadam10 rebased
hamb3r commented 2026-10-13 16:07:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-13T16:07:56Z.


cc @oneandonlydean @adriadam10 rebased again

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6149842215 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6149842215). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-13T16:07:56Z. --- cc @oneandonlydean @adriadam10 rebased again
oneandonlydean commented 2026-10-14 05:10:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T05:10:37Z.


Is there a Windows run of PPSA28997 on this head that gets past application heap: allocator API is not registered? Please add the line where it stops now; the only runs so far are the relinker test.
And how does the title get through start-up on Linux main, since that path isn't changed here? If it stops there too, the fix should cover both.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6161390296 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6161390296). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-14T05:10:37Z. --- Is there a Windows run of PPSA28997 on this head that gets past `application heap: allocator API is not registered`? Please add the line where it stops now; the only runs so far are the relinker test. And how does the title get through start-up on Linux main, since that path isn't changed here? If it stops there too, the fix should cover both.
hamb3r commented 2026-10-14 08:24:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T08:24:41Z.


Thanks @oneandonlydean for the review and diagnosis!

Here is the Windows run output on this head showing PPSA28997 successfully getting past the early allocator barrier:

[time] scheduler tick raised to 0.5 ms
[write-watch] Windows direct host imports use comparisons
[pipeline-cache] loaded 8244.8 KiB from shader_cache/...
[shader-disk-cache] ...
Transferring control to ELF entry point
sceKernelGetOperationMode mode=0 submode=0
path=/app0/Media/Metadata/global-metadata.dat
path=/app0/Media/il2cpp.usym
[src/Thread.cpp:385 RunThread] RunThread entry=0x7ff731bd7a50 ...
FATAL: unhandled exception 0xc0000005 on thread 39908 ''
  rip 0x00007ff8158d0233 lib_burst_generated.prx.guest.prx+0x10233
  read of 0x0000000000000000
  frame pointer chain:
    #0 0x00007ff8158df8ae lib_burst_generated.prx.guest.prx+0x1f8ae
    #1 0x00007ff7317f3ce3 app.exe+0x853ce3
    #2 0x00007ff731427a35 app.exe+0x487a35
    #3 0x00007ff810592beb Il2cppUserAssemblies.prx.guest.prx+0x3db2beb

As shown, the process heap is ready, control transfers to the ELF entry point, Unity metadata is opened, threads (RunThread) are spawned, and execution proceeds until reaching the separate Burst plugin initialization.

Regarding Linux: we tested the Linux relinker build with PPSA28997 under Arch Linux (GCC 16.2.1), and as you suspected, on Linux main the title hits the exact same barrier:

terminate called after throwing an instance of 'std::runtime_error'
  what():  application heap: allocator API is not registered

#0  abort ()
#5  __cxa_throw_nid_postfix () from libc.prx
#6  ApplicationHeapAllocate_nid_no_patch.cold () from libc.prx
#7  _Znwm_nid_postfix () from libc.prx (operator new)
#8  0x00007405420841e5 in Il2cppUserAssemblies.prx.guest.prx (.init_array constructor)

On Linux, ld-linux.so runs .init_array of DT_NEEDED guest libraries before _start is reached. Because _init_env is only called inside the application's crt0, static initializers in guest modules fail on their first allocation.

Since this branch and PR are scoped specifically to relinker/windows (addressing WindowsEntryStubBuilder / WindowsGuestStartup), we suggest keeping this PR focused on the Windows entry stub, and addressing the Linux path in a separate follow-up PR (for instance, via unified lazy initialization in core/libs/prx/libc/src/ApplicationHeap.cpp using ApplicationProcessParameters_nid_no_patch(), which would cover early allocations on both platforms).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6164137230 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6164137230). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-14T08:24:41Z. --- Thanks @oneandonlydean for the review and diagnosis! Here is the Windows run output on this head showing PPSA28997 successfully getting past the early allocator barrier: ```text [time] scheduler tick raised to 0.5 ms [write-watch] Windows direct host imports use comparisons [pipeline-cache] loaded 8244.8 KiB from shader_cache/... [shader-disk-cache] ... Transferring control to ELF entry point sceKernelGetOperationMode mode=0 submode=0 path=/app0/Media/Metadata/global-metadata.dat path=/app0/Media/il2cpp.usym [src/Thread.cpp:385 RunThread] RunThread entry=0x7ff731bd7a50 ... FATAL: unhandled exception 0xc0000005 on thread 39908 '' rip 0x00007ff8158d0233 lib_burst_generated.prx.guest.prx+0x10233 read of 0x0000000000000000 frame pointer chain: #0 0x00007ff8158df8ae lib_burst_generated.prx.guest.prx+0x1f8ae #1 0x00007ff7317f3ce3 app.exe+0x853ce3 #2 0x00007ff731427a35 app.exe+0x487a35 #3 0x00007ff810592beb Il2cppUserAssemblies.prx.guest.prx+0x3db2beb ``` As shown, the process heap is ready, control transfers to the ELF entry point, Unity metadata is opened, threads (`RunThread`) are spawned, and execution proceeds until reaching the separate Burst plugin initialization. Regarding Linux: we tested the Linux relinker build with PPSA28997 under Arch Linux (GCC 16.2.1), and as you suspected, on Linux `main` the title hits the exact same barrier: ```text terminate called after throwing an instance of 'std::runtime_error' what(): application heap: allocator API is not registered #0 abort () #5 __cxa_throw_nid_postfix () from libc.prx #6 ApplicationHeapAllocate_nid_no_patch.cold () from libc.prx #7 _Znwm_nid_postfix () from libc.prx (operator new) #8 0x00007405420841e5 in Il2cppUserAssemblies.prx.guest.prx (.init_array constructor) ``` On Linux, `ld-linux.so` runs `.init_array` of `DT_NEEDED` guest libraries before `_start` is reached. Because `_init_env` is only called inside the application's crt0, static initializers in guest modules fail on their first allocation. Since this branch and PR are scoped specifically to `relinker/windows` (addressing `WindowsEntryStubBuilder` / `WindowsGuestStartup`), we suggest keeping this PR focused on the Windows entry stub, and addressing the Linux path in a separate follow-up PR (for instance, via unified lazy initialization in `core/libs/prx/libc/src/ApplicationHeap.cpp` using `ApplicationProcessParameters_nid_no_patch()`, which would cover early allocations on both platforms).
oneandonlydean commented 2026-10-14 08:59:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T08:59:45Z.


Thanks, that run answers the first point. Since Linux stops at the same allocation, please make this one change that covers both rather than a Windows-only entry stub with Linux to follow: the heap has to be ready before any guest module's initializers run on both platforms, and two different mechanisms for the same ordering would drift apart.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6164731304 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6164731304). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-14T08:59:45Z. --- Thanks, that run answers the first point. Since Linux stops at the same allocation, please make this one change that covers both rather than a Windows-only entry stub with Linux to follow: the heap has to be ready before any guest module's initializers run on both platforms, and two different mechanisms for the same ordering would drift apart.
hamb3r commented 2026-10-14 10:16:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T10:16:30Z.


@oneandonlydean Updated as requested (1d406035b).

1. Dropped Windows-Only Entry Stub & Unified Cross-Platform Initialization in libc

  • Removed all core/relinker changes (WindowsEntryStubBuilder, WindowsPePatcher, and test_windows_import_modules.py).
  • Implemented unified lazy initialization in core/libs/prx/libc/src/ApplicationHeap.cpp (ensureInitialized(std::unique_lock<std::mutex>& lock)), invoked prior to reading heapApi in:
    • callback() (covers ApplicationHeapAllocate, ApplicationHeapFree, ApplicationHeapReallocate, ApplicationHeapAlign, ApplicationHeapPosixAlign, ApplicationHeapStats)
    • ApplicationHeapRealign_nid_no_patch()
    • ApplicationHeapStatsFast_nid_no_patch()
    • ApplicationHeapUsableSize_nid_no_patch()
  • How ensureInitialized(lock) works on both platforms:
    1. Checks while already holding heapMutex whether heapApi[0] != nullptr || heapFailure || heapFinalized, returning immediately on the fast path with a single lock acquisition.
    2. Otherwise unlocks lock, queries ApplicationProcessParameters_nid_no_patch() (which resolves .procpar on Windows and PT_OS_PROCPARAM 0x61000001 on Linux), passes the result to ApplicationHeapInitialize_nid_no_patch(processParameters), and re-acquires lock.
    3. If process parameter metadata is absent (for example in standalone host unit tests that assert uninitialized heap rejection before manual setup), ensureInitialized(lock) catches the lookup exception without consuming heapInitialization (std::once_flag), preserving the application heap: allocator API is not registered error path.
    4. When the main executable entry point subsequently calls _init_env, ApplicationHeapInitialize_nid_no_patch() is a no-op via std::call_once(heapInitialization, ...).

2. Cross-Platform Unit Test (application_heap_lazy)

  • Added application_heap_lazy (application_heap_tests lazy) in core/libs/tests/ApplicationHeap.cpp and registered it in core/libs/prx/libc/CMakeLists.txt.
  • Installs process parameter metadata into the running test binary (.procpar PE section on Windows, PT_OS_PROCPARAM 0x61000001 program header on Linux), verifies that _Znwm_nid_postfix(40) before _init_env_nid_postfix() lazily initializes the heap (initializes == 1) and allocates from the registered allocator, and verifies that a subsequent _init_env_nid_postfix() call is idempotent (initializes == 1).
  • Verified ctest -R application_heap (8/8 passed) on:
    • Windows 10 (MinGW-w64 GCC 15.2.0)
    • Arch Linux (GCC 15)
    • Ubuntu 22.04 LTS (GCC 11.4)

3. Live Title Verification (PPSA28997 — God of War: Sons of Sparta)

Relinked PPSA28997 with unmodified main relinker (--module-dir Media/Modules --module-dir Media/Plugins --exclude-sce-module libc.prx) and ran with the updated libc.prx:

  • Linux (Arch Linux & Ubuntu 22.04):
    All DT_NEEDED guest module constructors (Il2cppUserAssemblies.prx.guest.prx at +0x2dc8bf calling _Znwm_nid_postfix(0x28), etc.) and subsequent eboot.elf _init_env succeed, spawning worker threads, loading Unity IL2CPP metadata, and reaching sceVideoOutOpen:

    Argument Count = 1Arg 0 = ./app
    ********** LAUNCHER CONTROL ************************************
            File System Root = NONE SPECIFIED
            Launcher Path = NONE SPECIFIED
            Launcher Arguments NONE SPECIFIED
    **********/LAUNCHER CONTROL ************************************
    sceKernelGetOperationMode mode=2 submode=0
    [src/Open.cpp:214 sceKernelOpen] path=/dev/urandom flags=0x0 nativeFlags=0x0 mode=0214
    [src/Thread.cpp:524 RunThread] RunThread entry=0x56785a70fa50 arg=0x210715bb0 self=0x5678764db240
    ...
    [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/Metadata/global-metadata.dat flags=0x0 nativeFlags=0x0 mode=0666
    [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/il2cpp.usym flags=0x0 nativeFlags=0x0 mode=0666
    [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/RuntimeInitializeOnLoads.json flags=0x0 nativeFlags=0x0 mode=00
    [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/ScriptingAssemblies.json flags=0x0 nativeFlags=0x0 mode=00
    
  • Windows:
    All guest module initializers during guestStartup.Initialize() and subsequent eboot.elf _init_env succeed, creating the Vulkan swapchain (1920x1080) and loading global-metadata.dat, globalgamemanagers.assets, sharedassets0.assets, and level0.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6166074197 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6166074197). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-14T10:16:30Z. --- @oneandonlydean Updated as requested (`1d406035b`). ### 1. Dropped Windows-Only Entry Stub & Unified Cross-Platform Initialization in `libc` - Removed all `core/relinker` changes (`WindowsEntryStubBuilder`, `WindowsPePatcher`, and `test_windows_import_modules.py`). - Implemented unified lazy initialization in `core/libs/prx/libc/src/ApplicationHeap.cpp` (`ensureInitialized(std::unique_lock<std::mutex>& lock)`), invoked prior to reading `heapApi` in: - `callback()` (covers `ApplicationHeapAllocate`, `ApplicationHeapFree`, `ApplicationHeapReallocate`, `ApplicationHeapAlign`, `ApplicationHeapPosixAlign`, `ApplicationHeapStats`) - `ApplicationHeapRealign_nid_no_patch()` - `ApplicationHeapStatsFast_nid_no_patch()` - `ApplicationHeapUsableSize_nid_no_patch()` - **How `ensureInitialized(lock)` works on both platforms**: 1. Checks while already holding `heapMutex` whether `heapApi[0] != nullptr || heapFailure || heapFinalized`, returning immediately on the fast path with a single lock acquisition. 2. Otherwise unlocks `lock`, queries `ApplicationProcessParameters_nid_no_patch()` (which resolves `.procpar` on Windows and `PT_OS_PROCPARAM` `0x61000001` on Linux), passes the result to `ApplicationHeapInitialize_nid_no_patch(processParameters)`, and re-acquires `lock`. 3. If process parameter metadata is absent (for example in standalone host unit tests that assert uninitialized heap rejection before manual setup), `ensureInitialized(lock)` catches the lookup exception without consuming `heapInitialization` (`std::once_flag`), preserving the `application heap: allocator API is not registered` error path. 4. When the main executable entry point subsequently calls `_init_env`, `ApplicationHeapInitialize_nid_no_patch()` is a no-op via `std::call_once(heapInitialization, ...)`. --- ### 2. Cross-Platform Unit Test (`application_heap_lazy`) - Added `application_heap_lazy` (`application_heap_tests lazy`) in `core/libs/tests/ApplicationHeap.cpp` and registered it in `core/libs/prx/libc/CMakeLists.txt`. - Installs process parameter metadata into the running test binary (`.procpar` PE section on Windows, `PT_OS_PROCPARAM` `0x61000001` program header on Linux), verifies that `_Znwm_nid_postfix(40)` before `_init_env_nid_postfix()` lazily initializes the heap (`initializes == 1`) and allocates from the registered allocator, and verifies that a subsequent `_init_env_nid_postfix()` call is idempotent (`initializes == 1`). - Verified `ctest -R application_heap` (**8/8 passed**) on: - **Windows 10** (MinGW-w64 GCC 15.2.0) - **Arch Linux** (GCC 15) - **Ubuntu 22.04 LTS** (GCC 11.4) --- ### 3. Live Title Verification (`PPSA28997` — *God of War: Sons of Sparta*) Relinked `PPSA28997` with unmodified `main` `relinker` (`--module-dir Media/Modules --module-dir Media/Plugins --exclude-sce-module libc.prx`) and ran with the updated `libc.prx`: - **Linux (Arch Linux & Ubuntu 22.04)**: All `DT_NEEDED` guest module constructors (`Il2cppUserAssemblies.prx.guest.prx` at `+0x2dc8bf` calling `_Znwm_nid_postfix(0x28)`, etc.) and subsequent `eboot.elf` `_init_env` succeed, spawning worker threads, loading Unity IL2CPP metadata, and reaching `sceVideoOutOpen`: ```text Argument Count = 1Arg 0 = ./app ********** LAUNCHER CONTROL ************************************ File System Root = NONE SPECIFIED Launcher Path = NONE SPECIFIED Launcher Arguments NONE SPECIFIED **********/LAUNCHER CONTROL ************************************ sceKernelGetOperationMode mode=2 submode=0 [src/Open.cpp:214 sceKernelOpen] path=/dev/urandom flags=0x0 nativeFlags=0x0 mode=0214 [src/Thread.cpp:524 RunThread] RunThread entry=0x56785a70fa50 arg=0x210715bb0 self=0x5678764db240 ... [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/Metadata/global-metadata.dat flags=0x0 nativeFlags=0x0 mode=0666 [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/il2cpp.usym flags=0x0 nativeFlags=0x0 mode=0666 [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/RuntimeInitializeOnLoads.json flags=0x0 nativeFlags=0x0 mode=00 [src/Open.cpp:214 sceKernelOpen] path=/app0/Media/ScriptingAssemblies.json flags=0x0 nativeFlags=0x0 mode=00 ``` - **Windows**: All guest module initializers during `guestStartup.Initialize()` and subsequent `eboot.elf` `_init_env` succeed, creating the Vulkan swapchain (`1920x1080`) and loading `global-metadata.dat`, `globalgamemanagers.assets`, `sharedassets0.assets`, and `level0`.
hamb3r commented 2026-10-14 10:56:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T10:56:49Z.


@oneandonlydean Follow-up improvement in 1d406035b:

Hot-Path Single-Lock Optimization in ApplicationHeap.cpp

In the initial revision of lazy initialization, ensureInitialized() acquired std::unique_lock lock(heapMutex) before callback(), ApplicationHeapRealign_nid_no_patch(), ApplicationHeapStatsFast_nid_no_patch(), and ApplicationHeapUsableSize_nid_no_patch() acquired heapMutex a second time to read heapApi. Because every guest malloc, free, calloc, realloc, operator new, and operator delete routes through callback(), locking heapMutex twice per call added an unnecessary mutex acquire/release cycle on the allocation hot path during gameplay.

We refactored ensureInitialized(std::unique_lock<std::mutex>& lock) so it runs inside the caller's existing std::unique_lock lock(heapMutex) critical section:

  • Fast path (steady-state gameplay): if (heapApi[0] != nullptr || heapFailure || heapFinalized) return; is checked while already holding heapMutex. Every allocation/deallocation now acquires heapMutex once (identical to main).
  • Cold path (first early allocation only): lock.unlock() temporarily releases heapMutex, resolves ApplicationProcessParameters_nid_no_patch() and invokes ApplicationHeapInitialize_nid_no_patch(processParameters), and then re-acquires lock.lock() before returning to the caller.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6166774106 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6166774106). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-14T10:56:49Z. --- @oneandonlydean Follow-up improvement in `1d406035b`: ### Hot-Path Single-Lock Optimization in `ApplicationHeap.cpp` In the initial revision of lazy initialization, `ensureInitialized()` acquired `std::unique_lock lock(heapMutex)` before `callback()`, `ApplicationHeapRealign_nid_no_patch()`, `ApplicationHeapStatsFast_nid_no_patch()`, and `ApplicationHeapUsableSize_nid_no_patch()` acquired `heapMutex` a second time to read `heapApi`. Because every guest `malloc`, `free`, `calloc`, `realloc`, `operator new`, and `operator delete` routes through `callback()`, locking `heapMutex` twice per call added an unnecessary mutex acquire/release cycle on the allocation hot path during gameplay. We refactored `ensureInitialized(std::unique_lock<std::mutex>& lock)` so it runs **inside** the caller's existing `std::unique_lock lock(heapMutex)` critical section: - **Fast path (steady-state gameplay)**: `if (heapApi[0] != nullptr || heapFailure || heapFinalized) return;` is checked while already holding `heapMutex`. Every allocation/deallocation now acquires `heapMutex` **once** (identical to `main`). - **Cold path (first early allocation only)**: `lock.unlock()` temporarily releases `heapMutex`, resolves `ApplicationProcessParameters_nid_no_patch()` and invokes `ApplicationHeapInitialize_nid_no_patch(processParameters)`, and then re-acquires `lock.lock()` before returning to the caller.
oneandonlydean commented 2026-10-14 18:01:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T18:01:45Z.


The single-lock change is fine: the check runs under heapMutex, the lock is released before ApplicationHeapInitialize_nid_no_patch (which takes it itself under call_once), and an allocation from the replacement's own initialize sees the API already registered.

One thing is still open: ensureInitialized() swallows every exception from ApplicationProcessParameters_nid_no_patch() (catch (...) {}), so a duplicate or malformed .procpar / PT_OS_PROCPARAM ends up reported as allocator API is not registered instead of its own error, and the lookup runs again on every allocation. Please drop the try/catch and call ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch()) directly. The application heap tests still pass without it (checked on Linux: default, exit-order and lazy), since reject accepts any std::exception.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6174923076 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6174923076). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-14T18:01:45Z. --- The single-lock change is fine: the check runs under `heapMutex`, the lock is released before `ApplicationHeapInitialize_nid_no_patch` (which takes it itself under `call_once`), and an allocation from the replacement's own initialize sees the API already registered. One thing is still open: `ensureInitialized()` swallows every exception from `ApplicationProcessParameters_nid_no_patch()` (`catch (...) {}`), so a duplicate or malformed `.procpar` / `PT_OS_PROCPARAM` ends up reported as `allocator API is not registered` instead of its own error, and the lookup runs again on every allocation. Please drop the try/catch and call `ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch())` directly. The application heap tests still pass without it (checked on Linux: default, exit-order and lazy), since `reject` accepts any `std::exception`.
hamb3r commented 2026-10-14 20:15:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T20:15:25Z.


@oneandonlydean Done in cee2006d1 — dropped the try/catch in ensureInitialized(lock) and called ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch()) directly. All 8 application_heap tests pass.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6177455647 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4774#issuecomment-6177455647). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-14T20:15:25Z. --- @oneandonlydean Done in `cee2006d1` — dropped the `try/catch` in `ensureInitialized(lock)` and called `ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch())` directly. All 8 `application_heap` tests pass.
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!4774
No description provided.