feat(libc): lazily initialize application heap on first access #4774
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/4774"
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 hamb3r on 2026-10-12T21:28:47Z.
What
When launching titles with guest modules (such as Unity IL2CPP runtime modules like
Il2cppUserAssemblies.prx.guest.prxin PPSA28997), static C++ initializers inside guest modules execute before the main executable's entry point invokes_init_env— on Windows duringguestStartup.Initialize(), and on Linux during dynamic loaderDT_INIT/DT_INIT_ARRAYexecution forDT_NEEDEDshared objects.If any static initializer performs heap allocations (
operator new,malloc, etc.) before_init_envhas executed, the application terminates on startup: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:Lazy application heap initialization on first allocator access (
core/libs/prx/libc/src/ApplicationHeap.cpp):ensureInitialized(std::unique_lock<std::mutex>& lock), invoked before readingheapApiincallback(),ApplicationHeapRealign_nid_no_patch(),ApplicationHeapStatsFast_nid_no_patch(), andApplicationHeapUsableSize_nid_no_patch().heapMutex, ifheapApi[0] != nullptr || heapFailure || heapFinalized, returns immediately with a single lock acquisition on the fast path.lock, callsApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch())directly (which resolves.procparon Windows andPT_OS_PROCPARAM0x61000001on Linux, propagating any process parameter lookup error directly), and re-acquireslock._init_env,ApplicationHeapInitialize_nid_no_patch()is a no-op viastd::call_once(heapInitialization, ...).Cross-platform unit test (
application_heap_lazy) (core/libs/tests/ApplicationHeap.cpp,core/libs/prx/libc/CMakeLists.txt):.procparsection header on Windows,PT_OS_PROCPARAM0x61000001program header on Linux)._Znwm_nid_postfix(40)prior to_init_env_nid_postfix()lazily initializes the heap (initializes == 1) and allocates from the registered allocator._init_env_nid_postfix()call is idempotent (initializes == 1).Changes from Earlier Revisions
WindowsEntryStubBuilder,WindowsPePatcher,test_windows_import_modules.py) and replaced them with unified cross-platform lazy initialization incore/libs/prx/libc/src/ApplicationHeap.cpp.try/catcharoundApplicationProcessParameters_nid_no_patch()inensureInitialized(lock)so missing, duplicate, or malformed.procpar/PT_OS_PROCPARAMmetadata throws its own error directly.Tested
ctest -R application_heap— 8/8 passed on all platforms):application_heap_lazy).application_heap_lazy).application_heap_lazy).python tools/check_conventions.py --base origin/mainpasses with 0 errors.git diff --check origin/mainpasses with 0 errors.DT_INIT/DT_INIT_ARRAYconstructors (Il2cppUserAssemblies.prx.guest.prx, etc.) and subsequenteboot.elf_init_envcomplete withoutapplication heap: allocator API is not registered, spawning worker threads, loadingglobal-metadata.dat,il2cpp.usym,RuntimeInitializeOnLoads.json,ScriptingAssemblies.json, and reachingsceVideoOutOpen.eboot.elf_init_envcomplete withoutapplication heap: allocator API is not registered, initializing Vulkan swapchain (1920x1080) and loadingglobal-metadata.dat,globalgamemanagers.assets,sharedassets0.assets, andlevel0.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)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.
Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-13T04:52:41Z.
Windows test: head
0767d5e61merged onto currentmaine51428bf2(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/mainpassed. I did not run the new tests againstmainwithout the change.AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-13T13:39:58Z.
cc @oneandonlydean @adriadam10 rebased
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-13T16:07:56Z.
cc @oneandonlydean @adriadam10 rebased again
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.
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:
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
mainthe title hits the exact same barrier:On Linux,
ld-linux.soruns.init_arrayofDT_NEEDEDguest libraries before_startis reached. Because_init_envis 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(addressingWindowsEntryStubBuilder/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 incore/libs/prx/libc/src/ApplicationHeap.cppusingApplicationProcessParameters_nid_no_patch(), which would cover early allocations on both platforms).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.
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
libccore/relinkerchanges (WindowsEntryStubBuilder,WindowsPePatcher, andtest_windows_import_modules.py).core/libs/prx/libc/src/ApplicationHeap.cpp(ensureInitialized(std::unique_lock<std::mutex>& lock)), invoked prior to readingheapApiin:callback()(coversApplicationHeapAllocate,ApplicationHeapFree,ApplicationHeapReallocate,ApplicationHeapAlign,ApplicationHeapPosixAlign,ApplicationHeapStats)ApplicationHeapRealign_nid_no_patch()ApplicationHeapStatsFast_nid_no_patch()ApplicationHeapUsableSize_nid_no_patch()ensureInitialized(lock)works on both platforms:heapMutexwhetherheapApi[0] != nullptr || heapFailure || heapFinalized, returning immediately on the fast path with a single lock acquisition.lock, queriesApplicationProcessParameters_nid_no_patch()(which resolves.procparon Windows andPT_OS_PROCPARAM0x61000001on Linux), passes the result toApplicationHeapInitialize_nid_no_patch(processParameters), and re-acquireslock.ensureInitialized(lock)catches the lookup exception without consumingheapInitialization(std::once_flag), preserving theapplication heap: allocator API is not registerederror path._init_env,ApplicationHeapInitialize_nid_no_patch()is a no-op viastd::call_once(heapInitialization, ...).2. Cross-Platform Unit Test (
application_heap_lazy)application_heap_lazy(application_heap_tests lazy) incore/libs/tests/ApplicationHeap.cppand registered it incore/libs/prx/libc/CMakeLists.txt..procparPE section on Windows,PT_OS_PROCPARAM0x61000001program 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).ctest -R application_heap(8/8 passed) on:3. Live Title Verification (
PPSA28997— God of War: Sons of Sparta)Relinked
PPSA28997with unmodifiedmainrelinker(--module-dir Media/Modules --module-dir Media/Plugins --exclude-sce-module libc.prx) and ran with the updatedlibc.prx:Linux (Arch Linux & Ubuntu 22.04):
All
DT_NEEDEDguest module constructors (Il2cppUserAssemblies.prx.guest.prxat+0x2dc8bfcalling_Znwm_nid_postfix(0x28), etc.) and subsequenteboot.elf_init_envsucceed, spawning worker threads, loading Unity IL2CPP metadata, and reachingsceVideoOutOpen:Windows:
All guest module initializers during
guestStartup.Initialize()and subsequenteboot.elf_init_envsucceed, creating the Vulkan swapchain (1920x1080) and loadingglobal-metadata.dat,globalgamemanagers.assets,sharedassets0.assets, andlevel0.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.cppIn the initial revision of lazy initialization,
ensureInitialized()acquiredstd::unique_lock lock(heapMutex)beforecallback(),ApplicationHeapRealign_nid_no_patch(),ApplicationHeapStatsFast_nid_no_patch(), andApplicationHeapUsableSize_nid_no_patch()acquiredheapMutexa second time to readheapApi. Because every guestmalloc,free,calloc,realloc,operator new, andoperator deleteroutes throughcallback(), lockingheapMutextwice 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 existingstd::unique_lock lock(heapMutex)critical section:if (heapApi[0] != nullptr || heapFailure || heapFinalized) return;is checked while already holdingheapMutex. Every allocation/deallocation now acquiresheapMutexonce (identical tomain).lock.unlock()temporarily releasesheapMutex, resolvesApplicationProcessParameters_nid_no_patch()and invokesApplicationHeapInitialize_nid_no_patch(processParameters), and then re-acquireslock.lock()before returning to the caller.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 beforeApplicationHeapInitialize_nid_no_patch(which takes it itself undercall_once), and an allocation from the replacement's own initialize sees the API already registered.One thing is still open:
ensureInitialized()swallows every exception fromApplicationProcessParameters_nid_no_patch()(catch (...) {}), so a duplicate or malformed.procpar/PT_OS_PROCPARAMends up reported asallocator API is not registeredinstead of its own error, and the lookup runs again on every allocation. Please drop the try/catch and callApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch())directly. The application heap tests still pass without it (checked on Linux: default, exit-order and lazy), sincerejectaccepts anystd::exception.Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T20:15:25Z.
@oneandonlydean Done in
cee2006d1— dropped thetry/catchinensureInitialized(lock)and calledApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch())directly. All 8application_heaptests pass.