diff --git a/core/libs/prx/libkernel/Equeue/Equeue.hpp b/core/libs/prx/libkernel/Equeue/Equeue.hpp index b3163db0cf1b..d6c30871f4ff 100644 --- a/core/libs/prx/libkernel/Equeue/Equeue.hpp +++ b/core/libs/prx/libkernel/Equeue/Equeue.hpp @@ -155,6 +155,9 @@ KernelEqueueEvent EqueueDescriptorEvent(int descriptor, int16_t filter, uint16_t 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); +bool IsFileDataEvent(const KernelEqueueEvent& event); +void SetFileDataNotes(KernelEqueueEvent& event, uint32_t fflags); +int AddFileDataEvent(const KernelEqueueRef& queue, int descriptor, int16_t filter, uint32_t fflags, uint16_t flags, void* udata); 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 f94867ef1267..dfb7dda8eac5 100644 --- a/core/libs/prx/libkernel/Equeue/src/FileEvent.cpp +++ b/core/libs/prx/libkernel/Equeue/src/FileEvent.cpp @@ -2,6 +2,7 @@ #include "prx/libkernel/Equeue/Equeue.hpp" #include "prx/libc/include/HostThread.hpp" #include "prx/libc/include/General.hpp" +#include "prx/libkernel/File/include/ArchivedFile.hpp" #include "prx/libkernel/File/include/File.hpp" #include "prx/libkernel/Socket/include/SocketRuntime.hpp" @@ -58,7 +59,7 @@ constexpr std::uint32_t MAPPED_NOTES = NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | class VnodeWatch { public: - VnodeWatch(const KernelEqueueRef& owner, std::uintptr_t descriptor, std::uint32_t notes) : queue(owner), ident(descriptor), interest(notes) { + VnodeWatch(const KernelEqueueRef& owner, std::uintptr_t descriptor, std::int16_t filter, std::uint32_t notes) : queue(owner), ident(descriptor), filter(filter), interest(notes) { #ifdef _WIN32 stopEvent = ::CreateEventW(nullptr, TRUE, FALSE, nullptr); if (stopEvent == nullptr) { @@ -125,6 +126,7 @@ class VnodeWatch { private: std::weak_ptr queue; std::uintptr_t ident; + std::int16_t filter; std::atomic interest; std::atomic stopped{false}; #ifdef _WIN32 @@ -151,7 +153,7 @@ void VnodeWatch::Deliver(std::uint32_t hint) { return; } VnodeHint message{this, hint}; - owner->TriggerEvent(ident, EVFILT_VNODE, &message); + owner->TriggerEvent(ident, filter, &message); } #ifdef _WIN32 @@ -715,6 +717,45 @@ void StopVnode(KernelEqueue, KernelEqueueEvent* event) { static_cast(event->filter.data)->Stop(); } +constexpr std::uint32_t NOTE_FILE_POLL = 0x0002; +constexpr int GUEST_SEEK_CUR = 1; + +struct FileDataNote { + std::atomic notes; + std::shared_ptr watch; +}; + +bool PollFileRead(KernelEqueueEvent* event) { + const int descriptor = static_cast(event->event.ident); + FileStat status{}; + if (sceKernelFstat(descriptor, &status) != 0) { + return false; + } + const std::int64_t offset = sceKernelLseek(descriptor, 0, GUEST_SEEK_CUR); + if (offset < 0) { + return false; + } + event->event.data = static_cast(status.st_size - offset); + const auto* note = static_cast(event->filter.data); + return (note->notes.load() & NOTE_FILE_POLL) != 0 || event->event.data != 0; +} + +bool PollFileWrite(KernelEqueueEvent* event) { + event->event.data = 0; + return true; +} + +void TriggerFileRead(KernelEqueueEvent* event, void*) { + event->triggered = PollFileRead(event); +} + +void StopFileData(KernelEqueue, KernelEqueueEvent* event) { + const auto* note = static_cast(event->filter.data); + if (note->watch) { + note->watch->Stop(); + } +} + int VnodeDescriptorError(int descriptor) { if (descriptor < 0) { return GUEST_EBADF; @@ -751,7 +792,7 @@ int AddVnodeEvent(const KernelEqueueRef& queue, int descriptor, std::uint32_t ff } std::shared_ptr watch; try { - watch = std::make_shared(queue, static_cast(descriptor), fflags); + watch = std::make_shared(queue, static_cast(descriptor), EVFILT_VNODE, fflags); } catch (...) { CloseHostWatch(host); throw; @@ -787,6 +828,59 @@ int AddVnodeEvent(const KernelEqueueRef& queue, int descriptor, std::uint32_t ff return 0; } +bool IsFileDataEvent(const KernelEqueueEvent& event) { + return event.filter.deleteEventFunc == StopFileData; +} + +void SetFileDataNotes(KernelEqueueEvent& event, std::uint32_t fflags) { + static_cast(event.filter.data)->notes.store(fflags); +} + +int AddFileDataEvent(const KernelEqueueRef& queue, int descriptor, std::int16_t filter, std::uint32_t fflags, std::uint16_t flags, void* udata) { + auto note = std::make_shared(); + note->notes.store(fflags); + KernelEqueueEvent event{}; + event.event.ident = static_cast(descriptor); + event.event.filter = filter; + event.event.flags = flags; + event.event.udata = udata; + event.filter.data = note.get(); + event.filter.owner = note; + event.filter.deleteEventFunc = StopFileData; + if (filter == EVFILT_WRITE) { + event.filter.pollFunc = PollFileWrite; + return queue->AddEvent(event) & 0xffff; + } + event.filter.pollFunc = PollFileRead; + event.filter.triggerFunc = TriggerFileRead; + if (File::IsArchivedFile(descriptor)) { + return queue->AddEvent(event) & 0xffff; + } + HostWatch host; + if (const int error = OpenHostWatch(descriptor, MAPPED_NOTES, host)) { + return error; + } + try { + note->watch = std::make_shared(queue, static_cast(descriptor), EVFILT_READ, MAPPED_NOTES); + } catch (...) { + CloseHostWatch(host); + throw; + } + const int result = queue->AddEvent(event); + bool registered = false; + if (result == EQUEUE_OK) { + queue->EditEvent(event.event.ident, EVFILT_READ, [®istered, ¬e](KernelEqueueEvent& added) { + registered = added.filter.data == note.get(); + }); + } + if (!registered) { + CloseHostWatch(host); + return result == EQUEUE_OK ? 0 : result & 0xffff; + } + std::thread(RunHostWatch, note->watch, std::move(host)).detach(); + return 0; +} + extern "C" { int APS5_VABI sceKernelAddFileEvent(KernelEqueue eq, int fd, int watch, void* udata) { diff --git a/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp b/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp index e9dc7b27fd36..1124e7f30ce5 100644 --- a/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp +++ b/core/libs/prx/libkernel/Equeue/src/Kqueue.cpp @@ -327,6 +327,11 @@ int AddKqueueKnote(const KernelEqueueRef& queue, const KernelEqueueRef& watched, return GuestErrno(queue->AddEvent(event)); } +bool IsRegularFile(int descriptor) { + FileStat status{}; + return !GuestSockets::IsOpen(descriptor) && sceKernelFstat(descriptor, &status) == 0 && (status.st_mode & 0170000) == 0100000; +} + int AddDescriptorKnote(const KernelEqueueRef& queue, KernelEvent& change, std::uint16_t flags) { const int descriptor = static_cast(change.ident); if (const auto watched = FindKqueue(descriptor)) { @@ -343,6 +348,15 @@ int AddDescriptorKnote(const KernelEqueueRef& queue, KernelEvent& change, std::u if (descriptor == 0 && change.filter == EVFILT_READ && File::IsHostStream(descriptor)) { return AddStandardInputKnote(queue, change, flags); } + if (IsRegularFile(descriptor)) { + if ((flags & EV_CLEAR) != 0) { + NotImplemented_nid_no_patch("kevent: EV_CLEAR on a regular file"); + } + const std::uint32_t notes = change.fflags; + change.fflags = 0; + change.data = 0; + return AddFileDataEvent(queue, descriptor, change.filter, notes, flags, change.udata); + } const bool socket = GuestSockets::IsOpen(descriptor); std::int64_t data = 0; bool eof = false; @@ -578,6 +592,8 @@ int ModifyKnote(const KernelEqueueRef& queue, KernelEvent& change, bool setDefau RetriggerAioKnote(event); } else if (change.filter == EVFILT_VNODE) { SetVnodeNotes(event, change.fflags); + } else if (IsFileDataEvent(event)) { + SetFileDataNotes(event, change.fflags); } })); } diff --git a/core/libs/prx/libkernel/Socket/src/Udp.cpp b/core/libs/prx/libkernel/Socket/src/Udp.cpp index 35395a421f59..6b0b9fbd3602 100644 --- a/core/libs/prx/libkernel/Socket/src/Udp.cpp +++ b/core/libs/prx/libkernel/Socket/src/Udp.cpp @@ -689,9 +689,11 @@ bool GuestSockets::WaitAny(const std::vector& interests, std::uint64_t const auto found = sockets.find(interest.descriptor); if (found == sockets.end()) { #ifdef _WIN32 - pipes = true; + const auto handle = reinterpret_cast(::_get_osfhandle(interest.descriptor)); + if (handle != INVALID_HANDLE_VALUE && GetFileType(handle) == FILE_TYPE_PIPE) pipes = true; #else - entries.push_back({interest.descriptor, interest.write ? WriteMask : ReadMask, 0}); + struct stat status{}; + if (::fstat(interest.descriptor, &status) != 0 || (!S_ISREG(status.st_mode) && !S_ISDIR(status.st_mode))) entries.push_back({interest.descriptor, interest.write ? WriteMask : ReadMask, 0}); #endif continue; } diff --git a/core/libs/tests/GuestKqueue.cpp b/core/libs/tests/GuestKqueue.cpp index 88e55ddaa43f..c36bd7783419 100644 --- a/core/libs/tests/GuestKqueue.cpp +++ b/core/libs/tests/GuestKqueue.cpp @@ -75,6 +75,7 @@ static constexpr std::uint32_t NoteFfor = 0x80000000; static constexpr std::uint32_t NoteMseconds = 0x0002; static constexpr std::uint32_t NoteUseconds = 0x0004; static constexpr std::uint32_t NoteNseconds = 0x0008; +static constexpr std::uint32_t NoteFilePoll = 0x0002; static constexpr std::uint32_t NoteDelete = 0x0001; static constexpr std::uint32_t NoteWrite = 0x0002; static constexpr std::uint32_t NoteExtend = 0x0004; @@ -1526,6 +1527,55 @@ static void ProcdescOnFiles() { Require(close_nid_postfix(kq) == 0); } +static void RegularFile() { + const auto path = TemporaryName("data"); + const int file = open_nid_postfix(path.c_str(), ReadWrite | Create, 0644); + Require(file >= 0); + Require(write_nid_postfix(file, "abcd", 4) == 4); + Require(lseek_nid_postfix(file, 1, 0) == 1); + const int kq = kqueue_nid_postfix(); + const auto ident = static_cast(file); + int marker = 0; + KernelEvent events[4]{}; + Require(Apply(kq, Change(ident, EvfiltRead, EvAdd, 0, 0, &marker)) == 0); + Require(Poll(kq, events, 4) == 1); + Require(events[0].ident == ident && events[0].filter == EvfiltRead && events[0].flags == 0 && events[0].fflags == 0); + Require(events[0].data == 3 && events[0].udata == &marker); + char buffer[4]{}; + Require(read_nid_postfix(file, buffer, 3) == 3); + Require(Poll(kq, events, 4) == 0); + Require(lseek_nid_postfix(file, 6, 0) == 6); + Require(Poll(kq, events, 4) == 1 && events[0].data == -2); + Require(lseek_nid_postfix(file, 4, 0) == 4); + Require(Poll(kq, events, 4) == 0); + Require(Apply(kq, Change(ident, EvfiltRead, EvAdd, NoteFilePoll)) == 0); + Require(Poll(kq, events, 4) == 1 && events[0].data == 0 && events[0].udata == nullptr); + Require(Apply(kq, Change(ident, EvfiltRead, EvAdd, NoteLowat, 100, &marker)) == 0); + Require(Poll(kq, events, 4) == 0); + const int appender = open_nid_postfix(path.c_str(), ReadWrite, 0); + Require(appender >= 0 && lseek_nid_postfix(appender, 0, 2) == 4); + const auto start = std::chrono::steady_clock::now(); + std::thread writer([appender] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + Require(write_nid_postfix(appender, "ef", 2) == 2); + }); + const KernelTimespec limit{5, 0}; + Require(kevent_nid_postfix(kq, nullptr, 0, events, 4, &limit) == 1); + const auto waited = std::chrono::steady_clock::now() - start; + writer.join(); + Require(waited >= std::chrono::milliseconds(40) && waited < std::chrono::seconds(4)); + Require(events[0].ident == ident && events[0].data == 2 && events[0].udata == &marker); + Require(ftruncate_nid_postfix(appender, 4) == 0); + Require(Poll(kq, events, 4) == 0); + Require(Apply(kq, Change(ident, EvfiltWrite, EvAdd)) == 0); + Require(Poll(kq, events, 4) == 1 && events[0].filter == EvfiltWrite && events[0].data == 0); + Require(close_nid_postfix(appender) == 0); + Require(close_nid_postfix(file) == 0); + Require(Poll(kq, events, 4) == 0); + Require(unlink_nid_postfix(path.c_str()) == 0); + Require(close_nid_postfix(kq) == 0); +} + static void FileWatch() { const auto path = TemporaryName("file"); const int file = open_nid_postfix(path.c_str(), ReadWrite | Create, 0644); @@ -2119,6 +2169,7 @@ int main(int argc, char** argv) { ClearedKqueue(); ClearedKqueueRechecksTheWatchedCount(); FileWatch(); + RegularFile(); #ifndef _WIN32 RenameAndDeleteWatchedFile(); VnodeOneshotWatchStops(); diff --git a/docs/dev/debt/changes/docs-libkernel-vnode-attrib-console-1160.md b/docs/dev/debt/changes/docs-libkernel-vnode-attrib-console-1160.md index ec85e01d8ab0..d78eb1d4cf66 100644 --- a/docs/dev/debt/changes/docs-libkernel-vnode-attrib-console-1160.md +++ b/docs/dev/debt/changes/docs-libkernel-vnode-attrib-console-1160.md @@ -1,5 +1,5 @@ # libkernel -## change [EVFILT_VNODE, sceKernelAddFileEvent and sceKernelDeleteFileEvent] +## change a shrinking truncate of a watched file can also report `NOTE_WRITE` on Windows - [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. On a PS5 payload process (firmware 11.60) every `ftruncate` (growing, shrinking or to the size the file has), `fchmod` to the mode the file has and `utimes` reported `NOTE_ATTRIB` alone, a `pwrite` that grew the file `NOTE_WRITE | NOTE_EXTEND` and one that did not `NOTE_WRITE`, and a second `EV_ADD` replaced the `fflags` of the first; titles are not measured. Here a growing `ftruncate` reports `NOTE_WRITE | NOTE_EXTEND` where the console 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; a shrinking truncate of a watched file can also report `NOTE_WRITE` on Windows, because NTFS can show the truncate's new `LastWriteTime` before its new size (2 to 12 times per million back-to-back shrinking `SetEndOfFile` calls on a loaded machine, also through a single `NtQueryInformationFile(FileAllInformation)`), and a snapshot taken in between sees a write at the old size; 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) diff --git a/docs/dev/debt/changes/fix-libkernel-select-poll-reuse.md b/docs/dev/debt/changes/fix-libkernel-select-poll-reuse.md index b56d0af5dcb0..79daeca28027 100644 --- a/docs/dev/debt/changes/fix-libkernel-select-poll-reuse.md +++ b/docs/dev/debt/changes/fix-libkernel-select-poll-reuse.md @@ -4,6 +4,6 @@ - [select](../../../core/libs/prx/libkernel/Socket/src/Socket.cpp) (libkernel) - an invalid host descriptor fails with `EBADF`, and mixed host and socket sets are polled in short alternating slices so neither side waits out the full slice alone. A descriptor that stops being a socket, a kqueue or a pipe during the wait fails the call with `EBADF` when it is closed and is selected again with the rest of the timeout when its number was reused, as FreeBSD 11.4's [`kern_select`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c#L1129-L1140) looks every descriptor up again in each pass. A close that has already removed the descriptor from the guest's kqueue, pipe or file tables but not yet closed its host descriptor is seen by that new look-up as a descriptor of unknown kind, which fails with `EBADF` on Windows and is polled through the host on Linux. Wobbly Life (PPSA29413) selects on file descriptors while streaming its bundles -## change A kqueue closed during the wait reports +## change a count above the guest `RLIMIT_NOFILE` hard limit (`rlim_max`) fails with `EINVAL` - [poll](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) waits on guest sockets and pipes, through `WSAPoll` on Windows and `poll` on Linux; the `pollfd` layout and flag values are FreeBSD's. A libSceNet socket joins the same host wait through the native socket libSceNet lends to libkernel. `WSAPoll` rejects `POLLPRI`, so on Windows a socket's `POLLPRI` is asked as `POLLRDBAND` and `POLLIN` as `POLLRDNORM`; Winsock reports urgent data until it is read with `MSG_OOB`, where FreeBSD 11.4's `sopoll_generic` stops once the normal stream passes the mark. Guest `send` and `recv` refuse `MSG_OOB` with `EOPNOTSUPP`, so urgent data can only come from an outside peer and Windows keeps reporting `POLLPRI` after the stream passes the mark. A pipe follows FreeBSD's `pipe_poll`: the read end is readable when data is buffered, either end reports `POLLHUP` once the other end is closed, with the requested `POLLIN` and `POLLRDNORM` bits and without `POLLOUT`, which `pollscan` clears, and the write end is writable when `PIPE_BUF` (512) bytes are free on Windows, or when the host kernel says so on Linux. `POLLOUT` on a read end throws: FreeBSD opens both ends for reading and writing and reports it writable, and host pipes are one-way. Windows pipes cannot be waited on, so while a pipe is polled `poll` checks it with `NtQueryInformationFile` and waits on the sockets in slices of 1 ms. A kqueue is ready for `POLLIN` and `POLLRDNORM` while one of its events is triggered and for no other event, as FreeBSD 11.4's [`kqueue_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/kern_event.c#L1900-L1924) answers. A kqueue cannot be waited on either, so on every host `poll` checks it every millisecond and waits on the other descriptors in slices of 1 ms. A kqueue closed during the wait reports `POLLNVAL`, and one whose number was reused is polled again with the rest of the timeout, as FreeBSD 11.4's [`pollrescan`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c#L1499-L1519) looks the descriptor up again. A socket closed during the wait reports `POLLNVAL`, and when a new socket has taken its number it is polled again with the rest of the timeout, as `pollrescan` does. A close that has already removed the kqueue but not yet closed its host descriptor is seen as a descriptor of unknown kind, which throws. A regular file, a directory or a file read from app0.zar is always ready for `POLLIN`, `POLLRDNORM` and `POLLOUT` and never for `POLLPRI`, `POLLRDBAND` or `POLLWRBAND`, as FreeBSD 11.4's [`vop_stdpoll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/vfs_default.c#L563-L574) and `vop_nopoll` answer every event `poll` accepts; which of the two the console's filesystems use is not known, and they agree on these events. `/dev/random` and `/dev/urandom` follow FreeBSD 11.4's [`randomdev_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/dev/random/randomdev.c#L274-L285) for a seeded device: a request with `POLLIN` or `POLLRDNORM` gets only those bits back, and any other request gets every requested bit. At descriptors 0 to 2, regular files, directories and archived files use vnode readiness too, including host redirection (`< file`, `> log.txt` or `2> log.txt`). A standard descriptor that is not a socket, a kqueue, a random device or a vnode still takes the console fallback: descriptor 0 never reports an event and descriptors 1 and 2 report `POLLOUT`. A closed descriptor reports `POLLNVAL`, and an open descriptor that is neither a guest socket, a libSceNet socket, a pipe, a file, a directory, the random device nor descriptor 0 to 2 (other devices) throws, as do an infinite timeout with no socket, pipe or kqueue to wait on and, on a file, a directory, the random device or the console fallback at descriptors 0 to 2, event bits other than `POLLIN`, `POLLPRI`, `POLLOUT`, `POLLRDNORM`, `POLLRDBAND` and `POLLWRBAND` (the `POLLERR`, `POLLHUP` and `POLLNVAL` bits are ignored in `events`); a socket, a pipe or a kqueue ignores the other bits, and a kqueue `POLLINIGNEOF` too, as FreeBSD 11.4's `sopoll_generic`, `pipe_poll` and `kqueue_poll` test only the bits they know. A closed socket descriptor reports `POLLNVAL`; a count above the guest `RLIMIT_NOFILE` hard limit (`rlim_max`) fails with `EINVAL`, a count of 1024 or less is never refused, a hard limit of infinity (macOS) refuses nothing, and an allocation failure for the descriptor copy fails with `ENOMEM`, which FreeBSD's waiting `malloc` never does. FreeBSD 11.4's [`kern_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c) refuses a count above both `maxfilesperproc` and `FD_SETSIZE` (1024), and the console's `maxfilesperproc` is unknown, so the hard limit stands in for it: its initial value depends on the host, and lowering the guest hard limit with `setrlimit` lowers the bound diff --git a/docs/dev/debt/changes/fix-merge-libkernel-event-duplicates.md b/docs/dev/debt/changes/fix-merge-libkernel-event-duplicates.md new file mode 100644 index 000000000000..9ed222a574b8 --- /dev/null +++ b/docs/dev/debt/changes/fix-merge-libkernel-event-duplicates.md @@ -0,0 +1,5 @@ +# libkernel + +## remove cannot be watched; Linux uses inotify on the file + +## remove the console's limit on the descriptor count is unknown and not checked diff --git a/docs/dev/debt/libkernel.md b/docs/dev/debt/libkernel.md index e831063d1e68..037533bcca10 100644 --- a/docs/dev/debt/libkernel.md +++ b/docs/dev/debt/libkernel.md @@ -180,6 +180,8 @@ - [sceKernelMprotect protection bits](../../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - bits outside `0x3F7` are dropped instead of refused, in the POSIX `mprotect` as well (FreeBSD 11.4 masks the argument, `sys/vm/vm_mmap.c:613`; the console was measured only through `sceKernelMprotect`), as a PS5 (firmware 13.60) drops them: Onimusha: Way of the Sword (PPSA27836 01.000.001) maps direct memory with `0xf2` and then protects it with `0xfffffff2`, which the console reports as `0xf3` and then `0x3f3`. In a payload process the console also drops the CPU execute bit (`0x4`) of flexible, direct and JIT memory, and POSIX `mprotect` with write and execute reports write only (`0x2`). A title process may keep execute, so it is kept here. The map calls and `sceKernelMtypeprotect` refuse undefined bits on the console with `EINVAL` (`0x80020016`); here the five flexible and direct map calls do too, before mapping, as does `sceKernelMtypeprotect` (`0x8`, `0x400`, `0x800`, `0x3ff`, `0xffffff00`, `0xffffff7f`, `0xffffff80`, `0xfffffff2` and `0xffffffff` measured, runs `2026-11-12T172520Z_F_libkernel_mtypeprotect` and `2026-11-12T192537Z_F_libkernel_mtypeprotect`), but the batch map calls throw, and `sceKernelMtypeprotect` throws for `0x80000000`, which the console accepted - [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 and regular files (see the kevent on a regular file entry), 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 on a regular file, 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) - [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, signal and [vnode](../../../core/libs/prx/libkernel/Equeue/src/FileEvent.cpp) filters, `EVFILT_FS`, which takes `EV_CLEAR` as FreeBSD 11.4's [`filt_fsattach`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/vfs_subr.c#L4952-L4958) sets it and never fires, as nothing here signals a filesystem event, 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`, `EVFILT_PROCDESC` and `EVFILT_PROC` on the process itself with `NOTE_EXIT` or no notes (see the kevent measurements entry), `EV_CLEAR` on a socket or a pipe on Windows (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. The host must also report the socket writable (`POLLOUT`) before the free space is compared, so a socket the host does not yet call writable stays silent even when its free space reaches the mark. A write mark above 1 is taken on stream sockets only, as for reads, and an `EV_CLEAR` write event with a mark above 1 on a Linux TCP socket throws: Linux wakes `EPOLLOUT` waiters only after a send or poll found the socket not writable ([`tcp_check_space`](https://github.com/torvalds/linux/blob/v6.8/net/ipv4/tcp_input.c#L5639)), so the edge knote would wait forever once it found the free space below the mark, where FreeBSD 11's [`tcp_input.c`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/netinet/tcp_input.c#L2836-L2844) calls `sowwakeup` on every ACK that frees send space. A read mark below 1 is always met, as in `filt_soread`, except on a listening socket, where `filt_solisten` ignores marks; a write mark below 1 throws. - [sceKernelCreateEqueue and sceKernelGetKqueueFromEqueue](../../../core/libs/prx/libkernel/Equeue/Equeue.cpp) (libkernel) - an equeue is a kqueue descriptor, as in firmware 13.42 `libkernel_sys.sprx`, which creates a kqueue and a named object and returns `(id << 32) | descriptor`, waits with `kevent` on the descriptor and deletes the named object before closing it (disassembly, not run on a console). The id here is a counter, not a named object. `kevent` on an equeue's descriptor collects events with the `sceKernel*Equeue` loop and `sceKernelWaitEqueue` on a descriptor from `kqueue` with the kevent loop (see the kqueue and kevent entry), where the console has one queue; which loop the console follows for the other caller is unknown. A null `eq` returns `EINVAL`, where that module writes through it. A PS5 payload process (firmware 11.60, 2026-11-07) refused a name of 32 or more characters with `ENAMETOOLONG` and left the output unset, and accepted names of 0, 9 and 31 characters, as here; a title process was not measured - [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; a shrinking truncate of a watched file can also report `NOTE_WRITE` on Windows, because NTFS can show the truncate's new `LastWriteTime` before its new size (2 to 12 times per million back-to-back shrinking `SetEndOfFile` calls on a loaded machine, also through a single `NtQueryInformationFile(FileAllInformation)`), and a snapshot taken in between sees a write at the old size; 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) @@ -310,6 +312,15 @@ - [write to a pipe without a reader](../../../core/libs/prx/libkernel/File/src/Open.cpp) (libkernel) - `write`, `sceKernelWrite`, `writev` and `sceKernelWritev` fail with `EPIPE` once the read end is closed, as FreeBSD 11.4's [`pipe_write`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_pipe.c#L1062-L1069) does; on Windows the host reports `ERROR_NO_DATA`, which the C runtime would turn into `EINVAL`. [`dofilewrite`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c#L597-L601) also sends `SIGPIPE` to the writing thread: nothing is raised on Windows, and on Linux the host raises its own `SIGPIPE`, which is guest signal 13 as above. Not measured on a console - [Socket descriptor numbers](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel, libSceNet) - `socket`, `accept`, `socketpair`, `dup`, `sceNetSocket` and `sceNetAccept` take the lowest free number of the host descriptor table that files use, as FreeBSD 11.4 `fdalloc` takes the lowest free entry of the one process table (`kern_descrip.c`), so every number stays below `FD_SETSIZE` (1024) while fewer than 1024 descriptors are open. The number holds a zero-access `NUL` handle on Windows and a duplicate of the host socket on Linux, and the socket tables map it to the socket. The host table also holds the runtime's own files, so the numbers differ from the console's; the first number `socket` and `sceNetSocket` return on a console and its `getdtablesize` are not measured. Paths that bypass the socket tables see the placeholder: libc `fdopen` on a socket opens it, and libkernel `sceKernelClose` of a libSceNet socket releases the number but leaves the libSceNet socket open. Palworld (PPSA23126), The Mound (PPSA26223) and Dying Light 2 (PPSA02262) set socket bits in a 1024-bit `fd_set` - [fstat on a guest socket](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) fills the fields FreeBSD 11's soo_stat and pru_sense_null fill and zeroes the rest: S_IFSOCK, the read bits while the receive side is open or data is queued, the write bits while the send side is open, st_size and st_blksize. Only this process's shutdown closes a side here; a peer's shutdown, close or reset does not clear the bits as FreeBSD's socantrcvmore and socantsendmore do. st_size is the host's FIONREAD, which for a Linux datagram socket is the size of the next datagram where FreeBSD counts every queued byte, and st_blksize is the host's SO_SNDBUF, which Linux reports as twice the size that was set. A socketpair end's st_ino comes from a counter this process starts at 1, where FreeBSD's uipc_sense uses one counter for every local socket on the system, so the numbers differ from the console's +- [poll](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) waits on guest sockets and pipes, through `WSAPoll` on Windows and `poll` on Linux; the `pollfd` layout and flag values are FreeBSD's. A libSceNet socket joins the same host wait through the native socket libSceNet lends to libkernel. `WSAPoll` rejects `POLLPRI`, so on Windows a socket's `POLLPRI` is asked as `POLLRDBAND` and `POLLIN` as `POLLRDNORM`; Winsock reports urgent data until it is read with `MSG_OOB`, where FreeBSD 11.4's `sopoll_generic` stops once the normal stream passes the mark. Guest `send` and `recv` refuse `MSG_OOB` with `EOPNOTSUPP`, so urgent data can only come from an outside peer and Windows keeps reporting `POLLPRI` after the stream passes the mark. A pipe follows FreeBSD's `pipe_poll`: the read end is readable when data is buffered, either end reports `POLLHUP` once the other end is closed, with the requested `POLLIN` and `POLLRDNORM` bits and without `POLLOUT`, which `pollscan` clears, and the write end is writable when `PIPE_BUF` (512) bytes are free on Windows, or when the host kernel says so on Linux. `POLLOUT` on a read end throws: FreeBSD opens both ends for reading and writing and reports it writable, and host pipes are one-way. Windows pipes cannot be waited on, so while a pipe is polled `poll` checks it with `NtQueryInformationFile` and waits on the sockets in slices of 1 ms. A kqueue is ready for `POLLIN` and `POLLRDNORM` while one of its events is triggered and for no other event, as FreeBSD 11.4's [`kqueue_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/kern_event.c#L1900-L1924) answers. A kqueue cannot be waited on either, so on every host `poll` checks it every millisecond and waits on the other descriptors in slices of 1 ms. A kqueue closed during the wait reports `POLLNVAL`, and one whose number was reused is polled again with the rest of the timeout, as FreeBSD 11.4's [`pollrescan`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c#L1499-L1519) looks the descriptor up again. A close that has already removed the kqueue but not yet closed its host descriptor is seen as a descriptor of unknown kind, which throws. A regular file, a directory or a file read from app0.zar is always ready for `POLLIN`, `POLLRDNORM` and `POLLOUT` and never for `POLLPRI`, `POLLRDBAND` or `POLLWRBAND`, as FreeBSD 11.4's [`vop_stdpoll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/vfs_default.c#L563-L574) and `vop_nopoll` answer every event `poll` accepts; which of the two the console's filesystems use is not known, and they agree on these events. `/dev/random` and `/dev/urandom` follow FreeBSD 11.4's [`randomdev_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/dev/random/randomdev.c#L274-L285) for a seeded device: a request with `POLLIN` or `POLLRDNORM` gets only those bits back, and any other request gets every requested bit. At descriptors 0 to 2, regular files, directories and archived files use vnode readiness too, including host redirection (`< file`, `> log.txt` or `2> log.txt`). A standard descriptor that is not a socket, a kqueue, a random device or a vnode still takes the console fallback: descriptor 0 never reports an event and descriptors 1 and 2 report `POLLOUT`. A closed descriptor reports `POLLNVAL`, and an open descriptor that is neither a guest socket, a libSceNet socket, a pipe, a file, a directory, the random device nor descriptor 0 to 2 (other devices) throws, as do event bits other than `POLLIN`, `POLLPRI`, `POLLOUT`, `POLLRDNORM`, `POLLRDBAND` and `POLLWRBAND` (the `POLLERR`, `POLLHUP` and `POLLNVAL` bits are ignored in `events`), an infinite timeout with no socket, pipe or kqueue to wait on. A closed socket descriptor reports `POLLNVAL`; the console's limit on the descriptor count is unknown and not checked +- [poll](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) on Windows reports a guest stream socket whose peer closed as readable and adds `POLLHUP` only once the socket has shut its own sending side, as FreeBSD 11.4's [`sopoll_generic`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/uipc_socket.c#L3080-L3086) does; `WSAPoll` reports `POLLHUP` alone in both cases. A reset or refused connection (`POLLHUP` with `POLLERR`) keeps `WSAPoll`'s flags, a libSceNet socket keeps them too, and a call that asks for no event still returns early on the peer's close with nothing reported. Not measured on a console. +- [poll on a stream socket](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) - on Linux a socket that reports `POLLHUP` reports it without `POLLOUT`, as FreeBSD 11.4's `pollscan` clears `POLLOUT` whenever it reports `POLLHUP`; Linux, like FreeBSD, reports `POLLHUP` only once both of the socket's directions are shut. Windows keeps the flags `WSAPoll` reports. Not measured on a console +- [kevent EV_CLEAR on a socket or a pipe](../../../core/libs/prx/libkernel/Equeue/src/EdgeWatch.cpp) (libkernel) - FreeBSD 11 activates an `EV_CLEAR` knote when `kqueue_register` finds it ready, which every `EV_ADD` or `EV_ENABLE` of an enabled knote does again, and on each `KNOTE` the socket or pipe raises (`sorwakeup`, `sowwakeup`, `pipeselwakeup`); [`kqueue_scan`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/kern_event.c) checks the filter again before reporting, drops a knote that is no longer ready and deactivates a reported one until the next activation. On Linux each such knote registers the host socket or pipe with its own epoll instance in edge-triggered mode (`EPOLLIN | EPOLLRDHUP` for `EVFILT_READ`, `EPOLLOUT` for `EVFILT_WRITE`), and a wakeup of the host descriptor with that mask stands for a `KNOTE`: the knote is then checked with the same readiness test as a level-triggered one, `NOTE_LOWAT` mark included, and a wait blocks on the epoll descriptor instead of the socket, so a socket that stays readable does not wake it. The host's wakeups are not FreeBSD's: FreeBSD raises `sowwakeup` whenever send buffer space is freed, while Linux TCP wakes `EPOLLOUT` waiters only once the socket is writable again after a write found it full (`SOCK_NOSPACE`, [`tcp_check_space`](https://github.com/torvalds/linux/blob/v6.8/net/ipv4/tcp_input.c#L5639)), so a TCP writer that never fills its buffer sees fewer `EVFILT_WRITE` events than on FreeBSD; a host stack may also coalesce data wakeups, so the number of times a busy socket fires can differ. Windows and macOS throw, as the host there has no edge-triggered wait over these descriptors that is wired up; `EV_CLEAR` on the timer, user and vnode filters does not use this and works everywhere. +- [kevent on a pipe](../../../core/libs/prx/libkernel/Equeue/src/Kqueue.cpp) (libkernel) - host pipes are one-way, where FreeBSD's [`kern_pipe`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/kern/sys_pipe.c#L422) opens both ends for reading and writing, so `EVFILT_READ` on the write end and `EVFILT_WRITE` on the read end throw; on macOS `EVFILT_WRITE` on a pipe throws, as the host has no call for a pipe's capacity. `EVFILT_WRITE` reports the free space of the host buffer, not of FreeBSD's 16 KiB one, and on Linux fires when the host says the pipe is writable rather than at `PIPE_BUF` (512) free bytes. Windows pipes cannot be waited on, so a kqueue waiting on one checks it every 1 ms. Otherwise [`filt_piperead`](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/kern/sys_pipe.c#L1787-L1828) and `filt_pipewrite` are followed: `EV_EOF` once the other end closes, `EPIPE` for a write event added after the read end closed, and `NOTE_LOWAT` ignored. On Windows `fcntl` cannot make a pipe write end non-blocking, so the full-pipe and drain case of `EVFILT_WRITE` is tested on Linux only and the `NtQueryInformationFile` write quota is checked there only for the free space, `EV_EOF` and `EPIPE`. +- [kevent on a regular file](../../../core/libs/prx/libkernel/Equeue/src/FileEvent.cpp) (libkernel) - `EVFILT_READ` and `EVFILT_WRITE` on a regular file follow FreeBSD 11's [`vfs_kqfilter`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L4936-L4967), [`filt_vfsread`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L4983-L5009) and [`filt_vfswrite`](https://github.com/freebsd/freebsd-src/blob/34bd34750187bae02a0086402c78c031c59dd8b3/sys/kern/vfs_subr.c#L5012-L5029), assuming the console's file systems keep the default `VOP_KQFILTER`; nothing is measured on a console. A read event's `data` is the file size minus the descriptor's offset, negative past the end, and it is reported when that is not zero or `NOTE_FILE_POLL` is set; `NOTE_LOWAT` and the event's `data` are ignored, and re-adding the event replaces its `fflags` as `kqueue_register` does. A write event is always reported with `data` 0. Both are re-evaluated at every scan, where FreeBSD re-activates a knote only when the vnode posts a note: after reading to the end, a seek back is reported here without a write, and on FreeBSD only after the next write, truncation or attribute change. A waiting `kevent` is woken by the host watch `EVFILT_VNODE` uses (see its entry), so it sees writes from other descriptors and processes with that watch's latency; files served from `app0.zar` never change and have no watch. `EV_CLEAR` on a regular file throws, as on sockets and pipes. Directories and other descriptors that are neither sockets, pipes nor regular files still throw: a directory's `va_size` is not modelled. `sceKernelAddReadEvent` and `sceKernelAddWriteEvent` still refuse non-socket descriptors. +- [kevent on a kqueue](../../../core/libs/prx/libkernel/Equeue/src/Kqueue.cpp) (libkernel) - `EVFILT_READ` on a kqueue counts the watched queue's enabled notes that are ready when it is evaluated, where [`filt_kqueue`](https://github.com/freebsd/freebsd-src/blob/5ed7eb0d97ba4436218e810f61bd059acba984c2/sys/kern/kern_event.c#L363-L370) reports `kq_count`, the queued notes: a queued note counts until that kqueue is scanned, even once disabled or no longer ready (a socket or pipe read empty, a user note cleared, a watched kqueue drained), so FreeBSD can report it readable where this reports nothing. A queued `EV_ONESHOT` note is reported there with its last count and deleted; here it is evaluated again and, if the watched queue is empty by then, neither reported nor deleted. `EV_CLEAR` throws, as FreeBSD re-arms it only when the watched kqueue queues a note. A cycle of watches throws; a note on the queue itself is `EINVAL`. Not measured on a console +- [Socket error numbers](../../../core/libs/prx/libkernel/Socket/include/SocketError.hpp) (libkernel) - a host socket error becomes the FreeBSD 11 `errno.h` number of the same name; the numbers are not checked on the console. Winsock `WSAESHUTDOWN` becomes `EPIPE`, as a send after `shutdown` does on FreeBSD, and a host error with no FreeBSD socket counterpart becomes `EIO`. On Windows a refused nonblocking `connect` is never reported (`SO_ERROR` is unsupported), so a repeated one keeps reporting `EALREADY` where FreeBSD reports `ECONNREFUSED`. +- [getsockopt, setsockopt](../../../core/libs/prx/libkernel/Socket/src/SocketOptions.cpp) (libkernel) - a guest socket has the SOL_SOCKET level, eight `IPPROTO_TCP` options, `IPV6_V6ONLY` and ten `IPPROTO_IP` options. `SO_ACCEPTFILTER` (0x1000) fails with `EINVAL` for a set and a get on a socket that is not listening, as a payload process on a PS5 (firmware 13.60) did and as FreeBSD 11.4's `do_setopt_accept_filter` and `do_getopt_accept_filter` do; on a listening socket both throw, as accept filters are not modelled; the other options of these levels fail with `ENOPROTOOPT` and were not all measured. `SO_KEEPALIVE`, `SO_DONTROUTE`, `SO_BROADCAST`, `SO_OOBINLINE` and `SO_LINGER` act on the host socket, and a boolean one reads back as its own bit, as there. Winsock does not clear a pending error when `SO_ERROR` reads it, so on Windows a pending error is reported once and again only after a new `connect`; a second failure with the same code without a `connect` in between is hidden - [poll](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) waits on guest sockets and pipes, through `WSAPoll` on Windows and `poll` on Linux; the `pollfd` layout and flag values are FreeBSD's. A libSceNet socket joins the same host wait through the native socket libSceNet lends to libkernel. `WSAPoll` rejects `POLLPRI`, so on Windows a socket's `POLLPRI` is asked as `POLLRDBAND` and `POLLIN` as `POLLRDNORM`; Winsock reports urgent data until it is read with `MSG_OOB`, where FreeBSD 11.4's `sopoll_generic` stops once the normal stream passes the mark. Guest `send` and `recv` refuse `MSG_OOB` with `EOPNOTSUPP`, so urgent data can only come from an outside peer and Windows keeps reporting `POLLPRI` after the stream passes the mark. A pipe follows FreeBSD's `pipe_poll`: the read end is readable when data is buffered, either end reports `POLLHUP` once the other end is closed, with the requested `POLLIN` and `POLLRDNORM` bits and without `POLLOUT`, which `pollscan` clears, and the write end is writable when `PIPE_BUF` (512) bytes are free on Windows, or when the host kernel says so on Linux. `POLLOUT` on a read end throws: FreeBSD opens both ends for reading and writing and reports it writable, and host pipes are one-way. Windows pipes cannot be waited on, so while a pipe is polled `poll` checks it with `NtQueryInformationFile` and waits on the sockets in slices of 1 ms. A kqueue is ready for `POLLIN` and `POLLRDNORM` while one of its events is triggered and for no other event, as FreeBSD 11.4's [`kqueue_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/kern_event.c#L1900-L1924) answers. A kqueue cannot be waited on either, so on every host `poll` checks it every millisecond and waits on the other descriptors in slices of 1 ms. A kqueue closed during the wait reports `POLLNVAL`, and one whose number was reused is polled again with the rest of the timeout, as FreeBSD 11.4's [`pollrescan`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c#L1499-L1519) looks the descriptor up again. A close that has already removed the kqueue but not yet closed its host descriptor is seen as a descriptor of unknown kind, which throws. A regular file, a directory or a file read from app0.zar is always ready for `POLLIN`, `POLLRDNORM` and `POLLOUT` and never for `POLLPRI`, `POLLRDBAND` or `POLLWRBAND`, as FreeBSD 11.4's [`vop_stdpoll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/vfs_default.c#L563-L574) and `vop_nopoll` answer every event `poll` accepts; which of the two the console's filesystems use is not known, and they agree on these events. `/dev/random` and `/dev/urandom` follow FreeBSD 11.4's [`randomdev_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/dev/random/randomdev.c#L274-L285) for a seeded device: a request with `POLLIN` or `POLLRDNORM` gets only those bits back, and any other request gets every requested bit. At descriptors 0 to 2, regular files, directories and archived files use vnode readiness too, including host redirection (`< file`, `> log.txt` or `2> log.txt`). A standard descriptor that is not a socket, a kqueue, a random device or a vnode still takes the console fallback: descriptor 0 never reports an event and descriptors 1 and 2 report `POLLOUT`. A closed descriptor reports `POLLNVAL`, and an open descriptor that is neither a guest socket, a libSceNet socket, a pipe, a file, a directory, the random device nor descriptor 0 to 2 (other devices) throws, as do event bits other than `POLLIN`, `POLLPRI`, `POLLOUT`, `POLLRDNORM`, `POLLRDBAND` and `POLLWRBAND` (the `POLLERR`, `POLLHUP` and `POLLNVAL` bits are ignored in `events`), an infinite timeout with no socket, pipe or kqueue to wait on. A closed socket descriptor reports `POLLNVAL`; a count above the guest `RLIMIT_NOFILE` hard limit (`rlim_max`) fails with `EINVAL`, a count of 1024 or less is never refused, a hard limit of infinity (macOS) refuses nothing, and an allocation failure for the descriptor copy fails with `ENOMEM`, which FreeBSD's waiting `malloc` never does. FreeBSD 11.4's [`kern_poll`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c) refuses a count above both `maxfilesperproc` and `FD_SETSIZE` (1024), and the console's `maxfilesperproc` is unknown, so the hard limit stands in for it: its initial value depends on the host, and lowering the guest hard limit with `setrlimit` lowers the bound - [poll](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) on Windows - a libSceNet socket keeps `WSAPoll`'s flags, and a call that asks for no event still returns early on the peer's close with nothing reported. A guest stream socket follows what a payload process on PS5 firmware 13.60 got, as FreeBSD 11.4's [`sopoll_generic`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/uipc_socket.c#L3080-L3086) does: after the peer closes or shuts its sending side it is readable and, while it can still send, writable, without `POLLHUP`; `POLLHUP` comes once its own sending side is shut too; a reset gives `POLLHUP` and the requested read bits, never `POLLERR` or `POLLOUT` (0x10, 0x11, 0x11 for no event, `POLLIN` and `POLLIN|POLLOUT`), and the first `recv` then fails with `ECONNRESET`. `WSAPoll` reports `POLLHUP` alone, or with `POLLERR` on a reset, and is translated to those flags. - [poll on a stream socket](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) - on Linux a socket that reports `POLLHUP` reports it without `POLLOUT`, as FreeBSD 11.4's `pollscan` clears `POLLOUT` whenever it reports `POLLHUP`; Linux, like FreeBSD, reports `POLLHUP` only once both of the socket's directions are shut. Windows keeps the flags `WSAPoll` reports, except for a socket the guest shut in both directions, which reports `POLLHUP` without `POLLOUT`; `POLLHUP` is added when `WSAPoll` leaves it out while the connection is intact. FreeBSD's [`pollrescan`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_generic.c#L1474-L1522), which checks the descriptors again after a wait, does not clear `POLLOUT`, so a socket that hangs up while the call waits keeps `POLLOUT` beside `POLLHUP` there, and loses it here wherever `POLLOUT` is cleared as above. Not measured on a console