feat(libkernel): implement sceKernelMlock

Lock the guest pages of the range with VirtualLock or mlock, following FreeBSD mlock(2): the range is widened to guest pages, a zero length succeeds, a wrapping range is EINVAL and a range that is not mapped and accessible is ENOMEM. The Windows working set limits and the Linux RLIMIT_MEMLOCK soft limit are raised when the lock needs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DotDebian
2026-10-02 15:28:01 +02:00
committed by Claude
parent e440e2c22b
commit 774b34986c
2 changed files with 122 additions and 4 deletions
@@ -10,12 +10,17 @@
#define NOMINMAX
#include <windows.h>
#else
#include <cerrno>
#include <fstream>
#include <sstream>
#include <sys/mman.h>
#include <sys/resource.h>
#endif
#include <algorithm>
#include <limits>
#include <stdexcept>
#include <string>
#include <system_error>
#include <iterator>
#include <map>
#include <cstdio>
@@ -405,13 +410,73 @@ int APS5_VABI sceKernelBatchMap2(KernelBatchMapEntry* entries, int num_entries,
}
namespace {
#ifdef _WIN32
std::mutex g_workingSetLock;
bool HostRangeAccessible(std::uintptr_t start, std::uintptr_t end) {
for (auto cursor = start; cursor < end;) {
MEMORY_BASIC_INFORMATION region{};
if (VirtualQuery(reinterpret_cast<const void*>(cursor), &region, sizeof(region)) != sizeof(region)) return false;
if (region.State != MEM_COMMIT || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
cursor = reinterpret_cast<std::uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
int LockHostPages(std::uintptr_t start, std::uintptr_t end) {
if (!HostRangeAccessible(start, end)) return SCE_KERNEL_ERROR_ENOMEM;
auto* const address = reinterpret_cast<void*>(start);
const SIZE_T bytes = end - start;
std::lock_guard lock(g_workingSetLock);
if (VirtualLock(address, bytes)) return 0;
if (GetLastError() != ERROR_WORKING_SET_QUOTA) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualLock failed");
SIZE_T minimum = 0;
SIZE_T maximum = 0;
DWORD flags = 0;
if (!GetProcessWorkingSetSizeEx(GetCurrentProcess(), &minimum, &maximum, &flags)) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "GetProcessWorkingSetSizeEx failed");
if (bytes > std::numeric_limits<SIZE_T>::max() - maximum) return SCE_KERNEL_ERROR_EAGAIN;
if (!SetProcessWorkingSetSizeEx(GetCurrentProcess(), minimum + bytes, maximum + bytes, flags)) return SCE_KERNEL_ERROR_EAGAIN;
if (VirtualLock(address, bytes)) return 0;
if (GetLastError() != ERROR_WORKING_SET_QUOTA) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualLock failed");
return SCE_KERNEL_ERROR_EAGAIN;
}
#else
int LockHostPages(std::uintptr_t start, std::uintptr_t end) {
auto* const address = reinterpret_cast<void*>(start);
const std::size_t bytes = end - start;
if (::mlock(address, bytes) == 0) return 0;
int error = errno;
rlimit limit{};
if ((error == ENOMEM || error == EPERM || error == EAGAIN) && getrlimit(RLIMIT_MEMLOCK, &limit) == 0 && limit.rlim_cur < limit.rlim_max) {
limit.rlim_cur = limit.rlim_max;
if (setrlimit(RLIMIT_MEMLOCK, &limit) == 0) {
if (::mlock(address, bytes) == 0) return 0;
error = errno;
}
}
switch (error) {
case ENOMEM: return SCE_KERNEL_ERROR_ENOMEM;
case EPERM: return SCE_KERNEL_ERROR_EPERM;
case EAGAIN: return SCE_KERNEL_ERROR_EAGAIN;
default: throw std::system_error(error, std::generic_category(), "mlock failed");
}
}
#endif
}
extern "C" {
int APS5_VABI sceKernelMlock_nid_postfix(void* address, std::uint64_t length) {
(void)address;
(void)length;
NotImplemented_nid_no_patch(__func__);
return 0;
constexpr std::uintptr_t pageMask = PS5_PAGE_SIZE - 1;
const auto first = reinterpret_cast<std::uintptr_t>(address);
if (length > UINTPTR_MAX - first || first + length > UINTPTR_MAX - pageMask) return SCE_KERNEL_ERROR_EINVAL;
const auto start = first & ~pageMask;
const auto end = (first + length + pageMask) & ~pageMask;
if (start == end) return 0;
return LockHostPages(start, end);
}
}
+53
View File
@@ -28,6 +28,7 @@
#include <unistd.h>
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
@@ -57,6 +58,7 @@ int APS5_VABI sceKernelAioInitializeImpl(void*, std::int32_t);
int APS5_VABI sceKernelAioSubmitReadCommands(KernelAioRwRequest*, std::int32_t, std::int32_t, std::int32_t*);
int APS5_VABI sceKernelAioWaitRequest(std::int32_t, std::int32_t*, std::uint32_t*);
int APS5_VABI sceKernelAioDeleteRequest(std::int32_t, std::int32_t*);
int APS5_VABI sceKernelMlock_nid_postfix(void*, std::uint64_t);
}
static void Require(bool condition, std::source_location location = std::source_location::current()) {
@@ -205,6 +207,56 @@ static void CheckNoOverwriteRejectsHostOccupiedMapping() {
}
#endif
#if defined(__linux__)
static std::size_t LockedKilobytes() {
std::ifstream status("/proc/self/status");
std::string line;
while (std::getline(status, line)) {
if (line.rfind("VmLck:", 0) == 0) return std::strtoull(line.c_str() + 6, nullptr, 10);
}
return 0;
}
#endif
static void CheckMlock() {
constexpr std::size_t page = 0x4000;
#ifdef _WIN32
constexpr std::size_t length = 0x400000;
#else
constexpr std::size_t length = 0x10000;
#endif
constexpr int outOfMemory = static_cast<int>(0x8002000cu);
constexpr int invalid = static_cast<int>(0x80020016u);
void* mapped = nullptr;
Require(sceKernelMapFlexibleMemory(&mapped, length, 3, 0) == 0);
auto* bytes = static_cast<unsigned char*>(mapped);
Require(sceKernelMlock_nid_postfix(mapped, 0) == 0);
#if defined(__linux__)
const auto lockedBefore = LockedKilobytes();
#endif
Require(sceKernelMlock_nid_postfix(bytes + 1, length - page) == 0);
#ifdef _WIN32
SIZE_T minimum = 0;
SIZE_T maximum = 0;
DWORD limits = 0;
Require(GetProcessWorkingSetSizeEx(GetCurrentProcess(), &minimum, &maximum, &limits) && minimum >= length && maximum > minimum);
Require(VirtualUnlock(mapped, length));
Require(!VirtualUnlock(mapped, length) && GetLastError() == ERROR_NOT_LOCKED);
#elif defined(__linux__)
Require(LockedKilobytes() - lockedBefore == length / 1024);
#endif
Require(sceKernelMlock_nid_postfix(mapped, length) == 0);
Require(sceKernelMlock_nid_postfix(mapped, length) == 0);
bytes[length - 1] = 7;
Require(sceKernelMlock_nid_postfix(reinterpret_cast<void*>(std::numeric_limits<std::uintptr_t>::max() - page + 1), page * 2) == invalid);
void* reserved = nullptr;
Require(sceKernelReserveVirtualRange(&reserved, page, 0, 0) == 0);
Require(sceKernelMlock_nid_postfix(reserved, page) == outOfMemory);
Require(sceKernelMunmap(reserved, page) == 0);
Require(sceKernelMunmap(mapped, length) == 0);
Require(sceKernelMlock_nid_postfix(mapped, page) == outOfMemory);
}
static void CheckSharedDirectMemoryLifecycle() {
constexpr std::size_t page = 0x4000;
std::int64_t phys = 0;
@@ -586,6 +638,7 @@ int main() {
CheckInternalNamedFlexibleMapping();
CheckDirectMemoryFollowsPhysicalPages();
CheckFixedVirtualReservation();
CheckMlock();
CheckSharedDirectMemoryLifecycle();
CheckHeapAfterMappingReuse();
#ifdef _WIN32