Skip to content

fix(libkernel): stage APR file reads before writing guest memory - #4413

Closed
THEMANnt wants to merge 3 commits into
boykopovar:mainfrom
THEMANnt:fix/apr-stage-file-reads
Closed

THEMANnt wants to merge 3 commits into
boykopovar:mainfrom
THEMANnt:fix/apr-stage-file-reads

Conversation

@THEMANnt

@THEMANnt THEMANnt commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What

  • APR file reads now use a temporary buffer and copy into guest memory only after the full read succeeds.
  • Adds a three-attempt retry loop for file reads to handle transient short-read scenarios.
  • A regression test checks that a short read leaves the destination unchanged.

Tested

Windows — built and ran the APR test suite; no game-specific test was run for this isolated change.

  • cmake --build build --target guest_ampr_tests — passed
  • ctest --test-dir build -R '^guest_ampr_markers$' --output-on-failure — passed
  • python tools/check_conventions.py --base upstream/main — passed

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
  • Unblocks: none
  • AI-assisted: yes

@Dextroid17 Dextroid17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fix holds on Linux, and the added test is what proves it. Head f7cd1d4f6 (two commits: 961f2afb5 staging, f7cd1d4f6 retry); GitHub's base is e7c70a2df, whose fork point from this branch is 9bc362351 — Apr.cpp is byte-identical in both, so use one of those two for the file, not git diff e7c70a2df..HEAD (77 commits of churn). I built guest_ampr_tests and guest_ampr_threads_tests in a worktree and ran two arms: head Apr.cpp + head test file, then base Apr.cpp + head test file.

head      100% tests passed out of 2     (guest_ampr_markers, guest_ampr_threads)
          direct run of guest_ampr_tests: exit 0
baseline  guest_ampr_markers (Subprocess aborted) → GuestAmpr.cpp:642: requirement failed
          direct run: exit 134

Worth noting which line fails: the message assertion at GuestAmpr.cpp:641 passes on the base too — the base already throws returned 5 of 16 bytes. Line 642 is the destination check, so that is the load-bearing part of the new test, and it is the bug: e7c70a2df has stream.read(reinterpret_cast<char*>(command.destination), …) at line 165 with GuestArena::HostWrite destination(…) and its Open() check two lines above, so a short read wrote into guest memory and then threw. Guard-before-copy is the right shape.

Three things I noticed, in decreasing weight:

  1. A reading of the new order, not a run: the destination guard now sits below a host allocation sized by a guest value. In the head, std::vector<char> staging(static_cast<std::size_t>(command.size)) is line 161 and GuestArena::HostWrite destination(…) / Open() are 179-180 — and on Linux GuestArenaBeginHostWrite_nid_postfix calls GuestWriteWatch… and returns true unconditionally, so that guard rejects nothing here either before or after the move; on Windows it checks shared-view writability, not a size bound. command.size is a std::uint64_t out of the record, and the decoder bounds the record (APR: truncated command payload line 266, APR: malformed command 572), not this field. Through the guest-facing encoder it is capped at 0x100000000 (ValidReadLength, libSceAmpr/Export.cpp:60; GuestAmpr.cpp:769 pins that 0x100000001 is rejected), so the worst reachable allocation is a 4 GiB zero-filled vector; a hand-built record can put 2^64-1 there and get std::length_error instead of the intended message. If the guard is meant to run first, moving it above line 161 costs nothing — it does not depend on the read.
  2. The second commit is not in the body. f7cd1d4f6 adds the three-attempt retry loop, a different topic from staging (the checklist asks for one topic per PR), and the "What" paragraph describes only the staging change. Either a sentence there or a split, plus a word on what the retry targets: by inspection of the loop, a plain short read (eofbit/failbit) takes the else branch, clears the flags, re-seeks offset + read and re-reads the same tail, so only the badbit path (close/reopen) can make progress — the head's own test observes exactly 5 of 16 bytes after all three attempts.
  3. Coverage: the new test pins the short-read path, which is the fix. An invalid destination cannot be exercised at all on Linux (the guard is the no-op above), and size == 0 is rejected by the encoder, so the if (read != 0) before the memcpy can only be false for a hand-built record — with size > 0 either the copy runs or the short read has already thrown above it.

Checked and fine: dropping #include <cerrno> leaves no errno use anywhere in the file — only the GUEST_EINVAL constants.

Written with AI assistance.

Hermes Agent 🤖 at your service

@oneandonlydean oneandonlydean self-assigned this Oct 12, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

Closing: main already throws on a short or failed APR read, so leaving the destination untouched before that throw changes nothing a title can see, while the staging vector adds a second copy to every APR read. The three-attempt loop (Apr.cpp:168-182) is a retry after an error, which isn't allowed here (#182).

Reopen with a title where the staged read changes what it sees, without the retry.

MichalSy added a commit to MichalSy/AnyPS5 that referenced this pull request Oct 13, 2026
Add per-sample pixel inputs, correct tessellation component addressing, publish small imported GPU images at flips, prepare static shader ABIs on the background pool, and size Windows write-watch queries. Integrate pipelined release and metadata-fill corrections, finish resident linear targets, recycle cached fragment descriptor sets, and return positional-read errors while retaining descriptor isolation and owned-layout lifetime handling.

Validation: complete configured build and 52 targeted Linux checks pass, including full graphics/submission suites and upstream regression fixtures. Windows runtime execution and Sackboy rendering remain to be verified. Rejected APR staging/retry PR boykopovar#4413 and the unpublished blend-disabling GT7 workaround are excluded.
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.

3 participants