Skip to content

fix(libkernel): zero-fill APR reads that reach the end of the file - #5255

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
Nesyth:fix/libkernel-apr-read-past-eof-v2
Oct 14, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
Nesyth:fix/libkernel-apr-read-past-eof-v2

Conversation

@Nesyth

@Nesyth Nesyth commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

What

APR file reads threw when the file ended before the requested length (_readFile in core/libs/prx/libkernel/Apr/src/Apr.cpp; every read command goes through it, gather and scatter reads included). That throw came with #232, which replaced accepting a short read with the rest of the destination left untouched. This change keeps the throw for a short read that stops before the file's current end and zero-fills one that reaches it, instead of going back to leaving the rest untouched:

  • A short read that reaches the end of the file on disk completes: the bytes the file has are copied and the rest of the destination is zero-filled. A read that starts at or past the end fills the whole destination with zeros. The end is the file's size on disk when the read returns (std::filesystem::file_size), not the size from the resolve.
  • A short read that ends before that size still throws with the same message. For a descriptor that was closed and reused for another file (fix(libkernel): keep host standard streams open on guest close #3295), that catches a read only when the other file ends early; if it has enough bytes, the read returns them without an error, as on main. Whether a read of a file that is appended to while it runs throws or is zero-filled depends on timing.
  • A short read that never reached end-of-file still throws with the same message: a read whose seek fails, which in practice means a closed descriptor (fix(libkernel): keep host standard streams open on guest close #3295). A failed stream (bad()) still throws "APR: read failed".
  • On Windows (MinGW), a read of 2^32 bytes, the longest the recording API accepts, reads nothing: libstdc++ hands the count to _read, whose 32-bit count makes it 0, and takes the empty result as end-of-file. Such a read still throws "returned 0 of 4294967296 bytes", as on main, unless it starts at or past the end of the file, where it is now zero-filled.
  • The size is queried only for a short read that reached end-of-file; full reads and failed seeks never stat the file.
  • A file truncated between the read and the size query is zero-filled. On Linux (not run), a file unlinked in that window makes the read throw std::filesystem::filesystem_error instead of the APR message, and a file replaced by a rename is judged by the new file's size. On Windows neither can happen while the reader's stream is open: removing the file or renaming another file over it fails with a sharing violation (checked with a stand-alone copy of the read and its condition).
  • After a zero-filled read, the gather and scatter cursor moves on by the requested size, as after a full read: a scatter after it continues past the end of the file and is zero-filled, and a gather after that lands behind the zero-filled bytes.
  • docs/dev/debt/libkernel.md records the rule, and that the console's behaviour for a read past the end of a file is unverified (it may zero-fill, leave the destination untouched or fail the command).

Ready or Not (PPSA18605) reads its settings file this way. Traced with temporary logging on my bring-up build (run 185):

  1. At boot, an APR resolve returns /download0/readyornot/saved/ps5/gameusersettings.ini at 5480 bytes.
  2. The title saves its settings with sceKernelOpen, one 5479-byte sceKernelWrite and sceKernelClose. The only change in the file is InitialOptionsIsSet=False becoming True, one byte shorter.
  3. It reads the file back through APR, 5480 bytes at offset 0, the size from the boot resolve, and again after some later saves (6 reads for 10 saves in a session). The title keeps the size its boot resolve returned. Traced on main, it calls neither sceKernelAprGetFileSize nor sceKernelAprGetFileStat for the file (only its Epic Online Services module imports them), and its sceKernelStat after the save sees 5479 bytes.

Without this change the read throws and the title terminates:

terminate called after throwing an instance of 'std::runtime_error'
  what():  APR: read of ...\download0\readyornot\saved\ps5\gameusersettings.ini at offset 0 returned 5479 of 5480 bytes

Tests added to core/libs/tests/GuestAmpr.cpp (guest_ampr_tests, ctest guest_ampr_markers):

  • TestReadPastEndOfFileZeroFills resolves a 64-byte file in a new directory, rewrites it on the host as 63 different bytes, and submits into buffers filled with 0xA5: a 64-byte read at offset 0 (bytes 0-62 must be the new content and byte 63 zero), a 16-byte scatter after it (all zeros), an 8-byte gather at offset 0 after that (the file's first 8 bytes, behind the scatter's 16), and 16-byte reads at offset 63, the new end of the file, and at offset 4096 (both all zeros).
  • TestReadAtUnseekableOffsetThrows writes a read at offset 2^63 into the command buffer directly, since the recording API rejects offsets of 2^40 and above; the seek fails before the end of the file, and the submit must still throw "returned 0 of 4 bytes". It passes on main as well.
  • No test makes the size operand decide. It decides when a read reports end-of-file before the file's end on disk: when the descriptor and the path diverge inside one _readFile call (fix(libkernel): keep host standard streams open on guest close #3295's case) or a writer grows the file before the size query, which a test cannot arrange without racing the read, and on Windows for the 2^32-byte read above. No test is kept for that read, because it would require a valid read to fail, a limit main shares, and would break once such reads are split; a probe checks it instead (below). A read error does not reach the size operand: under a Windows byte-range lock, libstdc++ sets badbit and the read throws "APR: read failed" before the size check (below).

Overlaps:

Tested

Windows 11 Pro 10.0.22631, AMD Ryzen 7 7800X3D, AMD Radeon RX 7900 XTX, WinLibs GCC 15.2.0, Release, BUILD_TESTING=ON:

  • On main e0d388f, this head: ctest for libSceAmpr (4 of 4) and libkernel (125 of 125) passes, and the four libSceAmpr tests passed 10 runs in a row. TestResolveSymbolicLink is skipped without Developer Mode, as on main. tools/check_conventions.py --base e0d388fa2 passes.
  • On main 1268ba8, the base before, whose _readFile is the same, one change at a time, rebuilding libkernel and running guest_ampr_tests:
    • without the memset line, TestReadPastEndOfFileZeroFills fails (whole[size - 1] == 0);
    • with the condition as on main, with the resolved size in place of file_size, or with <= in place of <, TestReadPastEndOfFileZeroFills aborts with "APR: read of ...\ampr_read_past_end\settings.ini at offset 0 returned 63 of 64 bytes";
    • with the gather and scatter cursor moved on by the bytes read instead of the requested size, TestReadPastEndOfFileZeroFills fails (the gather lands on the scatter's zeros);
    • without the end-of-file operand, TestReadAtUnseekableOffsetThrows fails;
    • without the size operand, both tests pass.
  • A probe linked against those builds records a 2^32-byte read of a 100-byte file into 4 GiB of reserved memory, 64 KiB of it committed and filled with 0xA5. With this change the read at offset 0 throws "returned 0 of 4294967296 bytes" and leaves the committed bytes untouched, and the read at offset 200 is zero-filled (the committed bytes are zero when it writes past them). Without the size operand the read at offset 0 does not throw: it zero-fills without copying a byte of the file.
  • A temporary test holding a Windows byte-range lock on part of a 64 KiB file: a read inside the locked range, one crossing into it and one of the whole file each throw "APR: read failed" and leave the destination untouched.

Ready or Not (PPSA18605) ran on main d1fd937, this branch's first base; _readFile is the same there as on e0d388f. The runtime's libs held the 123 modules built from d1fd937, with libkernel without this change (run 300) and with it (run 302); app.exe, the title relinked for Windows, is from my bring-up runtime and was not rebuilt. Both runs started from the settings file the title wrote on its first boot (InitialOptionsIsSet=False, 5480 bytes), with APS5_TRACE_APR=1:

  • Without this change, the title saves the file and terminates 56 s after start on the next read, with the message above.
  • With it, no APR error. The title opened the file for writing 10 times and read it 6 times after the boot read (each read asks for 5480 bytes). 475 s after start, before its first frame, it stopped on a separate limit of main: "AGC graphics: color views of several array slices are unsupported" (State.cpp:1011; open feat(agc): render layered draws into 3D color targets #1077 adds layered 3D color targets).
  • Both runs left the file at 5479 bytes with InitialOptionsIsSet=True.

Linux: not run.

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 under Silent stubs in their library's technical debt file
  • 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: PPSA18605 Ready or Not (PPSA18605) #4184
  • GPUs tested: n/a
  • AI-assisted: yes

@coltken95

Copy link
Copy Markdown

Tested on Linux x86-64 (Release build), with 417ea99 merged into main 9d0a41d:

  • With the PR: guest_ampr_markers passes.
  • With main's sources and the PR's test: guest_ampr_markers aborts.

AI-assisted: yes (Claude Code)

@oneandonlydean
oneandonlydean merged commit 94f96c8 into boykopovar:main Oct 14, 2026
9 checks passed
@Nesyth
Nesyth deleted the fix/libkernel-apr-read-past-eof-v2 branch November 17, 2026 21:18
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