From cb750ff85695ea65ff493d321c3242407536895b Mon Sep 17 00:00:00 2001 From: Itamar Medyoni Date: Sat, 17 Oct 2026 15:08:00 +0300 Subject: [PATCH] feat(libkernel): report open, read and close notes on watched files EVFILT_VNODE and sceKernelAddFileEvent threw for NOTE_OPEN, NOTE_CLOSE, NOTE_CLOSE_WRITE, NOTE_READ, NOTE_REVOKE and unknown bits, and for a descriptor that is not a file, a directory, a pipe or a socket. As FreeBSD 11's vop_open_post, vop_read_post, vop_readdir_post and vop_close_post raise them, a successful open, read, readv, pread, preadv, AIO read or getdents now reports NOTE_OPEN or NOTE_READ to the vnode watches of that file, and closing the last descriptor of an open file, dup2 onto it included, reports NOTE_CLOSE, or NOTE_CLOSE_WRITE when the file was opened for writing. Files are matched by the st_dev and st_ino that fstat reports, and the watches of a closed descriptor are removed before its close is reported, as closefp calls knote_fdclose first. NOTE_REVOKE and unknown bits are accepted, as vfs_kqfilter does not check fflags, and a file read from app0.zar is watched for these notes only. A character device fails with ENODEV and a terminal with EINVAL, as no_kqfilter and ttydev_kqfilter answer. --- core/libs/prx/libkernel/Aio/src/Aio.cpp | 2 + core/libs/prx/libkernel/Equeue/Equeue.hpp | 18 ++- .../prx/libkernel/Equeue/src/FileEvent.cpp | 140 ++++++++++++++++-- core/libs/prx/libkernel/Equeue/src/Kqueue.cpp | 3 - .../File/include/DescriptorControl.hpp | 2 + .../libkernel/File/src/DescriptorControl.cpp | 11 ++ core/libs/prx/libkernel/File/src/Open.cpp | 7 +- core/libs/prx/libkernel/File/src/Stdio.cpp | 35 +++-- core/libs/tests/GuestKqueue.cpp | 106 ++++++++++++- docs/dev/debt/libkernel.md | 3 +- 10 files changed, 289 insertions(+), 38 deletions(-) diff --git a/core/libs/prx/libkernel/Aio/src/Aio.cpp b/core/libs/prx/libkernel/Aio/src/Aio.cpp index e228a480e50a..9ca4f0cec890 100644 --- a/core/libs/prx/libkernel/Aio/src/Aio.cpp +++ b/core/libs/prx/libkernel/Aio/src/Aio.cpp @@ -9,6 +9,7 @@ #include #include "SceTypes.hpp" #include "prx/libc/include/General.hpp" +#include "prx/libkernel/Equeue/Equeue.hpp" #include "prx/libc/include/GuestArena.hpp" #include "prx/libc/include/PreciseWait.hpp" #include "prx/libkernel/File/include/ArchivedFile.hpp" @@ -213,6 +214,7 @@ void RunRequest(KernelAioRwRequest& req, bool write) { req.result->state = AioCompleted; return; } + if (!write) EqueueNoteRead(req.fd); req.result->return_value = done; req.result->state = AioCompleted; } diff --git a/core/libs/prx/libkernel/Equeue/Equeue.hpp b/core/libs/prx/libkernel/Equeue/Equeue.hpp index 4cace734bd79..58768d8ccea1 100644 --- a/core/libs/prx/libkernel/Equeue/Equeue.hpp +++ b/core/libs/prx/libkernel/Equeue/Equeue.hpp @@ -134,9 +134,25 @@ void KqueueDescriptorReadShut(int descriptor); extern "C" bool IsKqueueDescriptor_nid_no_patch(int descriptor); std::optional KqueueReadable(int descriptor); KernelEqueueEvent EqueueDescriptorEvent(int descriptor, int16_t filter, uint16_t flags, void* udata); -void RequireVnodeNotes(uint32_t fflags); void SetVnodeNotes(KernelEqueueEvent& event, uint32_t fflags); int AddVnodeEvent(const KernelEqueueRef& queue, int descriptor, uint32_t fflags, uint16_t flags, void* udata); + +struct EqueueCloseNote { + uint32_t device = 0; + uint32_t inode = 0; + uint32_t note = 0; +}; + +void EqueueNoteOpen(int descriptor); +void EqueueNoteRead(int descriptor); +EqueueCloseNote EqueuePrepareCloseNote(int descriptor); +void EqueueDeliverCloseNote(const EqueueCloseNote& note); +void EqueueNoteClose(int descriptor); + +template Result EqueueNotedRead(int descriptor, Result result) { + if (result >= 0) EqueueNoteRead(descriptor); + return result; +} extern "C" { KernelEqueueRef EqueuePin_nid_postfix(KernelEqueue eq); diff --git a/core/libs/prx/libkernel/Equeue/src/FileEvent.cpp b/core/libs/prx/libkernel/Equeue/src/FileEvent.cpp index a9126e1e7eab..a26018d2e730 100644 --- a/core/libs/prx/libkernel/Equeue/src/FileEvent.cpp +++ b/core/libs/prx/libkernel/Equeue/src/FileEvent.cpp @@ -1,13 +1,18 @@ #include "prx/libkernel/include/Api.hpp" #include "prx/libkernel/Equeue/Equeue.hpp" #include "prx/libc/include/General.hpp" +#include "prx/libkernel/File/include/ArchivedFile.hpp" +#include "prx/libkernel/File/include/DescriptorControl.hpp" #include "prx/libkernel/File/include/File.hpp" +#include "prx/libkernel/File/include/NativeStat.hpp" #include "prx/libkernel/Socket/include/SocketRuntime.hpp" #include #include #include #include +#include +#include #include #include #include @@ -37,7 +42,12 @@ namespace { constexpr int GUEST_EBADF = 9; +constexpr int GUEST_ENODEV = 19; constexpr int GUEST_EINVAL = 22; +constexpr std::uint32_t GUEST_NOTE_OPEN = 0x0080; +constexpr std::uint32_t GUEST_NOTE_CLOSE = 0x0100; +constexpr std::uint32_t GUEST_NOTE_CLOSE_WRITE = 0x0200; +constexpr std::uint32_t GUEST_NOTE_READ = 0x0400; #ifdef __APPLE__ static_assert(NOTE_DELETE == 0x0001 && NOTE_WRITE == 0x0002 && NOTE_EXTEND == 0x0004 && NOTE_ATTRIB == 0x0008 && NOTE_LINK == 0x0010 && NOTE_RENAME == 0x0020); @@ -148,6 +158,70 @@ void VnodeWatch::Deliver(std::uint32_t hint) { owner->TriggerEvent(ident, EVFILT_VNODE, &message); } +struct VnodeIdentity { + std::uint32_t device; + std::uint32_t inode; +}; + +struct AccessWatch { + VnodeIdentity identity; + std::weak_ptr watch; +}; + +std::mutex g_accessMutex; +std::vector g_accessWatches; +std::atomic g_accessWatchCount{0}; + +std::optional DescriptorIdentity(int descriptor) { + FileStat status{}; + if (!File::FillFileStatFromDescriptor(descriptor, &status)) { + return std::nullopt; + } + return VnodeIdentity{status.st_dev, status.st_ino}; +} + +void WatchAccess(const VnodeIdentity& identity, const std::shared_ptr& watch) { + std::lock_guard lock(g_accessMutex); + g_accessWatches.push_back({identity, watch}); + g_accessWatchCount.store(g_accessWatches.size()); +} + +void ForgetAccess(const VnodeWatch* watch) { + std::lock_guard lock(g_accessMutex); + std::erase_if(g_accessWatches, [watch](const AccessWatch& entry) { + const auto live = entry.watch.lock(); + return !live || live.get() == watch; + }); + g_accessWatchCount.store(g_accessWatches.size()); +} + +void DeliverAccess(const VnodeIdentity& identity, std::uint32_t note) { + std::vector> watches; + { + std::lock_guard lock(g_accessMutex); + for (const auto& entry : g_accessWatches) { + if (entry.identity.device != identity.device || entry.identity.inode != identity.inode) { + continue; + } + if (auto live = entry.watch.lock()) { + watches.push_back(std::move(live)); + } + } + } + for (const auto& watch : watches) { + watch->Deliver(note); + } +} + +void DeliverAccess(int descriptor, std::uint32_t note) { + if (g_accessWatchCount.load() == 0) { + return; + } + if (const auto identity = DescriptorIdentity(descriptor)) { + DeliverAccess(*identity, note); + } +} + #ifdef _WIN32 constexpr DWORD VNODE_POLL_MILLISECONDS = 50; @@ -355,8 +429,12 @@ int OpenHostWatch(int descriptor, std::uint32_t notes, HostWatch& host) { if (type == FILE_TYPE_PIPE) { return GUEST_EINVAL; } + if (type == FILE_TYPE_CHAR) { + DWORD mode = 0; + return ::GetConsoleMode(handle, &mode) ? GUEST_EINVAL : GUEST_ENODEV; + } if (type != FILE_TYPE_DISK) { - NotImplemented_nid_no_patch("EVFILT_VNODE: a descriptor that is not a file or a directory"); + return GUEST_ENODEV; } host.target = ::ReOpenFile(handle, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0); } @@ -438,7 +516,7 @@ int OpenHostWatch(int descriptor, std::uint32_t, HostWatch& host) { return GUEST_EINVAL; } if (!S_ISREG(status.st_mode) && !S_ISDIR(status.st_mode)) { - NotImplemented_nid_no_patch("EVFILT_VNODE: a descriptor that is not a file or a directory"); + return ::isatty(descriptor) ? GUEST_EINVAL : GUEST_ENODEV; } host.target = ::fcntl(descriptor, F_DUPFD_CLOEXEC, 0); if (host.target < 0) { @@ -637,7 +715,7 @@ int OpenHostWatch(int descriptor, std::uint32_t, HostWatch& host) { return GUEST_EINVAL; } if (!S_ISREG(status.st_mode) && !S_ISDIR(status.st_mode)) { - NotImplemented_nid_no_patch("EVFILT_VNODE: a descriptor that is not a file or a directory"); + return ::isatty(descriptor) ? GUEST_EINVAL : GUEST_ENODEV; } host.directory = S_ISDIR(status.st_mode); const auto path = "/proc/self/fd/" + std::to_string(descriptor); @@ -682,7 +760,9 @@ void TriggerVnode(KernelEqueueEvent* event, void* data) { } void StopVnode(KernelEqueue, KernelEqueueEvent* event) { - static_cast(event->filter.data)->Stop(); + auto* watch = static_cast(event->filter.data); + ForgetAccess(watch); + watch->Stop(); } int VnodeDescriptorError(int descriptor) { @@ -700,25 +780,22 @@ int VnodeDescriptorError(int descriptor) { } -void RequireVnodeNotes(std::uint32_t fflags) { - if ((fflags & ~MAPPED_NOTES) != 0) { - NotImplemented_nid_no_patch(("EVFILT_VNODE: fflags " + std::to_string(fflags & ~MAPPED_NOTES)).c_str()); - } -} - void SetVnodeNotes(KernelEqueueEvent& event, std::uint32_t fflags) { static_cast(event.filter.data)->SetInterest(fflags); } int AddVnodeEvent(const KernelEqueueRef& queue, int descriptor, std::uint32_t fflags, std::uint16_t flags, void* udata) { - RequireVnodeNotes(fflags); if (const int error = VnodeDescriptorError(descriptor)) { return error; } + const bool archived = File::IsArchivedFile(descriptor); HostWatch host; - if (const int error = OpenHostWatch(descriptor, fflags, host)) { - return error; + if (!archived) { + if (const int error = OpenHostWatch(descriptor, fflags, host)) { + return error; + } } + const auto identity = DescriptorIdentity(descriptor); std::shared_ptr watch; try { watch = std::make_shared(queue, static_cast(descriptor), fflags); @@ -746,10 +823,44 @@ int AddVnodeEvent(const KernelEqueueRef& queue, int descriptor, std::uint32_t ff CloseHostWatch(host); return result == EQUEUE_OK ? 0 : result & 0xffff; } - std::thread(RunHostWatch, watch, std::move(host)).detach(); + if (identity) { + WatchAccess(*identity, watch); + } + if (!archived) { + std::thread(RunHostWatch, watch, std::move(host)).detach(); + } return 0; } +void EqueueNoteOpen(int descriptor) { + DeliverAccess(descriptor, GUEST_NOTE_OPEN); +} + +void EqueueNoteRead(int descriptor) { + DeliverAccess(descriptor, GUEST_NOTE_READ); +} + +EqueueCloseNote EqueuePrepareCloseNote(int descriptor) { + if (g_accessWatchCount.load() == 0 || !File::LastDescriptorOfOpenFile(descriptor)) { + return {}; + } + const auto identity = DescriptorIdentity(descriptor); + if (!identity) { + return {}; + } + return {identity->device, identity->inode, File::OpenFileWrites(descriptor) ? GUEST_NOTE_CLOSE_WRITE : GUEST_NOTE_CLOSE}; +} + +void EqueueDeliverCloseNote(const EqueueCloseNote& note) { + if (note.note != 0) { + DeliverAccess(VnodeIdentity{note.device, note.inode}, note.note); + } +} + +void EqueueNoteClose(int descriptor) { + EqueueDeliverCloseNote(EqueuePrepareCloseNote(descriptor)); +} + extern "C" { int APS5_VABI sceKernelAddFileEvent(KernelEqueue eq, int fd, int watch, void* udata) { @@ -758,7 +869,6 @@ int APS5_VABI sceKernelAddFileEvent(KernelEqueue eq, int fd, int watch, void* ud return SCE_KERNEL_ERROR_EBADF; } const auto notes = static_cast(watch); - RequireVnodeNotes(notes); if (const int error = VnodeDescriptorError(fd)) { return SceKernelError(error); } diff --git a/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp b/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp index eea3d985ab28..4798ee1d1aa1 100644 --- a/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp +++ b/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp @@ -403,9 +403,6 @@ int ModifyKnote(const KernelEqueueRef& queue, KernelEvent& change) { } const bool descriptor = change.filter == EVFILT_READ || change.filter == EVFILT_WRITE; const auto lowWater = descriptor ? DescriptorLowWater(change) : 0; - if (change.filter == EVFILT_VNODE) { - RequireVnodeNotes(change.fflags); - } return GuestErrno(queue->EditEvent(change.ident, change.filter, [&change, descriptor, lowWater](KernelEqueueEvent& event) { event.event.udata = change.udata; if (descriptor) { diff --git a/core/libs/prx/libkernel/File/include/DescriptorControl.hpp b/core/libs/prx/libkernel/File/include/DescriptorControl.hpp index f2555a2dae99..cfea071de656 100644 --- a/core/libs/prx/libkernel/File/include/DescriptorControl.hpp +++ b/core/libs/prx/libkernel/File/include/DescriptorControl.hpp @@ -34,6 +34,8 @@ class WriteSync { bool IsVnode(int fd); bool IsCharacterDevice(int fd); bool GrantsAccess(int fd, bool write); +bool LastDescriptorOfOpenFile(int fd); +bool OpenFileWrites(int fd); } diff --git a/core/libs/prx/libkernel/File/src/DescriptorControl.cpp b/core/libs/prx/libkernel/File/src/DescriptorControl.cpp index 337c823682c6..3ff904e94aa0 100644 --- a/core/libs/prx/libkernel/File/src/DescriptorControl.cpp +++ b/core/libs/prx/libkernel/File/src/DescriptorControl.cpp @@ -666,6 +666,17 @@ bool IsVnode(int fd) { #endif } +bool LastDescriptorOfOpenFile(int fd) { + std::lock_guard lock(g_mutex); + const auto found = g_entries.find(fd); + return found == g_entries.end() || found->second.status.use_count() == 1; +} + +bool OpenFileWrites(int fd) { + const auto kind = Classify(fd, "close"); + return kind == Kind::File && AccessMode(fd, "close") != ReadOnly; +} + } extern "C" bool DescriptorHasNoVnode_nid_no_patch(int fd) { diff --git a/core/libs/prx/libkernel/File/src/Open.cpp b/core/libs/prx/libkernel/File/src/Open.cpp index 13bfaf43b814..64dca59a93e5 100644 --- a/core/libs/prx/libkernel/File/src/Open.cpp +++ b/core/libs/prx/libkernel/File/src/Open.cpp @@ -225,6 +225,7 @@ static int OpenNative(const std::filesystem::path& native, int flags, std::uint1 if (const auto archived = File::OpenArchivedFile(native, flags)) { if (*archived < 0) return SceErrorFromErrno(-*archived); File::RememberDescriptor(*archived, flags); + EqueueNoteOpen(*archived); return *archived; } #ifdef _WIN32 @@ -289,6 +290,7 @@ static int OpenNative(const std::filesystem::path& native, int flags, std::uint1 if ((flags & SCE_KERNEL_O_ACCMODE) != SCE_KERNEL_O_RDONLY || (flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_TRUNC))) RecordWrittenPath_nid_no_patch(native); File::RememberDescriptor(fd, flags); + EqueueNoteOpen(fd); return fd; } @@ -340,6 +342,7 @@ int APS5_VABI sceKernelClose(int d) { #ifdef _WIN32 const auto positioned = File::LockPositionedTransfer(d); #endif + EqueueNoteClose(d); File::ForgetRandomDevice(d); File::ForgetDescriptor(d); ForgetJitSharedMemory(d); @@ -368,10 +371,10 @@ std::int64_t APS5_VABI sceKernelRead(int d, void* buf, std::size_t nbytes) { const GuestArena::HostWrite destination(buf, nbytes); if (!destination.Open()) errno = EFAULT; else if (File::ReadRandomDevice(d, buf, nbytes)) return static_cast(nbytes); - else if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, nullptr)) return *archived; + else if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, nullptr)) return EqueueNotedRead(d, *archived); auto n = destination.Open() ? NativeRead(d, buf, nbytes) : -1; if (n < 0) return SceIoErrorFromErrno(errno); - return static_cast(n); + return EqueueNotedRead(d, static_cast(n)); } std::int64_t APS5_VABI sceKernelWrite(int d, const void* buf, std::size_t nbytes) { diff --git a/core/libs/prx/libkernel/File/src/Stdio.cpp b/core/libs/prx/libkernel/File/src/Stdio.cpp index b94988ef1f44..6272ab13dc99 100644 --- a/core/libs/prx/libkernel/File/src/Stdio.cpp +++ b/core/libs/prx/libkernel/File/src/Stdio.cpp @@ -804,6 +804,7 @@ int APS5_VABI close_nid_postfix(int d) { #ifdef _WIN32 const auto positioned = File::LockPositionedTransfer(d); #endif + EqueueNoteClose(d); File::ForgetRandomDevice(d); File::ForgetDescriptor(d); ForgetJitSharedMemory(d); @@ -888,10 +889,12 @@ int APS5_VABI dup2_nid_postfix(int from, int to) { EqueueDescriptorClosed(to); auto positioned = File::LockPositionedTransfer(to); auto* const standard = HostStandardHandle_nid_no_patch(to); + const auto closing = EqueuePrepareCloseNote(to); int duplicated = File::ReplaceSharedMemoryDescriptor_nid_no_patch(from, to); if (duplicated == -2) duplicated = WithoutParameterHandler([from, to] { return ::_dup2(from, to); }); KeepStandardHandle_nid_no_patch(to, standard); if (duplicated != 0) return PosixFailure(SceErrorFromErrno(errno) & 0xffff); + EqueueDeliverCloseNote(closing); GuestSockets::Forget(to); File::ForgetDirectoryDescriptor(to); File::DuplicateDirectoryDescriptor(from, to); @@ -911,11 +914,13 @@ int APS5_VABI dup2_nid_postfix(int from, int to) { } if (to == 1) PreserveHostStandardOutput(); if (to == 2) PreserveHostStandardError(); + const auto closing = EqueuePrepareCloseNote(to); const int result = ::dup2(from, to); if (result < 0) return PosixFailure(SceErrorFromErrno(errno) & 0xffff); File::ForgetDirectoryDescriptor(to); File::DuplicateDirectoryDescriptor(from, to); EqueueDescriptorClosed(to); + EqueueDeliverCloseNote(closing); GuestSockets::Forget(to); File::ForgetRandomDevice(to); if (sourceIsRandom) File::RememberRandomDevice(to); @@ -1075,10 +1080,10 @@ int64_t APS5_VABI pread_nid_postfix(int d, void* buf, size_t nbytes, int64_t off const GuestArena::HostWrite destination(buf, nbytes); if (!destination.Open()) return PosixFailure(GUEST_EFAULT); if (File::ReadRandomDevice(d, buf, nbytes)) return static_cast(nbytes); - if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, &offset)) return *archived; + if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, &offset)) return EqueueNotedRead(d, *archived); char empty = 0; const auto result = NativePread(d, buf == nullptr ? &empty : buf, nbytes, offset); - return result < 0 ? PosixFailure(SceErrorFromErrno(errno) & 0xffff) : result; + return result < 0 ? PosixFailure(SceErrorFromErrno(errno) & 0xffff) : EqueueNotedRead(d, result); } int64_t APS5_VABI pwrite_nid_disambig1_nid_postfix(int d, const void* buf, size_t nbytes, int64_t offset) { @@ -1231,7 +1236,7 @@ int APS5_VABI sceKernelGetdirentries(int fd, char* buf, int nbytes, int64_t* bas const GuestArena::HostWrite destination(buf, static_cast(nbytes)); const GuestArena::HostWrite baseDestination(basep, basep == nullptr ? 0 : sizeof(*basep)); if (!destination.Open() || !baseDestination.Open()) return SceErrorFromErrno(GUEST_EFAULT); - return File::ReadDirectoryDescriptor(fd, buf, nbytes, basep); + return EqueueNotedRead(fd, File::ReadDirectoryDescriptor(fd, buf, nbytes, basep)); } int APS5_VABI sceKernelGetdents(int fd, char* buf, int nbytes) { @@ -1300,7 +1305,7 @@ int APS5_VABI sceKernelGetdirentries(int fd, char* buf, int nbytes, int64_t* bas const auto record = (GuestHeaderBytes + nameLength + 1 + 3) & ~std::size_t{3}; if (nameLength > GuestMaxName || written + record > static_cast(nbytes)) { if (::lseek(fd, resume, SEEK_SET) < 0) return SceErrorFromErrno(errno); - if (written != 0) return static_cast(written); + if (written != 0) return EqueueNotedRead(fd, static_cast(written)); return nameLength > GuestMaxName ? static_cast(0x80020000u | GUEST_ENAMETOOLONG) : SceErrorFromErrno(GUEST_EINVAL); } char* out = buf + written; @@ -1318,7 +1323,7 @@ int APS5_VABI sceKernelGetdirentries(int fd, char* buf, int nbytes, int64_t* bas offset += entry->d_reclen; } if (::lseek(fd, resume, SEEK_SET) < 0) return SceErrorFromErrno(errno); - return static_cast(written); + return EqueueNotedRead(fd, static_cast(written)); } int APS5_VABI sceKernelGetdents(int fd, char* buf, int nbytes) { @@ -1423,10 +1428,10 @@ int64_t APS5_VABI sceKernelPread(int d, void* buf, size_t nbytes, int64_t offset const GuestArena::HostWrite destination(buf, nbytes); if (!destination.Open()) return SceErrorFromErrno(GUEST_EFAULT); if (File::ReadRandomDevice(d, buf, nbytes)) return static_cast(nbytes); - if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, &offset)) return *archived; + if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, &offset)) return EqueueNotedRead(d, *archived); char empty = 0; const auto result = NativePread(d, nbytes == 0 && buf == nullptr ? &empty : buf, nbytes, offset); - return result < 0 ? SceErrorFromErrno(errno) : result; + return result < 0 ? SceErrorFromErrno(errno) : EqueueNotedRead(d, result); } int64_t APS5_VABI sceKernelPwrite(int d, const void* buf, size_t nbytes, int64_t offset) { @@ -1510,7 +1515,7 @@ static std::int64_t TransferIovecs(int d, const KernelIovec* guestIov, int iovcn int64_t APS5_VABI sceKernelReadv(int d, const KernelIovec* iov, int iovcnt) { if (File::IsDirectoryDescriptor(d)) return SceErrorFromErrno(GUEST_EISDIR); - return TransferIovecs(d, iov, iovcnt, nullptr, false); + return EqueueNotedRead(d, TransferIovecs(d, iov, iovcnt, nullptr, false)); } int64_t APS5_VABI sceKernelWritev(int d, const KernelIovec* iov, int iovcnt) { @@ -1520,7 +1525,7 @@ int64_t APS5_VABI sceKernelWritev(int d, const KernelIovec* iov, int iovcnt) { int64_t APS5_VABI sceKernelPreadv(int d, const KernelIovec* iov, int iovcnt, int64_t offset) { if (File::IsDirectoryDescriptor(d)) return SceErrorFromErrno(GUEST_EISDIR); - return TransferIovecs(d, iov, iovcnt, &offset, false); + return EqueueNotedRead(d, TransferIovecs(d, iov, iovcnt, &offset, false)); } int64_t APS5_VABI sceKernelPwritev(int d, const KernelIovec* iov, int iovcnt, int64_t offset) { @@ -1537,9 +1542,9 @@ int64_t APS5_VABI sceKernelPread(int d, void* buf, size_t nbytes, int64_t offset const GuestArena::HostWrite destination(buf, nbytes); if (!destination.Open()) return SceErrorFromErrno(GUEST_EFAULT); if (File::ReadRandomDevice(d, buf, nbytes)) return static_cast(nbytes); - if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, &offset)) return *archived; + if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, &offset)) return EqueueNotedRead(d, *archived); const auto result = NativePread(d, buf, nbytes, offset); - return result < 0 ? SceErrorFromErrno(errno) : result; + return result < 0 ? SceErrorFromErrno(errno) : EqueueNotedRead(d, result); } int64_t APS5_VABI sceKernelPwrite(int d, const void* buf, size_t nbytes, int64_t offset) { @@ -1564,9 +1569,9 @@ int64_t APS5_VABI sceKernelReadv(int d, const KernelIovec* guestIov, int iovcnt) return result < 0 ? SceKernelError(*__error_nid_postfix()) : result; } if (File::IsRandomDevice(d)) return ReadRandomIovecs(d, iov, iovcnt); - if (const auto archived = File::ReadArchivedIovecs(d, iov, iovcnt, nullptr)) return *archived; + if (const auto archived = File::ReadArchivedIovecs(d, iov, iovcnt, nullptr)) return EqueueNotedRead(d, *archived); const auto result = static_cast(::readv(d, NativeIovecs(iov), iovcnt)); - return result < 0 ? SceErrorFromErrno(errno) : result; + return result < 0 ? SceErrorFromErrno(errno) : EqueueNotedRead(d, result); } int64_t APS5_VABI sceKernelWritev(int d, const KernelIovec* guestIov, int iovcnt) { @@ -1596,9 +1601,9 @@ int64_t APS5_VABI sceKernelPreadv(int d, const KernelIovec* guestIov, int iovcnt std::deque destinations; if (!OpenIovecs(iov, iovcnt, destinations)) return SceErrorFromErrno(GUEST_EFAULT); if (File::IsRandomDevice(d)) return ReadRandomIovecs(d, iov, iovcnt); - if (const auto archived = File::ReadArchivedIovecs(d, iov, iovcnt, &offset)) return *archived; + if (const auto archived = File::ReadArchivedIovecs(d, iov, iovcnt, &offset)) return EqueueNotedRead(d, *archived); const auto result = static_cast(::preadv(d, NativeIovecs(iov), iovcnt, static_cast(offset))); - return result < 0 ? SceErrorFromErrno(errno) : result; + return result < 0 ? SceErrorFromErrno(errno) : EqueueNotedRead(d, result); } int64_t APS5_VABI sceKernelPwritev(int d, const KernelIovec* guestIov, int iovcnt, int64_t offset) { diff --git a/core/libs/tests/GuestKqueue.cpp b/core/libs/tests/GuestKqueue.cpp index 7b81a77b4a0d..1f206d5a3787 100644 --- a/core/libs/tests/GuestKqueue.cpp +++ b/core/libs/tests/GuestKqueue.cpp @@ -27,6 +27,7 @@ static constexpr int GuestEperm = 1; static constexpr int GuestEnoent = 2; static constexpr int GuestEbadf = 9; +static constexpr int GuestEnodev = 19; static constexpr int GuestEinval = 22; static constexpr int GuestEpipe = 32; static constexpr int GuestEagain = 35; @@ -71,12 +72,18 @@ static constexpr std::uint32_t NoteAttrib = 0x0008; static constexpr std::uint32_t NoteLink = 0x0010; static constexpr std::uint32_t NoteRename = 0x0020; static constexpr std::uint32_t NoteRevoke = 0x0040; +static constexpr std::uint32_t NoteOpen = 0x0080; +static constexpr std::uint32_t NoteClose = 0x0100; +static constexpr std::uint32_t NoteCloseWrite = 0x0200; +static constexpr std::uint32_t NoteRead = 0x0400; +static constexpr int ReadOnly = 0x0000; static constexpr int ReadWrite = 0x0002; static constexpr int Create = 0x0200; static constexpr int Directory = 0x00020000; static constexpr int SceOk = 0; static constexpr int SceEnoent = static_cast(0x80020002); static constexpr int SceEbadf = static_cast(0x80020009); +static constexpr int SceEnodev = static_cast(0x80020013); static constexpr int SceEinval = static_cast(0x80020016); static void Require(bool value) { if (!value) std::abort(); } @@ -1055,7 +1062,10 @@ static void FileWatch() { std::this_thread::sleep_for(std::chrono::milliseconds(200)); Require(ftruncate_nid_postfix(file, 0) == 0); Require(Wait(kq, events, 4) == 1 && events[0].fflags == NoteAttrib && events[0].udata == nullptr); - Require(Throws([kq, ident] { Apply(kq, Change(ident, EvfiltVnode, EvAdd, NoteRevoke)); })); + Require(Apply(kq, Change(ident, EvfiltVnode, EvAdd, NoteRevoke | 0x00100000)) == 0); + Require(write_nid_postfix(file, "abc", 3) == 3); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + Require(Poll(kq, events, 4) == 0); Require(Apply(kq, Change(ident, EvfiltVnode, EvDelete)) == 0); RequireFailure(Apply(kq, Change(ident, EvfiltVnode, EvDelete)), GuestEnoent); @@ -1091,6 +1101,98 @@ static void FileWatch() { Require(std::filesystem::remove(path)); } +static std::uint32_t PolledNotes(int kq, std::uintptr_t ident) { + KernelEvent events[4]{}; + const int count = Poll(kq, events, 4); + Require(count == 0 || (count == 1 && events[0].ident == ident && events[0].filter == EvfiltVnode)); + return count == 0 ? 0 : events[0].fflags; +} + +static void AccessNotes() { + const auto path = TemporaryName("access"); + const int created = open_nid_postfix(path.c_str(), ReadWrite | Create, 0644); + Require(created >= 0 && write_nid_postfix(created, "abc", 3) == 3 && close_nid_postfix(created) == 0); + const int watched = open_nid_postfix(path.c_str(), ReadOnly, 0); + Require(watched >= 0); + const int kq = kqueue_nid_postfix(); + const auto ident = static_cast(watched); + const std::uint32_t access = NoteOpen | NoteClose | NoteCloseWrite | NoteRead; + Require(Apply(kq, Change(ident, EvfiltVnode, EvAdd | EvClear, access)) == 0); + Require(PolledNotes(kq, ident) == 0); + + const int reader = open_nid_postfix(path.c_str(), ReadOnly, 0); + Require(reader >= 0 && PolledNotes(kq, ident) == NoteOpen); + char buffer[8]{}; + Require(read_nid_postfix(reader, buffer, sizeof(buffer)) == 3 && PolledNotes(kq, ident) == NoteRead); + Require(read_nid_postfix(reader, buffer, sizeof(buffer)) == 0 && PolledNotes(kq, ident) == NoteRead); + Require(pread_nid_postfix(reader, buffer, 1, 1) == 1 && buffer[0] == 'b' && PolledNotes(kq, ident) == NoteRead); + const int copy = dup_nid_postfix(reader); + Require(copy >= 0 && close_nid_postfix(reader) == 0 && PolledNotes(kq, ident) == 0); + Require(close_nid_postfix(copy) == 0 && PolledNotes(kq, ident) == NoteClose); + + const int writer = open_nid_postfix(path.c_str(), ReadWrite, 0); + Require(writer >= 0 && PolledNotes(kq, ident) == NoteOpen); + Require(close_nid_postfix(writer) == 0 && PolledNotes(kq, ident) == NoteCloseWrite); + + const int replaced = open_nid_postfix(path.c_str(), ReadOnly, 0); + Require(replaced >= 0 && PolledNotes(kq, ident) == NoteOpen); + int pipe[2]; + Require(pipe_nid_postfix(pipe) == 0); + Require(dup2_nid_postfix(pipe[0], replaced) == replaced && PolledNotes(kq, ident) == NoteClose); + Require(close_nid_postfix(replaced) == 0 && close_nid_postfix(pipe[0]) == 0 && close_nid_postfix(pipe[1]) == 0); + Require(PolledNotes(kq, ident) == 0); + + KernelEqueue eq = 0; + int marker = 0; + Require(sceKernelCreateEqueue(&eq, "access") == SceOk); + Require(sceKernelAddFileEvent(eq, watched, static_cast(NoteOpen), &marker) == SceOk); + const int opened = open_nid_postfix(path.c_str(), ReadOnly, 0); + Require(opened >= 0 && PolledNotes(kq, ident) == NoteOpen); + KernelEvent events[4]{}; + int count = 0; + const KernelUseconds second = 1000000; + Require(sceKernelWaitEqueue(eq, events, 4, &count, &second) == SceOk && count == 1); + Require(events[0].ident == ident && events[0].fflags == NoteOpen && events[0].udata == &marker); + Require(close_nid_postfix(opened) == 0 && PolledNotes(kq, ident) == NoteClose); + Require(sceKernelDeleteFileEvent(eq, watched) == SceOk); + + const int other = kqueue_nid_postfix(); + const int observer = open_nid_postfix(path.c_str(), ReadOnly, 0); + Require(observer >= 0 && PolledNotes(kq, ident) == NoteOpen); + const auto observerIdent = static_cast(observer); + Require(Apply(other, Change(observerIdent, EvfiltVnode, EvAdd | EvClear, access)) == 0); + Require(close_nid_postfix(watched) == 0 && PolledNotes(other, observerIdent) == NoteClose); + Require(Poll(kq, events, 4) == 0); + RequireFailure(Apply(kq, Change(ident, EvfiltVnode, EvDelete)), GuestEbadf); + Require(close_nid_postfix(observer) == 0 && Poll(other, events, 4) == 0); + + const int random = open_nid_postfix("/dev/urandom", ReadOnly, 0); + Require(random >= 0); + RequireFailure(Apply(kq, Change(static_cast(random), EvfiltVnode, EvAdd, NoteOpen)), GuestEnodev); + Require(sceKernelAddFileEvent(eq, random, static_cast(NoteOpen), nullptr) == SceEnodev); + Require(close_nid_postfix(random) == 0); + Require(sceKernelDeleteEqueue(eq) == SceOk); + Require(close_nid_postfix(other) == 0 && close_nid_postfix(kq) == 0); + Require(std::filesystem::remove(path)); +} + +static void DirectoryAccessNotes() { + const auto path = TemporaryName("listing"); + Require(mkdir_nid_postfix(path.c_str(), 0755) == 0); + const int directory = open_nid_postfix(path.c_str(), Directory, 0); + Require(directory >= 0); + const int kq = kqueue_nid_postfix(); + const auto ident = static_cast(directory); + Require(Apply(kq, Change(ident, EvfiltVnode, EvAdd | EvClear, NoteOpen | NoteClose | NoteCloseWrite | NoteRead)) == 0); + const int lister = open_nid_postfix(path.c_str(), Directory, 0); + Require(lister >= 0 && PolledNotes(kq, ident) == NoteOpen); + char entries[4096]; + Require(getdents_nid_postfix(lister, entries, sizeof(entries)) >= 0 && PolledNotes(kq, ident) == NoteRead); + Require(close_nid_postfix(lister) == 0 && PolledNotes(kq, ident) == NoteClose); + Require(close_nid_postfix(directory) == 0 && close_nid_postfix(kq) == 0); + Require(std::filesystem::remove(path)); +} + #ifndef _WIN32 static void RenameAndDeleteWatchedFile() { const auto path = TemporaryName("moved"); @@ -1498,6 +1600,8 @@ int main() { Errors(); LowWaterMarks(); FileWatch(); + AccessNotes(); + DirectoryAccessNotes(); #ifndef _WIN32 RenameAndDeleteWatchedFile(); VnodeOneshotWatchStops(); diff --git a/docs/dev/debt/libkernel.md b/docs/dev/debt/libkernel.md index f5780d81d7ff..c95eb82709dc 100644 --- a/docs/dev/debt/libkernel.md +++ b/docs/dev/debt/libkernel.md @@ -151,7 +151,8 @@ - [JIT shared memory on macOS](../../../core/libs/prx/libkernel/DirectMemory/Jit.cpp) (libkernel) - the object is an unlinked `mkstemp` file in the temporary directory, as `shm_open` makes its anonymous objects. macOS refuses an executable shared file mapping (`EPERM`), so an executable view is mapped without execute and then given it with `mprotect`. Under Rosetta 2 (Apple M2, macOS 26), code rewritten through one view after it ran from another keeps its old translation until the executable view's protection changes; first writes and a single read-write-execute view, as XPSemu PPSA97358 and VLC PPSA85300 map, are seen. `mmap` of a JIT descriptor is not supported, as file-backed guest `mmap` throws on macOS. - [JIT shared memory](../../../core/libs/prx/libkernel/DirectMemory/Jit.cpp) (libkernel) - `sceKernelJitCreateSharedMemory`, `sceKernelJitCreateAliasOfSharedMemory` and `sceKernelJitMapSharedMemory` take the signatures of [Orbital](https://github.com/AlexAltea/orbital)'s `tools/ida/db_types.json` (name, length, maximum protection, descriptor out; descriptor, maximum protection, descriptor out; descriptor, protection, address in and out), which ps4sdk, ps5-jar-loader and the call sites in RetroArch PPSA99169, XPSemu PPSA97358 and VLC PPSA85300 match; SharpProspero declares the alias as returning the descriptor. The object is a host anonymous file shared by its descriptors (a `memfd` on Linux, a delete-on-close temporary file mapped as an executable section on Windows), the alias is a duplicate descriptor, and every map maps the whole object, so writes through one view show through the others; a non-null address is a hint, as in `mmap` without `MAP_FIXED`. Not measured on the console: a length that is zero or not a multiple of 16 KiB and protection bits other than CPU read, write and execute are `EINVAL`; an alias or a map asking for more than the descriptor's maximum protection (write and execute counting as read) is `EACCES`, as FreeBSD 11's `vm_map_protect` treats a protection past `max_protection`; a descriptor that is not a JIT object is `EBADF`. The name is ignored, the objects do not count against the flexible memory budget, `mprotect` of a view is not limited to the maximum protection, and `mmap` of the descriptors maps the object as a [regular file](../../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp), so its views and the JIT views see each other's writes. On Linux the `memfd` is created without `MFD_EXEC`, which Linux 6.3 added and older kernels reject with `EINVAL`, and relies on the protection of the mapping: the flag only sets the file's execute permission bits, and the direct memory `memfd` is mapped executable the same way; a host with `vm.memfd_noexec` set to 2 refuses the creation and the call throws - [kqueue and kevent](../../../core/libs/prx/libkernel/Equeue/src/Kqueue.cpp) (libkernel) follow FreeBSD 11's [`kern_event.c`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/kern_event.c) (`kqueue_kevent`, `kqueue_register`, `kqueue_scan`, the timer and user filters) over the event queue; nothing here is taken from a console except what the kevent measurements entry lists. The descriptor is a host null device registered as the kqueue: `close` and `sceKernelClose` close the queue and `dup`/`dup2` of it throw, but `read`, `write` and `fstat` act on the null device instead of failing with `EOPNOTSUPP` or reporting `S_IFIFO`. Read and write events are supported on guest sockets only, plus `EVFILT_READ` on the read end and `EVFILT_WRITE` on the write end of a pipe (see the kevent on a pipe entry) and the timer, user and [vnode](../../../core/libs/prx/libkernel/Equeue/src/FileEvent.cpp) filters and a read event on the host stream on descriptor 0, which never triggers, as `select` never reports descriptor 0 readable; PPSA34015 registers descriptor 0 for reading in a new kqueue at start-up and does not check the result; other filters except `EVFILT_AIO`, `EVFILT_LIO`, `EVFILT_SENDFILE` and `EVFILT_PROCDESC` (see the kevent measurements entry), `EV_CLEAR` on a socket or a pipe off Linux (see the kevent EV_CLEAR entry) and every change to an existing timer except `EV_DELETE` and the `EV_ADD` re-adds that the kevent measurements entry describes throw. A `NOTE_NSECONDS` period above one second with a fraction is kept to the nanosecond, where 11.0 converts the fraction with the microsecond macro. `EV_DISABLE`, `EV_DISPATCH` and `EV_FORCEONESHOT` follow kern_event.c: a disabled knote stays registered, stops polling or firing and is not reported, a trigger raised while it is disabled is kept and reported after `EV_ENABLE`, where `knote` would drop it, `EV_DISPATCH` reports once and then disables the knote, and `EV_FORCEONESHOT` is ignored on a new knote while on an existing one it sets `EV_ONESHOT` and fires the knote; a negative `nevents` fails with `EINVAL`. A new user event keeps its `fflags` unmasked and is not triggered by `NOTE_TRIGGER`, because `filt_userattach` reads the already cleared `kn_fflags`. The timer limit `kq_calloutmax` (`ENOMEM`) is not enforced, and closing a kqueue wakes a thread waiting on it in `kevent` with `EBADF`, where `kqueue_drain` makes the close wait for that thread. A level-triggered event is reported once per call and moved behind the other events, as in `kqueue_scan`; the `sceKernel*Equeue` calls keep their own collection loop. `NOTE_LOWAT` on a socket sets the low-water mark as FreeBSD 11's [`filt_soread` and `filt_sowrite`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/kern/uipc_socket.c) do, and a later change of the knote replaces it as `kqueue_register` replaces `kn_sdata`: a read event fires once the buffered bytes reach the mark, or at end of file or on a listening socket. A read mark above 1 is taken on stream sockets only: on a datagram socket Linux's `FIONREAD` reports the next datagram where FreeBSD's `sbavail` counts every queued byte, so it throws. A write event fires once the send buffer's free space reaches the mark, as `filt_sowrite` does with `sbspace`; the host reports that space as `SO_SNDBUF` less `SIOCOUTQ` on Linux and as `SO_SNDBUF` alone elsewhere, so off Linux it does not shrink while data is queued. Marks below 1, which make FreeBSD's read filter always fire, throw -- [EVFILT_VNODE, sceKernelAddFileEvent and sceKernelDeleteFileEvent](../../../core/libs/prx/libkernel/Equeue/src/FileEvent.cpp) (libkernel) watch the host file or directory behind the descriptor and turn host changes into FreeBSD 11 vnode hints, which [`filt_vfsvnode`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L5032) adds whole when they share a bit with the requested `fflags`: a write that grows a file is `NOTE_WRITE | NOTE_EXTEND`, another write `NOTE_WRITE`, a shrinking truncate or an attribute change `NOTE_ATTRIB`, a higher link count `NOTE_LINK`, a lower one or a pending delete `NOTE_DELETE`, a new path `NOTE_RENAME`; in a directory, an entry created, removed or renamed is `NOTE_WRITE`, with `NOTE_LINK` for a subdirectory, and on Linux an entry moved from or to another directory adds `NOTE_EXTEND`; inotify queues the two halves of a rename one after the other, so a watcher woken by the first can read it alone, and a half read without the other is classified only after a `getdents64` on the watched directory, which takes the directory lock that `rename` holds until both halves are queued ([`do_renameat2`](https://github.com/torvalds/linux/blob/v6.8/fs/namei.c#L4975) around `vfs_rename` and its `fsnotify_move`, [`iterate_dir`](https://github.com/torvalds/linux/blob/v6.8/fs/readdir.c#L103)), an ordering taken from the kernel source, not from inotify(7), which promises none; a directory registered with `NOTE_EXTEND` on Windows is accepted, as `vfs_kqfilter` does not check it, but never receives it, because the directory handle cannot tell a move between directories from a removal plus an addition. FreeBSD's hints depend on the filesystem and the console's filesystems are not known: a growing `ftruncate` reports `NOTE_WRITE | NOTE_EXTEND` where `vop_setattr_post` reports `NOTE_ATTRIB`, and on Windows `utimes` on a file reports `NOTE_WRITE`. The three Windows notifications are told apart in the error, which names the `parent`, `entries` or `subdirectories` watch, the path it was given and `GetLastError`, but a `FindFirstChangeNotification` that fails still throws rather than returning an error to the guest: the EVFILT_VNODE attach path is [`vfs_kqfilter`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L4936), which returns `EINVAL`, `ENOMEM` or 0 after `fget` has turned a descriptor that is not open into `EBADF`, and consults no directory permission, so no FreeBSD errno stands for a host that refuses to notify, and what the console does on such a host is not measured. Only the `parent` watch can fail this way in practice: `entries` and `subdirectories` need the `FILE_LIST_DIRECTORY` that opening the watched directory already took. The parent handle produces no hint of its own, as `RunHostWatch` only calls `FindNextChangeNotification` on it, so a later change may leave the watch on its 50 ms poll instead of throwing; that is not done here. Windows uses `FindFirstChangeNotification` on the parent directory (and on a watched directory itself) and compares `GetFileInformationByHandleEx` snapshots at least every 50 ms, because a write through an open handle is reported only when the handle is flushed or closed, so file hints can arrive 50 ms late, and a file deleted while watched, which the POSIX delete of Windows 10 1903 moves into `$Extend\$Deleted` until its last handle closes, reports `NOTE_DELETE` without `NOTE_RENAME` and keeps its handle without a parent directory watch, as that directory cannot be watched; Linux uses inotify on the file and is not run. `NOTE_REVOKE`, `NOTE_OPEN`, `NOTE_CLOSE`, `NOTE_CLOSE_WRITE`, `NOTE_READ`, unknown bits and descriptors other than files, directories, pipes and sockets throw. `sceKernelAddFileEvent(eq, fd, watch, udata)` and `sceKernelDeleteFileEvent(eq, fd)` take the [OpenOrbis](https://github.com/OpenOrbis/OpenOrbis-PS4-Toolchain/blob/0a1aaf9d/include/orbis/libkernel.h#L35) and [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/5dfdb4b0/src/SharpProspero/Interop/Kernel/KernelEqueue.cs#L164) signatures; `watch` is taken as the `fflags` and the event is added with `EV_CLEAR`, neither confirmed on a title (feat(libkernel): implement kevent EV_DISABLE, EV_DISPATCH and EV_FORCEONESHOT) (fix(libkernel): follow kqueue_register for EV_FORCEONESHOT and modify flags) +- [EVFILT_VNODE, sceKernelAddFileEvent and sceKernelDeleteFileEvent](../../../core/libs/prx/libkernel/Equeue/src/FileEvent.cpp) (libkernel) watch the host file or directory behind the descriptor and turn host changes into FreeBSD 11 vnode hints, which [`filt_vfsvnode`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L5032) adds whole when they share a bit with the requested `fflags`: a write that grows a file is `NOTE_WRITE | NOTE_EXTEND`, another write `NOTE_WRITE`, a shrinking truncate or an attribute change `NOTE_ATTRIB`, a higher link count `NOTE_LINK`, a lower one or a pending delete `NOTE_DELETE`, a new path `NOTE_RENAME`; in a directory, an entry created, removed or renamed is `NOTE_WRITE`, with `NOTE_LINK` for a subdirectory, and on Linux an entry moved from or to another directory adds `NOTE_EXTEND`; inotify queues the two halves of a rename one after the other, so a watcher woken by the first can read it alone, and a half read without the other is classified only after a `getdents64` on the watched directory, which takes the directory lock that `rename` holds until both halves are queued ([`do_renameat2`](https://github.com/torvalds/linux/blob/v6.8/fs/namei.c#L4975) around `vfs_rename` and its `fsnotify_move`, [`iterate_dir`](https://github.com/torvalds/linux/blob/v6.8/fs/readdir.c#L103)), an ordering taken from the kernel source, not from inotify(7), which promises none; a directory registered with `NOTE_EXTEND` on Windows is accepted, as `vfs_kqfilter` does not check it, but never receives it, because the directory handle cannot tell a move between directories from a removal plus an addition. FreeBSD's hints depend on the filesystem and the console's filesystems are not known: a growing `ftruncate` reports `NOTE_WRITE | NOTE_EXTEND` where `vop_setattr_post` reports `NOTE_ATTRIB`, and on Windows `utimes` on a file reports `NOTE_WRITE`. The three Windows notifications are told apart in the error, which names the `parent`, `entries` or `subdirectories` watch, the path it was given and `GetLastError`, but a `FindFirstChangeNotification` that fails still throws rather than returning an error to the guest: the EVFILT_VNODE attach path is [`vfs_kqfilter`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L4936), which returns `EINVAL`, `ENOMEM` or 0 after `fget` has turned a descriptor that is not open into `EBADF`, and consults no directory permission, so no FreeBSD errno stands for a host that refuses to notify, and what the console does on such a host is not measured. Only the `parent` watch can fail this way in practice: `entries` and `subdirectories` need the `FILE_LIST_DIRECTORY` that opening the watched directory already took. The parent handle produces no hint of its own, as `RunHostWatch` only calls `FindNextChangeNotification` on it, so a later change may leave the watch on its 50 ms poll instead of throwing; that is not done here. Windows uses `FindFirstChangeNotification` on the parent directory (and on a watched directory itself) and compares `GetFileInformationByHandleEx` snapshots at least every 50 ms, because a write through an open handle is reported only when the handle is flushed or closed, so file hints can arrive 50 ms late, and a file deleted while watched, which the POSIX delete of Windows 10 1903 moves into `$Extend\$Deleted` until its last handle closes, reports `NOTE_DELETE` without `NOTE_RENAME` and keeps its handle without a parent directory watch, as that directory cannot be watched; Linux uses inotify on the file and is not run. `sceKernelAddFileEvent(eq, fd, watch, udata)` and `sceKernelDeleteFileEvent(eq, fd)` take the [OpenOrbis](https://github.com/OpenOrbis/OpenOrbis-PS4-Toolchain/blob/0a1aaf9d/include/orbis/libkernel.h#L35) and [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/5dfdb4b0/src/SharpProspero/Interop/Kernel/KernelEqueue.cs#L164) signatures; `watch` is taken as the `fflags` and the event is added with `EV_CLEAR`, neither confirmed on a title (feat(libkernel): implement kevent EV_DISABLE, EV_DISPATCH and EV_FORCEONESHOT) (fix(libkernel): follow kqueue_register for EV_FORCEONESHOT and modify flags) +- [NOTE_OPEN, NOTE_CLOSE, NOTE_CLOSE_WRITE and NOTE_READ](../../../core/libs/prx/libkernel/Equeue/src/FileEvent.cpp) (libkernel) come only from the guest's own libkernel calls: reads through libc streams (`fopen`, `fread`), which go through the host C runtime, and accesses by other host processes raise none of them. The watched file is matched by the `st_dev` and `st_ino` that `fstat` reports, so two Windows files whose folded `st_ino` agree share these notes. `NOTE_REVOKE` is accepted and never reported, as no descriptor is revoked. JIT shared memory is watched as the host file behind it, where FreeBSD's shared memory fails with `EINVAL` ([`invfo_kqfilter`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/uipc_shm.c#L136)). - [sem_open, sem_close, sem_unlink](../../../core/libs/prx/libkernel/Pthread/Posix/Sem.cpp) (libkernel) keep named semaphores in a table inside the process; FreeBSD 11.4's [`sem_new.c`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libc/gen/sem_new.c#L138-L308) backs each with a file `/tmp/SEMD`. A semaphore lasts until `sem_unlink` and its last `sem_close` but is not shared with other processes, and the mode is ignored (no permission errors, as for a root caller). Whether a title can create files under `/tmp` on the console is unverified. A name with a further `/` throws, as it would resolve below `/tmp`, and so does an initial value above `SEM_VALUE_MAX`, which FreeBSD stores unchecked. - [sem_timedwait](../../../core/libs/prx/libkernel/Pthread/Posix/Sem.cpp) (libkernel) consumes an available count before checking the timeout and waits indefinitely for a null timeout, following FreeBSD 11's `sem_timedwait`. A payload process on a PS5 (firmware 13.60) gave the same results: with a count available, a null timeout, `tv_nsec` of -1 or 1000000000 and a past deadline all returned 0 and took the count; with none, an invalid `tv_nsec` failed with `EINVAL`, and a past deadline or a negative `tv_sec` with `ETIMEDOUT`. One title (PPSA29866) disassembled for this entry has one call site (0x130916), in a wait helper that reads the clock with id 0 into a zeroed 16-byte time structure, adds the milliseconds multiplied by 1,000,000 to the nanoseconds and normalises them below 1e9, so its deadline is never null. It repeats the wait with the same deadline when the error is 4, returns false for any other error and when reading the clock fails, and does not tell a timeout from other errors. This title therefore gives no evidence on null or invalid timeouts. - [kevent measurements](../../../core/libs/prx/libkernel/Equeue/src/Kqueue.cpp) (libkernel) - in payload processes on a PS5 (firmware 12.70), re-adding an existing periodic `EVFILT_TIMER` with `EV_ADD`, `fflags` 0 and a positive period kept the armed expiry and the expirations already counted and applied the new period after that expiry, as FreeBSD 11.0 does, where 11.4's `filt_timertouch` restarts the timer: a 50 ms timer re-added with 10 ms fired first 46 ms after the re-add and then every 10 ms, a 10 ms timer re-added with 100 ms fired first 5 ms after the re-add and then every 100 ms, the 12 expirations counted before a re-add were reported after it, and `EV_ONESHOT` in the re-add left the timer periodic. Here such a re-add does the same; on firmware 13.60 a re-add with a unit in `fflags` (`NOTE_MSECONDS`, `NOTE_NSECONDS`) also applied the new period after the armed expiry, and re-adding a disabled timer returned 0 and left it disabled, as here; re-adding an armed one-shot timer, a period of 0 or less, a period too large to add to the armed expiry, other `fflags` or flags other than `EV_ONESHOT` were not measured and throw here, and the other changes to an existing timer except `EV_DELETE` throw here too. There `EV_ADD` failed with `EPERM` for `EVFILT_AIO`, `EVFILT_LIO` and `EVFILT_SENDFILE` at every ident tried (0, 5, 999, 2^40 and an open pipe) and, at ident 5, also with `EV_CLEAR`, `EV_ONESHOT` or `EV_DISABLE` added, and `EV_DELETE` and `EV_ENABLE` without `EV_ADD` failed with `ENOENT`. `EVFILT_PROCDESC` failed with `EBADF` on a descriptor that is not open and on an ident above `INT_MAX`, and with `EINVAL` on every open descriptor tried: Unix-domain stream and datagram sockets, descriptor 0 (a socket), an `AF_INET` UDP socket, both ends of a pipe, a regular file, a directory, another kqueue and the kqueue itself; `EV_DELETE` on a socket failed with `ENOENT`. Here these four filters answer the same way. `EV_ADD` of `EVFILT_PROCDESC` fails with `EINVAL` on the kinds of descriptor tried, since there are no process descriptors here, and also on shared memory and JIT shared memory, which are host files here: FreeBSD 11.0 gives `shm_open` objects [`invfo_kqfilter`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/kern/uipc_shm.c#L136), which answers `EINVAL`, but neither was measured. It throws on any other kind, such as `/dev/random` and `/dev/urandom`, and on descriptors 0 to 2 that are not sockets or kqueues, whatever they hold: the host's standard streams, a pipe or file that `dup2` put on one of them, or a descriptor opened on a number that was free when libkernel loaded. A change of any of the four without `EV_ADD` fails with `ENOENT`, for `EVFILT_PROCDESC` after the descriptor check, as `kqueue_register` finds no knote. When `EV_ADD` of one of the four fails with `EPERM`, or with `EINVAL` on a descriptor other than the kqueue itself, the error event has `fflags` 0 and the errno in `data`, as FreeBSD 11.0's [`kqueue_register`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/kern/kern_event.c#L1302-L1316) clears `fflags` and `data` before the attach and [`kqueue_kevent`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/kern/kern_event.c#L1005-L1006) then stores the error in `data`; a descriptor that is not open, the kqueue itself and `EV_ENABLE` with `EV_DISABLE` fail before that and keep their `fflags`. That error event was not measured. `EVFILT_PROC` on the process itself with `NOTE_EXIT`, `EVFILT_SIGNAL` for `SIGUSR1` and `EVFILT_FS` at ident 0 were accepted there and still throw here. Also measured there on Unix-domain socketpairs, and still throwing here: a `NOTE_LOWAT` mark of 0 on an empty stream socket gave a read event at once (`data` 0), and so did re-adding that knote with a mark of -1 once the socket was drained; a write mark of 2 on the other end of that stream socketpair gave an event (`data` 8192), and re-adding that knote with 2^30 gave none; a mark of 5 on a datagram socket gave no read event after one 1-byte datagram and a read event (`data` 11) after a second, 10-byte datagram. `EVFILT_READ` on another kqueue reported the number of events pending in it there (1, then 2) and throws here; `EVFILT_WRITE` on a kqueue and a kqueue registered on itself failed with `EINVAL` there, as they do here