feat(libs): let relinked Windows games opt into mimalloc #6067
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6067"
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 meh7an on 2026-10-14T21:10:08Z.
What
On Windows, a relinked game and its libraries allocate through the CRT, which goes to the Windows heap. On the S2 page of Sonic Origins Plus's main menu, the queue worker spent about 32 samples per frame (APS5 sampler, 15 s) in
RtlAllocateHeap,_malloc_baseand_free_base.This builds mimalloc 3.5.4 (a new submodule) as
mimalloc.dll, with its Windows redirection (MI_OVERRIDE,MI_WIN_REDIRECT).mimalloc.dllandmimalloc-redirect.dllare copied beside the libraries. WithAPS5_MIMALLOCset (to any value), the relinker's Windows entry stub loadsmimalloc.dllbefore every other library, so the redirection replaces the CRT allocator for the whole process. Without the variable the stub skips the load and the CRT heap stays, so nothing changes by default. Withoutmimalloc.dllthe stub's load fails quietly, and the CRT heap stays.pe_import_first, a build tool, makesmimalloc-redirect.dllthe first import of the copiedmimalloc.dll. The redirection needs this, and MinGW's linker does not guarantee the order.RuntimeHeap.csends mimalloc's own CRT calls (malloc,calloc,realloc,free,strdup) to the process heap through linker wraps, so they never reach the redirected allocator.mimalloc.dlllinks statically: GCC's emulated thread-locals (emutls, which hold mimalloc's own thread-locals), MinGW's thread-exit destructor list, and winpthreads.tools/package_release.pyships both DLLs.entry_stub(the relinker's entry stub tests, now linked withrelinker_core) pins the new stub code, for an absolute and for a module-relative run path:APS5_MIMALLOCwithGetEnvironmentVariableWbefore the allocator load, and an unset variable branches past exactly that load;mimalloc.dll's path before the first library's;LoadLibraryExWand the library search flags before that library;mimalloc.dllpath cannot fit the startup buffer fails with the same error as a library path, one character past the longest path that fits.PeImportFirst.cppis split into a header, its functions and the tool'smain.pe_import_first(a test registered on every platform) builds a small PE32+ image:docs/dev/ENVIRONMENT.mdgets theAPS5_MIMALLOCrow.docs/dev/ARCHITECTURE.mdgets a "Windows allocator" section: the two DLLs, the load order in the entry stub, guest versus host allocations, and the wraps.With mimalloc, the Windows heap's share fell from about 32 samples per frame to 0, and
operator newfell from 10.1 to 6.5 (Sonic Origins Plus, on this PR's first base).The allocator is opt-in after review. On current main, Sons of Sparta (two runs per arm) and three titles measured by @screamm show no frame-time win, and mimalloc adds 80-230 MiB of private memory. So it stays off unless
APS5_MIMALLOCasks for it.Tested
Windows 11 (10.0.26300), WinLibs GCC 15.2.0 (UCRT), Release, NVIDIA GeForce RTX 2080 Ti, driver 617.14.
5bf2e139ewith the opt-in switch.entry_stub,pe_import_firstandrelease_package.python tools/env_reference.py --checkandtools/check_conventions.pypass.APS5_MIMALLOC=1both load,mimalloc: malloc is redirected.and the v3.5.4 banner appear, and there are no mimalloc errors.2fab88d10, whoseCMakeLists.txtincludescmake/ZArchive.cmakewhere the mimalloc block goes; both stay.tools/package_release.pyalso packs #5729's Tracy runtime, so the Windows block adds the mimalloc DLLs and the Tracy files follow for every platform, and #5729's Tracy packaging test gets the mimalloc DLLs in its Windows fixture. On that main, with this change, the full ctest suite passes 1339 of 1342, includingentry_stub,pe_import_first,release_packageandwindows_import_modules.agc_driver_gpu_indirect_arguments_misaligned_writer_aheadis not run: main itself does not compile it with MinGW.select_testsfails in its setup on Windows without the symlink privilege (WinError 1314fromsymlink_to), as on main.agc_driver_store_over_untrackedfailed once in the parallel run; alone it passes 5 of 5.entry_stubfails; with the import move made a no-op,pe_import_firstfails.pe_import_firstare this PR's):MIMALLOC_VERBOSE=1andMIMALLOC_SHOW_ERRORS=1. mimalloc reportedfree mode: checkedandmalloc is redirected.freeof a block mimalloc does not own reports an error. The run reported no error and no warning.RtlAllocateHeap,_malloc_baseand_free_baseappear in no stack, and mimalloc is in about 9% of them.libSceAgcDriverand 1 fromlibc, both entering throughlibstdc++(operator newanddelete).malloconly when there is no arena) and frees them the same way, so no block moves between the guest heap and mimalloc. The new ARCHITECTURE.md section says so.nvoglv64.dllandnvgpucomp64.dlllink private copies of mimalloc 3.1.6, which printed their own reports underMIMALLOC_VERBOSE. They do not take part in the redirection.APS5_TRACE_SECONDS=200:5on the same machine in one session, caches warm. Traces attached.The FPS shown in the title went from 4.99 to 5.70 (median of six readings).
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)Traces and summary lines (baseline 61ac8fdf6bd7, this change 02d5af5593d1):
mimalloc-traces.zip
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-14T21:12:49Z.
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.
main)core/relinker/CMakeLists.txtL677-684core/relinker/elfpatcher/tests/EntryStubTests.cppL1, L38, L43Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
.gitmodulesCMakeLists.txttools/package_release.py.gitmodulesCMakeLists.txtcore/relinker/CMakeLists.txtCMakeLists.txt.gitmodulesCMakeLists.txtcore/libs/CMakeLists.txtcore/relinker/CMakeLists.txtdocs/dev/ENVIRONMENT.md.gitmodulestools/package_release.pytools/tests/test_package_release.pydocs/dev/ARCHITECTURE.mdCMakeLists.txtcore/libs/CMakeLists.txtcore/relinker/CMakeLists.txtdocs/dev/ARCHITECTURE.mddocs/dev/ARCHITECTURE.mddocs/dev/ENVIRONMENT.mddocs/dev/ENVIRONMENT.mdCMakeLists.txtdocs/dev/ARCHITECTURE.mdcore/relinker/CMakeLists.txtCMakeLists.txtcore/relinker/CMakeLists.txtdocs/dev/ARCHITECTURE.mdCMakeLists.txtdocs/dev/ARCHITECTURE.mddocs/dev/ENVIRONMENT.mdCMakeLists.txtdocs/dev/ARCHITECTURE.mddocs/dev/ENVIRONMENT.mdcore/relinker/CMakeLists.txtCMakeLists.txtcore/relinker/CMakeLists.txtCMakeLists.txtcore/libs/CMakeLists.txtCMakeLists.txtcore/libs/CMakeLists.txtcore/relinker/CMakeLists.txtdocs/dev/ENVIRONMENT.mdcore/relinker/CMakeLists.txtdocs/dev/ARCHITECTURE.mdcore/relinker/CMakeLists.txtdocs/dev/ENVIRONMENT.mdCMakeLists.txtdocs/dev/ARCHITECTURE.mddocs/dev/ENVIRONMENT.mddocs/dev/ARCHITECTURE.mdImported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-16T22:06:55Z.
Review: CHANGES_REQUESTED
Thanks, the measurement and the fallback when
mimalloc.dllis missing are clear. This replaces the allocator of every relinked game on Windows, so it needs more than the packaging test:WindowsEntryStubBuilder.cpp:122-131and:493-514emit new machine code (aLoadLibraryExWper allocator path, in both the absolute-path and the relative-path branch with thePathCapacitycheck) with no test.core/relinker/elfpatcher/tests/EntryStubTests.cppis the place: pin that the stub referencesmimalloc.dllbefore the first library in both branches, and that an over-long path throws like the library paths do.core/libs/allocator/PeImportFirst.cpphas no test. It rewrites a PE import directory in place; add a registered test (runs on Linux CI) with a small synthetic PE showing the named import moves to first and the others keep their order, and that a missing import, a truncated directory and a non-PE32+ file fail without touching the file.docs/dev/ARCHITECTURE.mdshould describe the new process-wide allocator, the load order in the entry stub, and theRuntimeHeap.cwraps (which calls of mimalloc itself go to the process heap and why), under the section it changes.mallocin a guest-bundled module and in a host library both land in mimalloc, and thatfreeacross the two works), since a pointer mixed between mimalloc and the CRT heap would corrupt silently.Build and the Linux test suite are fine (the failures I saw were load-related and pass alone). The Windows side still needs the full Build once these are in.
Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-16T23:32:59Z.
Thanks for the review. All four points are in 8977d03c8 and the description:
entry_stubbuilds the Windows stub for an absolute and a module-relative run path. It pins thatmimalloc.dll's path, and itsLoadLibraryExWwith the library search flags, come before the first library. A run path whosemimalloc.dllpath cannot fit the startup buffer throws the library paths' error, one character past the longest path that fits.PeImportFirst.cppis split into a header, its functions and the tool'smain.pe_import_first, registered on every platform, uses a synthetic PE32+ image:docs/dev/ARCHITECTURE.mdhas a "Windows allocator" section. The wraps cover the MinGW runtime thatmimalloc.dlllinks statically (emutls, MinGW's thread-exit destructor list, winpthreads), which would otherwise call back into mimalloc before the calling thread's mimalloc state exists.MIMALLOC_VERBOSE=1andMIMALLOC_SHOW_ERRORS=1, mimalloc reportsmalloc is redirected, with checked frees and no error over a run to the menu.Both new tests fail when the behaviour they pin is broken (the allocator loaded after the libraries; an import move that does nothing).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-16T23:45:53Z.
Review: APPROVED
Re-checked the four points against 8977d03c8:
entry_stubnow pinsmimalloc.dll's path and itsLoadLibraryExWcall before the first library, for both an absolute and a module-relative run path, and that a path one character past the startup buffer throws.pe_import_firstis split into header/functions/main and has a registered test with a synthetic PE32+ image (named import first, others keep order, missing import / truncated directory / PE32 fail without touching the file).Built on the merged tree;
pe_import_first,entry_stubandrelease_packagepass. Merging once the full Windows Build is green.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T03:52:25Z.
Picking this up while @adriadam10 is away. The code and tests look good to us, and full CI passes on 8977d03c8. Since this changes the allocator for every relinked Windows game, two things before we merge:
APS5_NO_MIMALLOC=1environment variable that makes the entry stub skip loadingmimalloc.dll. Please document it in ARCHITECTURE.md next to the mimalloc section. If you'd rather rely on mimalloc's ownMIMALLOC_DISABLE_REDIRECT=1, documenting that and confirming it fully restores the CRT heap would also work.MIMALLOC_VERBOSE=1showing "malloc is redirected" and no mimalloc errors. A frame-time comparison against main from the same scene would help. A second GPU vendor would be ideal, if you or a tester has one.Thanks for the work on this!
Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-18T07:31:37Z.
Thanks @oneandonlydean, both points are done.
1. Opt-out switch. de23d1600 adds
APS5_NO_MIMALLOC.mimalloc.dll. Nothing is redirected, and the process keeps the C runtime's heap; no other module imports mimalloc.entry_stub_testschecks two things, for both an absolute and a$ORIGINrun path:GetEnvironmentVariableWbefore the allocator load;LoadLibraryExW.2. Results on current main.
1b0c7cfa0with this PR merged and the switch on top (built from the working tree before it was committed), MinGW.--to-intel).Allocator checks:
MIMALLOC_VERBOSE=1 MIMALLOC_SHOW_ERRORS=1, the log showsmimalloc: malloc is redirected.with no mimalloc errors or warnings, andmimalloc.dllandmimalloc-redirect.dllare in the process's module list. The NVIDIA driver carries its own private mimalloc v3.1.6 copies, which print their version lines too.APS5_NO_MIMALLOC=1has no redirect line, and neither DLL is loaded.Frame times:
APS5_TRACE_SECONDS=90:20, warm caches, log not redirected.APS5_NO_MIMALLOC=1. The PR changes no library source, so that is main's allocator path; oneGetEnvironmentVariableWcall at startup is the only other difference.tools/performance_compare.py:APS5_NO_MIMALLOC=1No second GPU vendor here, sorry.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T09:04:38Z.
Thanks, the opt-out looks right. Could you post two more runs per arm (main vs this PR, same scene) so the p99 change isn't resting on one sample, ideally one of them on a second GPU vendor? And could you say what the 325 ms warm-up round is? Please also add an
APS5_NO_MIMALLOCrow to docs/dev/ENVIRONMENT.md.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T11:21:51Z.
Heads-up: #6078 has merged, so the environment reference check now runs on main.
APS5_NO_MIMALLOC(read in WindowsEntryStubBuilder.cpp) needs a row indocs/dev/ENVIRONMENT.md, or the conventions check fails once this PR is merged on top of current main. Could you rebase onto main and add the row (presence flag: skips loading mimalloc.dll so the process keeps the C runtime's heap), then runpython tools/env_reference.py --check?Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-18T13:37:37Z.
A Linux data point, in case it helps decide whether this should also cover Linux later. I built mimalloc from this PR's submodule commit (f8401befa6, v3.5.4) as
libmimalloc.sowith its default CMake options and loaded it withLD_PRELOAD. jemalloc 5.3.0 (Ubuntu 24.04'slibjemalloc2) is the other comparison. Machine: i7-13700K, RTX 4070 Ti, NVIDIA 595.99.02.Shader preparation.
agc_shader_replay(Release,ANYPS5_ENABLE_SPIRV_TOOLSoff,ANYPS5_NO_SHADER_CACHE=1) onmain5bf2e139ef, replaying 355 dumped MXGP 26 (PPSA30839) shader requests in one process./usr/bin/time, 2 runs per allocator, interleaved:System time is under 0.5 s in all of them. The largest single compute shader in my dumps (PPSA31162
0x1e401c0000, about 1M SPIR-V words) takes about 1.2 s on glibc and 0.48 s with jemalloc. The 462.spvfiles of the 466 requests are byte-identical under all three allocators.Gameplay. On 10-16 I ran MXGP on a test build from that day (5f469824dc, with my #6917 on top), 130 s with pad input and a warm cache, 3 runs each for glibc and mimalloc and 2 for jemalloc. The frame times in the 10 s trace window did not change measurably: p50 225 to 242 ms with glibc, 222 ms with jemalloc, 221 to 295 ms with mimalloc. The GPU was busy about 120 ms per present in every run, so that scene is GPU-bound here. In a cold-cache run of PPSA31162 on 24 host threads, the preparation threads kept up with the game either way, so the allocator showed up as idle CPU rather than more shaders. I only see a clear difference in CPU time.
If it would be useful once this is merged, I can do the Linux side: the relinked ELF would load
libmimalloc.sofirst, with the sameAPS5_NO_MIMALLOCswitch. That is only a suggestion; I'm not working on it unless you want it.AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by screamm on 2026-10-18T14:09:01Z.
Cross-validation on Windows 11 Pro 26220, NVIDIA GeForce RTX 4070 (driver 596.21), Ryzen 7 5700X, WinLibs MinGW-w64 GCC 15.2.0, Release. PR head
de23d1600merged on main0d078f75d(clean). No second GPU vendor here either.Tests.
pe_import_firstandentry_stub3 of 3 each;release_packagepasses. WithWindowsEntryStubBuilder.cppfrom main and the tests kept,entry_stubfails (the stub data does not hold the expected path); restored, it passes.tools/check_conventions.py --base origin/mainfails only on the known row:[env-reference] ... APS5_NO_MIMALLOC is read here but has no row in docs/dev/ENVIRONMENT.md.git diff --checkis clean. I did not finish a full build or the full suite in this round.Runs. Three titles, three arms, 3 runs each, interleaved (main, PR, PR with
APS5_NO_MIMALLOC=1, repeated), same scene, 65 s, no input. Every run was killed at the limit, with no stop line. main = main's relinker; PR and PR-off = this PR's relinker. All arms use the samelibs/build (the PR changes no library source), so the arms differ only in the entry stub and in whether the two DLLs are present. Env:MIMALLOC_VERBOSE=1 MIMALLOC_SHOW_ERRORS=1 APS5_TRACE_SUMMARY_EVERY=10. Frame metrics are medians of the 10 s summary intervals after the first 10 s. Memory is process private bytes / working set at 30 and 60 s.mimalloc: malloc is redirected.and thev3.5.4banner (twice on RetroArch, once for the launcher and once for the LoadExec child), withmimalloc.dllandmimalloc-redirect.dllin the module list. In the 18 main and PR-off runs there is no redirect line and neither DLL is loaded. There are no mimalloc errors or warnings in any of the 27 runs. The NVIDIA driver's own mimalloc 3.1.6 banners appear in every arm.Median (min-max) of 3 runs.
APS5_NO_MIMALLOC=1matches main within -37 to +2 MiB private, and its frame times are in main's range. That supports using it as the baseline, as in your GoW table.mimalloc-redirect.dllremoved fromlibs/, the stub's load fails without any message and the title runs on the CRT heap. That matches ARCHITECTURE.md ("fails quietly"). A line under the existing dependency diagnostics would make an incompletelibs/visible.mimalloc.dllis built from the submodule.mimalloc-redirect.dllis the prebuilt binary from the submodule'sbin/(byte-identical copy); upstream does not publish its source.Not checked: your titles (GoW Sons of Sparta, Sonic Origins Plus) aren't available here; AMD/Intel; Linux; sessions longer than 65 s; the full ctest suite.
Written with Claude Code assistance (validation by a subagent, reviewed in this session).
Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-18T16:12:57Z.
Thanks @oneandonlydean.
5bf2e139e, with theAPS5_NO_MIMALLOCrow in docs/dev/ENVIRONMENT.md.python tools/env_reference.py --checkpasses (437 names, all documented).The 325 ms round was warm-up, not the allocator:
Vulkan.GraphicsPipelinePrebuild,Vulkan.GraphicsPipelineandVulkan.GraphicsPipelineLibrary, about 9 ms per frame each.Driver.Draw.shader_compile_and_link.More runs. Sons of Sparta again, same scene and window:
APS5_TRACE_SECONDS=90:20, no input, warm caches, log not redirected, RTX 2080 Ti.APS5_NO_MIMALLOC=1(1)APS5_NO_MIMALLOC=1(2)Plain main
5bf2e139ecould not complete a traced run on this title:clock_gettime: GetProcessTimes failed: Invalid access to memory location, an uncaughtstd::system_errorfromCpuTimeNanosincore/libs/prx/libkernel/Time/Time.cpp.APS5_NO_MIMALLOC=1, the same C runtime heap, completed both of its runs.Still no second GPU vendor here, sorry.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T18:25:33Z.
Thanks for the honest re-measure, and thanks @screamm for the three-title runs. Putting them together: no Windows run shows a frame-time win (your title is neutral now that the worker-busy mode is accounted for), and screamm's runs show p99 worse on two paced titles (14.96 vs 8.71 ms, 19.0 vs 17.3 ms) and +80-230 MiB private memory, with
APS5_NO_MIMALLOC=1matching main.So we'd rather not swap the allocator for every relinked Windows game by default. Could you invert the switch, so mimalloc loads only when it's asked for (for example
APS5_MIMALLOC=1), with the ENVIRONMENT.md row updated to match? Then anyone who wants to try it can, at no cost to everyone else, and we'll rerun CI and merge.Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-18T21:15:39Z.
Done, thanks both, and thanks @screamm for the three-title cross-check.
mimalloc.dllonly whenAPS5_MIMALLOCis set (to any value); without it the stub skips the load, and the process keeps the C runtime's heap.APS5_NO_MIMALLOCis gone.entry_stubchecks the new branch for both run paths.5bf2e139e, and the title and description now match.python tools/env_reference.py --checkand the conventions check pass.APS5_MIMALLOC=1both load, the log shows the redirect line and the v3.5.4 banner, and there are no mimalloc errors.clock_gettimeabort (GetProcessTimes failed: Invalid access to memory location) also hit one untracedAPS5_MIMALLOC=1run, after the redirect.