Skip to content

fix(relinker): run guest preinit arrays before the module initializer - #6112

Merged
oneandonlydean merged 4 commits into
boykopovar:mainfrom
ayam04:fix/relinker-guest-preinit
Oct 18, 2026
Merged

oneandonlydean merged 4 commits into
boykopovar:mainfrom
ayam04:fix/relinker-guest-preinit

Conversation

@ayam04

@ayam04 ayam04 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What

Converted guest modules never run their DT_PREINIT_ARRAY entries. The reader validates the array and rejects one without an initializer, and the unused-NID filter keeps the array's targets as roots, but no writer emitted or ran it: the Linux output only tags DT_INIT_ARRAY/DT_FINI_ARRAY, and the macOS and Windows startup stubs only call the initializer and the init array.

ld.so runs a shared object's preinit array only for the main executable (_dl_init reads it from main_map), so the Linux output cannot use the tag. The preinit entries now run from the module's DT_INIT stub before the initializer, with zeroed argument registers and a null check per slot, the way the init array entries are called. The macOS and Windows startup stubs call them before the initializer. A deferred Windows module exports a thunk as its .ginit entry that runs the preinit entries before the initializer, since the deferred loader's slot list runs after the entry. The reader records the entries like the init and fini arrays.

A module with a preinit array and no initializer is still rejected: the Linux stub that would run the entries exists only with one.

Tested

Windows 11, WinLibs GCC 15.2.0 r7, Release, relinker-only build (-DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON, CMake 4.4.4, Ninja):

  • python3 tools/check_conventions.py --base origin/main: all checks passed
  • full ctest: 168/168 passed (167 on main plus the new guest_preinit)
  • guest_preinit converts a synthetic module with a two-entry preinit array whose entries record their calls:
    • Linux output: the DT_INIT stub runs the entries before the initializer, and the static check decodes the stub and its branch targets. On a Linux host the converted module loads and records (0, 0) for each preinit entry, then the initializer with the pending arguments, then its return value, in order.
    • macOS output: the startup stub calls both entries, with the branch targets resolving to the array slots.
    • Windows output: the startup stub calls both entries before the initializer; the converted app runs natively and exits 42 only when the preinit entries ran before the initializer (the fixture's initializer faults otherwise).
    • Windows deferred output: the .ginit entry RVA is the emitted thunk, its slots hold the array slots and the initializer, and the base relocations cover the slots.
  • Negative control: reverting the startup wiring fails the test (0x12840 is missing from the entry code).

Linux native execution of the new test runs in the relinker matrix on Linux hosts; it was not run here (Windows host only), and the other relinker tests skip native execution on Windows as on main.

Checklist

@ayam04

ayam04 commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Declared the merge order for the overlap: the checklist now reads Depends on: #5559, #5614. This one touches the same regions as #5559 (core/relinker/CMakeLists.txt, docs/dev/debt/relinker.md) and #5614 (the Linux stub emission in LinuxGuestModuleWriter.cpp), but there is no functional dependency in either direction, so the declaration is just the order: theirs first, and I will rebase this one onto main once either lands.

@JJenkx if you would rather have this one go first, say so and I will flip the declaration.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 15, 2026
This was referenced Oct 15, 2026
@ayam04

ayam04 commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @milescoviello. Rebased on main in da00f6f: guest_preinit now goes through add_asan_test_options(guest_preinit verify_asan_link_order=0), the same as the sibling module tests, so it should pass in an ANYPS5_ENABLE_ASAN build now. No other changes in the rebase.

@SandstromPL

Copy link
Copy Markdown
Contributor

@ayam04 one thing in the Windows preinit thunk (.ginitc, WindowsGuestModuleWriter.cpp), checked on da00f6f.

The thunk pushes r12, r13, r14 but pops them in the same order. This is test_guest_preinit.py's flag_module, converted as a deferred --module-dir module:

140014000:  41 54   push %r12
140014002:  41 55   push %r13
140014004:  41 56   push %r14
...
14001404f:  41 5c   pop  %r12
140014051:  41 5d   pop  %r13
140014053:  41 5e   pop  %r14
140014055:  c3      ret

So the caller gets its r12 and r14 back swapped. Both are callee-saved under SysV and Win64. The only caller is InitializeDeferredModule in DynamicLoader.cpp, which calls the entry word as an APS5_VABI function and keeps using base, table, count and the lock state after the call. If the compiler keeps any of them in r12 or r14, opening a deferred module that has a preinit array corrupts the loader's state. The startup path is not affected: it calls the preinit entries directly.

The fix keeps the length, so codeSize, the slot RVAs and the test offsets stay the same:

--- a/core/relinker/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp
+++ b/core/relinker/elfpatcher/src/windows/WindowsGuestModuleWriter.cpp
@@ -172,7 +172,7 @@
             code.Emit({0x4c, 0x89, 0xe7, 0x4c, 0x89, 0xee, 0x4c, 0x89, 0xf2});
             code.Rip({0x48, 0x8b, 0x05}, slotsRva + static_cast<std::uint32_t>(guest.PreInitArray.size()) * 8);
             code.Emit({0xff, 0xd0});
-            code.Emit({0x41, 0x5c, 0x41, 0x5d, 0x41, 0x5e, 0xc3});
+            code.Emit({0x41, 0x5e, 0x41, 0x5d, 0x41, 0x5c, 0xc3});
             auto thunk = code.TakeBytes();
             while (thunk.size() % 8 != 0) thunk.push_back(0x90);
             for (const auto slot : guest.PreInitArray) {
--- a/core/relinker/relinker/tests/test_guest_preinit.py
+++ b/core/relinker/relinker/tests/test_guest_preinit.py
@@ -173,7 +173,7 @@
     restore = 15 + 23 * len(slots)
     assert code[restore:restore + 12] == b'\x4c\x89\xe7\x4c\x89\xee\x4c\x89\xf2\x48\x8b\x05', code[restore:restore + 16]
     assert code[restore + 16:restore + 18] == b'\xff\xd0', code[restore:restore + 25]
-    assert code[restore + 18:restore + 25] == b'\x41\x5c\x41\x5d\x41\x5e\xc3', code[restore:restore + 25]
+    assert code[restore + 18:restore + 25] == b'\x41\x5e\x41\x5d\x41\x5c\xc3', code[restore:restore + 25]
     slots_offset = code_size + (8 - code_size % 8) % 8
     slots_rva = ginitc_rva + slots_offset
     for index, slot in enumerate(slots):

With that applied (Ubuntu 24.04, GCC 13.3, relinker-only Release), the converted thunk ends in pop %r14; pop %r13; pop %r12; ret and all 196 relinker tests pass. Without the test change, guest_preinit fails at the pinned bytes. Not run on Windows.

No test runs the thunk today: check_windows_deferred matches bytes, the nt run takes the startup path, and GuestDeferredModuleFixture.S has no thunk. A Windows test that opens a converted preinit module through dlopen would catch this kind of thing, if you want to add one.

AI-assisted: yes (Claude Code)

@ayam04

ayam04 commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

Good catch @SandstromPL, and thanks for the repro. Fixed in f294956: the thunk now ends pop %r14; pop %r13; pop %r12; ret instead of popping in push order, and test_guest_preinit pins the new bytes. The two hunks are exactly what you posted.

The failure mode you describe is the one that matters here: InitializeDeferredModule in DynamicLoader.cpp keeps base, table, count and the lock state live across the call into the thunk, and InitializeDeferredModule is a normal C++ function, so any of those living in r12 or r14 comes back swapped after the first deferred module with a preinit array is opened. Win64 and SysV both treat r12 and r14 as nonvolatile, so the thunk has to restore them in reverse push order.

Length is unchanged, so codeSize, the slot RVAs and the test offsets are the same, and the startup path from .ginit is untouched.

Verified locally on Windows (mingw g++, relinker Release): ctest -R ^guest_preinit$ passes and the wider guest/windows/amd64 set is 38/38. The Linux byte dump matches your 14001404f: pop %r14 / pop %r13 / pop %r12 / ret.

On a dlopen test for the converted preinit module: agreed that nothing runs the thunk today. Happy to add one in this PR if @milescoviello wants it here, otherwise it can land as a follow-up so this stays a two-hunk fix.

ayam04 and others added 4 commits October 18, 2026 19:09
Converted guest modules never ran their DT_PREINIT_ARRAY entries: the
reader validated the array and the unused-NID filter kept its targets,
but no writer emitted or ran it. ld.so runs a shared object's preinit
array only for the main executable, so the Linux output runs the
entries from the DT_INIT stub before the module initializer; the macOS
and Windows outputs run them before the initializer in their startup
stubs, and the deferred Windows output exports a thunk that runs them
before the initializer for runtime-loaded modules. A module with a
preinit array and no initializer is still rejected, since the Linux
stub exists only with one.
guest_preinit loads the instrumented guest_module_args_host.prx into Python, so in an ANYPS5_ENABLE_ASAN build it needs the same verify_asan_link_order=0 as the other module tests; without it, it fails with "ASan runtime does not come first in initial library list". add_asan_test_options does nothing outside ASan builds.

Signed-off-by: Ayamullah Khan <ayamullahkhan04@gmail.com>
The Windows deferred preinit thunk pushed r12, r13 and r14 and then
popped r12, r13 and r14, so the caller got r12 and r14 back swapped.
InitializeDeferredModule keeps the module base, table and count live
across the call to the thunk, so a compiler that keeps any of them in
r12 or r14 sees corrupted loader state after opening a deferred module
that has a preinit array. Pop in reverse push order instead and pin the
new bytes in test_guest_preinit.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@adriadam10
adriadam10 force-pushed the fix/relinker-guest-preinit branch from f294956 to e751268 Compare October 18, 2026 17:13
@milescoviello

Copy link
Copy Markdown
Contributor

@ayam04 the dlopen test point came from @SandstromPL, not me, so it's their call. For my part, a follow-up is fine and keeps this a two-hunk fix.

AI-assisted: yes (Claude Code)

@oneandonlydean
oneandonlydean merged commit 376c040 into boykopovar:main Oct 18, 2026
8 checks passed
@oneandonlydean

Copy link
Copy Markdown
Collaborator

Merged while @adriadam10 is away: the review passed and full CI is green on this head.

@babyhuey

Copy link
Copy Markdown
Contributor

@ayam04 @oneandonlydean since this merge, every title I run on Linux aborts at start-up with Thread destructor callback is already registered. The first parent of the merge, d7a455a90, is fine. Details and the bisect are in #7636.

AI-assisted: yes

CPritch pushed a commit to CPritch/AnyPS5 that referenced this pull request Oct 18, 2026
…uest-preinit"

This reverts commit 376c040, reversing
changes made to d7a455a.
oneandonlydean added a commit to oneandonlydean/AnyPS5 that referenced this pull request Oct 18, 2026
oneandonlydean added a commit that referenced this pull request Oct 18, 2026
revert(relinker): run guest preinit arrays before the module initializer (#6112)
oneandonlydean pushed a commit that referenced this pull request Nov 3, 2026
Model a module whose initializer dispatches its own preinit callback and assert the exact once-only callback, preserved arguments and return value. Retain zero-address and no-preinit controls and cover deferred Linux initialization.

Regression coverage for #7636, introduced by #6112 and reverted by #7646. The new test fails with the actual historical bad relinker at 376c040 and passes on main 9090972.

AI-assisted: yes. Independently reviewed staged patch 6e437226c361065dad96478101fc899f65cde86caf51a39415369c01c1725168.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants