libkernel: implement sceKernelTruncate and register sceKernelFdatasync #1170
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1170
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/1170/head"
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?
@overlordxrz-source on GitHub · 2026-10-07 22:50 UTC · original
overlordxrz-source:libkernel/truncate→main· +205 −4 · 4 files · 4 commits · closed without mergingsceKernelTruncate(WlyEA-sLDf0) andsceKernelFdatasync(30Rh4ixbKy4) are not registered. Games that import them get the unresolved-import stub, which returns 0 without doing anything.This is part of why NHL 27 saves never load (#1101). pinkton traced it there: the save index file is written through
sceKernelWritev(kAt6VDbHmro), and the same save path also callssceKernelTruncateandsceKernelFdatasync. All three are unregistered, so every call "succeeds", the index stays empty, and the next boot treats the profile as corrupt. The bulkDATAfile goes throughsceKernelPwritev, which Kyty implements, so that file looked fine and hid the problem.sceKernelWritevis covered by #1401 (HamsterCL), so it is not part of this PR. With this PR and #1401 merged, all three calls on that path are handled.Rebased onto current
main(9e41d8320).sceKernelFtruncate(VW3TVZiM4-E) was originally part of this PR.mainnow exports it (048fe9f41), so that registration is dropped here and only its test remains.Changes
sceKernelTruncateis new. It resolves the guest path the same wayKernelUnlinkdoes and flushes any writable descriptors open on that path, so buffered guest writes reach the file first. It then resizes the file by path withstd::filesystem::resize_file, which only needs write access.KernelClosenow closes the host file and clearsopenedwhile holding the file lock, so a flush fromsceKernelTruncatecan't race a close. The lock order is still table lock, then file lock.sceKernelFdatasyncuses the same handler assceKernelFsync(fTx66l5iWIA). The two only differ in whether metadata is flushed, and the host file layer doesn't make that distinction. This is the same registration as in pinkton's patch on #1101, and that commit credits him withCo-authored-by. If #1478 lands first and moves the fsync handler intokernel/fileSystem.cpp, this line just needs to point at the moved handler.I compared the rest of pinkton's
sceKernelTruncatewith this one and kept this version. It returns EFAULT rather than EINVAL for a null path, flushes open writers before resizing, and doesn't need read access to the file.Evidence
Unresolved import stub called ... symbol=WlyEA-sLDf0showed up right afterKernelStat: /temp0/_replay0.bin.sceKernelTruncatefrom its eboot and from its bundledlibc.prx. I found the same import in the logs of #1121 GTA III DE, #1134 Sonic Racing CrossWorlds, #1053 Saros, #1020 Aliens: Fireteam Elite and about 20 other game-status logs.sceKernelTruncate,sceKernelFtruncate,sceKernelFsync,sceKernelFdatasync) by hashing the names with the standard NID scheme.Testing
tests/KernelFileSystemTests.cpp:TestTruncateresolves both truncate NIDs throughInitLibKernel_1. It shrinks an open file withsceKernelFtruncate, extends a file that is open for writing withsceKernelTruncate, shrinks a closed file and checks that the leading bytes are kept. It also checks the error codes, a rename followed by a new file at the old path, a truncate racing a concurrent close, and a file the host only lets us write.TestFdatasyncchecks that30Rh4ixbKy4andfTx66l5iWIAresolve to the same handler, and thatsceKernelFdatasyncreturns OK on a written save fileCheckArchiveMountalso expects EROFS fromKernelTruncateon an archive memberI couldn't run
kernel_file_system_testsitself, because it needs a Vulkan device and the full emulator. What I ran instead:fileSystem.cpp,libKernel.cppandKernelFileSystemTests.cppforx86_64-linux-gnuwith clang (zig c++ 0.17) at-Wall -Wextra, on this branch and on this branch merged with #1401. Both merge cleanly, and the warnings are identical tomain's.src/kernel/fileSystem.cppandsrc/commonfile code, with network, archive, memory and logging stubbed. It runs theTestTruncatesequence plus an open, buffered index truncated by path (23/23 pass, on this branch and on this branch + #1401). On this branch + #1401 it also runs the NHL 27 index pattern: a stale longerINDEX,sceKernelWritevof two iovecs,sceKernelTruncateto the written length, close and read back (6/6 pass). The harness calls the functions directly, so the NID registration is only covered by the test above.src/lines are clean undersrc/.clang-format(clang-format 23.1.3)Not built on Windows or macOS.
AI assistance
An AI assistant helped me rebase this, compare it with pinkton's patch, write the
sceKernelFdatasyncchange and test, and run the builds above. I reviewed the code and the results.AI-assisted: yes
@coderabbitai[bot] on GitHub · 2026-10-07 22:54 UTC · original · edited 2026-10-15 18:26 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
334b306a-6059-4ed9-a027-452cbd58154f📥 Commits
Reviewing files that changed from the base of the PR and between 427ac3cd66bdde4152c6aa5a9de8456dca29074c and
e59f88cd31.📒 Files selected for processing: 4
src/kernel/fileSystem.cppsrc/kernel/fileSystem.hsrc/libs/libKernel.cpptests/KernelFileSystemTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
📝 Walkthrough
The change adds and registers
KernelTruncate(path, length). It validates the path and length, rejects archive paths and directories, flushes matching writable descriptors, and truncates the host file. Tests cover shrinking and extending files, content preservation, error cases, renamed paths, concurrent descriptor activity, write-only files, and archive-path rejection. Additional tests check thatsceKernelFdatasyncresolves to the fsync handler and succeeds on a written file.Suggested reviewers:
neveshenryPriority: ➖ Normal
Change: Bug fix
Merge Risk: ⚪ Minimal · up to
e59f8No change-specific issue remains that needs to be fixed before merge; normal build and test checks still apply.
Pre-merge checks:
4 ·
1
sceKernelTruncateand registeringsceKernelFdatasync.Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@coderabbitai[bot] on GitHub · 2026-10-07 22:54 UTC · original · reviewed
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
8318f8c6-3e1f-42e2-a9f3-88fdee463679📥 Commits
Reviewing files that changed from the base of the PR and between
420bb51d6cand 006ca9c3777dca57a76190c25d38fe586ad9ba37.📒 Files selected for processing (4)
src/kernel/fileSystem.cppsrc/kernel/fileSystem.hsrc/libs/libKernel.cpptests/KernelFileSystemTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@coderabbitai[bot] on GitHub · 2026-10-07 22:54 UTC · original · edited 2026-10-07 23:22 UTC
On
src/kernel/fileSystem.cppline 1251 (outdated):🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Select the file currently at the resolved path.
If a caller renames an open file and creates a replacement at its old path,
KernelRenameleaves the open descriptor'sreal_nameunchanged.GetFile(real_file_name)selects that older descriptor first.KernelTruncatethen reports success after truncating the renamed file, while the replacement keeps its size. Confirm file identity before reusing a descriptor, or truncate the file currently at the resolved path.🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Keep the selected descriptor alive through truncation.
If another thread calls
KernelCloseafterGetFile(real_file_name)returns,KernelClosecan deleteopen_filebefore this function reads its fields or takesopen_file->mutex. The resulting access can crash the process. Retain descriptor ownership or coordinate lookup, truncation, and close with the same lifetime lock.✅ Addressed in commit d6886d4
@overlordxrz-source on GitHub · 2026-10-07 23:15 UTC · original
On
src/kernel/fileSystem.cppline 1251 (outdated):Thanks, both were real. Fixed in the latest commit:
KernelTruncateno longer reuses a descriptor found byreal_name. It flushes every open writable descriptor for that path while holding the descriptor table lock, then truncates through a fresh handle opened at the path. A renamed open file is no longer chosen over the file now at the path, and buffered guest writes still land before the resize.m_mutex,DeleteDescriptorcan't free aFilemid-call.KernelClosestill callsf.Close()without takingfile->mutex, the same as read and write, so I left that as it is.TestTruncatenow renames an open file, creates a replacement at the old path, truncates the old path, and checks that only the replacement changes size. Without the fix, that check fails.@ -242,0 +249,4 @@Common::LockGuard file_lock(f->mutex);if (f->opened && f->writable && !f->directory && f->special == SpecialFile::None &&!f->f.IsInvalid()) {ok = f->f.Flush() && ok;@coderabbitai[bot] on GitHub · 2026-10-07 23:18 UTC · original · edited 2026-10-08 02:48 UTC
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Synchronize
KernelClosewith the flush.If
KernelCloseruns whileFlushWritableholdsf->mutex,KernelClosecan still callf.Close()without that mutex. The descriptor-table lock prevents deletion, but it does not keep the underlying handle open duringf->f.Flush(). Make close and flush use the same per-file synchronization so concurrent truncation cannot flush a closing handle.✅ Confirmed as addressed by @overlordxrz-source
@coderabbitai[bot] on GitHub · 2026-10-07 23:18 UTC · original · edited 2026-10-08 02:50 UTC
On
src/kernel/fileSystem.cppline 1272 (outdated):🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not require read access to truncate a writable file.
If the host file grants write access but not read access, opening it with
Mode::ReadWritecan fail even though truncation only needs write access.KernelTruncatethen returnsEIOwithout resizing the file. Use a truncation path that preserves existing contents and requires only write access.✅ Addressed in commit 427ac3c
@coderabbitai[bot] on GitHub · 2026-10-07 23:18 UTC · original · reviewed
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
21b490e5-7b29-487c-9840-bd4af7a18cb9📥 Commits
Reviewing files that changed from the base of the PR and between 006ca9c3777dca57a76190c25d38fe586ad9ba37 and d6886d4f22e2957b2af63ef30ca8c861718e5f97.
📒 Files selected for processing (2)
src/kernel/fileSystem.cpptests/KernelFileSystemTests.cpp🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.
@coderabbitai[bot] on GitHub · 2026-10-07 23:22 UTC · original
On
src/kernel/fileSystem.cppline 1251 (outdated):@overlordxrz-sourceThanks for the fix and clarification. The supplied code addresses both findings:KernelTruncateopens a fresh handle at the resolved path, so it no longer truncates the renamed file through a stale descriptor.FlushWritableholds the descriptor-table lock, soDeleteDescriptorcannot free aFileduring the flush.The existing
KernelClosesynchronization gap remains separate from these fixes. I have not runTestTruncate.✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@ -242,0 +249,4 @@Common::LockGuard file_lock(f->mutex);if (f->opened && f->writable && !f->directory && f->special == SpecialFile::None &&!f->f.IsInvalid()) {ok = f->f.Flush() && ok;@overlordxrz-source on GitHub · 2026-10-08 02:48 UTC · original
Fixed in "libkernel: close under the file lock and truncate by path".
KernelClosenow closes the host file and clearsopenedwhile holdingfile->mutex.FlushWritablechecksopenedunder that same lock, so it either finishes its flush before the close or sees a closed file and skips it. The lock order stays table lock, then file lock, andKernelClosenever holds both. TheKernelClosechange is the same as the one in #1177, so the two merge cleanly in either order.TestTruncatenow closes and reopens a writable descriptor on another thread while callingsceKernelTruncateon its path. I couldn't run the test binary (it needs Vulkan and the full emulator), but in a standalone harness built fromfileSystem.cppthe old code flushed a file that was being closed, and once hit theIsInvalid()assert inFile::Flush. The new code passes.@overlordxrz-source on GitHub · 2026-10-08 02:48 UTC · original
On
src/kernel/fileSystem.cppline 1272 (outdated):Fixed in "libkernel: close under the file lock and truncate by path".
KernelTruncatenow resizes the file withstd::filesystem::resize_fileinstead of opening it withMode::ReadWrite.Common::Filehas no write-only mode that keeps the contents on every host (the POSIX backend opensMode::Writewith"r+"). On POSIXresize_fileistruncate(2), and the MSVC STL opens the file for writing only. Any failure still returnsEIO, and the other error codes are unchanged.TestTruncatenow truncates a file with only owner write permission, and skips that check where the host can still read it (Windows, or running as root). In a standalone harness on Linux, the old code returnedEIOfor that file and the new code resizes it. I haven't built it on Windows or macOS.@ -242,0 +249,4 @@Common::LockGuard file_lock(f->mutex);if (f->opened && f->writable && !f->directory && f->special == SpecialFile::None &&!f->f.IsInvalid()) {ok = f->f.Flush() && ok;@coderabbitai[bot] on GitHub · 2026-10-08 02:48 UTC · original
@overlordxrz-sourceThanks for the fix and the locking explanation.The supplied code addresses this finding.
KernelCloseandFlushWritablenow use the same per-file mutex for close, theopenedcheck, and flush.KernelClosereleases that mutex before deleting the descriptor, so it does not reverse the table-lock-then-file-lock order.The reported harness result supports the fix. The full test binary remains untested.
✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-10-08 02:50 UTC · original
On
src/kernel/fileSystem.cppline 1272 (outdated):@overlordxrz-sourceThanks for the fix and the backend details. The suppliedKernelTruncateimplementation usesstd::filesystem::resize_file, which removes the unnecessary read-access requirement. TheEIOfailure mapping remains unchanged.The write-only-permission test covers this regression where the host enforces the permission restriction. Windows and macOS validation remains untested, as you stated.
✏️ Learnings added
🧠 Learnings used
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@Friskky1 on GitHub · 2026-10-08 02:55 UTC · original
is it merged yet?
@Nmzik on GitHub · 2026-10-15 23:34 UTC · original
Sole credited
56d3ce98f0Pull request closed