fix(libc): gracefully fallback to default allocator on early malloc #1900

Closed
hamb3r wants to merge 1 commit from upstream-pr/1900 into main
hamb3r commented 2026-10-08 23:07:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-08T23:07:52Z.


What

Fixes a crash/deadlock when games invoke malloc during early boot before ApplicationHeapInitialize completes, and securely routes early allocations after custom allocator registration.

Some engines (e.g., Unity) instantiate static singletons that invoke memory allocation before main and before ApplicationHeapInitialize explicitly registers the custom memory allocator. Previously, AnyPS5 either deadlocked via std::call_once or threw runtime_error during these early allocations:

[libc] unhandled exception 'St13runtime_error' thrown from 00007ffc0f874e86
terminate called after throwing an instance of 'std::runtime_error'
  what():  application heap: allocator API is not registered
FATAL: abort() (SIGABRT) on thread 27584

This PR provides a lock-safe, low-overhead fallback mechanism that routes early allocations to the GuestHeap, while seamlessly handling their reallocation and deletion after the custom allocator is established.

Implementations:

  • Read-Only Fallback: Removed std::call_once auto-initialization. Early allocations dynamically fallback to defaultApi() without modifying global initialization state, allowing later legitimate explicit registration of the game's custom allocator.
  • BSS Tracking Pool: All early pointers are tracked in a recursion-free BSS-allocated chunk pool (EarlyChunk array of size 2048, allowing up to 1,044,480 early allocations, consuming 8MB). This statically avoids any recursive dependency on GuestHeapAllocate (which can fall back to std::malloc if the guest arena is unavailable).
  • Fast-Path Min/Max Bounding Box: Eliminates O(N) linear scans on the global heapMutex during the game's hot path. Two atomic integers (minEarlyPointer and maxEarlyPointer) define a bounding box of early allocation addresses. Non-early pointers (99.999% of allocations) instantly fail this check without looping, skipping the O(N) scan. Reallocate and Realign check this bounding box before acquiring heapMutex, skipping a full lock-unlock cycle on the fast path.
  • Exception Safety and Concurrency: TOCTOU races during concurrent free/realloc are handled securely. ApplicationHeapFree removes the pointer under lock and correctly delays defaultFree until the lock is released. If defaultFree throws (e.g., due to GPU lease failure), the pointer is added back to the pool to prevent corruption. Reallocate uses atomic, in-place replaceEarlyPointerLocked to preserve realloc standard contracts on bad_alloc.
  • PosixAlign Leak Fix: Ensures that a failing custom allocator's memory is not mistakenly freed by the system's defaultFree.

Tested

  • Windows 10, NVIDIA RTX 3080, God of War Sons of Sparta (PPSA28997): verified Unity engine successfully boots past il2cpp_init early static allocation without deadlocking or crashing.
  • MinGW-w64 GCC, Release / Ninja.
  • Extended application_heap_tests to cover early malloc, calloc, posix_memalign, realloc, realign, and their subsequent free routing after custom initialization.
  • Validated overflow triggers on chunk pool allocation boundaries.
  • 4/4 application_heap tests passed successfully.
  • tools/check_conventions.py --base origin/main and git diff --check origin/main...HEAD pass.

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 (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
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4793857268 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1900). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-08T23:07:52Z. --- ### What Fixes a crash/deadlock when games invoke `malloc` during early boot before `ApplicationHeapInitialize` completes, and securely routes early allocations after custom allocator registration. Some engines (e.g., Unity) instantiate static singletons that invoke memory allocation before `main` and before `ApplicationHeapInitialize` explicitly registers the custom memory allocator. Previously, AnyPS5 either deadlocked via `std::call_once` or threw `runtime_error` during these early allocations: > ``` > [libc] unhandled exception 'St13runtime_error' thrown from 00007ffc0f874e86 > terminate called after throwing an instance of 'std::runtime_error' > what(): application heap: allocator API is not registered > FATAL: abort() (SIGABRT) on thread 27584 > ``` This PR provides a lock-safe, low-overhead fallback mechanism that routes early allocations to the GuestHeap, while seamlessly handling their reallocation and deletion after the custom allocator is established. Implementations: - **Read-Only Fallback**: Removed `std::call_once` auto-initialization. Early allocations dynamically fallback to `defaultApi()` without modifying global initialization state, allowing later legitimate explicit registration of the game's custom allocator. - **BSS Tracking Pool**: All early pointers are tracked in a recursion-free BSS-allocated chunk pool (`EarlyChunk` array of size 2048, allowing up to 1,044,480 early allocations, consuming 8MB). This statically avoids any recursive dependency on `GuestHeapAllocate` (which can fall back to `std::malloc` if the guest arena is unavailable). - **Fast-Path Min/Max Bounding Box**: Eliminates O(N) linear scans on the global `heapMutex` during the game's hot path. Two atomic integers (`minEarlyPointer` and `maxEarlyPointer`) define a bounding box of early allocation addresses. Non-early pointers (99.999% of allocations) instantly fail this check without looping, skipping the O(N) scan. `Reallocate` and `Realign` check this bounding box *before* acquiring `heapMutex`, skipping a full lock-unlock cycle on the fast path. - **Exception Safety and Concurrency**: TOCTOU races during concurrent `free`/`realloc` are handled securely. `ApplicationHeapFree` removes the pointer under lock and correctly delays `defaultFree` until the lock is released. If `defaultFree` throws (e.g., due to GPU lease failure), the pointer is added back to the pool to prevent corruption. `Reallocate` uses atomic, in-place `replaceEarlyPointerLocked` to preserve `realloc` standard contracts on `bad_alloc`. - **PosixAlign Leak Fix**: Ensures that a failing custom allocator's memory is not mistakenly freed by the system's `defaultFree`. ### Tested - Windows 10, NVIDIA RTX 3080, God of War Sons of Sparta (PPSA28997): verified Unity engine successfully boots past `il2cpp_init` early static allocation without deadlocking or crashing. - MinGW-w64 GCC, Release / Ninja. - Extended `application_heap_tests` to cover early `malloc`, `calloc`, `posix_memalign`, `realloc`, `realign`, and their subsequent `free` routing after custom initialization. - Validated overflow triggers on chunk pool allocation boundaries. - 4/4 `application_heap` tests passed successfully. - `tools/check_conventions.py --base origin/main` and `git diff --check origin/main...HEAD` pass. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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 in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [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] AI-assisted: yes
klosixgaming-arch commented 2026-10-09 00:42:53 +00:00 (Migrated from github.com)

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

Review: APPROVED


The intent is sound and the concurrency is handled: allocations made before the application heap is registered fall back to the default allocator, are tracked in an early-pointer pool, and are later freed with the matching default free/realloc/realign (with the pool entry restored if the default free throws). callback now only throws "not registered" when a heap is registered but the slot is missing — the right distinction. The test exercises early alloc/calloc/align/posix_memalign, a 515-pointer overflow, and post-registration realloc/realign of early pointers.

Concerns worth addressing before merge:

  1. ~8.4 MB of static memory is always allocated for chunkPool[2048] (2048 × 510 × sizeof(void*)). That's a fixed cost in every build regardless of whether any early allocation ever happens — heavy for a path that should be rare. Consider a smaller initial pool that grows on demand (you already throw bad_alloc at the cap, so growth fits the existing failure model), or a freelist sized to a realistic early-allocation count.
  2. minEarlyPointer/maxEarlyPointer are widened on add but never narrowed on remove, so once any early pointer exists the fast-reject window stays permanently wide and the lookups degrade to a full pool scan. Harmless, but it defeats the fast path after the first allocation.
  3. The require/reject macros replace the previous template functions across the whole test file — a broader change than this feature needs; keep the diff focused.

Written with AI assistance.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5464498619 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1900#pullrequestreview-5464498619). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-09T00:42:53Z. **Review:** APPROVED --- The intent is sound and the concurrency is handled: allocations made before the application heap is registered fall back to the default allocator, are tracked in an early-pointer pool, and are later freed with the matching default `free`/`realloc`/`realign` (with the pool entry restored if the default free throws). `callback` now only throws "not registered" when a heap *is* registered but the slot is missing — the right distinction. The test exercises early alloc/calloc/align/posix_memalign, a 515-pointer overflow, and post-registration realloc/realign of early pointers. Concerns worth addressing before merge: 1. **~8.4 MB of static memory is always allocated** for `chunkPool[2048]` (2048 × 510 × sizeof(void*)). That's a fixed cost in every build regardless of whether any early allocation ever happens — heavy for a path that should be rare. Consider a smaller initial pool that grows on demand (you already throw `bad_alloc` at the cap, so growth fits the existing failure model), or a freelist sized to a realistic early-allocation count. 2. `minEarlyPointer`/`maxEarlyPointer` are widened on add but never narrowed on remove, so once any early pointer exists the fast-reject window stays permanently wide and the lookups degrade to a full pool scan. Harmless, but it defeats the fast path after the first allocation. 3. The `require`/`reject` macros replace the previous template functions across the whole test file — a broader change than this feature needs; keep the diff focused. Written with AI assistance.
oneandonlydean commented 2026-10-09 09:22:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:22:43Z.


Allocations made before ApplicationHeapInitialize now go to the default heap and are tracked in a pointer pool so free/realloc can route them back. That's a fallback, which isn't allowed here; please find which module calls malloc before the heap is set up in PPSA28997 and initialize the heap before that point instead, so every allocation takes one path.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6078127006 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1900#issuecomment-6078127006). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T09:22:43Z. --- Allocations made before `ApplicationHeapInitialize` now go to the default heap and are tracked in a pointer pool so `free`/`realloc` can route them back. That's a fallback, which isn't allowed here; please find which module calls `malloc` before the heap is set up in PPSA28997 and initialize the heap before that point instead, so every allocation takes one path.
hamb3r commented 2026-10-09 16:19:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-09T16:19:27Z.


@oneandonlydean You were absolutely right. We did a deep dive into the relinker pipeline and found the true root cause for the malloc crash in Unity titles: the relinker eagerly loads the dynamic plugin (Il2cppUserAssemblies.prx) from the sce_module folder and forcibly runs its InitArrayRvas at startup, before the title can initialize the application heap.

The correct architectural fix is not a fallback allocator, but rather deferring the initialization of this module until the game dynamically calls sceKernelLoadStartModule. We now see that the infrastructure in PR #846 (exporting __aps5_guest_initialize) is the exact prerequisite needed to support this correctly on Windows.

Closing this PR as the fallback hack is a dead end. Thank you for the review!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6084824480 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1900#issuecomment-6084824480). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-09T16:19:27Z. --- @oneandonlydean You were absolutely right. We did a deep dive into the relinker pipeline and found the true root cause for the malloc crash in Unity titles: the relinker eagerly loads the dynamic plugin (Il2cppUserAssemblies.prx) from the sce_module folder and forcibly runs its InitArrayRvas at startup, *before* the title can initialize the application heap. The correct architectural fix is not a fallback allocator, but rather deferring the initialization of this module until the game dynamically calls sceKernelLoadStartModule. We now see that the infrastructure in PR #846 (exporting __aps5_guest_initialize) is the exact prerequisite needed to support this correctly on Windows. Closing this PR as the fallback hack is a dead end. Thank you for the review!

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