Skip to content

fix(libkernel): pass module args and argp to runtime-loaded modules on Linux - #1102

Merged
adriadam10 merged 4 commits into
boykopovar:mainfrom
jeffrey12cali:fix/module-args-on-linux
Oct 9, 2026
Merged

adriadam10 merged 4 commits into
boykopovar:mainfrom
jeffrey12cali:fix/module-args-on-linux

Conversation

@jeffrey12cali

@jeffrey12cali jeffrey12cali commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What

sceKernelLoadStartModule throws away its arguments, and the relinker's Linux guest writer synthesizes an initialisation trampoline that also clears the argument registers:

bytes.insert(bytes.end(), {0x31, 0xff, 0x31, 0xf6, 0x31, 0xd2, 0xe9});   // xor edi, esi, edx; jmp target

So a converted module always reaches its own start-up code with args = 0 and argp = NULL, whatever the caller passed. This PR delivers them.

That is not cosmetic. On PPSA28997, two of the title's own modules validate the parameter block as the first thing they do and dereference it unconditionally:

SaveData.prx:
4d0a: mov (%rsi),%eax     ; *(uint32*)argp - rsi (argp) is NULL
4d0c: cmp $0x10,%edi      ; args >= 0x10 ?
4d18: cmp $0x10,%eax      ; *argp == 0x10 ?

PSN.prx:    rip = PSN+0x3ee7, rbx = 0        (same validator shape)

The Windows branch delivers the block, so identical code takes its reported-error path and the title carries on. The gap is issue #918; #846 covers the Windows half of the same asymmetry, where the writer exports __aps5_guest_initialize and the loader calls it with args/argp.

libkernel records the pair in thread-local storage before dlopen and clears it after - thread-local because ld.so runs the initialiser on the calling thread, which makes the handoff per-call rather than per-process, and the emitted stub reads it through two accessors it exports:

00: 50            push rax
01: ff 15 <d1>    call [rip+d1]    ; __aps5_get_pending_module_args_nid_no_patch -> &{args, argp}
07: 48 8b 38      mov rdi,[rax]
0a: 48 8b 70 08   mov rsi,[rax+8]
0e: 31 d2         xor edx,edx
10: e8 <d2>       call target      ; the module's own initialiser
15: 89 c7         mov edi,eax
17: ff 15 <d3>    call [rip+d3]    ; __aps5_set_module_init_result_nid_no_patch(eax)
1d: 58            pop rax
1e: c3            ret

Two pushes keep rsp 16-byte aligned at every call. Calling the initialiser instead of tail-jumping is what makes the *res reporting possible. Two undefined symbols and two R_X86_64_GLOB_DAT relocations land in the extra block the writer already emits .dynsym, .dynstr, .gnu.hash and .rela.dyn into.

Scope is kept honest in two ways: modules the executable needs at start-up still receive (0, 0) - which is what both platforms do for them today - and a module with no initialiser gains no slots, no relocations and no imports at all, so guest_symbol_names passes unmodified.

The accessor names carry _nid_no_patch because ResolveNids hashes any unsuffixed export into a NID name; on the first attempt here the built library exported neither name and a plain-name import could never resolve.

Tested

Arch Linux, GCC, Release. ctest --test-dir build --output-on-failure after cmake -DBUILD_TESTING=ON: 392/392 passed (independently confirmed by @Dextroid17 on a second Linux/NVIDIA box, 390/390 at the time of that check).

On the title (PPSA28997, Linux relink, default configuration, no diagnostic flags), with #906's twin-library gap worked around separately so the module can load at all:

before after
dlopen(Media/Plugins/PSN.prx) (nil), undefined symbol: wTpfglkmv34, 4554 retries non-nil handle x6, no undefined symbol
SaveData plugin entry never reached resolved
title's managed bootstrap never finishes prints its own "Finished Initializing ... Scripts" milestone
early ERROR... stall present gone

Reproduction of the quoted fault: relink PPSA28997 with the three launcher-deferred modules made start-up dependencies; the registers quoted are from that core, which reproduces in about two seconds before main.

Checklist

@Dextroid17 #846 picks the name __aps5_guest_initialize for the Windows entry point. This lands the Linux half without renaming DT_INIT handling, and names its accessors __aps5_get_pending_module_args_nid_no_patch / __aps5_set_module_init_result_nid_no_patch. If you would rather have one shared accessor name across both platforms, say which and I will rename it - it is a two-line change here.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

The overlap flag is right, and it changes how I would rather do this.

I checked #846: it routes the shared function through a seam - sceKernelLoadStartModule now calls GuestLoadStartModule_nid_no_patch(path, kRtldNow, args, argp, res) - but that declaration and its implementation are inside #ifdef _WIN32, so on Linux the seam does not exist yet and the ELF branch of the function is simply absent. My commit instead invented a parallel mechanism (parked pair plus a stub that reads it), which duplicates intent on the same two lines of the same function. That is worse for whoever maintains this.

Proposal, and I will do it unless told otherwise: rebase this branch onto #846 and turn it into the ELF half of that seam - GuestLoadStartModule_nid_no_patch implemented for non-_WIN32, parking {args, argp} around dlopen and reading them back through the generated initialisation stub, with the *res reporting kept. Then there is one call path, one argument-passing story, and two platform implementations of it, instead of two designs competing in Module.cpp.

Two facts that survive the restructuring and are worth keeping somewhere in the design:

  • On Linux the module's initialiser is run by ld.so itself, so the arguments have to reach the code before dlopen returns and be read from inside the emitted stub. A Windows-style exported __aps5_guest_initialize that the loader calls afterwards is not directly transferable, because ELF DT_INIT has already run by then. Neutralising DT_INIT on Linux to make that model work would also change start-up ordering for every module the executable needs, which is a bigger question than this PR.
  • Helper symbols that must keep their names need the _nid_no_patch suffix; without it ResolveNids hashes them into NID names and the guest import can never resolve. That cost me one full build cycle to find.

Updated PR description now says Depends on: #846. Builds clean, and ctest is 390/390 with the change.

@Dextroid17

Copy link
Copy Markdown
Contributor

Independent checks from a Linux/NVIDIA box (RTX 3080 Ti, driver 615.71.09, subgroup 32), since I had the same area open for #1009/#1024 and wanted to see whether the plumbing actually binds.

It builds and the suite is green — ninja -C build (clean; only the two touched sources rebuilt, then the libraries) and ctest --test-dir build -j 8 give 100% tests passed out of 390, 0 skipped. That is not evidence for the change, though: outside Module.cpp nothing in the tree references sceKernelLoadStartModule, and the PR adds no test, so the suite runs the new path zero times. The evidence remains your PPSA28997 line. A guest test with an initialiser that asserts it received (args, argp) would be the thing that keeps this fixed — happy to help with it if you want one.

The _nid_no_patch naming does what you say, verified — worth recording so the next person does not spend the build cycle you did:

$ ninja -C build core/libs/libs/libkernel.prx
[55/56] Patching NIDs for libkernel
OK: .../build/core/libs/libs/libkernel.prx
$ nm -D build/core/libs/libs/libkernel.prx | grep pending_module
00000000000628a0 T __aps5_get_pending_module_args_nid_no_patch
00000000000628d0 T __aps5_set_module_init_result_nid_no_patch

Both survive the patcher as plain exported names, so the converted module's GLOB_DAT imports can bind them.

The emitted stub is the instruction sequence it claims to be. I took the 31 bytes from lifecycle() and disassembled them (objdump -D -b binary -m i386:x86-64 -M intel):

push rax
call [args slot]
mov  rdi,[rax]
mov  rsi,[rax+8]
xor  edx,edx
call <init>
mov  edi,eax
call [result slot]
pop  rax
ret

So a guest initialiser receives (args, argp, 0) and its return value reaches *res — the same shape as the Windows seam's Entry(args, argp, nullptr). Both calls are [rip+disp] on the GLOB_DAT slots, and the e8/ff 15 displacements are computed from the byte after each instruction, which is correct.

One question, and the rebase onto #846 does not change it: pendingModuleArgs and pendingModuleInitResult are one process-global pair. The mutex makes the store consistent, not per-call — two threads in sceKernelLoadStartModule at once (a title loading two plugins in parallel) mean the second park overwrites the first, so the first module's DT_INIT stub reads the other module's args/argp, and *res takes whichever initialiser ran last. Nested loads are fine as written: the stub reads the pair before calling the initialiser, so an initialiser that loads another module cannot disturb its caller. If titles only load from one thread, a TechnicalDebt line covers it; if they can load concurrently, the pair wants to be per-call rather than global.

And the answer to the naming question you put to me in #918: #846 introduces no pending-arguments accessor — it routes the shared function through GuestLoadStartModule_nid_no_patch(path, kRtldNow, args, argp, res) — so there is no name of mine to converge on. Yours are the only ones.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

The concurrency point is right and the fix is pushed - thank you for catching it.

You are correct that the mutex made the store consistent rather than the handoff per-call, and that two threads inside sceKernelLoadStartModule would have handed each other's args/argp to the wrong initialiser, with *res taking whichever ran last. The state is now thread_local for both the pair and the result, and the mutex is gone entirely:

thread_local PendingModuleArgs pendingModuleArgs;
thread_local int pendingModuleInitResult = 0;

That is the natural scope rather than a workaround, because ld.so runs a module's initialiser on the thread that called dlopen - so thread-local is per-call here. Concurrent loads from different threads each see their own pair with no lock; nested loads keep working for the reason you identified (the stub reads the pair before calling the initialiser, so an inner load cannot disturb its caller's read). I do not think this needs a TechnicalDebt line, but if you would rather see one recorded anyway, say so and I will add it.

On the test: yes, please take it - you have the harness open and I would rather not guess at the fixture conventions. What I think it needs to be worth having:

  • A fixture module with a DT_INIT: assert the converted image gains exactly the two accessor imports and two R_X86_64_GLOB_DAT relocations against them, and that the stub's RIP operands point at the relocated slots.
  • A fixture module without one: assert it gains neither (the guard is deliberate - guest_symbol_names passing unmodified is the current evidence for that, but it is implicit).
  • The runtime half you described: a guest initialiser that records rdi/rsi so the test can assert they equal the args/argp given to sceKernelLoadStartModule, and that *res equals the value the initialiser returned. That last one is the assertion my change genuinely lacks today - the suite exercises the new path zero times, exactly as you said, so the only evidence is the title line.

Also noted on the naming question: since #846 introduces no pending-arguments accessor, there is nothing to converge on, and I will keep these names. Your nm -D output is now the reference for why the _nid_no_patch suffix is load-bearing - I have put that reasoning in the commit message so the next person does not spend the build cycle I did.

Re-verified after the change: ninja -C build clean, ctest -j4 392/392 passed.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Adding the overlap the CI bot just reported, because it is a real one and the other author should know.

#1249 edits core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp at L55-56 and also edits core/relinker/relinker/tests/test_guest_symbol_names.py. My change edits the same writer function, and it adds two undefined symbols plus two R_X86_64_GLOB_DAT relocations to every converted module that has an initialiser. That is exactly the kind of change test_guest_symbol_names.py measures, so whichever of the two lands second will need the other's expectations updated.

@Raghav314 if your bucketed hash-table work changes how converted modules are laid out, tell me and I will rebase mine onto yours. My half is small and mechanical, so I would rather move than have you rework around it.

The same applies to #1156, which also touches this writer to suppress a bundled system library's lifecycle. I noted that over there.

@Raghav314

Raghav314 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Thanks,my #1249 doesn't change how converted modules are laid out, only what the DT_HASH table contains (one bucket per symbol instead of one bucket in total). Everything after it is still placed through address().

The conflict is only the count line. Keep the bucketed table and take the count from the symbol bytes, as #1102 already does, so the two appended imports are hashed too:

const auto count = static_cast<std::uint32_t>(symbols.size() / 24);

I tried that merge locally, it builds, and the relinker tests pass.

Edit: rebasing now isn't required, so it's up to you. The two only collide on the count line, and only once one of them is merged. If #1249 lands first, the line above is all #1102 needs when you update onto main.

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Build and ctest on main+PR are green (419/419), and I checked the stub encoding by hand (rip-relative displacements, 16-byte alignment, RWX extra segment). Requests before merging:

  • Module.cpp:148-150,157,162: the head still uses a global std::mutex + plain globals. You said on Oct 7 that thread_local without the mutex was pushed, but the only commit on the branch (0597cfb) predates that comment, so it never landed. With the current code two threads in sceKernelLoadStartModule can hand each other's args/argp and *res (the race @Dextroid17 reported). Please push the thread_local version.
  • LinuxGuestModuleWriter.cpp:111-125: the same stub is used for DT_FINI, so unloading also calls __aps5_set_module_init_result and __aps5_get_pending_module_args (args are zero/stale there). Use the args/result stub for DT_INIT only and keep a plain call-through for fini.
  • No test exercises the new path. Please add one on Linux CI: a relinked module whose initialiser records rdi/rsi, loaded via sceKernelLoadStartModule with a known args/argp, plus a check that *res carries the initialiser's return value. It must fail on main.
  • Rebase on main once #846 and #1249 settle (#1249 changes the count line; use symbols.size() / 24 as you already do).
  • CI hasn't run on this head because workflows from first-time contributors wait for maintainer approval; I'll approve the run after your next push.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Status update, and a blocker I should not decide alone. I did not push a rebased head, because the rebase does not pass.

I rebased this branch onto current main and ran the suite. 437 of 438 tests pass. guest_lifecycle_ownership (from #1156) fails, and the reason is a real semantic conflict rather than a merge problem:

OSError: .../consumer.prx.guest.prx: undefined symbol: __aps5_get_pending_module_args_nid_no_patch

That test loads a converted module with ctypes.CDLL, in a process that has no libkernel. My change makes every converted module with an initialiser import two libkernel accessors, so outside the engine the module cannot load at all. On main the same fixture loads fine, because the zeroing trampoline needs nothing.

What I tried before stopping: I made the two imports weak and added a null guard to the stub, so a module that cannot resolve them initialises with (0, 0) exactly as it does today. The load then succeeds, but their test crashes with SIGSEGV instead, and I stopped rather than keep editing the stub in place. The stub is 20-odd hand-placed bytes with four RIP operands, and I would rather get the design decided first than ship a fragile encoder.

Three ways forward, and I will implement whichever you pick:

  1. Weak imports plus a null-guarded stub. Smallest change, keeps ELF DT_INIT as the carrier. I finish it and add a test that loads a converted module without libkernel present, so the fallback is pinned.
  2. Follow feat(relinker): add --module-dir for modules loaded at run time #846 on Linux too. The writer neutralises DT_INIT and exports __aps5_guest_initialize, and sceKernelLoadStartModule calls it with args/argp. One seam on both platforms. This changes lifecycle-at-load semantics, which is exactly what fix(relinker): suppress duplicate system library lifecycle #1156's test now pins (HIAaih versus Hh), so it needs @ahir061's input as well.
  3. Drop the argument handoff from this PR and keep only the *res reporting, if the maintainers would rather solve the trampoline question separately.

My preference is 2, because it converges on the name #846 already introduced and removes the hand-placed stub entirely. But it touches the area #1156 just landed, so I am asking rather than assuming.

For reference, the original evidence still stands: on PPSA28997, SaveData faults at mov (%rsi),%eax with rsi = 0 and PSN faults at PSN+0x3ee7 with rbx = 0, and both are the parameter block that never arrives. The head here stays at 0597cfb8 until the direction is settled.

@Dextroid17

Copy link
Copy Markdown
Contributor

Main moved under the blocker six minutes after you posted, and it moved in your favour — the test you stopped on is gone, and so is the change it was pinning.

#1515 (revert of #1156) merged at 10:58:39Z. It deletes the file that carried the failure, and nothing on main references it any more:

$ gh pr view 1515 --json files        # merged 2026-10-08T10:58:39Z
  core/relinker/relinker/tests/test_guest_lifecycle_ownership.py
  core/relinker/relinker/tests/test_guest_host_libc.py
$ git grep -l guest_lifecycle_ownership upstream/main
  (no output)

So guest_lifecycle_ownership no longer exists on main, and the undefined symbol: __aps5_get_pending_module_args_nid_no_patch you hit cannot fire from it as written. Worth re-running your rebase on today's main before settling the direction: the failure you would get now is not the one you stopped on.

Why #1156 went, since it bears directly on option 2. #1515's body records that suppressing the bundled libc.prx's init/fini leaves titles calling that copy's malloc, which returns NULL because its mspace is never set up (#1500) — one title segfaults within 0.2 s of start, another stops with St9bad_alloc. It also notes that the #693 double heap handshake comes back with the revert and should be redone "together with a test that runs a title's bundled malloc".

That reading makes option 2 the point of convergence rather than the risky one: the __aps5_guest_initialize seam is where #846 already went, and the lifecycle test that objected to changing load-at-init semantics is no longer on main to object. This is one reviewer's read from what merged, not a decision — the trampoline question is boykopovar's and the lifecycle area is @ahir061's.

I only checked what landed on main; I did not run the option-2 rebase or a title, so I am not vouching for the design beyond that.

@jeffrey12cali
jeffrey12cali force-pushed the fix/module-args-on-linux branch from 0597cfb to 42af7e6 Compare October 8, 2026 11:45
@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Three of the four points are done and verified. Head is 42af7e61, rebased on current main, two files, +101/-10.

1. thread_local had genuinely never landed. You were right that 0597cfb89 predates my claim. I checked the branch before changing it: std::mutex and four lock_guard sites were still there. The state is now thread_local PendingModuleArgs plus thread_local int pendingModuleInitResult, and the mutex and every lock_guard are gone - grep for std::mutex and lock_guard in the file returns nothing. The reasoning is the one @Dextroid17 gave: ld.so runs a module's initialiser on the thread that called dlopen, so thread-local storage is per-call, and no lock is needed.

2. DT_FINI no longer shares the argument stub. The imports are gated on image.Init != 0, and fini now uses a separate plain call-through builder. Verified on real converted modules from this title rather than by reading the code:

PSN.prx.guest.prx   DT_INIT vaddr 0xbd1e8   stub bytes 50 ff 15 ...   (push rax; call [rip+slot])
                    DT_FINI vaddr 0xbd207   stub bytes e9 c4 05 f8 ff (jmp rel32)
                    accessor name appears 1 time in the file

So unloading neither reads stale arguments nor reports a result, and a module with a finaliser but no initialiser gains no imports at all.

4. Rebased. #1515 removed the blocker I stopped on, so the rebase is clean: 100% tests passed out of 448. @Dextroid17 was right that main moved in this direction shortly after I posted, and I re-ran rather than trusting that reading.

3. The test is the remaining item, and it needs one decision from you. The assertion you want is an initialiser that records rdi/rsi, loaded through sceKernelLoadStartModule with a known args/argp, plus *res. Two ways to get such an initialiser:

  • Add a .init_array entry to the existing guest_module_fixture. That needs a compiler constructor attribute, and CONTRIBUTING.md says to avoid non-standard extensions where standard C++ is enough.
  • Build a small ELF fixture with an explicit DT_INIT in the relinker's python test helpers, which already synthesise guest images. No extension needed, and it puts the test where the encoding is actually produced.

I prefer the second, and I will write it that way unless you would rather have the first. It will assert three things: the recorded args equals what was passed, the recorded argp equals the pointer, and *res equals the value the initialiser returned. It must fail on main, where handle 0 is rejected and the arguments never arrive.

5. Understood on CI - I will leave the head as pushed and wait for the run to be approved.

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebased head checked: build + ctest on main+PR 450/450, CI green on this head. thread_local state, separate plain jmp for DT_FINI, imports only when Init != 0, and the stub encoding (16-byte alignment, rip-relative displacements) all look right.

One thing left before merging:

  • No test runs the new path (nothing in ctest calls sceKernelLoadStartModule with args or reads *res). Please add the DT_INIT fixture you proposed: an initialiser that records rdi/rsi and returns a known value, loaded with known args/argp, asserting all three. It has to fail on main. Your second option (explicit DT_INIT in the relinker python helpers) is fine; note ctypes.CDLL needs the two accessors resolvable, so the test must load libkernel or provide them.

Ping when pushed and it can merge.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

A negative control for this change, measured on the title today.

I reverted only the argument load in the relinker stub. The stub kept its shape and its result capture. It
now sets argc to zero and argp to null instead of reading them from the pending block. I confirmed the
bytes in the converted modules before running: eight of nine carry 31 ff 31 f6 where the two loads were.

The result is a hard failure, not a slowdown. The run stops before the title's script initialisation. The
engine reports a repeating guest exception signal (signum=30, 22 dispatches) and the script-initialisation
line never appears. The same tree with this head reaches that line and draws the boot card.

So the parameter block is load-bearing for this title. The change is not cosmetic.

One second test was inconclusive and I am reporting it as such. I also moved the pending block back to a
shared global, to test whether the thread_local form matters here. That run also stopped early, but our
prepare step did not reliably copy the rebuilt library, so I cannot say which build that run used. I make
no claim about thread_local from it. I am fixing the stamping first and will not re-report until the
measurement is trustworthy.

@Dextroid17

Copy link
Copy Markdown
Contributor

The negative control is the right instrument, and it is the differential the change was missing: reverting only the two argument loads — reintroducing 31 ff 31 f6 in eight of nine converted modules — turns the title from drawing the boot card into a hard failure at signum=30 before the script-initialisation line ever prints. That is a stronger thing than a passing suite, because the suite runs the new path zero times and the revert shows what the path is actually carrying. The title evidence in the body and this revert together say the parameter block is load-bearing for PPSA28997, not cosmetic.

On the second run: holding it is the right call, and I would not spend the stamping fix on it — the run cannot separate the two forms however clean the copy gets. The shared-global pair and the thread_local pair are indistinguishable for a single-threaded start-up: with one thread there is nothing to overwrite, and the change the mutex guarded was the store, so the single-thread case kept working under both. The failure the global pair introduces needs two threads inside sceKernelLoadStartModule at the same moment, which one title's boot sequence does not produce. So the only measurement that can decide it is a concurrent one, and the thread_local scope answers that by construction rather than by a title log — I would report the title runs you already have and leave the concurrency claim where it is.

Nothing else from me. The remaining item is the DT_INIT test, and @adriadam10 has already said your option 2 (explicit DT_INIT in the relinker python helpers) is the acceptable one — that is his to settle, not mine.

Written with AI assistance.

@jeffrey12cali
jeffrey12cali force-pushed the fix/module-args-on-linux branch from 42af7e6 to 7f2c8b1 Compare October 8, 2026 15:17
@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

The DT_INIT test is pushed. Head is 7f2c8b19, rebased onto current main (4b005b22), two commits, five files.

What the test does (guest_module_args, option 2 as you agreed — explicit DT_INIT in the relinker python
helpers):

  • A hand-built guest module has a DT_INIT that forwards rdi and rsi to a host recorder untouched and
    returns 0x5A17.
  • The test sets a known block: args = 0x1122334455667788, argp = 0x99AABBCCDDEEFF00.
  • It asserts three things on the converted module: it imports both accessors; the initialiser received both
    values; and the stub forwarded the initialiser's return value.
  • Per your note about ctypes.CDLL, the test does not load libkernel. The host recorder exports
    __aps5_get_pending_module_args_nid_no_patch and __aps5_set_module_init_result_nid_no_patch itself, so
    the accessors resolve without dragging in the whole kernel library.

Control, as required. With LinuxGuestModuleWriter.cpp and Module.cpp taken from main, the test
fails: the converted module imports only RecordArgs, so the accessor imports are absent. Restored, it
passes. Suite: 464 of 464.

Two things you should know about the base. The previous head was rebased onto my fork's main, which is
stale, not onto boykopovar/AnyPS5 main. That is why the branch still carried
GuestLifecycleReplacement.cpp and test_guest_lifecycle_ownership.py, both deleted by the #1515 revert.
This rebase drops them. The new test therefore brings its own host fixture
(elfpatcher/tests/GuestModuleArgsHost.cpp) and depends on nothing that the revert removed.

Separately, tools/check_conventions.py reports seven findings on this head. None are in this range: they
are in libSceFont/src/WritingLine.cpp, libSceMsgDialog.native/Export.cpp, and four commit subjects that
came from main. And cmake --build build fails on a jpeg_turbo_external install step that wants to write
to /opt/libjpeg-turbo, which is why scripts/build.sh builds named targets instead; the test binaries all
build and run.

Ready to merge when you are.

Written with AI assistance.

@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

One more commit after the ping. Head is 5f4824ef.

I re-read my own diff for this review and found a bug in the writer change. The DT_RELA tags were still
guarded on the input module's relocation table, while the two accessor relocations are appended to a
copy of it. A module with an initialiser and no imports therefore kept the new stub but lost both
relocations that fill its GOT slots, so the stub called through a null pointer at load time. My first test
did not catch it, because its fixture has one import of its own.

Measured on a converted module whose DT_RELASZ is zero:

  • before the fix: DT_INIT present, DT_RELA absent, RELASZ 0
  • after the fix: DT_INIT present, DT_RELA present, RELASZ 48, both accessors imported

The test now converts that second module and asserts the relocation table and both imports. I also dropped
an unused parameter from the displacement helper.

Control re-run against main's writer: the test still fails. Suite: 464 of 464.

@Dextroid17

Copy link
Copy Markdown
Contributor

Independent confirmation on 5f4824ef from a Linux/NVIDIA x86-64 box, since the DT_INIT test was the one item left and you landed it before I got to it.

Suite green on this head. Full incremental build, then ctest -j16: 100% tests passed out of 467, none skipped.

The new test runs in CI and bites on main. It registers as ctest test #456 guest_module_args, so it is not another mode that CI silently omits. Negative control with main's writer (git checkout upstream/main -- core/relinker/elfpatcher/src/linux/LinuxGuestModuleWriter.cpp, relinker rebuilt, test kept):

AssertionError: {'RecordArgs'}

— the converted module imports only RecordArgs: both accessor imports and the relocation table are absent.

Your last commit is the fix, isolated. Reverting only the writer to the pre-fix 7f2c8b19 and rebuilding gives, on the no-import fixture:

  • before (7f2c8b19): assert GETTER in bare_imports → AssertionError: set() — the stub is emitted but both R_X86_64_GLOB_DAT slots stay unfilled, the null-pointer path you describe;
  • after (5f4824ef): passes, DT_RELA present, RELASZ 48.

On this box the native half also ran (sys.platform == 'linux' and x86-64), so the converted module was loaded through the fixture and the recording initialiser's args/argp/result assertions executed — not just the ELF checks. tools/check_conventions.py --base upstream/main → All checks passed.

CI on the head now shows conventions / report / windows / relinker (macos, ubuntu, windows) green, with linux still pending. Nothing is outstanding from my side — the merge is the maintainer's call.

Written with AI assistance.

jeffrey12cali added a commit to jeffrey12cali/SoS-PS5 that referenced this pull request Oct 9, 2026
sceKernelLoadStartModule discarded its args and argp parameters, so a module that
validates its parameter block faulted at start-up. The relinker synthesised a DT_INIT
that zeroed rdi, rsi and rdx before jumping to the real initialiser, which turned the
discarded block into a guaranteed null dereference for any module that reads it.

SaveData.prx from this title faults at its first instruction under that stub: the guest
address corresponding to SaveData.prx+0xd0a executes a load from rsi while rsi is zero,
next to a comparison of edi against 0x10, and PSN.prx shows the same shape. With the
block forwarded, both modules reach their own logic.

The kernel now records the block in thread-local storage around the dlopen, and the
relinker emits a DT_INIT stub that reads it back, calls the initialiser, and forwards the
return value to a setter the kernel reads into the caller's res pointer. The finaliser
keeps a plain call-through and the two accessor imports are emitted only for modules that
have an initialiser. The thread-local form is deliberate: a shared slot lets a concurrent
load overwrite the block that another thread's initialiser is about to read.

Proposed upstream as boykopovar/AnyPS5#1102, where it carries the measured negative
control: reverting only the two argument loads turns this title from drawing its boot
card into a hard failure before script initialisation.
@popcoder565

Copy link
Copy Markdown
Contributor

Native Windows run, since no Windows results were posted. Setup: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release. Head 5f4824ef, merged onto main 8b393b6 in one build with 31 other PRs that had no Windows run.

  • The change is Linux-only. On Windows guest_module_args passes with native execution skipped, so this only checks that it builds.
  • Full ctest in that build: 520 of 521. The one failure is guest_offline_imports, broken by feat(libSceRudp): implement sceRudpGetStatus #2359 (reported there).

No title was run.

🤖 Addressed by Claude Code

@adriadam10 adriadam10 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked on main + PR (rebased on current main): build and full ctest green (549/549), stub encoding and relocation handling look right.

One problem in guest_module_args, fixed in a commit on your branch (4459a01, test only):

  • test_guest_module_args.py: os.uname().machine == 'x86-64' is never true (Linux reports x86_64), so the native execution was always skipped, including on CI. The args/argp/result assertions had never run.
  • With it enabled the fixture crashed: the initialiser's call [rip+disp] used 0x2820 - 0x1016 but the next instruction is at 0x101a; and SetPendingArgs was called on the build-tree copy of the host library while the module binds to the libs/libc.prx copy, so the getter returned zeros. The loader now opens the libs/libc.prx copy.

With those fixed the module receives args=0x1122334455667788, argp=0x99AABBCCDDEEFF00 and *res reports 0x5A17. Merging once CI is green on the new head.

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 9, 2026
jeffrey12cali and others added 4 commits October 10, 2026 00:57
…n Linux

sceKernelLoadStartModule discarded its arguments, and the relinker's Linux guest writer
synthesized an initialisation trampoline that also cleared the argument registers before
jumping to the module entry point, so a converted module always reached its own start-up
code with args = 0 and argp = NULL.

On PPSA28997 two of the title's own modules validate that parameter block as their first
act and dereference it unconditionally: SaveData faults on `mov (%rsi),%eax` with rsi = 0
beside its `cmp $0x10` size checks, and PSN faults the same way at PSN+0x3ee7 with rbx = 0.
The Windows branch delivers the block, so identical code reports its parameter-version
error and continues instead of faulting.

sceKernelLoadStartModule now records the pair before dlopen and clears it afterwards, and
the emitted DT_INIT stub reads it through two accessors exported by libkernel. The
initialiser is called rather than tail-jumped so its return value can be reported through
*res as the PS5 API specifies. The state is thread_local, which makes the handoff per-call:
ld.so runs a module's initialiser on the thread that called dlopen. DT_FINI keeps a plain
call-through, so unloading neither reads stale arguments nor reports a result.

The accessor names use the _nid_no_patch suffix so the NID resolver leaves them alone and a
guest import can name them exactly.
…block

Add a hand-built guest module with an explicit DT_INIT that forwards rdi and rsi to a
host recorder without touching them and returns a known value. The test sets a known
argument count and argument pointer, loads the converted module, and asserts that the
initialiser received both values and that the stub forwarded its return value.

The host recorder also provides the two accessor symbols, so the test resolves them
without loading libkernel. The converted module must import both accessors, which is
what distinguishes the new behaviour from the previous stub that zeroed the arguments.
The DT_RELA tags were still guarded on the input module's relocation table, while the
new accessor relocations were appended to a copy of it. A module with an initialiser and
no imports therefore kept the argument stub but lost both relocations that fill its GOT
slots, so the stub called through a null pointer at load time.

Guard on the extended table instead, and drop the unused start parameter from the
displacement helper. The test now converts a module whose DT_RELASZ is zero and asserts
that the output carries both accessor imports and a 48-byte relocation table.
The machine check compared against 'x86-64' (uname reports 'x86_64'), so the
native execution was always skipped. With it enabled the fixture itself was
wrong: the initialiser's rip-relative call used the wrong displacement, and
the pending block was set on a different copy of the host library than the
one the module binds to.

Co-Authored-By: Claude <noreply@anthropic.com>
@adriadam10
adriadam10 force-pushed the fix/module-args-on-linux branch from 4459a01 to 8868d56 Compare October 9, 2026 23:01
@adriadam10

Copy link
Copy Markdown
Collaborator

main moved (#1249 changed the guest DT_HASH table) and this PR no longer merged cleanly, which is what the red eligibility check reported. Rebased onto current main and pushed.

Build and ctest on the rebased head: 97/97 in libkernel + relinker. Merging once CI is green.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 9, 2026
@adriadam10

Copy link
Copy Markdown
Collaborator

Re-checked the rebased head (8868d56) on top of current main: fresh build, libkernel + relinker ctest 97/97, guest_module_args passes with its native path running. The earlier red eligibility was the conflict with #1249, already resolved by the rebase. Merging once CI is green.

@adriadam10
adriadam10 merged commit ff8961d into boykopovar:main Oct 9, 2026
6 checks passed
SleglJan pushed a commit to SleglJan/AnyPS5 that referenced this pull request Oct 10, 2026
…-on-linux

fix(libkernel): pass module args and argp to runtime-loaded modules on Linux
@jeffrey12cali

Copy link
Copy Markdown
Contributor Author

Thank you for rebasing it and for catching the interaction with #1249. Taking the symbol count from
symbols.size() / 24 so the two appended accessor imports land in the bucketed hash is the correct fix, and
keeping guest_module_args running natively is what made the merge safe to call.

Recording the far end of it for anyone who revisits this path: the parameter block is what let PPSA28997
start its modules at all. With args/argp dropped, the title's modules fail their own validation and never
reach their initialiser. With #1102 the title reaches its main menu and holds 60 FPS through 15 minutes of
continuous play. The sceKernelStopUnloadModule pair is still unmeasured on our side, as I noted on #918, so
nothing further is owed there until a title is seen unloading a module.

jeffrey12cali added a commit to jeffrey12cali/SoS-PS5 that referenced this pull request Oct 10, 2026
sceKernelLoadStartModule discarded its args and argp parameters, so a module that
validates its parameter block faulted at start-up. The relinker synthesised a DT_INIT
that zeroed rdi, rsi and rdx before jumping to the real initialiser, which turned the
discarded block into a guaranteed null dereference for any module that reads it.

SaveData.prx from this title faults at its first instruction under that stub: the guest
address corresponding to SaveData.prx+0xd0a executes a load from rsi while rsi is zero,
next to a comparison of edi against 0x10, and PSN.prx shows the same shape. With the
block forwarded, both modules reach their own logic.

The kernel now records the block in thread-local storage around the dlopen, and the
relinker emits a DT_INIT stub that reads it back, calls the initialiser, and forwards the
return value to a setter the kernel reads into the caller's res pointer. The finaliser
keeps a plain call-through and the two accessor imports are emitted only for modules that
have an initialiser. The thread-local form is deliberate: a shared slot lets a concurrent
load overwrite the block that another thread's initialiser is about to read.

Proposed upstream as boykopovar/AnyPS5#1102, where it carries the measured negative
control: reverting only the two argument loads turns this title from drawing its boot
card into a hard failure before script initialisation.
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.

5 participants