Merge pull request #15849 from Nciibi/fix/libkernel-apr-guest-memory

fix(libkernel): check APR guest memory before the submit and command paths
This commit is contained in:
Dean authored and GitHub committed 2026-11-08 10:33:59 +13:00
commit 302864d48c
3 files changed
+64 -6

No files matched your search

+49 -6
View File
@@ -28,6 +28,7 @@
#include <fstream>
#include <map>
#include <mutex>
#include <new>
#include <set>
#include <stdexcept>
#include <string>
@@ -188,9 +189,28 @@ void _readFile(const Apr::ReadFileCommand& command) {
if (read != command.size) std::memset(reinterpret_cast<char*>(command.destination) + read, 0, static_cast<std::size_t>(command.size - read));
}
std::string _addressText(std::uint64_t address) {
char text[24];
std::snprintf(text, sizeof(text), "0x%llx", static_cast<unsigned long long>(address));
return text;
}
void _storeGuestAddress(std::uint64_t address, std::uint64_t value) {
if (!GuestCopyOut_nid_no_patch(reinterpret_cast<void*>(address), &value, sizeof(value)))
throw std::runtime_error("APR: the write address " + _addressText(address) + " is not writable guest memory");
std::atomic_ref<std::uint64_t>(*reinterpret_cast<std::uint64_t*>(address)).store(value, std::memory_order_release);
}
std::uint64_t _loadGuestAddress(std::uint64_t address) {
std::uint64_t value = 0;
if (!GuestCopyIn_nid_no_patch(&value, reinterpret_cast<const void*>(address), sizeof(value)))
throw std::runtime_error("APR: the wait address " + _addressText(address) + " is not readable guest memory");
return value;
}
void _writeAddress(const Apr::WriteAddressCommand& command) {
if (command.flags != 0) throw std::runtime_error("APR: WriteAddress flags " + std::to_string(command.flags) + " not implemented");
std::atomic_ref<std::uint64_t>(*reinterpret_cast<std::uint64_t*>(command.address)).store(command.value, std::memory_order_release);
_storeGuestAddress(command.address, command.value);
}
std::array<std::atomic<std::uint32_t>, 256> g_counters{};
@@ -651,6 +671,7 @@ std::optional<Deferred> _execute(const Apr::CommandBufferObject& buffer, std::ui
const auto command = _read<Apr::WaitCommand>(buffer, cursor);
const bool counter = header.opcode == Apr::Opcode::WaitOnCounter;
const std::uint32_t unused = counter ? 64u - _counterField(command.access).bits : 0u;
if (!counter) static_cast<void>(_loadGuestAddress(command.address));
const auto current = [&]() -> std::uint64_t {
if (counter) return _readCounter(command.counter, command.access);
return std::atomic_ref<std::uint64_t>(*reinterpret_cast<std::uint64_t*>(command.address)).load(std::memory_order_acquire);
@@ -668,7 +689,7 @@ std::optional<Deferred> _execute(const Apr::CommandBufferObject& buffer, std::ui
}
case Apr::Opcode::WriteAddressFromTimeCounter: {
const auto command = _read<Apr::WriteAddressFromCounterCommand>(buffer, cursor);
std::atomic_ref<std::uint64_t>(*reinterpret_cast<std::uint64_t*>(command.address)).store(sceKernelGetProcessTimeCounter(), std::memory_order_release);
_storeGuestAddress(command.address, sceKernelGetProcessTimeCounter());
break;
}
case Apr::Opcode::WriteAddressFromCounter:
@@ -676,7 +697,7 @@ std::optional<Deferred> _execute(const Apr::CommandBufferObject& buffer, std::ui
const auto command = _read<Apr::WriteAddressFromCounterCommand>(buffer, cursor);
std::uint64_t value = _counter(command.counter0);
if (header.opcode == Apr::Opcode::WriteAddressFromCounterPair) value |= static_cast<std::uint64_t>(_counter(command.counter1)) << 32u;
std::atomic_ref<std::uint64_t>(*reinterpret_cast<std::uint64_t*>(command.address)).store(value, std::memory_order_release);
_storeGuestAddress(command.address, value);
break;
}
default:
@@ -901,16 +922,37 @@ int APS5_VABI sceKernelAprGetFileStat(uint32_t id, FileStat* stat) {
return 0;
}
std::optional<std::vector<std::uint8_t>> _guestCommands(const Apr::CommandBufferObject& object) {
if (object.offset > object.size) return std::nullopt;
std::vector<std::uint8_t> commands;
try {
commands.resize(object.offset);
} catch (const std::bad_alloc&) {
return std::nullopt;
}
if (object.offset != 0 && !GuestCopyIn_nid_no_patch(commands.data(), object.base, object.offset)) return std::nullopt;
return commands;
}
int APS5_VABI sceKernelAprSubmitCommandBuffer(const Apr::CommandBufferObject* buffer, uint32_t priority) {
if (!buffer) return _fail(GUEST_EINVAL);
_submit(buffer->base, buffer->offset, false, priority);
Apr::CommandBufferObject object{};
if (!GuestCopyIn_nid_no_patch(&object, buffer, sizeof(object))) return _fail(GUEST_EFAULT);
const auto commands = _guestCommands(object);
if (!commands) return _fail(GUEST_EFAULT);
_submit(commands->data(), static_cast<std::uint32_t>(commands->size()), false, priority);
return 0;
}
int APS5_VABI sceKernelAprSubmitCommandBufferAndGetId(const Apr::CommandBufferObject* buffer, uint32_t priority, uint32_t* id) {
if (!id) return _fail(GUEST_EINVAL);
if (!buffer) return _fail(GUEST_EINVAL);
*id = _submit(buffer->base, buffer->offset, false, priority);
Apr::CommandBufferObject object{};
if (!GuestCopyIn_nid_no_patch(&object, buffer, sizeof(object))) return _fail(GUEST_EFAULT);
const auto commands = _guestCommands(object);
if (!commands) return _fail(GUEST_EFAULT);
const std::uint32_t submitted = _submit(commands->data(), static_cast<std::uint32_t>(commands->size()), false, priority);
if (!GuestCopyOut_nid_no_patch(id, &submitted, sizeof(submitted))) return _fail(GUEST_EFAULT);
return 0;
}
@@ -918,7 +960,8 @@ int APS5_VABI sceKernelAprSubmitCommandBufferAndGetResult(const Apr::CommandBuff
if (!result) return _fail(GUEST_EINVAL);
const int submitted = sceKernelAprSubmitCommandBufferAndGetId(buffer, priority, id);
if (submitted != 0) return submitted;
*result = 0;
const std::uint32_t succeeded = 0;
if (!GuestCopyOut_nid_no_patch(result, &succeeded, sizeof(succeeded))) return _fail(GUEST_EFAULT);
return 0;
}
+14
View File
@@ -232,6 +232,20 @@ void TestQueries() {
Require(sceKernelAprSubmitCommandBufferAndGetResult(nullptr, 0, &result, &first) == -1 && *__error_nid_postfix() == GuestEinval, "APR accepted a null command buffer");
Require(sceKernelAprSubmitCommandBufferAndGetResult(&buffer, 0, &result, nullptr) == -1 && *__error_nid_postfix() == GuestEinval, "APR accepted a null submission id");
Require(result == 0xFFFFFFFFu && first == 0, "a rejected APR submission wrote its result or id");
*__error_nid_postfix() = 0;
Require(sceKernelAprSubmitCommandBufferAndGetId(reinterpret_cast<const Apr::CommandBufferObject*>(0x10), 0, &first) == -1 && *__error_nid_postfix() == GuestEfault, "APR accepted an unreadable command buffer object");
Apr::CommandBufferObject unreadable{Apr::BufferType::Generic, 0, sizeof(memory), 1, sizeof(memory), nullptr};
*__error_nid_postfix() = 0;
Require(sceKernelAprSubmitCommandBufferAndGetId(&unreadable, 0, &first) == -1 && *__error_nid_postfix() == GuestEfault, "APR accepted a command buffer with an unreadable base");
const Apr::CommandBufferObject oversized{Apr::BufferType::Generic, 0, sizeof(memory) + 1, 1, sizeof(memory), memory.data()};
*__error_nid_postfix() = 0;
Require(sceKernelAprSubmitCommandBufferAndGetId(&oversized, 0, &first) == -1 && *__error_nid_postfix() == GuestEfault, "APR accepted a cursor past the command buffer capacity");
Require(sceKernelAprSubmitCommandBuffer(&oversized, 0) == -1 && *__error_nid_postfix() == GuestEfault, "APR accepted a cursor past the command buffer capacity without an id");
const Apr::CommandBufferObject zero{Apr::BufferType::Generic, 0, 1, 1, 0, memory.data()};
*__error_nid_postfix() = 0;
Require(sceKernelAprSubmitCommandBufferAndGetId(&zero, 0, &first) == -1 && *__error_nid_postfix() == GuestEfault, "APR accepted a cursor past a command buffer without capacity");
Require(sceKernelAprSubmitCommandBuffer(&zero, 0) == -1 && *__error_nid_postfix() == GuestEfault, "APR accepted a cursor past a command buffer without capacity without an id");
Require(first == 0 && result == 0xFFFFFFFFu, "a rejected APR submission wrote its result or id");
Require(sceKernelAprSubmitCommandBufferAndGetResult(&buffer, 0, &result, &first) == 0 && result == 0 && first != 0, "APR did not return a result and an id");
Require(sceKernelAprWaitCommandBuffer(first) == 0, "APR did not wait for the submission");
for (std::size_t index = 0; index < data.size(); ++index) Require(data[index] == FileByte(100 + index), "APR read through the submission with a result returned incorrect bytes");
+1
View File
@@ -345,6 +345,7 @@
- [sceKernelFcntl](../../../core/libs/prx/libkernel/File/src/Open.cpp) (libkernel) runs the POSIX `fcntl` below and returns its guest errno as `SCE_KERNEL_ERROR_*`, the form the other `sceKernel` file exports use. On PS5 firmware 13.60 it returns what `fcntl` returns there, and `0x80020000` plus the errno, which it also sets, on failure; this was measured for `F_GETFD`, `F_SETFD`, `F_GETFL`, `F_DUPFD`, `F_DUPFD_CLOEXEC`, `F_GETLK`, an unknown command and bad descriptors, not for the other commands
- [sceKernelStat on archived paths](../../../core/libs/prx/libkernel/File/src/Open.cpp) (libkernel) returns EFAULT when the output buffer is unwritable, checked on the host only.
- [sceKernelAprGetFileSize and sceKernelAprGetFileStat](../../../core/libs/prx/libkernel/Apr/src/Apr.cpp) (libkernel) - the console's answer for an unwritable output is not known; they return EFAULT, checked on the host only.
- [APR submit and command memory](../../../core/libs/prx/libkernel/Apr/src/Apr.cpp) (libkernel) - the console's answers for an unreadable command buffer object or command range, a cursor past the buffer's capacity, an unwritable id or result, and a write, wait or counter-write address that is not usable guest memory are not known; the submit forms return EFAULT, the executor refuses the address with a throw like its read commands, and every check runs on the host only
- [fcntl](../../../core/libs/prx/libkernel/File/src/DescriptorControl.cpp) (libkernel) follows FreeBSD 11.4's [`kern_fcntl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L479-L799) and [`kern_dup`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L812) on file, directory, pipe and character device descriptors; a socket keeps the libSceNet path (`F_DUPFD`, `F_DUP2FD`, `F_DUP2FD_CLOEXEC`, `F_GETFL`, `F_SETFL` with `O_NONBLOCK`, `F_GETFD` and `F_SETFD`, `EINVAL` for every other command, see the next entry). On Linux and macOS a host socket that is not a guest socket, such as a standard descriptor a service manager connected to its journal, takes the flag handling of a pipe end and `FIONREAD` asks the host for its queued bytes (for a datagram socket Linux counts only the next datagram, where FreeBSD's [`soo_ioctl`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/sys_socket.c#L202-L205) counts every buffered byte); its record locks and read-ahead hints fail with `EBADF`, as FreeBSD fails them on a descriptor without a vnode, and `O_ASYNC` on it throws. The close-on-exec flag and the status flags live in a guest table, the status flags shared by `dup`, `dup2` and `F_DUPFD` as in an open file description; a descriptor the table has not seen, such as 0 to 2, starts from the host's flags, since the console's are not known. `F_DUPFD` returns the lowest free host descriptor at or above the start, so the bound is the host table (`EMFILE` on Windows, `EINVAL` past `RLIMIT_NOFILE` on Linux), not the console's unknown `RLIMIT_NOFILE` and `kern.maxfilesperproc`. `O_NONBLOCK` switches a host pipe (`PIPE_NOWAIT` on Windows, where an empty read and a full write then report `EAGAIN`) and is only recorded on files, directories and the random device, as their reads never block; on a Windows console or other character device it throws. `O_ASYNC` on a pipe or character device (`SIGIO` is not delivered), `F_GETOWN`, `F_SETOWN` and `F_SETLK_REMOTE` throw; `O_FSYNC` set by `open` or `F_SETFL` makes each `write`, `pwrite`, `writev` and `pwritev` on a file sync it before returning, as `vn_write` adds `IO_SYNC`; the `sceKernelAioSubmitWriteCommands` writes are not synced, as whether the console's AIO honours the flag is unknown; on Linux a file opened with it keeps the host `O_SYNC` after `F_SETFL` clears it. `O_DIRECT`, `F_RDAHEAD` and `F_READAHEAD` are recorded as the hints they are. Record locks (`F_GETLK`, `F_SETLK`, `F_SETLKW` and their forms without `l_sysid`) use the host's POSIX locks on Linux and macOS. `F_GETLK` with `F_UNLCK` asks the host with `F_RDLCK`: as in [`lf_blocks`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_lockf.c#L866) only another owner's overlapping write lock conflicts with either request. On Windows they follow [`kern_fcntl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L607-L752) and [`lf_advlockasync`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_lockf.c#L433-L487) for the one guest process, which owns every lock: `EOVERFLOW` for an `SEEK_CUR` start past `OFF_MAX`, then `EBADF` for `F_RDLCK` without read access or `F_WRLCK` without write access and `EINVAL` for another type, then `EINVAL` and `EOVERFLOW` for the range; as [`lf_blocks`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_lockf.c#L866) never lets locks of one owner conflict, whichever descriptor or thread asks, `F_SETLK` and `F_SETLKW` then succeed without waiting and `F_GETLK` reports `F_UNLCK`, so no lock list is kept and merging, splitting and the release on close have nothing to change. Nothing is held on the host, since Windows byte-range locks are mandatory and would fail the guest's own reads and writes through other descriptors, so other host processes neither see these locks nor are seen; a lock from the end of a directory throws. The return values and error codes are unverified on a console
- [fcntl on a guest socket](../../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) answers `F_DUPFD`, `F_DUP2FD`, `F_DUP2FD_CLOEXEC`, `F_GETFD`, `F_SETFD`, `F_GETFL` and `F_SETFL`, fails `F_DUPFD_CLOEXEC` with `EOPNOTSUPP` as a PS5 does, and fails every other command with `EINVAL`; FreeBSD 11.4's `kern_fcntl` also handles `F_GETOWN` and `F_SETOWN` on a socket. `FD_CLOEXEC` is only recorded (there is no `exec`): `dup`, `dup2`, `F_DUPFD`, `F_DUP2FD` onto another descriptor and an accepted socket start without it, `F_DUP2FD` onto the same descriptor keeps it, and `SOCK_CLOEXEC` and `F_SETFD` set it. None of this was measured on a console.
- [F_DUPFD_CLOEXEC and F_DUP2FD_CLOEXEC](../../../core/libs/prx/libkernel/File/src/DescriptorControl.cpp) (libkernel) - `F_DUPFD_CLOEXEC` on a shared memory descriptor fails with `EOPNOTSUPP`, where PS5 firmware 13.60 returns 0 for any start without setting `errno`; whether it duplicates anything is not known, since descriptor 0 was already open. `F_DUP2FD_CLOEXEC` returns the lowest free descriptor, where the console picks scattered free numbers below 1024 (17 to 1012 measured). Otherwise both follow the console: `F_DUPFD_CLOEXEC` fails with `EOPNOTSUPP` for any start on files, sockets, pipes and kqueues, after `EBADF` for a bad descriptor; `F_DUP2FD_CLOEXEC` ignores its target, which it neither opens nor closes (-1, -2, `INT_MAX`, the source and an open descriptor alike), and returns a new descriptor for the same open file without `FD_CLOEXEC`, or `EBADF` for a bad source