fix(libc): gracefully fallback to default allocator on early malloc #1900
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/1900"
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-08T23:07:52Z.
What
Fixes a crash/deadlock when games invoke
mallocduring early boot beforeApplicationHeapInitializecompletes, and securely routes early allocations after custom allocator registration.Some engines (e.g., Unity) instantiate static singletons that invoke memory allocation before
mainand beforeApplicationHeapInitializeexplicitly registers the custom memory allocator. Previously, AnyPS5 either deadlocked viastd::call_onceor threwruntime_errorduring these early allocations: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:
std::call_onceauto-initialization. Early allocations dynamically fallback todefaultApi()without modifying global initialization state, allowing later legitimate explicit registration of the game's custom allocator.EarlyChunkarray of size 2048, allowing up to 1,044,480 early allocations, consuming 8MB). This statically avoids any recursive dependency onGuestHeapAllocate(which can fall back tostd::mallocif the guest arena is unavailable).heapMutexduring the game's hot path. Two atomic integers (minEarlyPointerandmaxEarlyPointer) 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.ReallocateandRealigncheck this bounding box before acquiringheapMutex, skipping a full lock-unlock cycle on the fast path.free/reallocare handled securely.ApplicationHeapFreeremoves the pointer under lock and correctly delaysdefaultFreeuntil the lock is released. IfdefaultFreethrows (e.g., due to GPU lease failure), the pointer is added back to the pool to prevent corruption.Reallocateuses atomic, in-placereplaceEarlyPointerLockedto preservereallocstandard contracts onbad_alloc.defaultFree.Tested
il2cpp_initearly static allocation without deadlocking or crashing.application_heap_teststo cover earlymalloc,calloc,posix_memalign,realloc,realign, and their subsequentfreerouting after custom initialization.application_heaptests passed successfully.tools/check_conventions.py --base origin/mainandgit diff --check origin/main...HEADpass.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)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).callbacknow 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:
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 throwbad_allocat the cap, so growth fits the existing failure model), or a freelist sized to a realistic early-allocation count.minEarlyPointer/maxEarlyPointerare 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.require/rejectmacros 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.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T09:22:43Z.
Allocations made before
ApplicationHeapInitializenow go to the default heap and are tracked in a pointer pool sofree/realloccan route them back. That's a fallback, which isn't allowed here; please find which module callsmallocbefore the heap is set up in PPSA28997 and initialize the heap before that point instead, so every allocation takes one path.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!
Pull request closed