From 77293cf2cbc0f72c78405d11bc5246ed73f6c1cb Mon Sep 17 00:00:00 2001 From: omurc4 Date: Mon, 12 Oct 2026 20:50:38 -0400 Subject: [PATCH 01/23] feat(relinker): hint at the MinGW runtime DLLs when a module fails to load with error 126 A relinked executable that cannot load a library reports "GetLastError: 126 - The specified module could not be found.", which also covers a library whose dependent DLLs are missing. On Windows a self-built libs/ directory needs libgcc_s_seh-1.dll, libstdc++-6.dll and libwinpthread-1.dll next to it. For error 126 the stub now adds a line naming them. Refs #4482 (cherry picked from commit 19150397ee245a72291bdce1cd31799304cc2c3f) --- .../elfpatcher/src/windows/WindowsEntryStubBuilder.cpp | 6 ++++++ core/relinker/relinker/tests/test_windows_import_modules.py | 1 + 2 files changed, 7 insertions(+) diff --git a/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp index 058f64d143f9..28707a85383e 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp @@ -196,6 +196,7 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con const auto failedModule = addString("Failed to load module: "); const auto skippedModule = addString(" -> not found; nothing is imported from it, continuing without it\n"); const auto errorPrefix = addString("GetLastError: "); + const auto moduleNotFoundHint = addString("hint: the module or one of its dependent DLLs was not found; a self-built libs/ also needs libgcc_s_seh-1.dll, libstdc++-6.dll and libwinpthread-1.dll from the toolchain's mingw64/bin next to it\n"); const auto messageSeparator = addString(" - "); const auto newline = addString("\n"); const auto searched = addString("Searched libraries:\n"); @@ -465,6 +466,11 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con writeString(resolvedPaths[index], true); writeString(newline, true); writeLastError(); + code.Rip({0x8b, 0x05}, lastError); + code.Emit({0x83, 0xf8, 0x7e}); + const auto notModuleNotFound = code.Branch({0x0f, 0x85}); + writeString(moduleNotFoundHint, true); + code.PatchBranch(notModuleNotFound, code.GetRva()); if (dependencyDiagnostics) { code.Rip({0x48, 0x8d, 0x0d}, resolvedPaths[index]); code.Rip({0x48, 0x8d, 0x15}, programText); diff --git a/core/relinker/relinker/tests/test_windows_import_modules.py b/core/relinker/relinker/tests/test_windows_import_modules.py index 97b31835ff72..c803ebbe73a5 100644 --- a/core/relinker/relinker/tests/test_windows_import_modules.py +++ b/core/relinker/relinker/tests/test_windows_import_modules.py @@ -668,6 +668,7 @@ def convert_stdio_case(case_name): run = subprocess.run([str(output)], capture_output=True, text=True, timeout=30) assert run.returncode != 0 and 'Failed to load module:' in run.stderr and 'missing.prx' in run.stderr, (run.returncode, run.stderr) assert run.stderr.startswith('Failed to load module:'), run.stderr + assert 'GetLastError: 126' in run.stderr and 'hint: the module or one of its dependent DLLs was not found' in run.stderr, run.stderr for index, (symbol, module_name) in enumerate([('shared#A#B', None), ('shared', None), ('shared#A#B', 'libSceJson')]): case = work / ('missing-unused-dependency-' + str(index)) From 17fc95c5ee74ad0513c95ba79663c9f52cd42094 Mon Sep 17 00:00:00 2001 From: SandstromPL Date: Wed, 14 Oct 2026 01:07:13 +0530 Subject: [PATCH 02/23] fix(relinker): share guest modules between executables that need different system libraries On Linux and macOS every guest module listed the converting executable's own DT_NEEDED system libraries, so its bytes could depend on which executable converted it. --executable then failed with "Guest modules convert differently" when the executables need different system libraries that the modules do not, or the same ones in another order. It is the error a title reports on Linux (#5268) for its launcher and main executable. Guest modules now list only the system libraries the guest modules themselves need, with the libSceLibcInternal.prx to libc.prx rule. The executable's own DT_NEEDED is unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 6adf63c7cc61e8c44fecee1979c92e4eae3319ea) --- .../relinker/src/guest/GuestModuleBuilder.cpp | 8 +++++++- core/relinker/relinker/tests/test_guest_host_libc.py | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp b/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp index 387d2f5ce074..fa5c5bbc7e3a 100644 --- a/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp +++ b/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp @@ -350,6 +350,12 @@ std::vector GuestModuleBuilder::Build(const std::filesystem::path if (!windows && runPath != "$ORIGIN" && !runPath.starts_with("$ORIGIN/") && !runPath.starts_with("$ORIGIN:") && !std::filesystem::path(runPath).is_absolute()) throw Domain::RelinkerException("Guest Linux run path must be absolute or begin with $ORIGIN"); const auto outputDirectory = std::filesystem::absolute(outputPath).parent_path().lexically_normal(); std::vector artifacts; + std::vector moduleHostLibraries; + std::set uniqueModuleHosts; + for (const auto& image : images) for (const auto& dependency : image.Dependencies) { + if (findGuest(dependency) == guestNames.end() && uniqueModuleHosts.insert(dependency).second) moduleHostLibraries.push_back(dependency); + } + if (uniqueModuleHosts.contains("libSceLibcInternal.prx") && uniqueModuleHosts.insert("libc.prx").second) moduleHostLibraries.push_back("libc.prx"); for (const auto index : order) { auto& image = images[index]; std::ostringstream moduleSize; @@ -398,7 +404,7 @@ std::vector GuestModuleBuilder::Build(const std::filesystem::path const auto dependencyPath = images[dependency].SourcePath.parent_path() / images[dependency].OutputName; needed.push_back("$ORIGIN/" + dependencyPath.lexically_relative(image.SourcePath.parent_path()).generic_string()); } - needed.insert(needed.end(), hostLibraries.begin(), hostLibraries.end()); + needed.insert(needed.end(), moduleHostLibraries.begin(), moduleHostLibraries.end()); output = macos ? Elfpatcher::GuestModuleWriter().WriteMacOs(image, needed, guestRunPath) : Elfpatcher::GuestModuleWriter().WriteLinux(image, needed, guestRunPath); } if (windows) { diff --git a/core/relinker/relinker/tests/test_guest_host_libc.py b/core/relinker/relinker/tests/test_guest_host_libc.py index bb1c776b0582..7393dd72ecfe 100644 --- a/core/relinker/relinker/tests/test_guest_host_libc.py +++ b/core/relinker/relinker/tests/test_guest_host_libc.py @@ -6,6 +6,7 @@ from test_guest_intel_trampolines import PLAIN_SITE, guest_fixture, main_fixture from test_guest_module_directories import needed_libraries +from test_guest_needed_modules import module_with_needed DYNAMIC = 0x4800 STRINGS = 0x4A00 @@ -60,6 +61,17 @@ def main(): needed = convert(relinker, work / "excluded", imports, ["libc.prx", "other.prx"], ["--exclude-sce-module", "libc.prx"]) assert needed == ["$ORIGIN/app0/sce_module/other.prx.guest.prx", *imports], needed + + case = work / "module-internal" + (case / "sce_module").mkdir(parents=True) + (case / "input.elf").write_bytes(importing("libkernel.prx")) + (case / "sce_module" / "user.prx").write_bytes(module_with_needed((b"libSceLibcInternal.prx",), (0,))) + result = subprocess.run([str(relinker), str(case / "input.elf"), str(case / "output.elf")], capture_output=True, text=True, timeout=30) + assert result.returncode == 0, (result.stdout, result.stderr) + needed = needed_libraries((case / "output.elf").read_bytes()) + assert needed == ["$ORIGIN/app0/sce_module/user.prx.guest.prx", "libkernel.prx", "libSceLibcInternal.prx", "libc.prx"], needed + needed = needed_libraries((case / "app0" / "sce_module" / "user.prx.guest.prx").read_bytes()) + assert needed == ["libSceLibcInternal.prx", "libc.prx"], needed print("Guest host libc integration tests passed") From 3d83482d23edd47e2a2e80e5c72291ce71c60e42 Mon Sep 17 00:00:00 2001 From: alosta Date: Tue, 13 Oct 2026 20:42:44 +0100 Subject: [PATCH 03/23] feat(libc): implement swprintf_s Add the missing wide secure formatting exports required by a title whose load failed with `undefined symbol: Im55VJ-Bekc`: swprintf_s and its va_list counterpart follow C11 Annex K.3.9.1.4 (the complete output, including the terminator, must fit), while vsnwprintf_s is the va_list counterpart of snwprintf_s (K.3.9.1.3, truncation with full length). The export names produce NIDs Im55VJ-Bekc, oDoV9tyHTbA and 8SKVXgeK1wY respectively. Document the new functions in docs/dev/debt/libc.md. (cherry picked from commit a0bd257a0945110e7d44ddfcf416908a9d57b899) --- core/libs/prx/libc/src/FormattingWide.cpp | 57 +++++++++++++++++++++++ core/libs/tests/GuestWideFormatting.cpp | 36 ++++++++++++++ docs/dev/TechnicalDebt.md | 2 + 3 files changed, 95 insertions(+) diff --git a/core/libs/prx/libc/src/FormattingWide.cpp b/core/libs/prx/libc/src/FormattingWide.cpp index 1aa78ba06727..e9a5661781b5 100644 --- a/core/libs/prx/libc/src/FormattingWide.cpp +++ b/core/libs/prx/libc/src/FormattingWide.cpp @@ -259,6 +259,63 @@ int APS5_VABI snwprintf_s_nid_postfix(char16_t* buffer, std::size_t size, const return result; } +int APS5_VABI vswprintf_s_nid_postfix(char16_t* buffer, std::size_t size, const char16_t* format, VaList* args) { + constexpr std::size_t RsizeMax = (SIZE_MAX >> 1) / sizeof(char16_t); + int result = -1; + if (buffer != nullptr && format != nullptr && args != nullptr && size != 0 && size <= RsizeMax) { + try { + const std::u16string text = FormatWide(format, args, true); + if (text.size() + 1 <= size && text.size() <= static_cast(INT_MAX)) { + std::memcpy(buffer, text.data(), text.size() * sizeof(char16_t)); + buffer[text.size()] = 0; + result = static_cast(text.size()); + } + } catch (const std::invalid_argument&) { + } + } + if (result < 0 && buffer != nullptr && size != 0 && size <= RsizeMax) buffer[0] = 0; + return result; +} + +int APS5_VABI swprintf_s_nid_postfix(char16_t* buffer, std::size_t size, const char16_t* format, ...) { + constexpr std::size_t RsizeMax = (SIZE_MAX >> 1) / sizeof(char16_t); + int result = -1; + if (buffer != nullptr && format != nullptr && size != 0 && size <= RsizeMax) { + APS5_VA_BEGIN(format); + try { + const std::u16string text = FormatWide(format, reinterpret_cast(args), true); + if (text.size() + 1 <= size && text.size() <= static_cast(INT_MAX)) { + std::memcpy(buffer, text.data(), text.size() * sizeof(char16_t)); + buffer[text.size()] = 0; + result = static_cast(text.size()); + } + } catch (const std::invalid_argument&) { + } + APS5_VA_END(); + } + if (result < 0 && buffer != nullptr && size != 0 && size <= RsizeMax) buffer[0] = 0; + return result; +} + +int APS5_VABI vsnwprintf_s_nid_postfix(char16_t* buffer, std::size_t size, const char16_t* format, VaList* args) { + constexpr std::size_t RsizeMax = (SIZE_MAX >> 1) / sizeof(char16_t); + int result = -1; + if (buffer != nullptr && format != nullptr && args != nullptr && size != 0 && size <= RsizeMax) { + try { + const std::u16string text = FormatWide(format, args, true); + if (text.size() <= static_cast(INT_MAX)) { + const std::size_t copied = text.size() < size - 1 ? text.size() : size - 1; + std::memcpy(buffer, text.data(), copied * sizeof(char16_t)); + buffer[copied] = 0; + result = static_cast(text.size()); + } + } catch (const std::invalid_argument&) { + } + } + if (result < 0 && buffer != nullptr && size != 0 && size <= RsizeMax) buffer[0] = 0; + return result; +} + int APS5_VABI wprintf_nid_postfix(const char16_t* format, ...) { APS5_VA_BEGIN(format); int result = -1; diff --git a/core/libs/tests/GuestWideFormatting.cpp b/core/libs/tests/GuestWideFormatting.cpp index adba600ad6cc..f372fd47e15f 100644 --- a/core/libs/tests/GuestWideFormatting.cpp +++ b/core/libs/tests/GuestWideFormatting.cpp @@ -10,6 +10,9 @@ extern "C" int APS5_VABI vswprintf_nid_postfix(char16_t*, std::size_t, const char16_t*, VaList*); extern "C" int APS5_VABI snwprintf_s_nid_postfix(char16_t*, std::size_t, const char16_t*, ...); +extern "C" int APS5_VABI vswprintf_s_nid_postfix(char16_t*, std::size_t, const char16_t*, VaList*); +extern "C" int APS5_VABI swprintf_s_nid_postfix(char16_t*, std::size_t, const char16_t*, ...); +extern "C" int APS5_VABI vsnwprintf_s_nid_postfix(char16_t*, std::size_t, const char16_t*, VaList*); extern "C" int APS5_VABI swprintf_nid_postfix(char16_t*, std::size_t, const char16_t*, ...); extern "C" std::size_t APS5_VABI strftime_nid_postfix(char*, std::size_t, const char*, const GuestTm*); extern "C" std::size_t APS5_VABI wcsftime_nid_postfix(char16_t*, std::size_t, const char16_t*, const GuestTm*); @@ -148,6 +151,38 @@ static void CheckGroupingFlag() { "snwprintf_s ' flag"); } +static void CheckSecureWideBoundary() { + constexpr std::size_t wideRsizeMax = (SIZE_MAX >> 1) / sizeof(char16_t); + char16_t buffer[4]; + for (auto& unit : buffer) unit = u'x'; + + buffer[0] = u'x'; + buffer[1] = u'y'; + Require(swprintf_s_nid_postfix(buffer, wideRsizeMax, u"%n") < 0 && buffer[0] == 0, "swprintf_s accepted-boundary failure clears"); + Require(buffer[1] == u'y', "swprintf_s does not clear beyond the first unit"); + + buffer[0] = u'x'; + buffer[1] = u'y'; + Require(swprintf_s_nid_postfix(buffer, wideRsizeMax + 1, u"%n") < 0 && buffer[0] == u'x' && buffer[1] == u'y', + "swprintf_s oversized size leaves the buffer untouched"); + + buffer[0] = u'x'; + buffer[1] = u'y'; + Require(vswprintf_s_nid_postfix(buffer, wideRsizeMax, u"%n", nullptr) < 0 && buffer[0] == 0, "vswprintf_s accepted-boundary failure clears"); + buffer[0] = u'x'; + buffer[1] = u'y'; + Require(vswprintf_s_nid_postfix(buffer, wideRsizeMax + 1, u"%n", nullptr) < 0 && buffer[0] == u'x' && buffer[1] == u'y', + "vswprintf_s oversized size leaves the buffer untouched"); + + buffer[0] = u'x'; + buffer[1] = u'y'; + Require(vsnwprintf_s_nid_postfix(buffer, wideRsizeMax, u"%n", nullptr) < 0 && buffer[0] == 0, "vsnwprintf_s accepted-boundary failure clears"); + buffer[0] = u'x'; + buffer[1] = u'y'; + Require(vsnwprintf_s_nid_postfix(buffer, wideRsizeMax + 1, u"%n", nullptr) < 0 && buffer[0] == u'x' && buffer[1] == u'y', + "vsnwprintf_s oversized size leaves the buffer untouched"); +} + static void CheckSwprintf() { char16_t buffer[8]; for (auto& unit : buffer) unit = u'x'; @@ -244,6 +279,7 @@ int main() { CheckPointer(); CheckCount(); CheckSwprintf(); + CheckSecureWideBoundary(); CheckWcsftime(); Check(u"%.2s", "\xc3\xa9\xc3\xa8", u"\u00e9\u00e8"); Check(u"%.1s", "\xc3\xa9\xc3\xa8", u"\u00e9"); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 9f84e8dee258..90a7080655a8 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -346,6 +346,8 @@ Throughout the project, every function at every stage either **does exactly what - [sceRtcFormatRFC2822, sceRtcFormatRFC2822LocalTime, sceRtcFormatRFC3339LocalTime](../../core/libs/prx/libSceRtc/Export.cpp) (libSceRtc) - only shadPS4 (PS4) has bodies. A null tick returns `INVALID_POINTER` like the existing `sceRtcFormatRFC3339`, where shadPS4 formats the current time instead; offsets outside ±1439 minutes return `INVALID_VALUE` like `sceRtcFormatRFC3339`; the local-time variants use the host's offset at the given instant (shadPS4 uses `sceKernelGettimezone`, the current offset) - [memcpy_s and memmove_s](../../core/libs/prx/libc/src/Strings.cpp) (libc) use the C11 K.3.7.1.1 and K.3.7.1.2 size constraints, with RSIZE_MAX taken as SIZE_MAX >> 1 as in memset_s. An oversized destination size returns ERANGE (34) without touching the destination; the console's RSIZE_MAX and exact error value are unverified. Constraint violations return an error without invoking the registered constraint handler, as before. - [snwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follows C11 K.3.9.1.3 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`. A runtime-constraint violation only returns a negative value: `set_constraint_handler_s` is not exported and the console's default handler is unknown. An invalid multibyte `%s` argument is copied byte by byte instead of being reported as an encoding error, as in `vswprintf` +- [swprintf_s and vswprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follow C11 K.3.9.1.4 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`: the complete output, including the terminating null, must fit in the buffer, otherwise it is a runtime-constraint violation that sets `buffer[0]` to zero and returns a negative value, and the buffer is not partially written. Argument and encoding checks match `snwprintf_s` +- [vsnwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - `va_list` counterpart of `snwprintf_s` (C11 K.3.9.1.3): truncates to the buffer and returns the full length, with the same constraints and argument checks - [vsnprintf_s and vsscanf_s](../../core/libs/prx/libc/src/Formatting.cpp) (libc) - `vsnprintf_s` forwards to `vsnprintf` semantics: the C11 K.3.7.1.5 runtime constraints (null buffer, `size == 0`, `%n`, null `%s`) are not checked, so `size == 0` returns the would-be length instead of a negative value, and no constraint handler is invoked. `vsscanf_s` returns the count of items converted before an undersized `%s`/`%c`/`%[` destination (0 when it is the first), not EOF. Neither is confirmed on a PS5 title - [libSceUlt ulthreads](../../core/libs/prx/libSceUlt/Export.cpp) - `_sceUltUlthreadRuntimeOptParamInitialize`, `_sceUltUlthreadRuntimeCreate` and `_sceUltUlthreadCreate` are assumed to take the same arguments as the existing exports without the underscore, including the trailing build version. `sceUltUlthreadTryJoin` is assumed to return `ULT_ERROR_BUSY` while the ulthread runs, and `sceUltUlthreadRuntimeDestroy` to return `ULT_ERROR_BUSY` while an ulthread created on the runtime is not joined. Neither error has been confirmed on PS5 hardware - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) - the added `sceUltQueuePop`, `sceUltQueueTryPush`, `sceUltQueueDestroy` and `sceUltQueueDataResourcePoolDestroy` signatures are inferred from the existing push/pop and object APIs. Queue destruction is assumed to reject blocked callers with `ULT_ERROR_BUSY` and otherwise discard queued data; pool exhaustion returns `ULT_ERROR_AGAIN`. These rules, alignment checks and shared slot limits have not been confirmed on PS5 hardware or a title. Non-null queue and data-pool option parameters throw because their layouts are unknown. From 09a9e30b2eee734c6e7175142f11de5828adcc7a Mon Sep 17 00:00:00 2001 From: ryyReid Date: Tue, 13 Oct 2026 19:23:51 -0500 Subject: [PATCH 04/23] feat(tools): unwrap decrypted SELF containers into clean ELF The relinker reads a plain ELF executable and skips SELF containers with a warning, so an eboot.bin or a *.prx taken from a title cannot be relinked before it is unwrapped, and the repository has no tool for that. The inner ELF program headers of a container carry stale offsets: a SELF inserts its own metadata blocks between the segments, so the data sits at the offsets of the SELF segment-record table at file offset 0x40. The segments are also packed without honouring p_align, while ELF requires p_offset % p_align == p_vaddr % p_align, which the relinker enforces on guest modules. The tool places the segments from the records, falls back to the vaddr to file mapping of the containing PT_LOAD for segments the table does not cover, copies every region to an offset satisfying the alignment, and refuses a container whose load segments all look encrypted. (cherry picked from commit 2a01e9eb1831eaff27a1982816db89db0b7d5f08) --- CMakeLists.txt | 2 + docs/user/USAGE.md | 2 +- tools/tests/test_unwrap_self.py | 178 +++++++++++++++++++++ tools/unwrap_self.py | 275 ++++++++++++++++++++++++++++++++ 4 files changed, 456 insertions(+), 1 deletion(-) create mode 100644 tools/tests/test_unwrap_self.py create mode 100644 tools/unwrap_self.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 0413913967bf..ed3d76986e46 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -104,6 +104,8 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_encoding.py) add_test(NAME import_audit COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_import_audit.py) + add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py) add_test(NAME conventions_function_bodies COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_comments.py) add_test(NAME test_registration COMMAND ${Python3_EXECUTABLE} diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index 7beb2fce115d..f2f4464b4277 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -2,7 +2,7 @@ ## Input and conversion -Use a clean ELF executable. Place its bundled ELF modules in `sce_module/`, `sce_modules/`, or `prx/` beside the input executable, or under the parent directory selected with `--sce-module-path `. The option accepts absolute paths and paths relative to the current working directory; do not include the `sce_module` directory itself. Only files directly inside the module directories are processed. SELF/fSELF containers are skipped with a warning; unwrap them before relinking if they need to be included. `prx/` can coexist with either `sce_module/` or `sce_modules/`. Both `sce_module/` and `sce_modules/` present, or all three absent, is an error. +Use a clean ELF executable. Place its bundled ELF modules in `sce_module/`, `sce_modules/`, or `prx/` beside the input executable, or under the parent directory selected with `--sce-module-path `. The option accepts absolute paths and paths relative to the current working directory; do not include the `sce_module` directory itself. Only files directly inside the module directories are processed. SELF/fSELF containers are skipped with a warning; unwrap them before relinking if they need to be included. `tools/unwrap_self.py ` does that for a decrypted container: it places the segments at the offsets of the SELF segment records and restores `p_offset % p_align == p_vaddr % p_align`, and it refuses a container whose load segments all look encrypted. `prx/` can coexist with either `sce_module/` or `sce_modules/`. Both `sce_module/` and `sce_modules/` present, or all three absent, is an error. ```text source/ diff --git a/tools/tests/test_unwrap_self.py b/tools/tests/test_unwrap_self.py new file mode 100644 index 000000000000..44e1897ccb61 --- /dev/null +++ b/tools/tests/test_unwrap_self.py @@ -0,0 +1,178 @@ +import struct +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import unwrap_self + +SELF_MAGIC = 0x1D3D154F +ELF_HEADER_OFFSET = 0x1A0 +PROGRAM_TABLE_OFFSET = 0x40 +PT_LOAD = 1 +PT_DYNAMIC = 2 +FIRST_REGION = 0x400 + +HEADER = b"\x7fELF\x02\x01\x01\x09" + b"\x00" * 56 +PAGE = 0x1000 + + +def pattern(seed, size): + return bytes((seed + index * 7) % 251 for index in range(size)) + + +def build_elf(segments): + header = bytearray(HEADER) + struct.pack_into(" [--verbose] +""" + +import argparse +import math +import struct +import sys +from collections import Counter +from pathlib import Path + +SELF_MAGIC = 0x1D3D154F +SELF_MAGIC_KERNEL = 0xEEF51454 +RECORD_OFFSET = 0x40 +RECORD_SIZE = 0x20 +FIRST_REGION = 0x400 +PT_LOAD = 1 +ENTROPY_LIMIT = 7.5 +ENTROPY_SAMPLE = 0x10000 + +PHDR_NAMES = { + PT_LOAD: "PT_LOAD", + 2: "PT_DYNAMIC", + 3: "PT_INTERP", + 4: "PT_NOTE", + 6: "PT_PHDR", + 7: "PT_TLS", + 0x6474E550: "PT_GNU_EH_FRAME", + 0x6474E551: "PT_GNU_STACK", + 0x6474E552: "PT_GNU_RELRO", + 0x61000000: "PT_SCE_DYNLIBDATA", + 0x61000001: "PT_OS_PROCPARAM", + 0x61000002: "PT_OS_0x61000002", + 0x6FFFFF00: "PT_OS_0x6fffff00", + 0x6FFFFF01: "PT_OS_0x6fffff01", +} + + +class Refused(Exception): + pass + + +def entropy(data): + if not data: + return 0.0 + counts = Counter(data) + length = len(data) + return -sum((count / length) * math.log2(count / length) for count in counts.values()) + + +def read_records(data): + records = [] + offset = RECORD_OFFSET + while offset + RECORD_SIZE <= FIRST_REGION: + flags, segment, size, size_again = struct.unpack_from("= len(data) or segment < 0x350 or segment % 0x10 != 0: + break + if size > len(data): + break + records.append((flags, segment, size)) + offset += RECORD_SIZE + return records + + +def align_up(value, alignment): + if alignment <= 1: + return value + return (value + alignment - 1) // alignment * alignment + + +def parse_elf(data): + inner = data.find(b"\x7fELF") + if inner < 0: + raise Refused("no inner ELF header") + header = bytearray(data[inner:inner + 0x40]) + program_offset = struct.unpack_from(" tail[0]: + tail = (header["offset"], header["source"] - header["offset"]) + elif header["size"]: + header["source"] = header["offset"] + (tail[1] if tail else 0) + if header["source"] > len(data): + header["source"] = len(data) + keep = max(0, len(data) - header["source"]) + header["size"] = min(header["size"], keep) + header["memory"] = min(header["memory"], keep) + + for header in headers: + if header["source"] > len(data) or header["size"] > len(data) - header["source"]: + raise Refused("segment %d does not fit the file" % header["index"]) + + +def check_decrypted(data, headers): + encrypted = [] + for header in headers: + if header["type"] != PT_LOAD or header["size"] == 0: + continue + sample = data[header["source"]:header["source"] + min(header["size"], ENTROPY_SAMPLE)] + value = entropy(sample) + if value >= ENTROPY_LIMIT: + encrypted.append((header["index"], header["source"], value)) + if encrypted and len(encrypted) == len([h for h in headers if h["type"] == PT_LOAD and h["size"]]): + listed = ", ".join("segment %d at %#x (%.2f bits per byte)" % item for item in encrypted) + raise Refused("every load segment looks encrypted: " + listed) + + +def unwrap(path, output, verbose=False): + data = bytes(Path(path).read_bytes()) + if len(data) < FIRST_REGION: + raise Refused("file is smaller than the SELF header area") + magic = struct.unpack_from(" len(result): + raise Refused("segment %d escaped the output" % header["index"]) + + result[0:0x40] = elf_header + struct.pack_into(" Date: Tue, 13 Oct 2026 20:32:24 -0400 Subject: [PATCH 05/23] feat(libkernel): export sceKernelGetSocPowerConsumption (cherry picked from commit 31abd1a2af65a7a10b34f5f980c46544b568cbf1) --- core/libs/prx/libkernel/System/src/ThermalSensors.cpp | 5 +++++ core/libs/tests/GuestThermalSensors.cpp | 9 +++++++++ docs/dev/TechnicalDebt.md | 1 + 3 files changed, 15 insertions(+) diff --git a/core/libs/prx/libkernel/System/src/ThermalSensors.cpp b/core/libs/prx/libkernel/System/src/ThermalSensors.cpp index 992e6e468d24..bd83c4282c09 100644 --- a/core/libs/prx/libkernel/System/src/ThermalSensors.cpp +++ b/core/libs/prx/libkernel/System/src/ThermalSensors.cpp @@ -272,4 +272,9 @@ int APS5_VABI sceKernelGetSocSensorTemperature(int sensorId, int* outCelsius) { return 0; } +int APS5_VABI sceKernelGetSocPowerConsumption(void* consumption) { + if (consumption == nullptr) return SCE_KERNEL_ERROR_EFAULT; + return SCE_KERNEL_ERROR_EINVAL; +} + } diff --git a/core/libs/tests/GuestThermalSensors.cpp b/core/libs/tests/GuestThermalSensors.cpp index 4694194aeb78..a62992aba81f 100644 --- a/core/libs/tests/GuestThermalSensors.cpp +++ b/core/libs/tests/GuestThermalSensors.cpp @@ -1,16 +1,19 @@ #include "prx/libc/include/general/VabiMacros.hpp" #include "prx/libkernel/KernelErrors.hpp" +#include #include #include #include #include #include +#include #include extern "C" { void ReadThermalSensors_nid_no_patch(const char* root, int celsius[3]); int APS5_VABI sceKernelGetCpuTemperature(int* outCelsius); int APS5_VABI sceKernelGetSocSensorTemperature(int sensorId, int* outCelsius); +int APS5_VABI sceKernelGetSocPowerConsumption(void* consumption); } static void Require(bool value) { @@ -71,6 +74,12 @@ int main() { const int result = sceKernelGetSocSensorTemperature(0, &probe); Require(result == 0 ? (probe >= 0 && probe <= 130) : (result == SCE_KERNEL_ERROR_EINVAL && probe == -12345)); + Require(sceKernelGetSocPowerConsumption(nullptr) == SCE_KERNEL_ERROR_EFAULT); + std::uint32_t consumption[32]; + std::fill(std::begin(consumption), std::end(consumption), 0xa5a5a5a5u); + Require(sceKernelGetSocPowerConsumption(consumption) == SCE_KERNEL_ERROR_EINVAL); + Require(std::all_of(std::begin(consumption), std::end(consumption), [](std::uint32_t word) { return word == 0xa5a5a5a5u; })); + std::filesystem::remove_all(root); return 0; } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 90a7080655a8..77d8d86f143a 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -1,5 +1,6 @@ # Project technical debt +- [sceKernelGetSocPowerConsumption](../../core/libs/prx/libkernel/System/src/ThermalSensors.cpp) (libkernel) - returns `EINVAL` and writes nothing, as `sceKernelGetSocSensorTemperature` does when the host has no sensor: the host's package power is not read (Linux RAPL `energy_uj` is readable by root only, and Windows has no general source). The prototype is not documented. PS5LM Plus (PPSA99581) passes a zeroed 128-byte buffer and, on success, reads its first 32-bit word as milliwatts, accepting 1000 to 350000; on failure it shows 0 W ### Build - Building on Windows requires a specific version of mingw - MinGW-w64 GCC 15.2.0 (`winlibs-gcc15`, `x86_64-ucrt-posix-seh`) From 3a6e5156c483aa9df759f0b7d03f931469bac54a Mon Sep 17 00:00:00 2001 From: Feuris Date: Tue, 13 Oct 2026 21:35:45 -0300 Subject: [PATCH 06/23] feat(libc): implement wcsnlen_s (cherry picked from commit 6beefccfa50feb24e6c3c498d80896709fa89d4e) --- core/libs/prx/libc/src/Strings.cpp | 7 +++++++ core/libs/tests/GuestWideStrings.cpp | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/core/libs/prx/libc/src/Strings.cpp b/core/libs/prx/libc/src/Strings.cpp index 176ee966685d..812f97a7ba69 100644 --- a/core/libs/prx/libc/src/Strings.cpp +++ b/core/libs/prx/libc/src/Strings.cpp @@ -405,6 +405,13 @@ size_t APS5_VABI wcslen_nid_postfix(const char16_t* s) { return Length(s); } +size_t APS5_VABI wcsnlen_s_nid_postfix(const char16_t* s, size_t maxlen) { + if (!s) return 0; + size_t length = 0; + while (length < maxlen && s[length] != 0) ++length; + return length; +} + int APS5_VABI wcscmp_nid_postfix(const char16_t* s1, const char16_t* s2) { for (; *s1 == *s2; ++s1, ++s2) { if (*s1 == 0) return 0; diff --git a/core/libs/tests/GuestWideStrings.cpp b/core/libs/tests/GuestWideStrings.cpp index 101ea50e68dd..39b16ff31e49 100644 --- a/core/libs/tests/GuestWideStrings.cpp +++ b/core/libs/tests/GuestWideStrings.cpp @@ -15,6 +15,7 @@ int APS5_VABI wmemcmp_nid_postfix(const char16_t* s1, const char16_t* s2, std::s char16_t* APS5_VABI wmemcpy_nid_postfix(char16_t* dest, const char16_t* src, std::size_t n); char16_t* APS5_VABI wmemmove_nid_postfix(char16_t* dest, const char16_t* src, std::size_t n); std::size_t APS5_VABI wcslen_nid_postfix(const char16_t* s); +std::size_t APS5_VABI wcsnlen_s_nid_postfix(const char16_t* s, std::size_t maxlen); int APS5_VABI wcscmp_nid_postfix(const char16_t* s1, const char16_t* s2); int APS5_VABI wcsncmp_nid_postfix(const char16_t* s1, const char16_t* s2, std::size_t n); char16_t* APS5_VABI wcscpy_nid_postfix(char16_t* dest, const char16_t* src); @@ -59,6 +60,13 @@ int main() { require(wcslen_nid_postfix(u"héllo") == 5); require(wcslen_nid_postfix(split) == 2); + require(wcsnlen_s_nid_postfix(nullptr, 10) == 0); + require(wcsnlen_s_nid_postfix(u"", 5) == 0); + require(wcsnlen_s_nid_postfix(u"héllo", 0) == 0); + require(wcsnlen_s_nid_postfix(u"héllo", 3) == 3); + require(wcsnlen_s_nid_postfix(u"héllo", 10) == 5); + require(wcsnlen_s_nid_postfix(split, 4) == 2); + require(wcscmp_nid_postfix(u"abc", u"abc") == 0); require(wcscmp_nid_postfix(u"abc", u"abd") < 0); require(wcscmp_nid_postfix(u"abd", u"abc") > 0); From 3e08bbeb19e03ffe458f73b41daa74653c488665 Mon Sep 17 00:00:00 2001 From: Evgeniy Kazarin Date: Wed, 14 Oct 2026 03:48:36 +0300 Subject: [PATCH 07/23] feat(libkernel): support fixed anonymous mmap Map fixed private anonymous ranges through the existing guest arena. Preserve occupied ranges for MAP_EXCL and use FreeBSD 11.4 errors. Cover replacement, exclusivity, range validation, rounding, and memory access. (cherry picked from commit 6215101d28d7024a52f38cd2afab6d2a2c35560a) --- core/libs/prx/libkernel/CMakeLists.txt | 3 +- .../libkernel/DirectMemory/DirectMemory.cpp | 3 +- .../libkernel/DirectMemory/DirectMemory.hpp | 2 +- .../libkernel/DirectMemory/PosixMemory.cpp | 20 ++++- core/libs/tests/GuestMemory.cpp | 79 ++++++++++++++++++- docs/dev/TechnicalDebt.md | 1 + 6 files changed, 100 insertions(+), 8 deletions(-) diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 1f2ea3b8f9c8..9c1598f6f346 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -1167,8 +1167,9 @@ if(BUILD_TESTING) add_dependencies(guest_memory_tests guest_memory_module) target_compile_definitions(guest_memory_tests PRIVATE GUEST_MEMORY_MODULE="$") add_test(NAME guest_memory COMMAND guest_memory_tests) + add_test(NAME guest_mmap_fixed_anonymous COMMAND guest_memory_tests fixed-anonymous) if(WIN32) - set_tests_properties(guest_memory PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(guest_memory guest_mmap_fixed_anonymous PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test_executable(guest_flexible_memory_budget_tests ${LIBS_INCLUDE_DIR}/tests/GuestFlexibleMemoryBudget.cpp) diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp index e7c8bbabc804..abb12bfcba49 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp @@ -1012,13 +1012,14 @@ int DoMapDirect(void** addr, size_t len, int prot, int flags, int64_t physStart, return 0; } -int DoMapAnon(void** addr, size_t len, int prot, int flags, size_t alignment) { +int DoMapAnon(void** addr, size_t len, int prot, int flags, size_t alignment, bool exclusive) { ValidateOutput(addr); #if defined(__APPLE__) if (!DarwinRelocateFixed(addr, len, flags)) return SCE_KERNEL_ERROR_ENOMEM; #endif if (len == 0 || (len & (PS5_PAGE_SIZE - 1)) != 0) return SCE_KERNEL_ERROR_EINVAL; GuestAllocations::Mutation mutation; + if (exclusive && mutation.Overlaps(*addr, len)) return SCE_KERNEL_ERROR_ENOMEM; flags = PlaceHintInReservation(*addr, len, flags); if (FixedNoOverwriteConflict(mutation, *addr, len, flags)) return SCE_KERNEL_ERROR_ENOMEM; if (RemapFixedIntoRegistered(mutation, *addr, len, prot, flags)) { diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp index 1e9fca3b7080..8f237376bd00 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp @@ -39,7 +39,7 @@ void DirectMemoryRetype(int64_t start, size_t len, int memoryType); bool DirectMemoryLargestFree(int64_t searchStart, int64_t searchEnd, size_t alignment, int64_t* startOut, size_t* sizeOut); size_t DirectMemoryFreeRun(uint64_t offset, uint64_t limit); int DoMapDirect(void** addr, size_t len, int prot, int flags, int64_t physStart, size_t alignment); -int DoMapAnon(void** addr, size_t len, int prot, int flags, size_t alignment = PS5_PAGE_SIZE); +int DoMapAnon(void** addr, size_t len, int prot, int flags, size_t alignment = PS5_PAGE_SIZE, bool exclusive = false); int DoMapFileBacked_nid_no_patch(void** addr, size_t len, int prot, int flags, int descriptor, std::uint64_t offset, size_t alignment); int DoMapShared(void** addr, size_t len, int prot, HostSharedMemory object); int DoMprotect(const void* addr, size_t len, int prot); diff --git a/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp b/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp index 1e314660cf16..9b660c8dcbd3 100644 --- a/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp +++ b/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp @@ -2,6 +2,7 @@ #include "SceTypes.hpp" #include "prx/libc/include/general/VabiMacros.hpp" #include "prx/libc/include/General.hpp" +#include "prx/libc/include/GuestArena.hpp" #include "prx/libkernel/File/include/SharedMemory.hpp" #include #include @@ -30,6 +31,7 @@ constexpr int GuestShared = 0x1; constexpr int GuestPrivate = 0x2; constexpr int GuestAnonymous = 0x1000; constexpr int GuestMapFixed = 0x10; +constexpr int GuestMapExclusive = 0x4000; constexpr int GuestMapNoOverwrite = 0x80; constexpr int GuestMapNoCoalesce = 0x400000; constexpr int GuestSyncAsync = 0x1; @@ -90,14 +92,26 @@ void* APS5_VABI mmap_nid_postfix(void* address, std::size_t length, int protecti std::size_t rounded; if (!RoundLength(length, rounded) || (protection & ~7) != 0) return failed(GuestInvalid); + if ((flags & (GuestMapExclusive | GuestMapFixed)) == GuestMapExclusive) return failed(GuestInvalid); const int mappingFlags = flags & ~GuestAlignedSuper; - if (mappingFlags == (GuestPrivate | GuestAnonymous)) { + const bool fixedAnonymous = (mappingFlags & ~(GuestMapFixed | GuestMapExclusive)) == (GuestPrivate | GuestAnonymous) + && (mappingFlags & GuestMapFixed) != 0; + if (mappingFlags == (GuestPrivate | GuestAnonymous) || fixedAnonymous) { if (descriptor != -1 || offset != 0) return failed(GuestInvalid); - void* mapped = nullptr; + const auto start = reinterpret_cast(address); + if (fixedAnonymous && ((start & (PS5_PAGE_SIZE - 1)) != 0 || + rounded > std::numeric_limits::max() - start || + !GuestArena::GuestArenaContains_nid_postfix(address, rounded))) return failed(GuestInvalid); + const bool exclusive = fixedAnonymous && (mappingFlags & GuestMapExclusive) != 0; + const int placement = fixedAnonymous ? GuestMapFixed | (exclusive ? GuestMapNoOverwrite : 0) : 0; + void* mapped = fixedAnonymous ? address : nullptr; + const auto alignment = !fixedAnonymous && (flags & GuestAlignedSuper) != 0 ? SuperpageSize : PS5_PAGE_SIZE; try { - const auto result = DoMapAnon(&mapped, rounded, protection, 0, (flags & GuestAlignedSuper) != 0 ? SuperpageSize : PS5_PAGE_SIZE); + const auto result = DoMapAnon(&mapped, rounded, protection, placement, alignment, exclusive); if (result != 0) return failed(GuestNoMemory); return mapped; + } catch (const std::invalid_argument&) { + return failed(fixedAnonymous ? GuestInvalid : GuestNoMemory); } catch (const std::bad_alloc&) { return failed(GuestNoMemory); } catch (const std::exception&) { diff --git a/core/libs/tests/GuestMemory.cpp b/core/libs/tests/GuestMemory.cpp index ed3d3fa45080..6fc04a991751 100644 --- a/core/libs/tests/GuestMemory.cpp +++ b/core/libs/tests/GuestMemory.cpp @@ -1897,6 +1897,76 @@ static void CheckVirtualQueryForNonReadableGuestRange() { Require(sceKernelMunmap(mapped, page) == 0); } +static void CheckPosixFixedAnonymousMapping() { + constexpr std::size_t page = 0x4000; + constexpr int fixed = 0x1012; + constexpr int exclusive = 0x5012; + const auto failed = reinterpret_cast(static_cast(-1)); + void* reservation = nullptr; + Require(sceKernelReserveVirtualRange(&reservation, page * 4, 0, 0) == 0); + auto* memory = static_cast(reservation); + Require(mmap_nid_postfix(memory, page, 3, fixed, -1, 0) == memory); + Require(std::all_of(memory, memory + page, [](unsigned char value) { return value == 0; })); + memory[0] = 0x31; + memory[page - 1] = 0x32; + Require(memory[0] == 0x31 && memory[page - 1] == 0x32); + Require(mmap_nid_postfix(memory, page, 3, fixed, -1, 0) == memory); + Require(std::all_of(memory, memory + page, [](unsigned char value) { return value == 0; })); + memory[0] = 0x41; + memory[page - 1] = 0x42; + *__error_nid_postfix() = 0; + Require(mmap_nid_postfix(memory, page, 3, exclusive, -1, 0) == failed); + Require(*__error_nid_postfix() == 12); + Require(memory[0] == 0x41 && memory[page - 1] == 0x42); + VirtualQueryInfo before{}; + VirtualQueryInfo after{}; + Require(sceKernelVirtualQuery(memory + page, 0, &before, sizeof(before)) == 0); + *__error_nid_postfix() = 0; + Require(mmap_nid_postfix(memory + page, page, 3, exclusive, -1, 0) == failed); + Require(*__error_nid_postfix() == 12); + Require(sceKernelVirtualQuery(memory + page, 0, &after, sizeof(after)) == 0); + Require(before.start == after.start && before.end == after.end && before.is_committed == after.is_committed); + Require(mmap_nid_postfix(memory + page, page * 2, 3, fixed, -1, 0) == memory + page); + memory[page] = 0x51; + memory[page * 2 - 1] = 0x52; + memory[page * 2] = 0x61; + Require(sceKernelMunmap(memory + page * 3, page) == 0); + Require(mmap_nid_postfix(memory + page * 3, page, 3, exclusive, -1, 0) == memory + page * 3); + Require(std::all_of(memory + page * 3, memory + page * 4, [](unsigned char value) { return value == 0; })); + memory[page * 4 - 1] = 0x62; + Require(memory[page * 4 - 1] == 0x62); + Require(mmap_nid_postfix(memory + page * 2, page + 1, 3, fixed, -1, 0) == memory + page * 2); + Require(std::all_of(memory + page * 2, memory + page * 4, [](unsigned char value) { return value == 0; })); + Require(memory[0] == 0x41 && memory[page - 1] == 0x42); + Require(memory[page] == 0x51 && memory[page * 2 - 1] == 0x52); + memory[page * 4 - 1] = 0x71; + Require(memory[page * 4 - 1] == 0x71); + const auto invalid = [&](void* address, std::size_t length, int protection, int flags, int descriptor, std::int64_t offset) { + *__error_nid_postfix() = 0; + Require(mmap_nid_postfix(address, length, protection, flags, descriptor, offset) == failed); + Require(*__error_nid_postfix() == 22); + Require(memory[0] == 0x41 && memory[page * 4 - 1] == 0x71); + }; + invalid(memory, 0, 3, fixed, -1, 0); + invalid(memory, std::numeric_limits::max(), 3, fixed, -1, 0); + invalid(memory + 1, page, 3, fixed, -1, 0); + invalid(nullptr, page, 3, fixed, -1, 0); + invalid(memory, page, 8, fixed, -1, 0); + invalid(memory, page, 3, fixed, 0, 0); + invalid(memory, page, 3, fixed, -1, 1); + invalid(memory, page, 3, fixed, -1, -1); + invalid(nullptr, page, 3, 0x5002, -1, 0); + std::uintptr_t arenaBase = 0; + std::size_t arenaBytes = 0; + GuestArena::GuestArenaRange_nid_postfix(&arenaBase, &arenaBytes); + Require(arenaBase >= page && arenaBytes >= page); + invalid(reinterpret_cast(arenaBase - page), page, 3, fixed, -1, 0); + invalid(reinterpret_cast(arenaBase + arenaBytes), page, 3, fixed, -1, 0); + invalid(reinterpret_cast(arenaBase + arenaBytes - page), page * 2, 3, fixed, -1, 0); + invalid(reinterpret_cast(std::numeric_limits::max() - page + 1), page * 2, 3, fixed, -1, 0); + Require(munmap_nid_postfix(memory, page * 4) == 0); +} + static void CheckSceKernelMmap() { constexpr std::size_t page = 0x4000; void* mapped = nullptr; @@ -1990,10 +2060,15 @@ static void CheckMunmapOverUnmappedPages() { Require(sceKernelMunmap(memory, 0) == SCE_KERNEL_ERROR_EINVAL); } -int main() { +int main(int argc, char** argv) { #ifdef _WIN32 _putenv_s("APS5_PIN_WAIT_MS", "1000"); #endif + if (argc == 2 && std::strcmp(argv[1], "fixed-anonymous") == 0) { + CheckPosixFixedAnonymousMapping(); + return 0; + } + Require(argc == 1); CheckAvailableDirectMemoryIsLargestFreeBlock(); CheckVirtualQuerySplitFlexibleRanges(); CheckVirtualQueryForNonReadableGuestRange(); @@ -2074,7 +2149,7 @@ int main() { reject(page, 3, 0x1002, 0, 0, 22); reject(page, 3, 0x1002, -1, 1, 22); reject(page, 3, 0x1001, -1, 0, 45); // shared - reject(page, 3, 0x1012, -1, 0, 45); // fixed + reject(page, 3, 0x1012, -1, 0, 22); reject(page, 3, 0x2, 0, 0, 45); // file-backed reject(page, 3, 0x22, -1, 0, 45); // Linux MAP_ANON is not guest MAP_ANON diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 77d8d86f143a..82a1f8163f21 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -228,6 +228,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 is accepted and ignored; its meaning is not established. KytyPS5 (`GUEST_MAP_UNKNOWN_8000`) and sharpemu accept it without reading it. Every known caller is the SDK 9 `libc.prx` heap (Astro Bot PPSA21564, PPSA22520), which passes it with read/write protection and uses the mapping as an older `libc.prx` uses `sceKernelMapNamedFlexibleMemory` with flags 0 - [sceKernelMtypeprotect](../../core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp) (libkernel) - sets the memory type of the direct mappings in the page-rounded range and of the direct memory behind them, as shadPS4 and prosper do (KytyPS5 ignores the type); the type is not validated, flexible pages in the range only get the protection, and a later map of the retyped direct memory reports the type it was allocated with. `sceKernelBatchMap2` operation 4 takes the same path with the entry type - [Map hints inside a reservation](../../core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp) (libkernel) - `sceKernelMapDirectMemory` and the flexible and anonymous maps place a mapping without `MAP_FIXED` at its hint address when the whole range lies in a range still reserved by `sceKernelReserveVirtualRange`, as if `MAP_FIXED` were set. Taken from PPSA01474, which reserves 64 GiB and then maps its heaps inside it with hints and no `MAP_FIXED`, and uses the hint addresses afterwards; not measured on the console. Hints outside a reservation, or over a range that is partly mapped, stay hints +- [Fixed anonymous mmap](../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp) (libkernel) - `MAP_PRIVATE | MAP_ANON | MAP_FIXED` replaces the requested range through the existing guest mapping machinery and zeroes the new memory. `MAP_EXCL` is checked under the allocation-registry mutation lock, including virtual reservations, and returns `ENOMEM` without changing an occupied range; without `MAP_FIXED` it is `EINVAL`. Lengths are rounded to 16 KiB, while fixed addresses must be aligned and the complete rounded range must lie inside the guest arena. This follows FreeBSD 11.4 [argument validation and rounding](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_mmap.c#L226-L299), [fixed replacement](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_map.c#L1455-L1464), and [collision errno](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_mmap.c#L1604-L1613). The console behaviour has not been measured. AnyPS5 starts the guest arena at 0x200000000, so the fixed path rejects the low 0x400000 address requested by PICO-8 PPSA99808. The console address-space layout is unmeasured; executable placement outside the host arena is tracked in #5217. Static catalog disassembly finds `0x1012` in PPSA98001/PPSA99808 and `0x5012` in PPSA99808; these titles were not run. - [tzname](../../core/libs/prx/libc/src/Time.cpp) (libc) points at the host's zone names, read at load and again by `tzset`: the abbreviations a `TZ` string gives (`EST5EDT` is `EST` and `EDT` on both hosts), but on Windows without `TZ` the CRT's full names such as `GMT Standard Time`, which ICU's [uprv_tzname](https://github.com/unicode-org/icu/blob/457157a92aa053e632cc7fcfd0e12f8a943b2d11/icu4c/source/common/putil.cpp#L1244-L1264) cannot map to a zone ID. A zone with no daylight-saving time has `tzname[1]` empty on Windows and equal to `tzname[0]` on Linux, where FreeBSD leaves three spaces. The console's names are not known - [Guest arena](../../core/libs/prx/libc/src/GuestArena.cpp) (libc) - the application map area is assumed to end at 0xFC_0000_0000, as `SCE_KERNEL_APP_MAP_AREA_END_ADDR` does on the PS4. On Windows, host allocations made in the arena before libc loads stay, and a fixed guest mapping over one throws - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature From 900c36ac91ce18839c24d2d067e435de6177c3f1 Mon Sep 17 00:00:00 2001 From: Nixitov Date: Wed, 14 Oct 2026 01:20:26 +0200 Subject: [PATCH 08/23] feat(libkernel): implement setpriority A title imports setpriority and stops at start-up once getpriority is implemented. Accept PRIO_PROCESS, PRIO_PGRP and PRIO_USER for the guest's own process and fail with ESRCH for any other id and EINVAL for any other which, leaving errno unchanged on success like FreeBSD's libc; the value is not applied, since the guest nice is not the host's scheduling class. (cherry picked from commit afc04c73ad741195251f2f13f7c8e688ad40df2c) --- .../libs/prx/libkernel/System/src/Process.cpp | 22 +++++++++++++++-- core/libs/tests/GuestSchedPriority.cpp | 24 +++++++++++++++++++ docs/dev/TechnicalDebt.md | 2 +- 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libkernel/System/src/Process.cpp b/core/libs/prx/libkernel/System/src/Process.cpp index 161196864987..82986498c9c3 100644 --- a/core/libs/prx/libkernel/System/src/Process.cpp +++ b/core/libs/prx/libkernel/System/src/Process.cpp @@ -135,7 +135,9 @@ constexpr int guestRlimitFsize = 1; constexpr int guestPriorityProcess = 0; constexpr int guestPriorityGroup = 1; constexpr int guestPriorityUser = 2; -constexpr int guestNice = 0; +std::atomic guestNice{0}; +constexpr int guestNiceMin = -20; +constexpr int guestNiceMax = 20; constexpr int guestRlimitData = 2; constexpr int guestRlimitCore = 4; constexpr int guestRlimitSbsize = 9; @@ -597,7 +599,23 @@ int APS5_VABI getpriority_nid_postfix(int which, int who) { *__error_nid_postfix() = guestNoProcess; return -1; } - return guestNice; + return guestNice.load(std::memory_order_relaxed); +} + +int APS5_VABI setpriority_nid_postfix(int which, int who, int niceval) { + if (which != guestPriorityProcess && which != guestPriorityGroup && which != guestPriorityUser) { + *__error_nid_postfix() = guestInvalid; + return -1; + } + const bool found = which == guestPriorityUser ? (who == 0 ? getuid_nid_postfix() : who) == getuid_nid_postfix() + : who == 0 || who == getpid_nid_postfix(); + if (!found) { + *__error_nid_postfix() = guestNoProcess; + return -1; + } + const int clamped = niceval < guestNiceMin ? guestNiceMin : (niceval > guestNiceMax ? guestNiceMax : niceval); + guestNice.store(clamped, std::memory_order_relaxed); + return 0; } int APS5_VABI getdtablesize_nid_postfix(void) { diff --git a/core/libs/tests/GuestSchedPriority.cpp b/core/libs/tests/GuestSchedPriority.cpp index 8da97ce71017..a83bebd23102 100644 --- a/core/libs/tests/GuestSchedPriority.cpp +++ b/core/libs/tests/GuestSchedPriority.cpp @@ -6,6 +6,7 @@ extern "C" { int APS5_VABI sched_get_priority_max_nid_postfix(int policy); int APS5_VABI sched_get_priority_min_nid_postfix(int policy); int APS5_VABI getpriority_nid_postfix(int which, int who); +int APS5_VABI setpriority_nid_postfix(int which, int who, int niceval); int APS5_VABI getpid_nid_postfix(void); int* APS5_VABI __error_nid_postfix(); } @@ -27,6 +28,14 @@ static void RequireError(int which, int who, int error) { *__error_nid_postfix() = 0; Require(getpriority_nid_postfix(which, who) == -1 && *__error_nid_postfix() == error); } +static void RequireSet(int which, int who, int nice) { + *__error_nid_postfix() = 13; + Require(setpriority_nid_postfix(which, who, nice) == 0 && *__error_nid_postfix() == 13); +} +static void RequireSetError(int which, int who, int nice, int error) { + *__error_nid_postfix() = 0; + Require(setpriority_nid_postfix(which, who, nice) == -1 && *__error_nid_postfix() == error); +} int main() { Require(Rejects(-1) && Rejects(2) && Rejects(5)); for (int policy : {1, 3}) { @@ -46,4 +55,19 @@ int main() { RequireError(PrioUser, 1000, 3); RequireError(3, 0, 22); RequireError(-1, self, 22); + RequireSet(PrioProcess, 0, 0); + RequireSet(PrioProcess, self, 5); + RequireSet(PrioProcess, self, -20); + RequireSet(PrioGroup, 0, 20); + RequireSet(PrioUser, 0, -1); + RequireSetError(PrioProcess, self + 1, 0, 3); + RequireSetError(PrioProcess, -1, 0, 3); + RequireSetError(PrioGroup, self + 1, 0, 3); + RequireSetError(PrioUser, 1000, 0, 3); + RequireSetError(3, 0, 0, 22); + RequireSetError(-1, self, 0, 22); + Require(setpriority_nid_postfix(PrioProcess, 0, 10) == 0 && getpriority_nid_postfix(PrioProcess, 0) == 10); + Require(setpriority_nid_postfix(PrioProcess, 0, 99) == 0 && getpriority_nid_postfix(PrioProcess, 0) == 20); + Require(setpriority_nid_postfix(PrioProcess, 0, -99) == 0 && getpriority_nid_postfix(PrioProcess, 0) == -20); + Require(setpriority_nid_postfix(PrioProcess, 0, 0) == 0 && getpriority_nid_postfix(PrioProcess, 0) == 0); } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 82a1f8163f21..472abe2ba301 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -70,7 +70,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelGetSystemSwVersion](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports baseline system software version `0x01000000` ("01.000.000"); the console's firmware version is not modeled. Measured on PS5 firmware 13.42: record values 0, 24, 39, 40, 41, 48 and 64 in the leading 64-bit field are accepted and preserved, the 28-byte string at offset 8 and packed version at 0x24 are filled, and bytes from 0x28 onward remain untouched. This API reports "13.590.001" / `0x13590001` in that environment, while the Prospero variant reports "13.420.000" / `0x13420000`; their values must not be assumed identical. A null pointer still returns `SCE_KERNEL_ERROR_EFAULT`, which was not measured; other firmware versions and record values remain unverified. - [sysconf](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) - `_SC_CLK_TCK` returns 128, FreeBSD's `CLK_TCK` as its [`sysconf`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libc/gen/sysconf.c#L100-L101) returns it ([`time.h`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/include/time.h#L48-L54)); the console's value is not checked, and no `times` reports ticks at that rate. CPython's `posix` module stops its import with "cannot read ticks_per_second" when the value is below 1, as a guest Python runtime does. Names other than `_SC_CLK_TCK`, `_SC_PAGESIZE`, `_SC_NPROCESSORS_CONF`, `_SC_NPROCESSORS_ONLN` and `_SC_PHYS_PAGES` fail with `EINVAL` - [getdtablesize](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - throws: FreeBSD returns the smaller of the `RLIMIT_NOFILE` soft limit and `maxfilesperproc` ([`sys_getdtablesize`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L338-L355)), and neither value is known for the console, where `getrlimit(RLIMIT_NOFILE)` throws too. A guest application imports it for a `closefrom` loop in the child of its spawn helper ([libc_stubs.c](https://github.com/ZiZc3/VLC/blob/d46be6a68f4244466b041c2dc1b640915ac1a983/ps5/compat/libc_stubs.c#L66-L72)), which never runs because its `fork` fails with `ENOSYS` -- [getpriority](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) follows FreeBSD 11.4's [`sys_getpriority`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_resource.c#L93-L165) for the only guest process, which is taken to run at nice 0: `PRIO_PROCESS` and `PRIO_PGRP` with 0 or its own pid (the guest is taken to lead its own process group, see `kill`) and `PRIO_USER` with 0 or its user id 0 return 0, any other id fails with `ESRCH` and any other `which` with `EINVAL`. As in FreeBSD's libc, where `getpriority` is the bare system call, errno is left unchanged on success. The nice value of a title process on the console is unverified, and the host nice of the process or of the threads `APS5_THREAD_PRIORITY=high` raises is not reported +- [getpriority](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) follows FreeBSD 11.4's [`sys_getpriority`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_resource.c#L93-L165) for the only guest process, which is taken to run at nice 0: `PRIO_PROCESS` and `PRIO_PGRP` with 0 or its own pid (the guest is taken to lead its own process group, see `kill`) and `PRIO_USER` with 0 or its user id 0 return 0, any other id fails with `ESRCH` and any other `which` with `EINVAL`. As in FreeBSD's libc, where `getpriority` is the bare system call, errno is left unchanged on success. The nice value of a title process on the console is unverified, and the host nice of the process or of the threads `APS5_THREAD_PRIORITY=high` raises is not reported. `setpriority` accepts the same target ids (any other id fails with `ESRCH`, any other `which` with `EINVAL`), clamps the value to FreeBSD's `PRIO_MIN`-`PRIO_MAX` (-20 to 20) and stores it as the guest process's nice value, which `getpriority` returns; the host scheduling class is not changed, and whether a title process may lower the value without privilege is unverified - [chflags](../../core/libs/prx/libkernel/File/src/Stdio.cpp) (libkernel) follows FreeBSD 11.4's [`kern_chflagsat`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_syscalls.c#L2366-L2383) and UFS's [`ufs_setattr`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/ufs/ufs/ufs_vnops.c#L509-L556) for a root caller: the path lookup reports `EFAULT`, `ENOENT` and `ENOTDIR`, a flag outside the 17 UFS stores (`VNOVAL` included) `EOPNOTSUPP`, and `SF_SNAPSHOT` `EPERM`. Neither host keeps BSD file flags, so every file is taken to have none (`stat` reports `st_flags` 0): flags 0 succeed without touching the file, and any other flag throws, naming the flags. `UF_READONLY`, `UF_HIDDEN`, `UF_SYSTEM` and `UF_ARCHIVE` are FreeBSD's names for the Windows attributes but are not mapped to them: UFS stores them without enforcing them, `FILE_ATTRIBUTE_READONLY` already carries the owner write bit of `chmod` on Windows, and Linux has no equivalent a process can set without `CAP_LINUX_IMMUTABLE`. The console's filesystem types, `EROFS` on read-only mounts and the change-time update are not modelled - [pthread_setaffinity_np](../../core/libs/prx/libkernel/Pthread/Posix/Thread.cpp) (libkernel) - follows [FreeBSD 11.4](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libthr/thread/thr_affinity.c#L41-L62) libthr over `kern_cpuset_setaffinity` for the calling thread and any live guest thread: a size other than the 32-byte `cpuset_t` returns `ERANGE`, an unknown or finished thread `ESRCH`. Bits outside `sceKernelGetAvailableCpumask` are dropped and a mask with none of those bits returns `EDEADLK`, as `cpuset_setaffinity` does; the affinity is recorded on the guest thread and not applied to the host thread, and the console result is unverified - [APR reads past the end of a file](../../core/libs/prx/libkernel/Apr/src/Apr.cpp) (libkernel) - a read that reaches the current end of the file on disk copies the bytes the file has and fills the rest of the destination with zeros; a read that comes back short before that end still throws. resolves its settings file once, rewrites it one byte shorter and reads it again with the size that resolve returned. The console's behaviour for a read past the end of a file is unverified: it may zero-fill, leave the destination untouched or fail the command From 9efa82dbc068a88e2369c94413e607d7d9486bb8 Mon Sep 17 00:00:00 2001 From: akkadbakkad89 Date: Mon, 12 Oct 2026 19:40:50 +0000 Subject: [PATCH 09/23] feat(libkernel): count committed ranges in sceKernelGetPageTableStats Charge each recorded protection ranges 2 MiB granules to the gpu pool when the range has GPU-access protection bits and to the cpu pool otherwise, so the available counts reflect committed usage instead of staying at the 2048-entry budget. Follows KytyPS5s counting model. (cherry picked from commit 975ed1213df97feeeacd7fd270a7794d2b9d0a41) --- core/libs/prx/libkernel/CMakeLists.txt | 9 ++ .../libkernel/DirectMemory/DirectMemory.cpp | 14 ++ .../libkernel/DirectMemory/DirectMemory.hpp | 1 + .../prx/libkernel/DirectMemory/Export.cpp | 14 +- core/libs/tests/GuestPageTableStats.cpp | 138 ++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 6 files changed, 172 insertions(+), 5 deletions(-) create mode 100644 core/libs/tests/GuestPageTableStats.cpp diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 9c1598f6f346..2738a1318b6a 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -1201,6 +1201,15 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endforeach() + add_test_executable(guest_page_table_stats_tests ${LIBS_INCLUDE_DIR}/tests/GuestPageTableStats.cpp) + target_include_directories(guest_page_table_stats_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_page_table_stats_tests PRIVATE libkernel libc) + configure_windows_unwind(guest_page_table_stats_tests) + add_test(NAME guest_page_table_stats COMMAND guest_page_table_stats_tests) + if(WIN32) + set_tests_properties(guest_page_table_stats PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_mlock_tests ${LIBS_INCLUDE_DIR}/tests/GuestMlock.cpp) target_include_directories(guest_mlock_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_mlock_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp index abb12bfcba49..0e77ef96c9be 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp @@ -1293,6 +1293,20 @@ bool GuestProtection(uintptr_t addr, int* prot) { return true; } +void GuestPageTableUsage(std::uint64_t granularity, std::uint64_t* cpuEntries, std::uint64_t* gpuEntries) { + std::uint64_t cpu = 0; + std::uint64_t gpu = 0; + std::lock_guard lock(g_protectionLock); + for (const auto& [start, range] : g_protections) { + if (range.end <= start) continue; + const auto entries = (range.end - 1) / granularity - start / granularity + 1; + if (range.prot & 0x7) cpu += entries; + if (range.prot & GuestProtGpuReadWrite) gpu += entries; + } + *cpuEntries = cpu; + *gpuEntries = gpu; +} + bool QueryDirectMapping(std::uintptr_t address, std::uintptr_t* start, std::uintptr_t* end, std::uint64_t* offset, int* memoryType) { std::lock_guard lock(g_directLock); const auto next = g_directMappings.upper_bound(address); diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp index 8f237376bd00..035f9a25baa1 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp @@ -51,5 +51,6 @@ bool GuestReservation(std::uintptr_t addr, std::uintptr_t* start, std::uintptr_t bool GuestRangeMapped(std::uintptr_t start, std::uintptr_t end); void ForgetJitSharedMemory(int descriptor); void DuplicateJitSharedMemory(int from, int to); +void GuestPageTableUsage(std::uint64_t granularity, std::uint64_t* cpu_entries, std::uint64_t* gpu_entries); #endif \ No newline at end of file diff --git a/core/libs/prx/libkernel/DirectMemory/Export.cpp b/core/libs/prx/libkernel/DirectMemory/Export.cpp index 0556f35df56e..0214e4c3d8dd 100644 --- a/core/libs/prx/libkernel/DirectMemory/Export.cpp +++ b/core/libs/prx/libkernel/DirectMemory/Export.cpp @@ -426,11 +426,15 @@ int APS5_VABI sceKernelClearVirtualRangeName(const void* addr, uint64_t len) { int APS5_VABI sceKernelGetPageTableStats(int* cpu_total, int* cpu_available, int* gpu_total, int* gpu_available) { if (!cpu_total || !cpu_available || !gpu_total || !gpu_available) return SCE_KERNEL_ERROR_EFAULT; - constexpr int pageTableEntries = static_cast((4ull << 30) / (2ull << 20)); - *cpu_total = pageTableEntries; - *cpu_available = pageTableEntries; - *gpu_total = pageTableEntries; - *gpu_available = pageTableEntries; + constexpr std::uint64_t PageTableGranularity = 2ULL * 1024 * 1024; + constexpr std::uint64_t PageTablePoolEntries = 2048; + std::uint64_t cpuUsed = 0; + std::uint64_t gpuUsed = 0; + GuestPageTableUsage(PageTableGranularity, &cpuUsed, &gpuUsed); + *cpu_total = static_cast(PageTablePoolEntries); + *gpu_total = static_cast(PageTablePoolEntries); + *cpu_available = static_cast(cpuUsed >= PageTablePoolEntries ? 0 : PageTablePoolEntries - cpuUsed); + *gpu_available = static_cast(gpuUsed >= PageTablePoolEntries ? 0 : PageTablePoolEntries - gpuUsed); return 0; } diff --git a/core/libs/tests/GuestPageTableStats.cpp b/core/libs/tests/GuestPageTableStats.cpp new file mode 100644 index 000000000000..6a47951c8aea --- /dev/null +++ b/core/libs/tests/GuestPageTableStats.cpp @@ -0,0 +1,138 @@ +#include "prx/libc/include/general/VabiMacros.hpp" +#include "prx/libkernel/KernelErrors.hpp" + +#include +#include +#include +#include +#include + +extern "C" { +int APS5_VABI sceKernelGetPageTableStats(int*, int*, int*, int*); +int APS5_VABI sceKernelMapFlexibleMemory(void**, std::size_t, int, int); +int APS5_VABI sceKernelMapDirectMemory(void**, std::size_t, int, int, std::int64_t, std::size_t); +int APS5_VABI sceKernelAllocateDirectMemory(std::int64_t, std::int64_t, std::size_t, std::size_t, int, std::int64_t*); +int APS5_VABI sceKernelReleaseDirectMemory(std::int64_t, std::size_t); +int APS5_VABI sceKernelReserveVirtualRange(void**, std::size_t, int, std::size_t); +int APS5_VABI sceKernelMprotect(const void*, std::size_t, int); +int APS5_VABI sceKernelMunmap(void*, std::size_t); +} + +static void Require(bool condition, std::source_location location = std::source_location::current()) { + if (!condition) { + std::fprintf(stderr, "Page table stats check failed at %s:%u\n", location.file_name(), static_cast(location.line())); + std::abort(); + } +} + +constexpr std::size_t PageTableGranule = 0x200000; +constexpr int PageTableTotal = 2048; + +struct Stats { + int cpuTotal; + int cpuAvailable; + int gpuTotal; + int gpuAvailable; +}; + +static Stats Query() { + Stats stats{}; + Require(sceKernelGetPageTableStats(&stats.cpuTotal, &stats.cpuAvailable, &stats.gpuTotal, &stats.gpuAvailable) == 0); + return stats; +} + +static int Granules(const void* addr, std::size_t len) { + const auto start = reinterpret_cast(addr); + return static_cast((start + len - 1) / PageTableGranule - start / PageTableGranule + 1); +} + +static void CheckRejectedArguments() { + int value = 0; + Require(sceKernelGetPageTableStats(nullptr, &value, &value, &value) == SCE_KERNEL_ERROR_EFAULT); + Require(sceKernelGetPageTableStats(&value, nullptr, &value, &value) == SCE_KERNEL_ERROR_EFAULT); + Require(sceKernelGetPageTableStats(&value, &value, nullptr, &value) == SCE_KERNEL_ERROR_EFAULT); + Require(sceKernelGetPageTableStats(&value, &value, &value, nullptr) == SCE_KERNEL_ERROR_EFAULT); +} + +static void CheckFlexibleMapping() { + const auto before = Query(); + Require(before.cpuTotal == PageTableTotal && before.gpuTotal == PageTableTotal); + Require(before.cpuAvailable <= before.cpuTotal && before.gpuAvailable <= before.gpuTotal); + + constexpr std::size_t len = 3 * PageTableGranule; + void* mapped = nullptr; + Require(sceKernelMapFlexibleMemory(&mapped, len, 3, 0) == 0 && mapped != nullptr); + const auto entries = Granules(mapped, len); + auto during = Query(); + Require(during.cpuAvailable == before.cpuAvailable - entries); + Require(during.gpuAvailable == before.gpuAvailable); + + Require(sceKernelMprotect(mapped, len, 0x30) == 0); + during = Query(); + Require(during.cpuAvailable == before.cpuAvailable); + Require(during.gpuAvailable == before.gpuAvailable - entries); + + Require(sceKernelMunmap(mapped, len) == 0); + const auto after = Query(); + Require(after.cpuAvailable == before.cpuAvailable && after.gpuAvailable == before.gpuAvailable); +} + +static void CheckDualAccessMapping() { + const auto before = Query(); + constexpr std::size_t len = PageTableGranule; + void* mapped = nullptr; + Require(sceKernelMapFlexibleMemory(&mapped, len, 0x33, 0) == 0 && mapped != nullptr); + const auto entries = Granules(mapped, len); + const auto during = Query(); + Require(during.cpuAvailable == before.cpuAvailable - entries); + Require(during.gpuAvailable == before.gpuAvailable - entries); + Require(sceKernelMunmap(mapped, len) == 0); + const auto after = Query(); + Require(after.cpuAvailable == before.cpuAvailable && after.gpuAvailable == before.gpuAvailable); +} + +static void CheckSharedGranule() { + const auto before = Query(); + constexpr std::size_t page = 0x4000; + void* span = nullptr; + Require(sceKernelReserveVirtualRange(&span, 2 * PageTableGranule, 0, PageTableGranule) == 0 && span != nullptr); + const auto base = reinterpret_cast(span); + const auto aligned = base % PageTableGranule == 0 ? base : (base / PageTableGranule + 1) * PageTableGranule; + void* first = reinterpret_cast(aligned); + void* second = reinterpret_cast(aligned + page); + Require(sceKernelMapFlexibleMemory(&first, page, 3, 0) == 0 && first == reinterpret_cast(aligned)); + Require(sceKernelMapFlexibleMemory(&second, page, 3, 0) == 0 && second == reinterpret_cast(aligned + page)); + const auto during = Query(); + Require(during.cpuAvailable == before.cpuAvailable - 2); + Require(during.gpuAvailable == before.gpuAvailable); + Require(sceKernelMunmap(first, page) == 0); + Require(sceKernelMunmap(second, page) == 0); + const auto after = Query(); + Require(after.cpuAvailable == before.cpuAvailable && after.gpuAvailable == before.gpuAvailable); +} + +static void CheckGpuDirectMapping() { + const auto before = Query(); + constexpr std::size_t len = 2 * PageTableGranule; + std::int64_t phys = 0; + Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, len, 0, 0, &phys) == 0); + void* mapped = nullptr; + Require(sceKernelMapDirectMemory(&mapped, len, 0x33, 0, phys, 0) == 0 && mapped != nullptr); + const auto entries = Granules(mapped, len); + const auto during = Query(); + Require(during.gpuAvailable == before.gpuAvailable - entries); + Require(during.cpuAvailable == before.cpuAvailable - entries); + Require(sceKernelMunmap(mapped, len) == 0); + Require(sceKernelReleaseDirectMemory(phys, len) == 0); + const auto after = Query(); + Require(after.cpuAvailable == before.cpuAvailable && after.gpuAvailable == before.gpuAvailable); +} + +int main() { + CheckRejectedArguments(); + CheckFlexibleMapping(); + CheckDualAccessMapping(); + CheckSharedGranule(); + CheckGpuDirectMapping(); + return 0; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 472abe2ba301..baf3e024e902 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -698,6 +698,7 @@ Throughout the project, every function at every stage either **does exactly what - PPSA07411 PS VR2 imports declared without parameters, signatures unknown, added without an implementation because the title fails to load without them: [sceHmd2GetDeviceInformationByHandle, sceHmd2GetFieldOfView and sceHmd2Terminate](../../core/libs/prx/libSceHmd2/Export.cpp) (libSceHmd2), [scePadVrControllerSetVibration, scePadVrControllerSetVibrationMode and scePadVrControllerReadCombinedState](../../core/libs/prx/libScePad/Export.cpp) (libScePad) and [sceVrTracker2ResetLocalCoordinate](../../core/libs/prx/libSceVrTracker2/Export.cpp) (libSceVrTracker2) - [Descriptor pool recycling](../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) avoids individually freed sets: [RADV 26.2.2](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-26.2.2/src/amd/vulkan/radv_descriptor_pool.c) initializes its free-set heap with 32 bytes beyond the backing allocation. An allocation-only RX 6600 test reproduces acceptance of a 4,128-byte set in a 4,096-byte pool; the path without individual frees rejects it. Pools reset after their last set is released. A cached set can retain unused slots in an exhausted pool until eviction; peak gameplay pool memory remains unmeasured. - [_fstatfs](../../core/libs/prx/libkernel/File/src/Stdio.cpp) (libkernel) fills the FreeBSD 11 `struct statfs` of the PS5 payload SDK with the host volume that holds the file: block size, transfer size, total, free and available blocks, maximum name length and the read-only, `nosuid` and `noexec` flags (on Windows only read-only, and `f_files` and `f_ffree` are 0, as NTFS has no fixed number of files). The filesystem type number and name, mount paths, owner, filesystem id and I/O counters are left 0 or empty, since they would describe a host mount, not a console one. Sockets and pipes return `EINVAL`, as FreeBSD's `getvnode` does; a Windows descriptor that is neither a file nor a pipe throws. Stremio Plus (PPSA74126) reads the free space before a download and only logs the other fields +- [sceKernelGetPageTableStats](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) reports page-table entries over the recorded protection ranges (committed mappings; reservations are not recorded): each range charges one entry per 2 MiB granule it spans to the cpu pool when it has CPU access bits (0x7) and to the gpu pool when it has GPU access bits (0x30), so a range with both counts in both and two ranges sharing one granule charge it once each, as KytyPS5 sums per committed range. Mappings with no access bits, such as PROT_NONE or ACP-only protections, charge neither pool. The 2048-entry budget per side, its constants, and whether the console counts reservations or guest image segments are unverified. Resonance: A Plague Tale Legacy (PPSA30601) reaches this call after the other missing exports of its start-up are provided - [fstatvfs](../../core/libs/prx/libSceLibcInternal/FilesystemStatistics.cpp) (libSceLibcInternal) converts `_fstatfs` to the 88-byte `struct statvfs` as FreeBSD 9.2's `sfs2svfs` does (`f_bsize` from the transfer size, `f_frsize` from the block size, `f_favail` equal to `f_ffree`, `f_fsid` 0, `ST_RDONLY` and `ST_NOSUID` only). Differences: `f_namemax` is the `statfs` value, not `fpathconf(_PC_NAME_MAX)`; negative `f_bavail` and `f_ffree` wrap to unsigned without `EOVERFLOW`, as the same-width copy in FreeBSD does; inode counts are 0 on Windows, inherited from `_fstatfs`; a null output returns `EFAULT` after the descriptor is validated, where FreeBSD would fault. Layout and conversion are unverified against the PS5 library (PS5MC imports `fstatvfs` but was not run) - [sceVoiceQoSEnd](../../core/libs/prx/libSceVoiceQoS/Export.cpp) (libSceVoiceQoS) - `0x804E0901` (not initialized) before any initialization was measured on a PS5 (firmware 13.60, #1407); ending an initialized library was not, because a valid `sceVoiceQoSInit` never returns inside a homebrew payload. PPSA14632 calls it at shutdown and PPSA26344 after a nonzero `sceVoiceQoSInit`. After an initialization it returns 0 and clears the init flag, so the library can be initialized again. Whether the console also ends the libSceVoice instance that its `sceVoiceQoSInit` starts ([prosper](https://github.com/mattias800/prosper)'s reading of the module), and what it answers while endpoints exist, is unknown; no endpoint is implemented - [sceSharePlayGetCurrentConnectionInfoA](../../core/libs/prx/libSceSharePlay/Export.cpp) (libSceSharePlay) - reports no Share Play session, as the library keeps none: status 0 (DORMANT), mode 0, empty online IDs, account IDs 0 and both user IDs -1 (`SCE_USER_SERVICE_USER_ID_INVALID`). A null pointer returns `SCE_SHARE_PLAY_ERROR_INVALID_ARGS` (0x810E0001). The 72-byte `SceSharePlayConnectionInfoA` layout and the error code follow [KytyPS5](https://github.com/KytyPS5/KytyPS5/blob/main/src/libs/libNet.cpp) and [fpPS4](https://github.com/red-prig/fpPS4/blob/trunk/src/ps4_libsceshareplay.pas), which agree on both; KytyPS5 sets the user IDs to -1 and fpPS4 leaves them 0, and which one the console returns is not verified. KytyPS5 also returns `SCE_SHARE_PLAY_ERROR_NOT_INITIALIZED` before `sceSharePlayInitialize`; this library keeps no initialization state and does not. From fea2f0208a23e45aeb10afc2f3e2ab3ab4f364e5 Mon Sep 17 00:00:00 2001 From: Sanxchep Sharma Date: Tue, 13 Oct 2026 14:07:56 +0200 Subject: [PATCH 10/23] perf(relinker): stream scans and reuse executable buffers Partial port: the streamed instruction scans (VisitCodeSection in the instruction scanner, the syscall scanner and the call-site resolver) are kept. The executable-buffer reuse and scan progress reporting are not, because this fork's relinker pipeline has no progress reporting and a different conversion entry point. (cherry picked from commit 94ae3f1bfe85636f954596902e1b1b7f59479546) --- .../include/codegen/IInstructionScanner.hpp | 8 ++ .../codegen/src/InstructionScanner.cpp | 22 ++++- .../src/analysis/CallSiteResolver.cpp | 82 +++++++------------ .../relinker/src/analysis/SyscallScanner.cpp | 65 ++++++++------- .../relinker/tests/CallSiteResolverTests.cpp | 4 + 5 files changed, 96 insertions(+), 85 deletions(-) diff --git a/core/relinker/codegen/include/codegen/IInstructionScanner.hpp b/core/relinker/codegen/include/codegen/IInstructionScanner.hpp index 1f639525f568..a437ed7c9e44 100644 --- a/core/relinker/codegen/include/codegen/IInstructionScanner.hpp +++ b/core/relinker/codegen/include/codegen/IInstructionScanner.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -17,6 +18,13 @@ class IInstructionScanner { Domain::FileByteOffset codeSectionOffset, Domain::FileByteOffset codeSectionSize ) const = 0; + + virtual void VisitCodeSection( + const std::vector& codeSection, + Domain::FileByteOffset codeSectionOffset, + Domain::FileByteOffset codeSectionSize, + const std::function& visit + ) const = 0; }; std::unique_ptr MakeInstructionScanner(); diff --git a/core/relinker/codegen/src/InstructionScanner.cpp b/core/relinker/codegen/src/InstructionScanner.cpp index 921420e3e8a5..d52c8bc250ca 100644 --- a/core/relinker/codegen/src/InstructionScanner.cpp +++ b/core/relinker/codegen/src/InstructionScanner.cpp @@ -15,18 +15,24 @@ class InstructionScanner : public IInstructionScanner { Domain::FileByteOffset codeSectionOffset, Domain::FileByteOffset codeSectionSize ) const override; + void VisitCodeSection( + const std::vector& codeSection, + Domain::FileByteOffset codeSectionOffset, + Domain::FileByteOffset codeSectionSize, + const std::function& visit + ) const override; }; -std::vector InstructionScanner::ScanCodeSection( +void InstructionScanner::VisitCodeSection( const std::vector& codeSection, const Domain::FileByteOffset codeSectionOffset, - const Domain::FileByteOffset codeSectionSize + const Domain::FileByteOffset codeSectionSize, + const std::function& visit ) const { if (codeSectionSize > std::numeric_limits::max() - codeSectionOffset) throw CodegenException("Code section offset overflow", codeSectionOffset); const std::size_t limit = std::min(codeSection.size(), static_cast(codeSectionSize)); const X64InstructionDecoder decoder; - std::vector matches; std::size_t i = 0; while (i < limit) { @@ -41,11 +47,19 @@ std::vector InstructionScanner::ScanCodeSection( throw CodegenException(std::string("Cannot decode instruction: ") + e.what(), codeSectionOffset + i); } - matches.push_back({codeSectionOffset + i, length}); + visit({codeSectionOffset + i, length}); i += length; } +} +std::vector InstructionScanner::ScanCodeSection( + const std::vector& codeSection, + const Domain::FileByteOffset codeSectionOffset, + const Domain::FileByteOffset codeSectionSize +) const { + std::vector matches; + VisitCodeSection(codeSection, codeSectionOffset, codeSectionSize, [&](const InstructionMatch& match) { matches.push_back(match); }); return matches; } diff --git a/core/relinker/relinker/src/analysis/CallSiteResolver.cpp b/core/relinker/relinker/src/analysis/CallSiteResolver.cpp index 120e7abac6da..63a1b2450cf1 100644 --- a/core/relinker/relinker/src/analysis/CallSiteResolver.cpp +++ b/core/relinker/relinker/src/analysis/CallSiteResolver.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -18,52 +19,33 @@ std::int32_t readDisp32(const std::vector& text, std::size_t offse return static_cast(v); } -bool isRipRelativeFF(const std::vector& text, const Codegen::InstructionMatch& m) { - std::size_t cur = static_cast(m.Offset); - std::size_t end = cur + m.Length; - while (cur < end) { - std::uint8_t b = text[cur]; - if (b >= RexMin && b <= RexMax) { ++cur; continue; } - if (b == OneByteGrp5Rm && cur + 2 <= end) { - std::uint8_t modrm = text[cur + 1]; - std::uint8_t mod = (modrm >> ModRmModShift) & ModRmModMask; - std::uint8_t rm = modrm & ModRmRmMask; - const auto operation = (modrm >> ModRmRegShift) & ModRmRegMask; - return mod == ModRmModIndirect && rm == ModRmRmRipRelative && (operation >= 2 && operation <= 6); - } - break; - } - return false; -} - -std::size_t ffDispOffset(const std::vector& text, const Codegen::InstructionMatch& m) { - std::size_t cur = static_cast(m.Offset); - while (text[cur] >= RexMin && text[cur] <= RexMax) ++cur; - return cur + 2; -} - -bool isRipRelativeMov64(const std::vector& text, const Codegen::InstructionMatch& m) { +std::optional ripRelativeDispOffset(const std::vector& text, const Codegen::InstructionMatch& m) { std::size_t cur = static_cast(m.Offset); std::size_t end = cur + m.Length; bool hasRexW = false; while (cur < end) { std::uint8_t b = text[cur]; - if (b >= RexMin && b <= RexMax) { if (b & RexWBit) hasRexW = true; ++cur; continue; } - if (hasRexW && b == OneByteModRmRangeJMax && cur + 2 <= end) { - std::uint8_t modrm = text[cur + 1]; - std::uint8_t mod = (modrm >> ModRmModShift) & ModRmModMask; - std::uint8_t rm = modrm & ModRmRmMask; - return mod == ModRmModIndirect && rm == ModRmRmRipRelative; + if (b >= RexMin && b <= RexMax) { + if (b & RexWBit) hasRexW = true; + ++cur; + continue; } break; } - return false; -} - -std::size_t mov64DispOffset(const std::vector& text, const Codegen::InstructionMatch& m) { - std::size_t cur = static_cast(m.Offset); - while (text[cur] >= RexMin && text[cur] <= RexMax) ++cur; - return cur + 2; + if (cur + 2 > end) return std::nullopt; + const std::uint8_t opcode = text[cur]; + if (opcode != OneByteGrp5Rm && (!hasRexW || opcode != OneByteModRmRangeJMax)) + return std::nullopt; + const std::uint8_t modrm = text[cur + 1]; + const std::uint8_t mod = (modrm >> ModRmModShift) & ModRmModMask; + const std::uint8_t rm = modrm & ModRmRmMask; + if (mod != ModRmModIndirect || rm != ModRmRmRipRelative) return std::nullopt; + const auto operation = (modrm >> ModRmRegShift) & ModRmRegMask; + if (opcode == OneByteGrp5Rm && operation >= 2 && operation <= 6) + return cur + 2; + if (opcode == OneByteModRmRangeJMax && hasRexW) + return cur + 2; + return std::nullopt; } } @@ -84,26 +66,20 @@ std::vector CallSiteResolver::ResolveCallSites(const std::vector if (textSection.empty()) return {}; if (_cachedTextPtr != &textSection || _cachedTextVAddr != textSectionVAddr) { auto scanner = Codegen::MakeInstructionScanner(); - auto instructions = scanner->ScanCodeSection(textSection, 0, textSection.size()); _cachedTargetToInstr.clear(); - const auto referenceCount = std::count_if(instructions.begin(), instructions.end(), [&](const auto& match) { - return isRipRelativeFF(textSection, match) || isRipRelativeMov64(textSection, match); + const auto candidateCount = std::count_if(textSection.begin(), textSection.end(), [](std::uint8_t b) { + return b == OneByteGrp5Rm || b == OneByteModRmRangeJMax; }); - _cachedTargetToInstr.reserve(static_cast(referenceCount)); - for (const auto& m : instructions) { - std::size_t dispOff = 0; - if (isRipRelativeFF(textSection, m)) - dispOff = ffDispOffset(textSection, m); - else if (isRipRelativeMov64(textSection, m)) - dispOff = mov64DispOffset(textSection, m); - else - continue; - if (dispOff + 4 > textSection.size()) continue; - std::int32_t disp = readDisp32(textSection, dispOff); + constexpr std::size_t MinRipRelativeInstructionBytes = 6; + _cachedTargetToInstr.reserve(std::min(static_cast(candidateCount), textSection.size() / MinRipRelativeInstructionBytes)); + scanner->VisitCodeSection(textSection, 0, textSection.size(), [&](const Codegen::InstructionMatch& m) { + const auto dispOff = ripRelativeDispOffset(textSection, m); + if (!dispOff || *dispOff + 4 > textSection.size()) return; + std::int32_t disp = readDisp32(textSection, *dispOff); VirtualAddress instrEnd = textSectionVAddr + m.Offset + static_cast(m.Length); VirtualAddress target = instrEnd + static_cast(static_cast(disp)); _cachedTargetToInstr.emplace_back(target, m.Offset); - } + }); std::sort(_cachedTargetToInstr.begin(), _cachedTargetToInstr.end()); _cachedTextPtr = &textSection; _cachedTextVAddr = textSectionVAddr; diff --git a/core/relinker/relinker/src/analysis/SyscallScanner.cpp b/core/relinker/relinker/src/analysis/SyscallScanner.cpp index f83eb1eead40..5b4e47de6c0f 100644 --- a/core/relinker/relinker/src/analysis/SyscallScanner.cpp +++ b/core/relinker/relinker/src/analysis/SyscallScanner.cpp @@ -70,23 +70,37 @@ static constexpr std::array SDK_MMAP_EXEC_INLINE{ 0x49, 0x89, 0xC7, 0x49, 0xF7, 0xDF, 0x84, 0xC9, 0x4C, 0x0F, 0x45, 0xF8, 0x4D, 0x85, 0xFF, }; +struct RecentInstructions { + static constexpr std::size_t Capacity = 64; + std::array matches{}; + std::size_t count = 0; + + void Push(const Codegen::InstructionMatch& match) { + matches[count % Capacity] = match; + ++count; + } + + [[nodiscard]] const Codegen::InstructionMatch& Before(std::size_t step) const { + return matches[(count - 1 - step) % Capacity]; + } + + [[nodiscard]] bool Contains(FileByteOffset offset) const { + for (std::size_t step = 0; step < std::min(count, Capacity); ++step) + if (Before(step).Offset == offset) return true; + return false; + } +}; + template -static bool MatchesSdkInlineStub(const std::vector& code, std::size_t syscallOffset, std::size_t limit, - const std::array& pattern, std::size_t beforeSyscall, - const std::vector& matches, FileByteOffset codeOffset) { +static bool MatchesSdkInlineStub(const std::vector& code, std::size_t syscallOffset, std::size_t limit, const std::array& pattern, std::size_t beforeSyscall, const RecentInstructions& recent, FileByteOffset codeOffset) { if (syscallOffset < beforeSyscall || syscallOffset > limit) return false; const auto start = syscallOffset - beforeSyscall; if (pattern.size() > limit - start || !std::equal(pattern.begin(), pattern.end(), code.begin() + static_cast(start))) return false; - const auto instruction = std::lower_bound(matches.begin(), matches.end(), codeOffset + start, - [](const Codegen::InstructionMatch& match, FileByteOffset offset) { return match.Offset < offset; }); - return instruction != matches.end() && instruction->Offset == codeOffset + start; + return recent.Contains(codeOffset + start); } -static bool IsSdkMmanSyscallStub(const std::vector& code, std::size_t syscallOffset, std::size_t limit, - const std::vector& matches, FileByteOffset codeOffset) { - return MatchesSdkInlineStub(code, syscallOffset, limit, SDK_MPROTECT_INLINE, 42, matches, codeOffset) - || MatchesSdkInlineStub(code, syscallOffset, limit, SDK_MMAP_INLINE, 17, matches, codeOffset) - || MatchesSdkInlineStub(code, syscallOffset, limit, SDK_MMAP_EXEC_INLINE, 23, matches, codeOffset); +static bool IsSdkMmanSyscallStub(const std::vector& code, std::size_t syscallOffset, std::size_t limit, const RecentInstructions& recent, FileByteOffset codeOffset) { + return MatchesSdkInlineStub(code, syscallOffset, limit, SDK_MPROTECT_INLINE, 42, recent, codeOffset) || MatchesSdkInlineStub(code, syscallOffset, limit, SDK_MMAP_INLINE, 17, recent, codeOffset) || MatchesSdkInlineStub(code, syscallOffset, limit, SDK_MMAP_EXEC_INLINE, 23, recent, codeOffset); } static ForbiddenInstruction ClassifyForbiddenInstruction( @@ -133,13 +147,9 @@ static std::optional ConstantRaxLoad(const std::uint8_t* bytes, c return std::nullopt; } -static std::optional ConstantSyscallNumber( - const std::vector& codeSection, - const FileByteOffset codeSectionOffset, - const std::vector& matches, - const std::size_t syscallIndex) { - for (std::size_t step = 1; step <= SYSCALL_NUMBER_LOOKBACK && step <= syscallIndex; ++step) { - const auto& match = matches[syscallIndex - step]; +static std::optional ConstantSyscallNumber(const std::vector& codeSection, const FileByteOffset codeSectionOffset, const RecentInstructions& recent) { + for (std::size_t step = 1; step <= SYSCALL_NUMBER_LOOKBACK && step < recent.count; ++step) { + const auto& match = recent.Before(step); const std::size_t start = static_cast(match.Offset - codeSectionOffset); if (start >= codeSection.size() || match.Length > codeSection.size() - start) @@ -181,12 +191,11 @@ std::vector SyscallScanner::ScanCodeSectionForSyscalls( const FileByteOffset codeSectionSize) { const std::size_t limit = std::min(codeSection.size(), static_cast(codeSectionSize)); - const auto scanner = Codegen::MakeInstructionScanner(); - const auto matches = scanner->ScanCodeSection(codeSection, codeSectionOffset, codeSectionSize); - + RecentInstructions recent; std::vector trapped; - for (std::size_t index = 0; index < matches.size(); ++index) { - const auto& match = matches[index]; + const auto scanner = Codegen::MakeInstructionScanner(); + scanner->VisitCodeSection(codeSection, codeSectionOffset, codeSectionSize, [&](const Codegen::InstructionMatch& match) { + recent.Push(match); const std::size_t start = static_cast(match.Offset - codeSectionOffset); const auto opcodeOffset = Codegen::DecodedInstruction{codeSection.data() + start, match.Length}.OpcodeOffset(); const std::size_t opcode = start + opcodeOffset; @@ -195,24 +204,24 @@ std::vector SyscallScanner::ScanCodeSectionForSyscalls( const auto kind = ClassifyForbiddenInstruction(codeSection, opcode, spanLimit); if (kind == ForbiddenInstruction::None) - continue; + return; if (_trapSdkStubs && kind == ForbiddenInstruction::Invocation && - (IsSdkSyscallStub(codeSection, opcode) || IsSdkMmanSyscallStub(codeSection, opcode, limit, matches, codeSectionOffset))) { + (IsSdkSyscallStub(codeSection, opcode) || IsSdkMmanSyscallStub(codeSection, opcode, limit, recent, codeSectionOffset))) { trapped.push_back(opcode); std::cout << "Trapping SDK syscall instruction at code offset 0x" << std::hex << match.Offset << std::dec << '\n'; - continue; + return; } std::ostringstream msg; msg << "Forbidden syscall instruction at code offset 0x" << std::hex << match.Offset; if (kind == ForbiddenInstruction::Invocation) - if (const auto number = ConstantSyscallNumber(codeSection, codeSectionOffset, matches, index)) + if (const auto number = ConstantSyscallNumber(codeSection, codeSectionOffset, recent)) msg << ": syscall number " << std::dec << *number; throw RelinkerException(msg.str(), match.Offset); - } + }); return trapped; } diff --git a/core/relinker/relinker/tests/CallSiteResolverTests.cpp b/core/relinker/relinker/tests/CallSiteResolverTests.cpp index f780307eb3fa..f06fab07fa5f 100644 --- a/core/relinker/relinker/tests/CallSiteResolverTests.cpp +++ b/core/relinker/relinker/tests/CallSiteResolverTests.cpp @@ -29,6 +29,10 @@ int main() { check("far indirect call", {0xff, 0x1d, 0xfa, 0, 0, 0}, true); check("far indirect jump", {0xff, 0x2d, 0xfa, 0, 0, 0}, true); check("RIP-relative function pointer load", {0x48, 0x8b, 0x05, 0xf9, 0, 0, 0}, true); + check("REX-prefixed indirect call", {0x48, 0xff, 0x15, 0xf9, 0, 0, 0}, true); + check("multiple REX prefixes on pointer load", {0x40, 0x48, 0x8b, 0x05, 0xf8, 0, 0, 0}, true); + check("pointer load without REX.W", {0x40, 0x8b, 0x05, 0xf9, 0, 0, 0}, false); + check("register pointer load", {0x48, 0x8b, 0x00}, false); check("increment memory", {0xff, 0x05, 0xfa, 0, 0, 0}, false); check("decrement memory", {0xff, 0x0d, 0xfa, 0, 0, 0}, false); check("push memory", {0xff, 0x35, 0xfa, 0, 0, 0}, true); From 29b110de0cc8cf16a2cd9886d057814079deeec1 Mon Sep 17 00:00:00 2001 From: Yossi Yadgar Date: Tue, 13 Oct 2026 12:45:34 +0300 Subject: [PATCH 11/23] feat(libkernel): map regular files with mmap on Linux (cherry picked from commit bc71ffb4336aec760304b66664d8e3aa465bd974) --- core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp b/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp index 9b660c8dcbd3..6754109203ec 100644 --- a/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp +++ b/core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp @@ -11,6 +11,7 @@ #include #if defined(__linux__) #include +#include #include #endif @@ -61,6 +62,11 @@ class ScopedDescriptor { int descriptor = -1; int error = 0; }; + +bool RegularFile(int descriptor) { + struct stat status{}; + return ::fstat(descriptor, &status) == 0 && S_ISREG(status.st_mode); +} #endif bool RoundLength(std::size_t length, std::size_t& rounded) { @@ -138,7 +144,7 @@ void* APS5_VABI mmap_nid_postfix(void* address, std::size_t length, int protecti const int accessMode = descriptorFlags & O_ACCMODE; if ((protection & 1) != 0 && accessMode == O_WRONLY) return failed(GuestAccess); if (kind == GuestShared && (protection & 2) != 0 && accessMode == O_RDONLY) return failed(GuestAccess); - if (!File::IsSharedMemoryDescriptor_nid_no_patch(mappingDescriptor)) return failed(GuestNotSupported); + if (!File::IsSharedMemoryDescriptor_nid_no_patch(mappingDescriptor) && !RegularFile(mappingDescriptor)) return failed(GuestNotSupported); #else const int mappingDescriptor = descriptor; if (!File::IsSharedMemoryDescriptor_nid_no_patch(mappingDescriptor)) return failed(GuestNotSupported); From b4535361085fe2804f7ed1d08ec0be3e5cb78eda Mon Sep 17 00:00:00 2001 From: Yossi Yadgar Date: Tue, 13 Oct 2026 12:45:34 +0300 Subject: [PATCH 12/23] test(libkernel): cover shared and private mappings of a regular file (cherry picked from commit e53268d9e93f7a34d6701efa7b3fd7e69e2207e2) --- core/libs/tests/GuestMemory.cpp | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/core/libs/tests/GuestMemory.cpp b/core/libs/tests/GuestMemory.cpp index 6fc04a991751..8542b531d9be 100644 --- a/core/libs/tests/GuestMemory.cpp +++ b/core/libs/tests/GuestMemory.cpp @@ -1638,6 +1638,55 @@ static void CheckDirectMemoryBackingNeedsNoFilesystem() { Require(sceKernelReleaseDirectMemory(phys, page) == 0); } +static void CheckRegularFileMapping() { + constexpr std::size_t page = 0x4000; + const auto path = std::filesystem::path("anyps5-file-mapping-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".bin"); + { + std::ofstream stream(path, std::ios::binary); + std::vector seed(page * 2, 0x11); + std::fill(seed.begin() + page, seed.end(), 0x22); + stream.write(seed.data(), static_cast(seed.size())); + } + const auto byteAt = [&](int fd, std::int64_t offset) { + unsigned char byte = 0; + Require(sceKernelPread(fd, &byte, 1, offset) == 1); + return byte; + }; + const int fd = sceKernelOpen(path.string().c_str(), SCE_KERNEL_O_RDWR, 0); + Require(fd >= 0); + auto* shared = static_cast(mmap_nid_postfix(nullptr, page * 2, 3, 0x1, fd, 0)); + Require(shared != reinterpret_cast(static_cast(-1))); + Require(shared[0] == 0x11 && shared[page] == 0x22); + shared[5] = 0x77; + Require(munmap_nid_postfix(const_cast(shared), page * 2) == 0); + Require(byteAt(fd, 5) == 0x77); + auto* privateCopy = static_cast(mmap_nid_postfix(nullptr, page, 3, 0x2, fd, 0)); + Require(privateCopy != reinterpret_cast(static_cast(-1))); + Require(privateCopy[5] == 0x77); + privateCopy[6] = 0x66; + Require(munmap_nid_postfix(const_cast(privateCopy), page) == 0); + Require(byteAt(fd, 6) == 0x11); + auto* second = static_cast(mmap_nid_postfix(nullptr, page, 1, 0x1, fd, page)); + Require(second != reinterpret_cast(static_cast(-1)) && second[0] == 0x22); + Require(munmap_nid_postfix(const_cast(second), page) == 0); + Require(sceKernelClose(fd) == 0); + const int readOnly = sceKernelOpen(path.string().c_str(), SCE_KERNEL_O_RDONLY, 0); + Require(readOnly >= 0); + *__error_nid_postfix() = 0; + Require(mmap_nid_postfix(nullptr, page, 3, 0x1, readOnly, 0) == reinterpret_cast(static_cast(-1)) && *__error_nid_postfix() == 13); + auto* readable = static_cast(mmap_nid_postfix(nullptr, page, 1, 0x1, readOnly, 0)); + Require(readable != reinterpret_cast(static_cast(-1)) && readable[5] == 0x77); + Require(munmap_nid_postfix(const_cast(readable), page) == 0); + Require(sceKernelClose(readOnly) == 0); + int ends[2] = {-1, -1}; + Require(pipe(ends) == 0); + *__error_nid_postfix() = 0; + Require(mmap_nid_postfix(nullptr, page, 1, 0x1, ends[0], 0) == reinterpret_cast(static_cast(-1)) && *__error_nid_postfix() == 45); + close(ends[0]); + close(ends[1]); + std::filesystem::remove(path); +} + static void CheckDirectMemorySharedBacking() { constexpr std::size_t page = 0x4000; std::int64_t phys = 0; @@ -2134,6 +2183,7 @@ int main(int argc, char** argv) { CheckDirectMemorySharedBacking(); CheckVirtualQueryFindsNeighbours(); CheckReleaseFindsEveryDirectMapping(); + CheckRegularFileMapping(); #endif constexpr std::size_t page = 0x4000; const auto failed = reinterpret_cast(static_cast(-1)); From aafb249c8a9639dcdc266f0ad0350416b8f7ad46 Mon Sep 17 00:00:00 2001 From: Yossi Yadgar Date: Tue, 13 Oct 2026 12:45:34 +0300 Subject: [PATCH 13/23] docs(debt): note regular file mappings of mmap (cherry picked from commit 6b8ddfb5dea6715ff90b156db24e0ad212e949e0) --- docs/dev/TechnicalDebt.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index baf3e024e902..629a29df8142 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -690,6 +690,7 @@ Throughout the project, every function at every stage either **does exactly what - [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. The return values and error codes are unverified on a console - [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_GETFL`, `F_SETFL` with `O_NONBLOCK`, `EINVAL` for every other command, `F_GETFD` and `F_SETFD` included). 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_GETFL` takes the access mode from the host (the granted access of the handle on Windows), so pipe ends report `O_RDONLY` and `O_WRONLY` where FreeBSD's bidirectional pipes report `O_RDWR`. `F_DUPFD` and `F_DUPFD_CLOEXEC` return 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. Changing `O_APPEND` on a Windows file, changing `O_FSYNC` on a file, `O_ASYNC` on a pipe or character device (`SIGIO` is not delivered), `F_GETOWN`, `F_SETOWN` and `F_SETLK_REMOTE` throw; `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 throw on Windows, and `F_GETLK` with `F_UNLCK` throws. The return values and error codes are unverified on a console - [ioctl, _ioctl](../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) handle only `FIONBIO` and `FIONREAD` on a socket, and any other request there fails with `ENOTTY`. On the other descriptors they follow FreeBSD's [`kern_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/sys_generic.c#L758), [`vn_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_vnops.c#L1488) and [`pipe_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/sys_pipe.c#L1346): `FIONBIO` sets `O_NONBLOCK` as `fcntl` does, `FIOCLEX` and `FIONCLEX` set and clear the close-on-exec flag `F_GETFD` reports, and `FIONREAD` reports the size past the offset of a file, the queued bytes of a pipe's read end, 0 on its write end and `ENOTTY` on the random device, while it throws on a directory or another character device. Every termios request (group `t`, `TIOCGWINSZ` included) fails with `ENOTTY`, since those descriptors are taken as not a terminal, as in `tcgetattr`, and any other request throws. Stremio Plus imports `_ioctl` for its statically linked `tc*` functions, which send `TIOCGETA`, `TIOCSETA`, `TIOCSPGRP` and the other termios requests +- [Regular file mappings](../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp) (libkernel) - on Linux `mmap` maps a regular file's descriptor shared or private like a shared memory object, with the same access checks; SQLite's WAL index (`-shm`) needs it. FreeBSD 11 `mmap(2)` and shadPS4's `MemoryManager::MapFile` map regular files; the console's behaviour is not measured. Other descriptors (pipes, sockets, directories, devices) still fail with `EOPNOTSUPP`, and Windows maps no files. - [pthread_kill](../../core/libs/prx/libkernel/System/src/Signals.cpp) (libkernel) returns the error number like FreeBSD's `pthread_kill`: `EINVAL` for signals outside 0 to 128 and `ESRCH` for a null thread. Signal 0 reports any other thread handle as existing, without checking that the thread is still alive. A signal to the calling thread goes through `raise`, so it shares `raise`'s limits; a signal to another thread throws, since guest signals are not delivered to a chosen thread - [select](../../core/libs/prx/libkernel/Socket/src/Socket.cpp) (libkernel) validates `tv_usec` but saturates a valid timeout beyond the remaining `steady_clock` range at `time_point::max()`, so the wait can continue effectively indefinitely. The console's behavior for a valid timeout outside the host clock's range is unknown. - [AJM](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp), [APR](../../core/libs/prx/libkernel/Apr/src/Apr.cpp) and [NGS2](../../core/libs/prx/libSceNgs2.native/src/System.cpp) state is allocated with `new` and never freed on purpose: title threads still call into these libraries while `std::exit` runs static destructors, so ordinary statics would be destroyed under them. Keep them leaked; `guest_ajm_teardown` covers the AJM case on Unix. From 20ec58d599c99e26a5ec413b682045401ae73dd8 Mon Sep 17 00:00:00 2001 From: p3nicillin Date: Tue, 13 Oct 2026 14:45:17 +0100 Subject: [PATCH 14/23] feat(libkernel): report RLIMIT_NOFILE through getrlimit A title queries RLIMIT_NOFILE at start-up in QEMU's os_setup_limits and stopped on the unsupported resource. It reports the descriptor count after which AnyPS5 fails with EMFILE: the C runtime's 8192 low-level descriptors on Windows and the host limit on Linux. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1aaec9728d328b686565082ce3932177b8dbce4e) --- .../libs/prx/libkernel/System/src/Process.cpp | 15 +++++++++ core/libs/tests/GuestGetrlimit.cpp | 33 ++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libkernel/System/src/Process.cpp b/core/libs/prx/libkernel/System/src/Process.cpp index 82986498c9c3..c85f5e7c1653 100644 --- a/core/libs/prx/libkernel/System/src/Process.cpp +++ b/core/libs/prx/libkernel/System/src/Process.cpp @@ -140,6 +140,7 @@ constexpr int guestNiceMin = -20; constexpr int guestNiceMax = 20; constexpr int guestRlimitData = 2; constexpr int guestRlimitCore = 4; +constexpr int guestRlimitNofile = 8; constexpr int guestRlimitSbsize = 9; constexpr int guestRlimitVmem = 10; constexpr int guestRlimitNpts = 11; @@ -568,6 +569,20 @@ int APS5_VABI getrlimit_nid_postfix(int resource, GuestResourceLimit* limit) { throw std::system_error(errno, std::generic_category(), "getrlimit: getrlimit failed"); limit->rlim_cur = toGuestLimit(native.rlim_cur); limit->rlim_max = toGuestLimit(native.rlim_max); +#endif + return 0; + } + case guestRlimitNofile: { +#ifdef _WIN32 + constexpr std::int64_t crtDescriptors = 8192; + limit->rlim_cur = crtDescriptors; + limit->rlim_max = crtDescriptors; +#else + rlimit native{}; + if (::getrlimit(RLIMIT_NOFILE, &native) != 0) + throw std::system_error(errno, std::generic_category(), "getrlimit: getrlimit failed"); + limit->rlim_cur = toGuestLimit(native.rlim_cur); + limit->rlim_max = toGuestLimit(native.rlim_max); #endif return 0; } diff --git a/core/libs/tests/GuestGetrlimit.cpp b/core/libs/tests/GuestGetrlimit.cpp index 5312d114f100..b02f16a2879b 100644 --- a/core/libs/tests/GuestGetrlimit.cpp +++ b/core/libs/tests/GuestGetrlimit.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #ifndef _WIN32 #include #endif @@ -16,6 +17,9 @@ struct ResourceLimit { extern "C" int APS5_VABI getrlimit_nid_postfix(int resource, ResourceLimit* limit); extern "C" int* APS5_VABI __error_nid_postfix(); extern "C" int APS5_VABI getdtablesize_nid_postfix(void); +extern "C" int APS5_VABI setrlimit_nid_postfix(int resource, const ResourceLimit* limit); +extern "C" int APS5_VABI pipe_nid_postfix(int* descriptors); +extern "C" int APS5_VABI close_nid_postfix(int descriptor); static constexpr int GUEST_EFAULT = 14; static constexpr int GUEST_EINVAL = 22; @@ -46,6 +50,33 @@ static ResourceLimit GuestLimit(int resource) { return limit; } +static void CheckOpenFileLimit() { + constexpr int GUEST_EMFILE = 24; + const ResourceLimit limit = GuestLimit(GUEST_RLIMIT_NOFILE); + Require(limit.rlim_cur == limit.rlim_max); +#ifdef _WIN32 + Require(limit.rlim_cur == 8192); + std::vector descriptors; + int pair[2]{-1, -1}; + *__error_nid_postfix() = 0; + while (pipe_nid_postfix(pair) == 0) { + Require(pair[0] >= 0 && pair[0] < limit.rlim_cur && pair[1] >= 0 && pair[1] < limit.rlim_cur); + descriptors.push_back(pair[0]); + descriptors.push_back(pair[1]); + Require(descriptors.size() <= static_cast(limit.rlim_cur)); + } + Require(*__error_nid_postfix() == GUEST_EMFILE); + Require(descriptors.size() + 64 >= static_cast(limit.rlim_cur)); + for (const int descriptor : descriptors) Require(close_nid_postfix(descriptor) == 0); +#else + rlimit host{}; + Require(getrlimit(RLIMIT_NOFILE, &host) == 0); + Require(host.rlim_cur == host.rlim_max); + Require(host.rlim_cur == RLIM_INFINITY ? limit.rlim_cur == GUEST_RLIM_INFINITY : limit.rlim_cur == static_cast(host.rlim_cur)); +#endif + Require(setrlimit_nid_postfix(GUEST_RLIMIT_NOFILE, &limit) == 0); +} + static void RequireError(int resource, ResourceLimit* limit, int error) { *__error_nid_postfix() = 0; Require(getrlimit_nid_postfix(resource, limit) == -1); @@ -121,7 +152,6 @@ int main() { GUEST_RLIMIT_RSS, GUEST_RLIMIT_MEMLOCK, GUEST_RLIMIT_NPROC, - GUEST_RLIMIT_NOFILE, }) { RequireUnsupported(resource); } @@ -132,4 +162,5 @@ int main() { unsupported = true; } Require(unsupported); + CheckOpenFileLimit(); } From 659c30274e1301294d54cc0a80f0582e553d99f4 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Wed, 14 Oct 2026 20:29:57 +1300 Subject: [PATCH 15/23] feat(libkernel): stop at start-up on a host CPU without the PS5's extensions Titles run natively, so a host CPU without an extension that compiled Zen 2 code uses faults with an illegal instruction deep inside a title (#3719: SHLX, BMI2). libkernel now reads CPUID and XCR0 when it loads on Linux and Windows, logs the host CPU's extensions and throws, naming the CPU and the missing extensions, before any title code runs. (cherry picked from commit 83a268a8678b364b3edef6451906afba1a7fd1ce) --- core/libs/prx/libkernel/CMakeLists.txt | 10 + .../prx/libkernel/System/include/HostCpu.hpp | 31 +++ .../libs/prx/libkernel/System/src/HostCpu.cpp | 199 ++++++++++++++++++ .../System/src/SystemConfiguration.cpp | 18 +- core/libs/tests/HostCpu.cpp | 139 ++++++++++++ docs/user/USAGE.md | 2 + 6 files changed, 382 insertions(+), 17 deletions(-) create mode 100644 core/libs/prx/libkernel/System/include/HostCpu.hpp create mode 100644 core/libs/prx/libkernel/System/src/HostCpu.cpp create mode 100644 core/libs/tests/HostCpu.cpp diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 2738a1318b6a..146db866249d 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -64,6 +64,7 @@ add_library(libkernel SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/System/src/Rtld.cpp ${CMAKE_CURRENT_SOURCE_DIR}/System/src/Process.cpp ${CMAKE_CURRENT_SOURCE_DIR}/System/src/Sandbox.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/System/src/HostCpu.cpp ${CMAKE_CURRENT_SOURCE_DIR}/System/src/SystemConfiguration.cpp ${CMAKE_CURRENT_SOURCE_DIR}/System/src/Login.cpp ${CMAKE_CURRENT_SOURCE_DIR}/System/src/SoftwareVersion.cpp @@ -971,6 +972,15 @@ if(BUILD_TESTING) set_tests_properties(guest_jit_shared_memory PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(host_cpu_tests ${LIBS_INCLUDE_DIR}/tests/HostCpu.cpp) + target_include_directories(host_cpu_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(host_cpu_tests PRIVATE libkernel libc) + configure_windows_unwind(host_cpu_tests) + add_test(NAME host_cpu COMMAND host_cpu_tests) + if(WIN32) + set_tests_properties(host_cpu PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_system_configuration_tests ${LIBS_INCLUDE_DIR}/tests/GuestSystemConfiguration.cpp) target_include_directories(guest_system_configuration_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_system_configuration_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/System/include/HostCpu.hpp b/core/libs/prx/libkernel/System/include/HostCpu.hpp new file mode 100644 index 000000000000..11b3368dbf99 --- /dev/null +++ b/core/libs/prx/libkernel/System/include/HostCpu.hpp @@ -0,0 +1,31 @@ +#ifndef CORE_LIBS_PRX_LIBKERNEL_SYSTEM_HOSTCPU_HPP +#define CORE_LIBS_PRX_LIBKERNEL_SYSTEM_HOSTCPU_HPP + +#include +#include +#include + +struct HostCpuRegisters { + std::uint32_t Leaf1Ecx = 0; + std::uint32_t Leaf1Edx = 0; + std::uint32_t Leaf7Ebx = 0; + std::uint32_t Leaf7Ecx = 0; + std::uint32_t LeafDSub1Eax = 0; + std::uint32_t Leaf80000001Ecx = 0; + std::uint32_t Leaf80000008Ebx = 0; + std::uint64_t Xcr0 = 0; +}; + +struct HostCpuFeature { + const char* Name; + bool Required; + bool Present; +}; + +HostCpuRegisters ReadHostCpuRegisters(); +std::string HostCpuModel(); +std::vector HostCpuFeatures(const HostCpuRegisters& registers); +std::vector MissingHostCpuFeatures(const HostCpuRegisters& registers); +void CheckHostCpu(const HostCpuRegisters& registers, const std::string& model); + +#endif diff --git a/core/libs/prx/libkernel/System/src/HostCpu.cpp b/core/libs/prx/libkernel/System/src/HostCpu.cpp new file mode 100644 index 000000000000..a27d29b6dce4 --- /dev/null +++ b/core/libs/prx/libkernel/System/src/HostCpu.cpp @@ -0,0 +1,199 @@ +#include "prx/libkernel/System/include/HostCpu.hpp" +#include "prx/libc/include/general/LogMacros.hpp" +#if defined(__x86_64__) || defined(__i386__) +#include +#endif +#include +#include +#include +#include +#include +#include + +namespace { + +enum class Register : std::uint8_t { + Leaf1Ecx, + Leaf1Edx, + Leaf7Ebx, + Leaf7Ecx, + LeafDSub1Eax, + Leaf80000001Ecx, + Leaf80000008Ebx +}; + +struct FeatureBit { + const char* Name; + Register Source; + unsigned Bit; + bool Required; +}; + +constexpr FeatureBit kFeatures[] = { + {"SSE", Register::Leaf1Edx, 25, true}, + {"SSE2", Register::Leaf1Edx, 26, true}, + {"SSE3", Register::Leaf1Ecx, 0, true}, + {"SSSE3", Register::Leaf1Ecx, 9, true}, + {"SSE4.1", Register::Leaf1Ecx, 19, true}, + {"SSE4.2", Register::Leaf1Ecx, 20, true}, + {"POPCNT", Register::Leaf1Ecx, 23, true}, + {"LZCNT", Register::Leaf80000001Ecx, 5, true}, + {"BMI1", Register::Leaf7Ebx, 3, true}, + {"BMI2", Register::Leaf7Ebx, 8, true}, + {"MOVBE", Register::Leaf1Ecx, 22, true}, + {"CMPXCHG16B", Register::Leaf1Ecx, 13, true}, + {"LAHF/SAHF", Register::Leaf80000001Ecx, 0, true}, + {"AVX", Register::Leaf1Ecx, 28, true}, + {"AVX2", Register::Leaf7Ebx, 5, true}, + {"FMA", Register::Leaf1Ecx, 12, true}, + {"F16C", Register::Leaf1Ecx, 29, true}, + {"AES", Register::Leaf1Ecx, 25, false}, + {"PCLMULQDQ", Register::Leaf1Ecx, 1, false}, + {"RDRAND", Register::Leaf1Ecx, 30, false}, + {"RDSEED", Register::Leaf7Ebx, 18, false}, + {"ADX", Register::Leaf7Ebx, 19, false}, + {"SHA", Register::Leaf7Ebx, 29, false}, + {"CLFLUSHOPT", Register::Leaf7Ebx, 23, false}, + {"CLWB", Register::Leaf7Ebx, 24, false}, + {"RDPID", Register::Leaf7Ecx, 22, false}, + {"XSAVEOPT", Register::LeafDSub1Eax, 0, false}, + {"XSAVEC", Register::LeafDSub1Eax, 1, false}, + {"SSE4A", Register::Leaf80000001Ecx, 6, false}, + {"PREFETCHW", Register::Leaf80000001Ecx, 8, false}, + {"CLZERO", Register::Leaf80000008Ebx, 0, false}, +}; + +constexpr unsigned kOsxsaveBit = 27; +constexpr std::uint64_t kXcr0SseAvxState = 0x6; + +std::uint32_t Value(const HostCpuRegisters& registers, const Register source) { + switch (source) { + case Register::Leaf1Ecx: + return registers.Leaf1Ecx; + case Register::Leaf1Edx: + return registers.Leaf1Edx; + case Register::Leaf7Ebx: + return registers.Leaf7Ebx; + case Register::Leaf7Ecx: + return registers.Leaf7Ecx; + case Register::LeafDSub1Eax: + return registers.LeafDSub1Eax; + case Register::Leaf80000001Ecx: + return registers.Leaf80000001Ecx; + case Register::Leaf80000008Ebx: + return registers.Leaf80000008Ebx; + } + throw std::logic_error("unknown CPUID register"); +} + +bool AvxStateEnabled(const HostCpuRegisters& registers) { + return (registers.Leaf1Ecx >> kOsxsaveBit & 1) != 0 && (registers.Xcr0 & kXcr0SseAvxState) == kXcr0SseAvxState; +} + +std::string DisplayModel(const std::string& model) { + const auto end = model.find_last_not_of(' '); + return end == std::string::npos ? std::string("unknown model") : model.substr(0, end + 1); +} + +std::string Join(const std::vector& names) { + std::string text; + for (const auto& name : names) { + if (!text.empty()) text += ", "; + text += name; + } + return text; +} + +} + +HostCpuRegisters ReadHostCpuRegisters() { + HostCpuRegisters registers; +#if defined(__x86_64__) || defined(__i386__) + unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0; + const unsigned int basic = __get_cpuid_max(0, nullptr); + if (basic >= 1) { + __cpuid(1, eax, ebx, ecx, edx); + registers.Leaf1Ecx = ecx; + registers.Leaf1Edx = edx; + } + if (basic >= 7) { + __cpuid_count(7, 0, eax, ebx, ecx, edx); + registers.Leaf7Ebx = ebx; + registers.Leaf7Ecx = ecx; + } + if (basic >= 0xD) { + __cpuid_count(0xD, 1, eax, ebx, ecx, edx); + registers.LeafDSub1Eax = eax; + } + const unsigned int extended = __get_cpuid_max(0x80000000, nullptr); + if (extended >= 0x80000001) { + __cpuid(0x80000001, eax, ebx, ecx, edx); + registers.Leaf80000001Ecx = ecx; + } + if (extended >= 0x80000008) { + __cpuid(0x80000008, eax, ebx, ecx, edx); + registers.Leaf80000008Ebx = ebx; + } + if ((registers.Leaf1Ecx >> kOsxsaveBit & 1) != 0) { + std::uint32_t low = 0, high = 0; + __asm__ volatile("xgetbv" : "=a"(low), "=d"(high) : "c"(0)); + registers.Xcr0 = static_cast(high) << 32 | low; + } +#endif + return registers; +} + +std::string HostCpuModel() { +#if defined(__x86_64__) || defined(__i386__) + if (__get_cpuid_max(0x80000000, nullptr) < 0x80000004) return {}; + unsigned int brand[12] = {}; + for (unsigned int leaf = 0; leaf < 3; ++leaf) + __get_cpuid(0x80000002 + leaf, &brand[leaf * 4], &brand[leaf * 4 + 1], &brand[leaf * 4 + 2], &brand[leaf * 4 + 3]); + std::string model(reinterpret_cast(brand), strnlen(reinterpret_cast(brand), sizeof(brand))); + model.erase(0, model.find_first_not_of(' ')); + return model; +#else + return {}; +#endif +} + +std::vector HostCpuFeatures(const HostCpuRegisters& registers) { + std::vector features; + features.reserve(std::size(kFeatures) + 1); + for (const auto& feature : kFeatures) + features.push_back({feature.Name, feature.Required, (Value(registers, feature.Source) >> feature.Bit & 1) != 0}); + features.push_back({"OS AVX state (XCR0)", true, AvxStateEnabled(registers)}); + return features; +} + +std::vector MissingHostCpuFeatures(const HostCpuRegisters& registers) { + std::vector missing; + for (const auto& feature : HostCpuFeatures(registers)) + if (feature.Required && !feature.Present) missing.emplace_back(feature.Name); + return missing; +} + +void CheckHostCpu(const HostCpuRegisters& registers, const std::string& model) { + const auto missing = MissingHostCpuFeatures(registers); + if (missing.empty()) return; + throw std::runtime_error("The host CPU (" + DisplayModel(model) + ") lacks " + Join(missing) + + ". The PS5's Zen 2 CPU has these extensions and titles run their instructions natively, so this CPU cannot run them."); +} + +#if (defined(__x86_64__) || defined(__i386__)) && !defined(__APPLE__) +namespace { + +const bool HostCpuChecked = [] { + const auto registers = ReadHostCpuRegisters(); + const auto model = HostCpuModel(); + std::vector present; + std::vector absent; + for (const auto& feature : HostCpuFeatures(registers)) + (feature.Present ? present : absent).emplace_back(feature.Name); + APS5_LOG_OUT("host CPU %s: has %s; lacks %s", DisplayModel(model).c_str(), Join(present).c_str(), absent.empty() ? "none" : Join(absent).c_str()); + CheckHostCpu(registers, model); + return true; +}(); + +} +#endif diff --git a/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp b/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp index 94219edc18cc..199c37be9bb4 100644 --- a/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp +++ b/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp @@ -1,10 +1,8 @@ #include "prx/libc/include/general/VabiMacros.hpp" #include "prx/libkernel/DirectMemory/DirectMemory.hpp" #include "prx/libkernel/KernelErrors.hpp" +#include "prx/libkernel/System/include/HostCpu.hpp" #include -#if defined(__x86_64__) || defined(__i386__) -#include -#endif #include #include #include @@ -49,20 +47,6 @@ bool IsLeafMib(const int* name) { return (name[0] == 6 && (name[1] == 2 || name[1] == 3 || name[1] == 5)) || (name[0] == 1 && name[1] == 37); } -std::string HostCpuModel() { -#if defined(__x86_64__) || defined(__i386__) - if (__get_cpuid_max(0x80000000, nullptr) < 0x80000004) return {}; - unsigned int brand[12] = {}; - for (unsigned int leaf = 0; leaf < 3; ++leaf) - __get_cpuid(0x80000002 + leaf, &brand[leaf * 4], &brand[leaf * 4 + 1], &brand[leaf * 4 + 2], &brand[leaf * 4 + 3]); - std::string model(reinterpret_cast(brand), strnlen(reinterpret_cast(brand), sizeof(brand))); - model.erase(0, model.find_first_not_of(' ')); - return model; -#else - return {}; -#endif -} - } extern "C" { diff --git a/core/libs/tests/HostCpu.cpp b/core/libs/tests/HostCpu.cpp new file mode 100644 index 000000000000..7c5d3aea880c --- /dev/null +++ b/core/libs/tests/HostCpu.cpp @@ -0,0 +1,139 @@ +#include "prx/libkernel/System/include/HostCpu.hpp" +#include +#include +#include +#include +#include + +static void Require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +static constexpr std::uint32_t Bit(unsigned bit) { + return std::uint32_t{1} << bit; +} + +static HostCpuRegisters Zen2() { + HostCpuRegisters registers; + registers.Leaf1Ecx = Bit(0) | Bit(1) | Bit(9) | Bit(12) | Bit(13) | Bit(19) | Bit(20) | Bit(22) | Bit(23) | Bit(25) | Bit(26) | Bit(27) | Bit(28) | Bit(29) | Bit(30); + registers.Leaf1Edx = Bit(25) | Bit(26); + registers.Leaf7Ebx = Bit(3) | Bit(5) | Bit(8) | Bit(18) | Bit(19) | Bit(23) | Bit(24) | Bit(29); + registers.Leaf7Ecx = Bit(22); + registers.LeafDSub1Eax = Bit(0) | Bit(1); + registers.Leaf80000001Ecx = Bit(0) | Bit(5) | Bit(6) | Bit(8); + registers.Leaf80000008Ebx = Bit(0); + registers.Xcr0 = 0x7; + return registers; +} + +static std::string Text(const std::vector& names) { + std::string text; + for (const auto& name : names) text += (text.empty() ? "" : ",") + name; + return text; +} + +static void CheckMissing(const HostCpuRegisters& registers, const std::vector& expected, const std::string& label) { + const auto missing = MissingHostCpuFeatures(registers); + Require(missing == expected, label + ": expected [" + Text(expected) + "], got [" + Text(missing) + "]"); +} + +static void CheckZen2() { + CheckMissing(Zen2(), {}, "Zen 2"); + for (const auto& feature : HostCpuFeatures(Zen2())) + Require(feature.Present, std::string("Zen 2 lacks ") + feature.Name); +} + +static void CheckIntelWithoutAmdOnlyExtensions() { + auto registers = Zen2(); + registers.Leaf7Ebx &= ~(Bit(18) | Bit(19) | Bit(23) | Bit(24) | Bit(29)); + registers.Leaf7Ecx = 0; + registers.LeafDSub1Eax = Bit(0); + registers.Leaf80000001Ecx &= ~(Bit(6) | Bit(8)); + registers.Leaf80000008Ebx = 0; + CheckMissing(registers, {}, "AVX2 host without SSE4A, CLZERO, SHA, ADX, RDSEED, CLFLUSHOPT, CLWB, RDPID"); +} + +static void CheckSingleMissingExtension() { + struct Case { + const char* Name; + std::uint32_t HostCpuRegisters::* Register; + unsigned Bit; + }; + const Case cases[] = { + {"BMI2", &HostCpuRegisters::Leaf7Ebx, 8}, + {"BMI1", &HostCpuRegisters::Leaf7Ebx, 3}, + {"AVX2", &HostCpuRegisters::Leaf7Ebx, 5}, + {"MOVBE", &HostCpuRegisters::Leaf1Ecx, 22}, + {"FMA", &HostCpuRegisters::Leaf1Ecx, 12}, + {"F16C", &HostCpuRegisters::Leaf1Ecx, 29}, + {"POPCNT", &HostCpuRegisters::Leaf1Ecx, 23}, + {"SSE4.2", &HostCpuRegisters::Leaf1Ecx, 20}, + {"CMPXCHG16B", &HostCpuRegisters::Leaf1Ecx, 13}, + {"LZCNT", &HostCpuRegisters::Leaf80000001Ecx, 5}, + {"LAHF/SAHF", &HostCpuRegisters::Leaf80000001Ecx, 0}, + }; + for (const auto& entry : cases) { + auto registers = Zen2(); + registers.*entry.Register &= ~Bit(entry.Bit); + CheckMissing(registers, {entry.Name}, std::string("without ") + entry.Name); + } +} + +static void CheckAvxWithoutOsState() { + auto registers = Zen2(); + registers.Xcr0 = 0x3; + CheckMissing(registers, {"OS AVX state (XCR0)"}, "XCR0 without YMM state"); + registers = Zen2(); + registers.Leaf1Ecx &= ~Bit(27); + CheckMissing(registers, {"OS AVX state (XCR0)"}, "OSXSAVE clear"); +} + +static void CheckPreHaswell() { + auto registers = Zen2(); + registers.Leaf1Ecx &= ~(Bit(12) | Bit(22)); + registers.Leaf7Ebx = 0; + registers.Leaf80000001Ecx &= ~Bit(5); + CheckMissing(registers, {"LZCNT", "BMI1", "BMI2", "MOVBE", "AVX2", "FMA"}, "AVX host without AVX2"); +} + +static void CheckError() { + auto registers = Zen2(); + registers.Leaf7Ebx &= ~Bit(8); + CheckHostCpu(Zen2(), "AMD Ryzen 7 3700X 8-Core Processor"); + try { + CheckHostCpu(registers, "Example CPU"); + throw std::logic_error("missing BMI2 did not throw"); + } catch (const std::runtime_error& error) { + const std::string message = error.what(); + Require(message.find("(Example CPU) lacks BMI2.") != std::string::npos, "unexpected message: " + message); + } + try { + CheckHostCpu(registers, "AMD Example "); + throw std::logic_error("missing BMI2 did not throw"); + } catch (const std::runtime_error& error) { + const std::string message = error.what(); + Require(message.find("(AMD Example) lacks BMI2.") != std::string::npos, "unexpected message: " + message); + } + try { + CheckHostCpu(registers, ""); + throw std::logic_error("missing BMI2 did not throw"); + } catch (const std::runtime_error& error) { + const std::string message = error.what(); + Require(message.find("(unknown model) lacks BMI2.") != std::string::npos, "unexpected message: " + message); + } +} + +int main() { + try { + CheckZen2(); + CheckIntelWithoutAmdOnlyExtensions(); + CheckSingleMissingExtension(); + CheckAvxWithoutOsState(); + CheckPreHaswell(); + CheckError(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index f2f4464b4277..a282eb43f9d8 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -35,6 +35,8 @@ relinker --macos source/input.elf eboot Add `--to-intel` for Intel hosts, or `--to-rosetta` for Rosetta; a title that runs under Rosetta on Apple silicon is relinked with `--macos --to-rosetta`. The output format defaults to Linux ELF regardless of the filename; `.exe` alone does not select Windows. +Titles run natively, so the host CPU needs the extensions of the PS5's Zen 2 CPU that compiled code uses without checking, among them AVX2, FMA, F16C, BMI1, BMI2, LZCNT and MOVBE. On Linux and Windows a converted title logs the host CPU's extensions at start-up and stops before running any title code, naming the CPU and the missing extensions, if one is absent ([list](../dev/debt/libkernel.md)). + The executable, registry, Windows import diagnostics, icon and desktop entry output files must not refer to the input executable or a bundled module being converted, including through a hard link or symbolic link. These collisions fail before any output is written. An existing output file can be replaced if it is separate from those inputs. ## Options From 199ff4190a59a7b2e9110d823e1b93ce17f94218 Mon Sep 17 00:00:00 2001 From: Ahmad Date: Wed, 14 Oct 2026 00:28:13 +0300 Subject: [PATCH 16/23] feat(libkernel): implement sysctlnametomib for the sysctl names AnyPS5 serves Map hw.model, hw.ncpu, hw.physmem, hw.realmem, kern.arandom and kern.proc.pathname to their FreeBSD MIBs with the size handling of FreeBSD's libc wrapper over name2oid, fail with ENOENT and ENAMETOOLONG as name2oid does, and throw for null pointers, which FreeBSD's wrapper dereferences, and for names sysctl does not serve. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit cc3d25d6367ff98bf8967a7df8520c64a8133be1) --- .../System/src/SystemConfiguration.cpp | 35 +++++++ core/libs/tests/GuestSystemConfiguration.cpp | 94 +++++++++++++++++++ 2 files changed, 129 insertions(+) diff --git a/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp b/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp index 199c37be9bb4..38d001ce4a32 100644 --- a/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp +++ b/core/libs/prx/libkernel/System/src/SystemConfiguration.cpp @@ -238,4 +238,39 @@ int APS5_VABI sceKernelGetSystemSwVersion_nid_postfix(SceKernelSystemSwVersion* version->version = 0x01000000; return 0; } + +int APS5_VABI sysctlnametomib_nid_postfix(const char* name, int* mib, std::size_t* size) { + struct KnownName { + const char* name; + int mib[3]; + std::size_t length; + }; + static constexpr KnownName known[] = { + {"hw.model", {6, 2}, 2}, + {"hw.ncpu", {6, 3}, 2}, + {"hw.physmem", {6, 5}, 2}, + {"hw.realmem", {6, 12}, 2}, + {"kern.arandom", {1, 37}, 2}, + {"kern.proc.pathname", {1, 14, 12}, 3}, + }; + constexpr std::size_t MaximumPath = 1024; + if (name == nullptr || size == nullptr) throw std::invalid_argument(std::string(__func__) + ": null name or size"); + const std::size_t nameLength = strnlen(name, MaximumPath); + if (nameLength == MaximumPath) { + *__error_nid_postfix() = 63; + return -1; + } + if (nameLength == 0 || std::strcmp(name, "machdep.cacheline_size") == 0) { + *__error_nid_postfix() = 2; + return -1; + } + for (const auto& entry : known) { + if (std::strcmp(name, entry.name) != 0) continue; + std::size_t bytes = *size * sizeof(int); + const int result = CopyOut(entry.mib, entry.length * sizeof(int), mib, &bytes); + *size = bytes / sizeof(int); + return result; + } + throw std::runtime_error(std::string(__func__) + ": unsupported name " + name); +} } diff --git a/core/libs/tests/GuestSystemConfiguration.cpp b/core/libs/tests/GuestSystemConfiguration.cpp index b20d8eec848a..25aa064b5502 100644 --- a/core/libs/tests/GuestSystemConfiguration.cpp +++ b/core/libs/tests/GuestSystemConfiguration.cpp @@ -20,6 +20,7 @@ int APS5_VABI getpagesize_nid_postfix(); int* APS5_VABI __error_nid_postfix(); int APS5_VABI sysctl_nid_postfix(const int*, std::uint32_t, void*, std::size_t*, const void*, std::size_t); int APS5_VABI sysctlbyname_nid_postfix(const char*, void*, std::size_t*, const void*, std::size_t); +int APS5_VABI sysctlnametomib_nid_postfix(const char*, int*, std::size_t*); int APS5_VABI sceKernelGetSystemSwVersion_nid_postfix(SceKernelSystemSwVersion*); int APS5_VABI getpid_nid_postfix(); std::uint64_t APS5_VABI sceKernelGetTscFrequency(void); @@ -280,6 +281,98 @@ static void CheckArandomSysctl() { Require(sysctl_nid_postfix(mib, 2, first, nullptr, nullptr, 0) == 0); Require(*__error_nid_postfix() == 13); } +static void CheckNameToMib() { + struct Expected { + const char* name; + int mib[3]; + std::size_t length; + }; + const Expected expected[] = { + {"hw.model", {6, 2}, 2}, + {"hw.ncpu", {6, 3}, 2}, + {"hw.physmem", {6, 5}, 2}, + {"hw.realmem", {6, 12}, 2}, + {"kern.arandom", {1, 37}, 2}, + {"kern.proc.pathname", {1, 14, 12}, 3}, + }; + *__error_nid_postfix() = 13; + for (const auto& entry : expected) { + std::size_t size = 0; + Require(sysctlnametomib_nid_postfix(entry.name, nullptr, &size) == 0 && size == entry.length); + int mib[5] = {0x5a5a5a5a, 0x5a5a5a5a, 0x5a5a5a5a, 0x5a5a5a5a, 0x5a5a5a5a}; + size = 5; + Require(sysctlnametomib_nid_postfix(entry.name, mib, &size) == 0 && size == entry.length); + Require(std::memcmp(mib, entry.mib, entry.length * sizeof(int)) == 0 && mib[entry.length] == 0x5a5a5a5a); + } + Require(*__error_nid_postfix() == 13); + + int mib[4] = {}; + std::size_t size = 4; + Require(sysctlnametomib_nid_postfix("hw.ncpu", mib, &size) == 0 && size == 2); + int processors = 0; + std::size_t length = sizeof(processors); + Require(sysctl_nid_postfix(mib, static_cast(size), &processors, &length, nullptr, 0) == 0); + Require(processors == static_cast(sysconf_nid_postfix(58))); + size = 4; + Require(sysctlnametomib_nid_postfix("hw.realmem", mib, &size) == 0 && size == 2); + std::uint64_t realmem = 0; + length = sizeof(realmem); + Require(sysctl_nid_postfix(mib, static_cast(size), &realmem, &length, nullptr, 0) == 0); + std::uint64_t namedRealmem = 0; + length = sizeof(namedRealmem); + Require(sysctlbyname_nid_postfix("hw.realmem", &namedRealmem, &length, nullptr, 0) == 0 && realmem == namedRealmem); + size = 4; + Require(sysctlnametomib_nid_postfix("kern.proc.pathname", mib, &size) == 0 && size == 3); + mib[3] = -1; + char path[32] = {}; + length = sizeof(path); + Require(sysctl_nid_postfix(mib, 4, path, &length, nullptr, 0) == 0 && std::strcmp(path, "/app0/eboot.bin") == 0); + + int truncated[3] = {0x5a5a5a5a, 0x5a5a5a5a, 0x5a5a5a5a}; + size = 1; + Require(sysctlnametomib_nid_postfix("hw.ncpu", truncated, &size) == -1 && *__error_nid_postfix() == 12); + Require(size == 1 && truncated[0] == 6 && truncated[1] == 0x5a5a5a5a); + size = 0; + Require(sysctlnametomib_nid_postfix("hw.ncpu", truncated, &size) == -1 && *__error_nid_postfix() == 12); + Require(size == 0 && truncated[0] == 6); + + size = 4; + Require(sysctlnametomib_nid_postfix("", mib, &size) == -1 && *__error_nid_postfix() == 2); + Require(sysctlnametomib_nid_postfix("machdep.cacheline_size", mib, &size) == -1 && *__error_nid_postfix() == 2); + char tooLong[1025]; + std::memset(tooLong, 'a', sizeof(tooLong) - 1); + tooLong[sizeof(tooLong) - 1] = 0; + Require(sysctlnametomib_nid_postfix(tooLong, mib, &size) == -1 && *__error_nid_postfix() == 63); + tooLong[1023] = 0; + bool threw = false; + try { + sysctlnametomib_nid_postfix(tooLong, mib, &size); + } catch (const std::runtime_error&) { + threw = true; + } + Require(threw); + threw = false; + try { + sysctlnametomib_nid_postfix(nullptr, mib, &size); + } catch (const std::invalid_argument&) { + threw = true; + } + Require(threw); + threw = false; + try { + sysctlnametomib_nid_postfix("hw.ncpu", mib, nullptr); + } catch (const std::invalid_argument&) { + threw = true; + } + Require(threw); + threw = false; + try { + sysctlnametomib_nid_postfix("kern.cp_times", mib, &size); + } catch (const std::runtime_error&) { + threw = true; + } + Require(threw); +} int main() { CheckProcessorCountSysctl(); CheckPhysicalMemorySysctl(); @@ -294,6 +387,7 @@ int main() { CheckPseudoRandomSysctl(); CheckSdkVersionSysctl(); CheckArandomSysctl(); + CheckNameToMib(); *__error_nid_postfix() = 13; Require(sysconf_nid_postfix(3) == 128); Require(sysconf_nid_postfix(47) == 0x4000); From 89dea3a6771b930e4f74028f7a2fbebc0b004523 Mon Sep 17 00:00:00 2001 From: thibaut Date: Tue, 13 Oct 2026 21:01:59 +0200 Subject: [PATCH 17/23] feat(relinker): report every unresolved ELF import before failing on Windows The Windows startup stub stopped at the first import it could not resolve, so a title missing several functions showed one "FAIL: unresolved ELF import" line per run and needed a run per missing function to list them all. The stub now counts unresolved imports, writes the FAIL line of each and goes on with the next import. After the last import it fails once, with the searched library list and the last Windows error as before, and exits with STATUS_ENTRYPOINT_NOT_FOUND. Weak imports, lazy binding and a startup where every import resolves are unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4ae26f8ba091ec2b0a06e66ab09c3c0f75887ea0) --- .../src/windows/WindowsEntryStubBuilder.cpp | 12 ++++++- .../tests/test_windows_import_modules.py | 34 ++++++++++++++----- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp index 28707a85383e..34ada6aacf5f 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp @@ -188,6 +188,7 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con } const auto lastError = reserve(4); + const auto unresolvedCount = reserve(4); const auto errorDigits = reserve(11); const auto errorMessage = reserve(ErrorMessageCapacity); const auto loading = addString("Loading PRX: "); @@ -492,6 +493,7 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con } std::vector unresolvedBranches; + bool anyUnresolvable = false; std::vector lazyUnresolvedImports; std::vector tlsResolverAddresses; for (std::size_t index = 0; index < imports.size(); ++index) { @@ -543,7 +545,8 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con } captureLastError(); writeString(errorRvas.at(3 + index), true); - unresolvedBranches.push_back(code.Branch({0xe9})); + code.Rip({0xff, 0x05}, unresolvedCount); + const auto nextImport = code.Branch({0xe9}); code.PatchBranch(resolved, code.GetRva()); if (imports[index].RelocationType == 16) code.Emit({0x48, 0x8b, 0x00}); if (imports[index].RelocationType == 17) code.Emit({0x48, 0x8b, 0x40, 8}); @@ -553,8 +556,15 @@ WindowsEntryStub WindowsEntryStubBuilder::Build(const std::uint32_t dataRva, con code.Emit({0x48, 0x01, 0xd0}); } guestStartup.WriteImport(code, imports[index], handles); + code.PatchBranch(nextImport, code.GetRva()); + anyUnresolvable = true; } + if (anyUnresolvable) { + code.Rip({0x8b, 0x05}, unresolvedCount); + code.Emit({0x85, 0xc0}); + unresolvedBranches.push_back(code.Branch({0x0f, 0x85})); + } guestStartup.Initialize(code, guestModules, handles); writeString(enteringElf); code.Rip({0x48, 0x8d, 0x0d}, shellLibrary); diff --git a/core/relinker/relinker/tests/test_windows_import_modules.py b/core/relinker/relinker/tests/test_windows_import_modules.py index c803ebbe73a5..afce347960b1 100644 --- a/core/relinker/relinker/tests/test_windows_import_modules.py +++ b/core/relinker/relinker/tests/test_windows_import_modules.py @@ -187,11 +187,17 @@ def consumer(owner, symbol='shared#A#B', expected=22, module_name=None): return image -def executable(owner, symbol='shared#A#B', module_name=None, extra_dependencies=()): +def executable(owner, symbol='shared#A#B', module_name=None, extra_dependencies=(), extra_symbols=()): image = main_fixture() struct.pack_into(' Date: Tue, 13 Oct 2026 19:56:36 -0400 Subject: [PATCH 18/23] feat(libc): implement fegetenv Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 74b93adb6c635174299616aa26eb4d927c043de9) --- core/libs/prx/libc/src/Math.cpp | 18 +++++++++++ core/libs/tests/GuestMath.cpp | 53 +++++++++++++++++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 3 files changed, 72 insertions(+) diff --git a/core/libs/prx/libc/src/Math.cpp b/core/libs/prx/libc/src/Math.cpp index 23cded8ab656..3e7ca055632f 100644 --- a/core/libs/prx/libc/src/Math.cpp +++ b/core/libs/prx/libc/src/Math.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -9,6 +10,7 @@ #include #include #include +#include #include "prx/libc/include/General.hpp" #include "prx/libc/include/SonyCrt.hpp" @@ -163,10 +165,26 @@ long double AsinDenominator(long double t) { return 1.0L + t * (q[0] + t * (q[1] + t * (q[2] + t * (q[3] + t * q[4])))); } +struct GuestFloatingPointEnvironment { + std::uint32_t control; + std::uint32_t status; + std::uint32_t tag; + unsigned char other[16]; + std::uint32_t mxcsr; +}; +static_assert(sizeof(GuestFloatingPointEnvironment) == 32 && offsetof(GuestFloatingPointEnvironment, mxcsr) == 28); + } extern "C" { +int APS5_VABI fegetenv_nid_postfix(GuestFloatingPointEnvironment* environment) { + if (environment == nullptr) throw std::invalid_argument("fegetenv: null environment"); + asm volatile("fnstenv %0\n\tfldcw %0" : "+m"(*environment)); + environment->mxcsr = _mm_getcsr(); + return 0; +} + std::lldiv_t APS5_VABI lldiv_nid_postfix(long long numerator, long long denominator) { return std::lldiv(numerator, denominator); } diff --git a/core/libs/tests/GuestMath.cpp b/core/libs/tests/GuestMath.cpp index 0fc18ffcf331..3808fca56218 100644 --- a/core/libs/tests/GuestMath.cpp +++ b/core/libs/tests/GuestMath.cpp @@ -9,7 +9,17 @@ #include #include #include +#include +struct GuestFloatingPointEnvironment { + std::uint32_t control; + std::uint32_t status; + std::uint32_t tag; + unsigned char other[16]; + std::uint32_t mxcsr; +}; +static_assert(sizeof(GuestFloatingPointEnvironment) == 32); extern "C" { +int APS5_VABI fegetenv_nid_postfix(GuestFloatingPointEnvironment*); double APS5_VABI atof_nid_postfix(const char*); double APS5_VABI strtod_nid_postfix(const char*, char**); double APS5_VABI wcstod_nid_postfix(const char16_t*, char16_t**); @@ -784,7 +794,50 @@ void CheckNoConversionIsPositiveZero() { Require(parsedWideLong == 0.L && !std::signbit(parsedWideLong) && wideEnd == wide); } +static std::uint16_t X87ControlWord() { + std::uint16_t control; + asm volatile("fnstcw %0" : "=m"(control)); + return control; +} + +static std::uint16_t X87StatusWord() { + std::uint16_t status; + asm volatile("fnstsw %0" : "=m"(status)); + return status; +} + +static void CheckFegetenv() { + const std::uint16_t savedControl = X87ControlWord(); + const unsigned savedCsr = _mm_getcsr(); + const std::uint16_t control = 0x0f7e; + const unsigned csr = 0x7fa0; + asm volatile("fldcw %0" : : "m"(control)); + _mm_setcsr(csr); + volatile long double zero = 0.0L; + volatile long double quotient = 1.0L / zero; + (void)quotient; + const std::uint16_t status = X87StatusWord(); + Require((status & 0x04) != 0 && (status & 0x01) == 0); + + GuestFloatingPointEnvironment environment; + std::memset(&environment, 0xcc, sizeof(environment)); + Require(fegetenv_nid_postfix(&environment) == 0); + const std::uint16_t controlAfter = X87ControlWord(); + const unsigned csrAfter = _mm_getcsr(); + + asm volatile("fnclex"); + asm volatile("fldcw %0" : : "m"(savedControl)); + _mm_setcsr(savedCsr); + + Require((environment.control & 0xffff) == control); + Require((environment.status & 0xffff) == status); + Require(environment.mxcsr == csr); + Require(controlAfter == control); + Require(csrAfter == csr); +} + int main() { + CheckFegetenv(); CheckFloatClassification(); CheckMissingClassificationExports(); CheckNoConversionIsPositiveZero(); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 629a29df8142..040a0a05152f 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -357,6 +357,7 @@ Throughout the project, every function at every stage either **does exactly what - [set_constraint_handler_s](../../core/libs/prx/libc/src/WideConversion.cpp) (libc, re-exported by libSceAmpr) - the default handler is assumed to abort; each module keeps its own handler state, so a handler set through one library is not seen by the other. `ctime_s` and `asctime_s` follow the Dinkumware 26-byte format with `EINVAL` for a buffer under 26 bytes, a null pointer or an out-of-range weekday/month; `ctime_s` uses the guest time zone of `localtime_s`, and the console's exact checks are not verified - [__udivti3](../../core/libs/prx/libc/src/RuntimeSupport.cpp) (libc, re-exported by libSceAmpr) - the hardware traps on a zero divisor; this throws instead - [__umodti3](../../core/libs/prx/libc/src/RuntimeSupport.cpp) (libc) - the hardware traps on a zero divisor; this throws instead +- [fegetenv](../../core/libs/prx/libc/src/Math.cpp) (libSceLibcInternal, implemented in libc, NID `psx0YiAKm7k`) follows FreeBSD amd64 [fenv.c](https://github.com/freebsd/freebsd-src/blob/d8b6461f8c56237a00ddc32678b3928bf76f5440/lib/msun/amd64/fenv.c) with the 32-byte `fenv_t` of [x86/fenv.h](https://github.com/freebsd/freebsd-src/blob/d8b6461f8c56237a00ddc32678b3928bf76f5440/lib/msun/x86/fenv.h): `fnstenv` fills the 28-byte x87 part, MXCSR follows at 0x1c, and the x87 control word is reloaded because `fnstenv` masks every x87 exception. That the console's `libSceLibcInternal` has the same code and layout is assumed, not read from its binary. A null pointer throws instead of faulting - [AC1FtjqMCL0](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature - [0iEKNAvT600](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature - [2cELEBPdYQ0](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature From 9cce5666fd21343b05ba37c24373f6be34aba92b Mon Sep 17 00:00:00 2001 From: Karim Ibrahim <40270714+karimibrahim07@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:56:36 -0400 Subject: [PATCH 19/23] test(libc): cover fegetenv with a null environment and pending x87 flags Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 34cf0e223f4a60faba7896732de3d7a0663131a5) --- core/libs/tests/GuestMath.cpp | 4 ++++ docs/dev/TechnicalDebt.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core/libs/tests/GuestMath.cpp b/core/libs/tests/GuestMath.cpp index 3808fca56218..3c0d4450b2c9 100644 --- a/core/libs/tests/GuestMath.cpp +++ b/core/libs/tests/GuestMath.cpp @@ -811,6 +811,7 @@ static void CheckFegetenv() { const unsigned savedCsr = _mm_getcsr(); const std::uint16_t control = 0x0f7e; const unsigned csr = 0x7fa0; + asm volatile("fnclex"); asm volatile("fldcw %0" : : "m"(control)); _mm_setcsr(csr); volatile long double zero = 0.0L; @@ -834,6 +835,9 @@ static void CheckFegetenv() { Require(environment.mxcsr == csr); Require(controlAfter == control); Require(csrAfter == csr); + bool threw = false; + try { fegetenv_nid_postfix(nullptr); } catch (...) { threw = true; } + Require(threw); } int main() { diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 040a0a05152f..53d3c979e5ee 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -357,7 +357,7 @@ Throughout the project, every function at every stage either **does exactly what - [set_constraint_handler_s](../../core/libs/prx/libc/src/WideConversion.cpp) (libc, re-exported by libSceAmpr) - the default handler is assumed to abort; each module keeps its own handler state, so a handler set through one library is not seen by the other. `ctime_s` and `asctime_s` follow the Dinkumware 26-byte format with `EINVAL` for a buffer under 26 bytes, a null pointer or an out-of-range weekday/month; `ctime_s` uses the guest time zone of `localtime_s`, and the console's exact checks are not verified - [__udivti3](../../core/libs/prx/libc/src/RuntimeSupport.cpp) (libc, re-exported by libSceAmpr) - the hardware traps on a zero divisor; this throws instead - [__umodti3](../../core/libs/prx/libc/src/RuntimeSupport.cpp) (libc) - the hardware traps on a zero divisor; this throws instead -- [fegetenv](../../core/libs/prx/libc/src/Math.cpp) (libSceLibcInternal, implemented in libc, NID `psx0YiAKm7k`) follows FreeBSD amd64 [fenv.c](https://github.com/freebsd/freebsd-src/blob/d8b6461f8c56237a00ddc32678b3928bf76f5440/lib/msun/amd64/fenv.c) with the 32-byte `fenv_t` of [x86/fenv.h](https://github.com/freebsd/freebsd-src/blob/d8b6461f8c56237a00ddc32678b3928bf76f5440/lib/msun/x86/fenv.h): `fnstenv` fills the 28-byte x87 part, MXCSR follows at 0x1c, and the x87 control word is reloaded because `fnstenv` masks every x87 exception. That the console's `libSceLibcInternal` has the same code and layout is assumed, not read from its binary. A null pointer throws instead of faulting +- [fegetenv](../../core/libs/prx/libc/src/Math.cpp) (libSceLibcInternal, implemented in libc, NID `psx0YiAKm7k`) follows FreeBSD 11 amd64 [fenv.c](https://github.com/freebsd/freebsd-src/blob/4554bee35405b36ea19e9e60d6abe6ea534e36e0/lib/msun/amd64/fenv.c) with the 32-byte `fenv_t` of [x86/fenv.h](https://github.com/freebsd/freebsd-src/blob/4554bee35405b36ea19e9e60d6abe6ea534e36e0/lib/msun/x86/fenv.h): `fnstenv` fills the 28-byte x87 part, MXCSR follows at 0x1c, and the x87 control word is reloaded because `fnstenv` masks every x87 exception. That the console's `libSceLibcInternal` has the same code and layout is assumed, not read from its binary. A null pointer throws instead of faulting - [AC1FtjqMCL0](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature - [0iEKNAvT600](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature - [2cELEBPdYQ0](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature From dac1976b543902a418883fc8e983ea9ffd2b23ea Mon Sep 17 00:00:00 2001 From: Karim Ibrahim <40270714+karimibrahim07@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:28:02 -0400 Subject: [PATCH 20/23] refactor(libc): move fegetenv and its test out of the lines #5495 changes Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f49c54243f88acc74bcf989afbe42f5a46e8bf09) --- core/libs/prx/libc/src/Math.cpp | 32 +++++------ core/libs/tests/GuestMath.cpp | 94 ++++++++++++++++----------------- 2 files changed, 63 insertions(+), 63 deletions(-) diff --git a/core/libs/prx/libc/src/Math.cpp b/core/libs/prx/libc/src/Math.cpp index 3e7ca055632f..e22f4a860068 100644 --- a/core/libs/prx/libc/src/Math.cpp +++ b/core/libs/prx/libc/src/Math.cpp @@ -165,26 +165,10 @@ long double AsinDenominator(long double t) { return 1.0L + t * (q[0] + t * (q[1] + t * (q[2] + t * (q[3] + t * q[4])))); } -struct GuestFloatingPointEnvironment { - std::uint32_t control; - std::uint32_t status; - std::uint32_t tag; - unsigned char other[16]; - std::uint32_t mxcsr; -}; -static_assert(sizeof(GuestFloatingPointEnvironment) == 32 && offsetof(GuestFloatingPointEnvironment, mxcsr) == 28); - } extern "C" { -int APS5_VABI fegetenv_nid_postfix(GuestFloatingPointEnvironment* environment) { - if (environment == nullptr) throw std::invalid_argument("fegetenv: null environment"); - asm volatile("fnstenv %0\n\tfldcw %0" : "+m"(*environment)); - environment->mxcsr = _mm_getcsr(); - return 0; -} - std::lldiv_t APS5_VABI lldiv_nid_postfix(long long numerator, long long denominator) { return std::lldiv(numerator, denominator); } @@ -552,6 +536,22 @@ int APS5_VABI _Fltrounds_nid_postfix(void) { return SonyFltrounds(); } +struct GuestFloatingPointEnvironment { + std::uint32_t control; + std::uint32_t status; + std::uint32_t tag; + unsigned char other[16]; + std::uint32_t mxcsr; +}; +static_assert(sizeof(GuestFloatingPointEnvironment) == 32 && offsetof(GuestFloatingPointEnvironment, mxcsr) == 28); + +int APS5_VABI fegetenv_nid_postfix(GuestFloatingPointEnvironment* environment) { + if (environment == nullptr) throw std::invalid_argument("fegetenv: null environment"); + asm volatile("fnstenv %0\n\tfldcw %0" : "+m"(*environment)); + environment->mxcsr = _mm_getcsr(); + return 0; +} + union SonyDconst { unsigned short _Word[8]; float _Float; diff --git a/core/libs/tests/GuestMath.cpp b/core/libs/tests/GuestMath.cpp index 3c0d4450b2c9..4c96f738c87f 100644 --- a/core/libs/tests/GuestMath.cpp +++ b/core/libs/tests/GuestMath.cpp @@ -197,6 +197,52 @@ static void CheckNearbyint() { Require(std::fetestexcept(FE_INEXACT) == 0); } +static std::uint16_t X87ControlWord() { + std::uint16_t control; + asm volatile("fnstcw %0" : "=m"(control)); + return control; +} + +static std::uint16_t X87StatusWord() { + std::uint16_t status; + asm volatile("fnstsw %0" : "=m"(status)); + return status; +} + +static void CheckFegetenv() { + const std::uint16_t savedControl = X87ControlWord(); + const unsigned savedCsr = _mm_getcsr(); + const std::uint16_t control = 0x0f7e; + const unsigned csr = 0x7fa0; + asm volatile("fnclex"); + asm volatile("fldcw %0" : : "m"(control)); + _mm_setcsr(csr); + volatile long double zero = 0.0L; + volatile long double quotient = 1.0L / zero; + (void)quotient; + const std::uint16_t status = X87StatusWord(); + Require((status & 0x04) != 0 && (status & 0x01) == 0); + + GuestFloatingPointEnvironment environment; + std::memset(&environment, 0xcc, sizeof(environment)); + Require(fegetenv_nid_postfix(&environment) == 0); + const std::uint16_t controlAfter = X87ControlWord(); + const unsigned csrAfter = _mm_getcsr(); + + asm volatile("fnclex"); + asm volatile("fldcw %0" : : "m"(savedControl)); + _mm_setcsr(savedCsr); + + Require((environment.control & 0xffff) == control); + Require((environment.status & 0xffff) == status); + Require(environment.mxcsr == csr); + Require(controlAfter == control); + Require(csrAfter == csr); + bool threw = false; + try { fegetenv_nid_postfix(nullptr); } catch (...) { threw = true; } + Require(threw); +} + static bool ExtendedBits(long double value, std::uint64_t mantissa, std::uint16_t signExponent) { unsigned char bytes[sizeof(long double)]{}; std::memcpy(bytes, &value, sizeof(value)); @@ -794,54 +840,7 @@ void CheckNoConversionIsPositiveZero() { Require(parsedWideLong == 0.L && !std::signbit(parsedWideLong) && wideEnd == wide); } -static std::uint16_t X87ControlWord() { - std::uint16_t control; - asm volatile("fnstcw %0" : "=m"(control)); - return control; -} - -static std::uint16_t X87StatusWord() { - std::uint16_t status; - asm volatile("fnstsw %0" : "=m"(status)); - return status; -} - -static void CheckFegetenv() { - const std::uint16_t savedControl = X87ControlWord(); - const unsigned savedCsr = _mm_getcsr(); - const std::uint16_t control = 0x0f7e; - const unsigned csr = 0x7fa0; - asm volatile("fnclex"); - asm volatile("fldcw %0" : : "m"(control)); - _mm_setcsr(csr); - volatile long double zero = 0.0L; - volatile long double quotient = 1.0L / zero; - (void)quotient; - const std::uint16_t status = X87StatusWord(); - Require((status & 0x04) != 0 && (status & 0x01) == 0); - - GuestFloatingPointEnvironment environment; - std::memset(&environment, 0xcc, sizeof(environment)); - Require(fegetenv_nid_postfix(&environment) == 0); - const std::uint16_t controlAfter = X87ControlWord(); - const unsigned csrAfter = _mm_getcsr(); - - asm volatile("fnclex"); - asm volatile("fldcw %0" : : "m"(savedControl)); - _mm_setcsr(savedCsr); - - Require((environment.control & 0xffff) == control); - Require((environment.status & 0xffff) == status); - Require(environment.mxcsr == csr); - Require(controlAfter == control); - Require(csrAfter == csr); - bool threw = false; - try { fegetenv_nid_postfix(nullptr); } catch (...) { threw = true; } - Require(threw); -} - int main() { - CheckFegetenv(); CheckFloatClassification(); CheckMissingClassificationExports(); CheckNoConversionIsPositiveZero(); @@ -948,6 +947,7 @@ int main() { CheckExp2Errno(); CheckExactOperations(); CheckNearbyint(); + CheckFegetenv(); CheckLongDouble(); CheckNearbyintl(); CheckAsinl(); From 41caef770485dc88e942f683563171fa6754da18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Wed, 14 Oct 2026 14:00:57 +0200 Subject: [PATCH 21/23] docs(libc): move the fegetenv debt line off the end of its section (cherry picked from commit 32a11a57d1e782d509d2ea69e03a9371c2d529e5) --- docs/dev/TechnicalDebt.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 53d3c979e5ee..629a29df8142 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -357,7 +357,6 @@ Throughout the project, every function at every stage either **does exactly what - [set_constraint_handler_s](../../core/libs/prx/libc/src/WideConversion.cpp) (libc, re-exported by libSceAmpr) - the default handler is assumed to abort; each module keeps its own handler state, so a handler set through one library is not seen by the other. `ctime_s` and `asctime_s` follow the Dinkumware 26-byte format with `EINVAL` for a buffer under 26 bytes, a null pointer or an out-of-range weekday/month; `ctime_s` uses the guest time zone of `localtime_s`, and the console's exact checks are not verified - [__udivti3](../../core/libs/prx/libc/src/RuntimeSupport.cpp) (libc, re-exported by libSceAmpr) - the hardware traps on a zero divisor; this throws instead - [__umodti3](../../core/libs/prx/libc/src/RuntimeSupport.cpp) (libc) - the hardware traps on a zero divisor; this throws instead -- [fegetenv](../../core/libs/prx/libc/src/Math.cpp) (libSceLibcInternal, implemented in libc, NID `psx0YiAKm7k`) follows FreeBSD 11 amd64 [fenv.c](https://github.com/freebsd/freebsd-src/blob/4554bee35405b36ea19e9e60d6abe6ea534e36e0/lib/msun/amd64/fenv.c) with the 32-byte `fenv_t` of [x86/fenv.h](https://github.com/freebsd/freebsd-src/blob/4554bee35405b36ea19e9e60d6abe6ea534e36e0/lib/msun/x86/fenv.h): `fnstenv` fills the 28-byte x87 part, MXCSR follows at 0x1c, and the x87 control word is reloaded because `fnstenv` masks every x87 exception. That the console's `libSceLibcInternal` has the same code and layout is assumed, not read from its binary. A null pointer throws instead of faulting - [AC1FtjqMCL0](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature - [0iEKNAvT600](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature - [2cELEBPdYQ0](../../core/libs/prx/libkernel/Unimplemented.cpp) (libkernel) - unknown name, signature From 7aeca2834bd24d8ccfb81f840bf261acf66b8dc0 Mon Sep 17 00:00:00 2001 From: RINNECODER <93304526+RINNECODER@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:37:40 -0500 Subject: [PATCH 22/23] docs(debt): port the getrlimit, hw.model, host CPU check and fegetenv debt lines Upstream keeps these in docs/dev/debt/*.md; this fork keeps them in docs/dev/TechnicalDebt.md. The Host CPU check does not run on macOS hosts. Co-Authored-By: Claude Opus 5.5 --- docs/dev/TechnicalDebt.md | 4 ++++ docs/user/USAGE.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 629a29df8142..b0f52a84369d 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -70,6 +70,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelGetSystemSwVersion](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports baseline system software version `0x01000000` ("01.000.000"); the console's firmware version is not modeled. Measured on PS5 firmware 13.42: record values 0, 24, 39, 40, 41, 48 and 64 in the leading 64-bit field are accepted and preserved, the 28-byte string at offset 8 and packed version at 0x24 are filled, and bytes from 0x28 onward remain untouched. This API reports "13.590.001" / `0x13590001` in that environment, while the Prospero variant reports "13.420.000" / `0x13420000`; their values must not be assumed identical. A null pointer still returns `SCE_KERNEL_ERROR_EFAULT`, which was not measured; other firmware versions and record values remain unverified. - [sysconf](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) - `_SC_CLK_TCK` returns 128, FreeBSD's `CLK_TCK` as its [`sysconf`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libc/gen/sysconf.c#L100-L101) returns it ([`time.h`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/include/time.h#L48-L54)); the console's value is not checked, and no `times` reports ticks at that rate. CPython's `posix` module stops its import with "cannot read ticks_per_second" when the value is below 1, as a guest Python runtime does. Names other than `_SC_CLK_TCK`, `_SC_PAGESIZE`, `_SC_NPROCESSORS_CONF`, `_SC_NPROCESSORS_ONLN` and `_SC_PHYS_PAGES` fail with `EINVAL` - [getdtablesize](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - throws: FreeBSD returns the smaller of the `RLIMIT_NOFILE` soft limit and `maxfilesperproc` ([`sys_getdtablesize`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L338-L355)), and neither value is known for the console, where `getrlimit(RLIMIT_NOFILE)` throws too. A guest application imports it for a `closefrom` loop in the child of its spawn helper ([libc_stubs.c](https://github.com/ZiZc3/VLC/blob/d46be6a68f4244466b041c2dc1b640915ac1a983/ps5/compat/libc_stubs.c#L66-L72)), which never runs because its `fork` fails with `ENOSYS` +- [getrlimit](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - `RLIMIT_CPU`, `RLIMIT_FSIZE`, `RLIMIT_CORE`, `RLIMIT_SBSIZE`, `RLIMIT_VMEM`/`AS`, `RLIMIT_NPTS`, `RLIMIT_SWAP`, `RLIMIT_KQUEUES` and `RLIMIT_UMTXP` report infinity as in FreeBSD's process-0 defaults, and `RLIMIT_DATA` mirrors the host limit. `RLIMIT_NOFILE` reports, as both soft and hard limit, the number of descriptors after which AnyPS5 itself fails with `EMFILE`: on Windows the C runtime's 8192 low-level descriptors ([`_setmaxstdio`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio)), which guest files, pipes and sockets all take, and on Linux the host's `RLIMIT_NOFILE`, whose soft limit libkernel raises to the hard limit at load. The console's limit is not known; XPSemu (PPSA97358) reads it in QEMU's `os_setup_limits` and raises the soft limit to the hard one when they differ. `RLIMIT_STACK`, `RLIMIT_RSS`, `RLIMIT_MEMLOCK` and `RLIMIT_NPROC` throw because no console values are established. - [getpriority](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) follows FreeBSD 11.4's [`sys_getpriority`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_resource.c#L93-L165) for the only guest process, which is taken to run at nice 0: `PRIO_PROCESS` and `PRIO_PGRP` with 0 or its own pid (the guest is taken to lead its own process group, see `kill`) and `PRIO_USER` with 0 or its user id 0 return 0, any other id fails with `ESRCH` and any other `which` with `EINVAL`. As in FreeBSD's libc, where `getpriority` is the bare system call, errno is left unchanged on success. The nice value of a title process on the console is unverified, and the host nice of the process or of the threads `APS5_THREAD_PRIORITY=high` raises is not reported. `setpriority` accepts the same target ids (any other id fails with `ESRCH`, any other `which` with `EINVAL`), clamps the value to FreeBSD's `PRIO_MIN`-`PRIO_MAX` (-20 to 20) and stores it as the guest process's nice value, which `getpriority` returns; the host scheduling class is not changed, and whether a title process may lower the value without privilege is unverified - [chflags](../../core/libs/prx/libkernel/File/src/Stdio.cpp) (libkernel) follows FreeBSD 11.4's [`kern_chflagsat`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_syscalls.c#L2366-L2383) and UFS's [`ufs_setattr`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/ufs/ufs/ufs_vnops.c#L509-L556) for a root caller: the path lookup reports `EFAULT`, `ENOENT` and `ENOTDIR`, a flag outside the 17 UFS stores (`VNOVAL` included) `EOPNOTSUPP`, and `SF_SNAPSHOT` `EPERM`. Neither host keeps BSD file flags, so every file is taken to have none (`stat` reports `st_flags` 0): flags 0 succeed without touching the file, and any other flag throws, naming the flags. `UF_READONLY`, `UF_HIDDEN`, `UF_SYSTEM` and `UF_ARCHIVE` are FreeBSD's names for the Windows attributes but are not mapped to them: UFS stores them without enforcing them, `FILE_ATTRIBUTE_READONLY` already carries the owner write bit of `chmod` on Windows, and Linux has no equivalent a process can set without `CAP_LINUX_IMMUTABLE`. The console's filesystem types, `EROFS` on read-only mounts and the change-time update are not modelled - [pthread_setaffinity_np](../../core/libs/prx/libkernel/Pthread/Posix/Thread.cpp) (libkernel) - follows [FreeBSD 11.4](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libthr/thread/thr_affinity.c#L41-L62) libthr over `kern_cpuset_setaffinity` for the calling thread and any live guest thread: a size other than the 32-byte `cpuset_t` returns `ERANGE`, an unknown or finished thread `ESRCH`. Bits outside `sceKernelGetAvailableCpumask` are dropped and a mask with none of those bits returns `EDEADLK`, as `cpuset_setaffinity` does; the affinity is recorded on the guest thread and not applied to the host thread, and the console result is unverified @@ -348,6 +349,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceRtcFormatRFC2822, sceRtcFormatRFC2822LocalTime, sceRtcFormatRFC3339LocalTime](../../core/libs/prx/libSceRtc/Export.cpp) (libSceRtc) - only shadPS4 (PS4) has bodies. A null tick returns `INVALID_POINTER` like the existing `sceRtcFormatRFC3339`, where shadPS4 formats the current time instead; offsets outside ±1439 minutes return `INVALID_VALUE` like `sceRtcFormatRFC3339`; the local-time variants use the host's offset at the given instant (shadPS4 uses `sceKernelGettimezone`, the current offset) - [memcpy_s and memmove_s](../../core/libs/prx/libc/src/Strings.cpp) (libc) use the C11 K.3.7.1.1 and K.3.7.1.2 size constraints, with RSIZE_MAX taken as SIZE_MAX >> 1 as in memset_s. An oversized destination size returns ERANGE (34) without touching the destination; the console's RSIZE_MAX and exact error value are unverified. Constraint violations return an error without invoking the registered constraint handler, as before. - [snwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follows C11 K.3.9.1.3 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`. A runtime-constraint violation only returns a negative value: `set_constraint_handler_s` is not exported and the console's default handler is unknown. An invalid multibyte `%s` argument is copied byte by byte instead of being reported as an encoding error, as in `vswprintf` +- [fegetenv](../../core/libs/prx/libc/src/Math.cpp) (libSceLibcInternal, implemented in libc, NID `psx0YiAKm7k`) follows FreeBSD 11 amd64 [fenv.c](https://github.com/freebsd/freebsd-src/blob/4554bee35405b36ea19e9e60d6abe6ea534e36e0/lib/msun/amd64/fenv.c) with the 32-byte `fenv_t` of [x86/fenv.h](https://github.com/freebsd/freebsd-src/blob/4554bee35405b36ea19e9e60d6abe6ea534e36e0/lib/msun/x86/fenv.h): `fnstenv` fills the 28-byte x87 part, MXCSR follows at 0x1c, and the x87 control word is reloaded because `fnstenv` masks every x87 exception. That the console's `libSceLibcInternal` has the same code and layout is assumed, not read from its binary. A null pointer throws instead of faulting - [swprintf_s and vswprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follow C11 K.3.9.1.4 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`: the complete output, including the terminating null, must fit in the buffer, otherwise it is a runtime-constraint violation that sets `buffer[0]` to zero and returns a negative value, and the buffer is not partially written. Argument and encoding checks match `snwprintf_s` - [vsnwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - `va_list` counterpart of `snwprintf_s` (C11 K.3.9.1.3): truncates to the buffer and returns the full length, with the same constraints and argument checks - [vsnprintf_s and vsscanf_s](../../core/libs/prx/libc/src/Formatting.cpp) (libc) - `vsnprintf_s` forwards to `vsnprintf` semantics: the C11 K.3.7.1.5 runtime constraints (null buffer, `size == 0`, `%n`, null `%s`) are not checked, so `size == 0` returns the would-be length instead of a negative value, and no constraint handler is invoked. `vsscanf_s` returns the count of items converted before an undersized `%s`/`%c`/`%[` destination (0 when it is the first), not EOF. Neither is confirmed on a PS5 title @@ -691,6 +693,8 @@ Throughout the project, every function at every stage either **does exactly what - [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_GETFL`, `F_SETFL` with `O_NONBLOCK`, `EINVAL` for every other command, `F_GETFD` and `F_SETFD` included). 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_GETFL` takes the access mode from the host (the granted access of the handle on Windows), so pipe ends report `O_RDONLY` and `O_WRONLY` where FreeBSD's bidirectional pipes report `O_RDWR`. `F_DUPFD` and `F_DUPFD_CLOEXEC` return 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. Changing `O_APPEND` on a Windows file, changing `O_FSYNC` on a file, `O_ASYNC` on a pipe or character device (`SIGIO` is not delivered), `F_GETOWN`, `F_SETOWN` and `F_SETLK_REMOTE` throw; `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 throw on Windows, and `F_GETLK` with `F_UNLCK` throws. The return values and error codes are unverified on a console - [ioctl, _ioctl](../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) handle only `FIONBIO` and `FIONREAD` on a socket, and any other request there fails with `ENOTTY`. On the other descriptors they follow FreeBSD's [`kern_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/sys_generic.c#L758), [`vn_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_vnops.c#L1488) and [`pipe_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/sys_pipe.c#L1346): `FIONBIO` sets `O_NONBLOCK` as `fcntl` does, `FIOCLEX` and `FIONCLEX` set and clear the close-on-exec flag `F_GETFD` reports, and `FIONREAD` reports the size past the offset of a file, the queued bytes of a pipe's read end, 0 on its write end and `ENOTTY` on the random device, while it throws on a directory or another character device. Every termios request (group `t`, `TIOCGWINSZ` included) fails with `ENOTTY`, since those descriptors are taken as not a terminal, as in `tcgetattr`, and any other request throws. Stremio Plus imports `_ioctl` for its statically linked `tc*` functions, which send `TIOCGETA`, `TIOCSETA`, `TIOCSPGRP` and the other termios requests - [Regular file mappings](../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp) (libkernel) - on Linux `mmap` maps a regular file's descriptor shared or private like a shared memory object, with the same access checks; SQLite's WAL index (`-shm`) needs it. FreeBSD 11 `mmap(2)` and shadPS4's `MemoryManager::MapFile` map regular files; the console's behaviour is not measured. Other descriptors (pipes, sockets, directories, devices) still fail with `EOPNOTSUPP`, and Windows maps no files. +- [Host CPU check](../../core/libs/prx/libkernel/System/src/HostCpu.cpp) (libkernel) - when libkernel loads on a Linux or Windows x86-64 host, it logs which of the PS5 CPU's user-mode extensions CPUID reports and throws, naming the host CPU, if any extension is missing that LLVM selects from plain C/C++ for the PS5's Zen 2 (`-march=znver2`, [feature list](https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/llvm/lib/Target/X86/X86.td#L1459-L1513)): SSE to SSE4.2, SSSE3, POPCNT, LZCNT, BMI1, BMI2, MOVBE, CMPXCHG16B, LAHF/SAHF, AVX, AVX2, FMA, F16C, and the operating system's AVX state in XCR0 (#3719). SSE4A, CLZERO and SHA, which `--to-intel` converts, and AES, PCLMULQDQ, RDRAND, RDSEED, ADX, CLFLUSHOPT, CLWB, RDPID, XSAVEOPT, XSAVEC and PREFETCHW, which compilers emit only for intrinsics or explicit prefetches, are logged but not required: a title that executes one of them on a host without it still stops with an illegal instruction. macOS hosts are not checked, because Rosetta runs AVX2, FMA, BMI1/2, F16C and MOVBE without reporting them through CPUID +- [hw.model](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports the [host CPU's name](../../core/libs/prx/libkernel/System/src/HostCpu.cpp), built as FreeBSD 11 builds `hw.model`: the CPUID brand string (leaves 0x80000002 to 0x80000004) without leading spaces ([identcpu.c](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/x86/x86/identcpu.c#L683-L691)). Trailing padding stays, as it does there, so an AMD host's name ends in spaces. The name a PS5 reports is unknown. A write returns -1 with `EPERM`. A host without an x86 CPUID brand string, such as an Apple Silicon Mac, throws. PPSA99203 only prints it (`[console] hw.model: %s`) - [pthread_kill](../../core/libs/prx/libkernel/System/src/Signals.cpp) (libkernel) returns the error number like FreeBSD's `pthread_kill`: `EINVAL` for signals outside 0 to 128 and `ESRCH` for a null thread. Signal 0 reports any other thread handle as existing, without checking that the thread is still alive. A signal to the calling thread goes through `raise`, so it shares `raise`'s limits; a signal to another thread throws, since guest signals are not delivered to a chosen thread - [select](../../core/libs/prx/libkernel/Socket/src/Socket.cpp) (libkernel) validates `tv_usec` but saturates a valid timeout beyond the remaining `steady_clock` range at `time_point::max()`, so the wait can continue effectively indefinitely. The console's behavior for a valid timeout outside the host clock's range is unknown. - [AJM](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp), [APR](../../core/libs/prx/libkernel/Apr/src/Apr.cpp) and [NGS2](../../core/libs/prx/libSceNgs2.native/src/System.cpp) state is allocated with `new` and never freed on purpose: title threads still call into these libraries while `std::exit` runs static destructors, so ordinary statics would be destroyed under them. Keep them leaked; `guest_ajm_teardown` covers the AJM case on Unix. diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index a282eb43f9d8..aa3694bd106f 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -35,7 +35,7 @@ relinker --macos source/input.elf eboot Add `--to-intel` for Intel hosts, or `--to-rosetta` for Rosetta; a title that runs under Rosetta on Apple silicon is relinked with `--macos --to-rosetta`. The output format defaults to Linux ELF regardless of the filename; `.exe` alone does not select Windows. -Titles run natively, so the host CPU needs the extensions of the PS5's Zen 2 CPU that compiled code uses without checking, among them AVX2, FMA, F16C, BMI1, BMI2, LZCNT and MOVBE. On Linux and Windows a converted title logs the host CPU's extensions at start-up and stops before running any title code, naming the CPU and the missing extensions, if one is absent ([list](../dev/debt/libkernel.md)). +Titles run natively, so the host CPU needs the extensions of the PS5's Zen 2 CPU that compiled code uses without checking, among them AVX2, FMA, F16C, BMI1, BMI2, LZCNT and MOVBE. On Linux and Windows a converted title logs the host CPU's extensions at start-up and stops before running any title code, naming the CPU and the missing extensions, if one is absent ([list](../dev/TechnicalDebt.md)). The executable, registry, Windows import diagnostics, icon and desktop entry output files must not refer to the input executable or a bundled module being converted, including through a hard link or symbolic link. These collisions fail before any output is written. An existing output file can be replaced if it is separate from those inputs. From ed06a35c0304669aad90f67de513efb43270cd17 Mon Sep 17 00:00:00 2001 From: RINNECODER <93304526+RINNECODER@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:38:35 -0500 Subject: [PATCH 23/23] docs(debt): keep title names out of the ported debt lines Co-Authored-By: Claude Opus 5.5 --- docs/dev/TechnicalDebt.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index b0f52a84369d..2167b33bd517 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -1,6 +1,6 @@ # Project technical debt -- [sceKernelGetSocPowerConsumption](../../core/libs/prx/libkernel/System/src/ThermalSensors.cpp) (libkernel) - returns `EINVAL` and writes nothing, as `sceKernelGetSocSensorTemperature` does when the host has no sensor: the host's package power is not read (Linux RAPL `energy_uj` is readable by root only, and Windows has no general source). The prototype is not documented. PS5LM Plus (PPSA99581) passes a zeroed 128-byte buffer and, on success, reads its first 32-bit word as milliwatts, accepting 1000 to 350000; on failure it shows 0 W +- [sceKernelGetSocPowerConsumption](../../core/libs/prx/libkernel/System/src/ThermalSensors.cpp) (libkernel) - returns `EINVAL` and writes nothing, as `sceKernelGetSocSensorTemperature` does when the host has no sensor: the host's package power is not read (Linux RAPL `energy_uj` is readable by root only, and Windows has no general source). The prototype is not documented. A title passes a zeroed 128-byte buffer and, on success, reads its first 32-bit word as milliwatts, accepting 1000 to 350000; on failure it shows 0 W ### Build - Building on Windows requires a specific version of mingw - MinGW-w64 GCC 15.2.0 (`winlibs-gcc15`, `x86_64-ucrt-posix-seh`) @@ -70,7 +70,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelGetSystemSwVersion](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports baseline system software version `0x01000000` ("01.000.000"); the console's firmware version is not modeled. Measured on PS5 firmware 13.42: record values 0, 24, 39, 40, 41, 48 and 64 in the leading 64-bit field are accepted and preserved, the 28-byte string at offset 8 and packed version at 0x24 are filled, and bytes from 0x28 onward remain untouched. This API reports "13.590.001" / `0x13590001` in that environment, while the Prospero variant reports "13.420.000" / `0x13420000`; their values must not be assumed identical. A null pointer still returns `SCE_KERNEL_ERROR_EFAULT`, which was not measured; other firmware versions and record values remain unverified. - [sysconf](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) - `_SC_CLK_TCK` returns 128, FreeBSD's `CLK_TCK` as its [`sysconf`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libc/gen/sysconf.c#L100-L101) returns it ([`time.h`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/include/time.h#L48-L54)); the console's value is not checked, and no `times` reports ticks at that rate. CPython's `posix` module stops its import with "cannot read ticks_per_second" when the value is below 1, as a guest Python runtime does. Names other than `_SC_CLK_TCK`, `_SC_PAGESIZE`, `_SC_NPROCESSORS_CONF`, `_SC_NPROCESSORS_ONLN` and `_SC_PHYS_PAGES` fail with `EINVAL` - [getdtablesize](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - throws: FreeBSD returns the smaller of the `RLIMIT_NOFILE` soft limit and `maxfilesperproc` ([`sys_getdtablesize`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_descrip.c#L338-L355)), and neither value is known for the console, where `getrlimit(RLIMIT_NOFILE)` throws too. A guest application imports it for a `closefrom` loop in the child of its spawn helper ([libc_stubs.c](https://github.com/ZiZc3/VLC/blob/d46be6a68f4244466b041c2dc1b640915ac1a983/ps5/compat/libc_stubs.c#L66-L72)), which never runs because its `fork` fails with `ENOSYS` -- [getrlimit](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - `RLIMIT_CPU`, `RLIMIT_FSIZE`, `RLIMIT_CORE`, `RLIMIT_SBSIZE`, `RLIMIT_VMEM`/`AS`, `RLIMIT_NPTS`, `RLIMIT_SWAP`, `RLIMIT_KQUEUES` and `RLIMIT_UMTXP` report infinity as in FreeBSD's process-0 defaults, and `RLIMIT_DATA` mirrors the host limit. `RLIMIT_NOFILE` reports, as both soft and hard limit, the number of descriptors after which AnyPS5 itself fails with `EMFILE`: on Windows the C runtime's 8192 low-level descriptors ([`_setmaxstdio`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio)), which guest files, pipes and sockets all take, and on Linux the host's `RLIMIT_NOFILE`, whose soft limit libkernel raises to the hard limit at load. The console's limit is not known; XPSemu (PPSA97358) reads it in QEMU's `os_setup_limits` and raises the soft limit to the hard one when they differ. `RLIMIT_STACK`, `RLIMIT_RSS`, `RLIMIT_MEMLOCK` and `RLIMIT_NPROC` throw because no console values are established. +- [getrlimit](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - `RLIMIT_CPU`, `RLIMIT_FSIZE`, `RLIMIT_CORE`, `RLIMIT_SBSIZE`, `RLIMIT_VMEM`/`AS`, `RLIMIT_NPTS`, `RLIMIT_SWAP`, `RLIMIT_KQUEUES` and `RLIMIT_UMTXP` report infinity as in FreeBSD's process-0 defaults, and `RLIMIT_DATA` mirrors the host limit. `RLIMIT_NOFILE` reports, as both soft and hard limit, the number of descriptors after which AnyPS5 itself fails with `EMFILE`: on Windows the C runtime's 8192 low-level descriptors ([`_setmaxstdio`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio)), which guest files, pipes and sockets all take, and on Linux the host's `RLIMIT_NOFILE`, whose soft limit libkernel raises to the hard limit at load. The console's limit is not known; a title reads it in QEMU's `os_setup_limits` and raises the soft limit to the hard one when they differ. `RLIMIT_STACK`, `RLIMIT_RSS`, `RLIMIT_MEMLOCK` and `RLIMIT_NPROC` throw because no console values are established. - [getpriority](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) follows FreeBSD 11.4's [`sys_getpriority`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/kern_resource.c#L93-L165) for the only guest process, which is taken to run at nice 0: `PRIO_PROCESS` and `PRIO_PGRP` with 0 or its own pid (the guest is taken to lead its own process group, see `kill`) and `PRIO_USER` with 0 or its user id 0 return 0, any other id fails with `ESRCH` and any other `which` with `EINVAL`. As in FreeBSD's libc, where `getpriority` is the bare system call, errno is left unchanged on success. The nice value of a title process on the console is unverified, and the host nice of the process or of the threads `APS5_THREAD_PRIORITY=high` raises is not reported. `setpriority` accepts the same target ids (any other id fails with `ESRCH`, any other `which` with `EINVAL`), clamps the value to FreeBSD's `PRIO_MIN`-`PRIO_MAX` (-20 to 20) and stores it as the guest process's nice value, which `getpriority` returns; the host scheduling class is not changed, and whether a title process may lower the value without privilege is unverified - [chflags](../../core/libs/prx/libkernel/File/src/Stdio.cpp) (libkernel) follows FreeBSD 11.4's [`kern_chflagsat`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_syscalls.c#L2366-L2383) and UFS's [`ufs_setattr`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/ufs/ufs/ufs_vnops.c#L509-L556) for a root caller: the path lookup reports `EFAULT`, `ENOENT` and `ENOTDIR`, a flag outside the 17 UFS stores (`VNOVAL` included) `EOPNOTSUPP`, and `SF_SNAPSHOT` `EPERM`. Neither host keeps BSD file flags, so every file is taken to have none (`stat` reports `st_flags` 0): flags 0 succeed without touching the file, and any other flag throws, naming the flags. `UF_READONLY`, `UF_HIDDEN`, `UF_SYSTEM` and `UF_ARCHIVE` are FreeBSD's names for the Windows attributes but are not mapped to them: UFS stores them without enforcing them, `FILE_ATTRIBUTE_READONLY` already carries the owner write bit of `chmod` on Windows, and Linux has no equivalent a process can set without `CAP_LINUX_IMMUTABLE`. The console's filesystem types, `EROFS` on read-only mounts and the change-time update are not modelled - [pthread_setaffinity_np](../../core/libs/prx/libkernel/Pthread/Posix/Thread.cpp) (libkernel) - follows [FreeBSD 11.4](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libthr/thread/thr_affinity.c#L41-L62) libthr over `kern_cpuset_setaffinity` for the calling thread and any live guest thread: a size other than the 32-byte `cpuset_t` returns `ERANGE`, an unknown or finished thread `ESRCH`. Bits outside `sceKernelGetAvailableCpumask` are dropped and a mask with none of those bits returns `EDEADLK`, as `cpuset_setaffinity` does; the affinity is recorded on the guest thread and not applied to the host thread, and the console result is unverified @@ -229,7 +229,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 is accepted and ignored; its meaning is not established. KytyPS5 (`GUEST_MAP_UNKNOWN_8000`) and sharpemu accept it without reading it. Every known caller is the SDK 9 `libc.prx` heap (Astro Bot PPSA21564, PPSA22520), which passes it with read/write protection and uses the mapping as an older `libc.prx` uses `sceKernelMapNamedFlexibleMemory` with flags 0 - [sceKernelMtypeprotect](../../core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp) (libkernel) - sets the memory type of the direct mappings in the page-rounded range and of the direct memory behind them, as shadPS4 and prosper do (KytyPS5 ignores the type); the type is not validated, flexible pages in the range only get the protection, and a later map of the retyped direct memory reports the type it was allocated with. `sceKernelBatchMap2` operation 4 takes the same path with the entry type - [Map hints inside a reservation](../../core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp) (libkernel) - `sceKernelMapDirectMemory` and the flexible and anonymous maps place a mapping without `MAP_FIXED` at its hint address when the whole range lies in a range still reserved by `sceKernelReserveVirtualRange`, as if `MAP_FIXED` were set. Taken from PPSA01474, which reserves 64 GiB and then maps its heaps inside it with hints and no `MAP_FIXED`, and uses the hint addresses afterwards; not measured on the console. Hints outside a reservation, or over a range that is partly mapped, stay hints -- [Fixed anonymous mmap](../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp) (libkernel) - `MAP_PRIVATE | MAP_ANON | MAP_FIXED` replaces the requested range through the existing guest mapping machinery and zeroes the new memory. `MAP_EXCL` is checked under the allocation-registry mutation lock, including virtual reservations, and returns `ENOMEM` without changing an occupied range; without `MAP_FIXED` it is `EINVAL`. Lengths are rounded to 16 KiB, while fixed addresses must be aligned and the complete rounded range must lie inside the guest arena. This follows FreeBSD 11.4 [argument validation and rounding](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_mmap.c#L226-L299), [fixed replacement](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_map.c#L1455-L1464), and [collision errno](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_mmap.c#L1604-L1613). The console behaviour has not been measured. AnyPS5 starts the guest arena at 0x200000000, so the fixed path rejects the low 0x400000 address requested by PICO-8 PPSA99808. The console address-space layout is unmeasured; executable placement outside the host arena is tracked in #5217. Static catalog disassembly finds `0x1012` in PPSA98001/PPSA99808 and `0x5012` in PPSA99808; these titles were not run. +- [Fixed anonymous mmap](../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp) (libkernel) - `MAP_PRIVATE | MAP_ANON | MAP_FIXED` replaces the requested range through the existing guest mapping machinery and zeroes the new memory. `MAP_EXCL` is checked under the allocation-registry mutation lock, including virtual reservations, and returns `ENOMEM` without changing an occupied range; without `MAP_FIXED` it is `EINVAL`. Lengths are rounded to 16 KiB, while fixed addresses must be aligned and the complete rounded range must lie inside the guest arena. This follows FreeBSD 11.4 [argument validation and rounding](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_mmap.c#L226-L299), [fixed replacement](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_map.c#L1455-L1464), and [collision errno](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/vm/vm_mmap.c#L1604-L1613). The console behaviour has not been measured. AnyPS5 starts the guest arena at 0x200000000, so the fixed path rejects the low 0x400000 address requested by a title. The console address-space layout is unmeasured; executable placement outside the host arena is tracked in #5217. Static catalog disassembly finds `0x1012` in the audited titles and `0x5012` in the audited titles; these titles were not run. - [tzname](../../core/libs/prx/libc/src/Time.cpp) (libc) points at the host's zone names, read at load and again by `tzset`: the abbreviations a `TZ` string gives (`EST5EDT` is `EST` and `EDT` on both hosts), but on Windows without `TZ` the CRT's full names such as `GMT Standard Time`, which ICU's [uprv_tzname](https://github.com/unicode-org/icu/blob/457157a92aa053e632cc7fcfd0e12f8a943b2d11/icu4c/source/common/putil.cpp#L1244-L1264) cannot map to a zone ID. A zone with no daylight-saving time has `tzname[1]` empty on Windows and equal to `tzname[0]` on Linux, where FreeBSD leaves three spaces. The console's names are not known - [Guest arena](../../core/libs/prx/libc/src/GuestArena.cpp) (libc) - the application map area is assumed to end at 0xFC_0000_0000, as `SCE_KERNEL_APP_MAP_AREA_END_ADDR` does on the PS4. On Windows, host allocations made in the arena before libc loads stay, and a fixed guest mapping over one throws - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature @@ -694,7 +694,7 @@ Throughout the project, every function at every stage either **does exactly what - [ioctl, _ioctl](../../core/libs/prx/libkernel/Socket/src/Udp.cpp) (libkernel) handle only `FIONBIO` and `FIONREAD` on a socket, and any other request there fails with `ENOTTY`. On the other descriptors they follow FreeBSD's [`kern_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/sys_generic.c#L758), [`vn_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/vfs_vnops.c#L1488) and [`pipe_ioctl`](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/sys/kern/sys_pipe.c#L1346): `FIONBIO` sets `O_NONBLOCK` as `fcntl` does, `FIOCLEX` and `FIONCLEX` set and clear the close-on-exec flag `F_GETFD` reports, and `FIONREAD` reports the size past the offset of a file, the queued bytes of a pipe's read end, 0 on its write end and `ENOTTY` on the random device, while it throws on a directory or another character device. Every termios request (group `t`, `TIOCGWINSZ` included) fails with `ENOTTY`, since those descriptors are taken as not a terminal, as in `tcgetattr`, and any other request throws. Stremio Plus imports `_ioctl` for its statically linked `tc*` functions, which send `TIOCGETA`, `TIOCSETA`, `TIOCSPGRP` and the other termios requests - [Regular file mappings](../../core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp) (libkernel) - on Linux `mmap` maps a regular file's descriptor shared or private like a shared memory object, with the same access checks; SQLite's WAL index (`-shm`) needs it. FreeBSD 11 `mmap(2)` and shadPS4's `MemoryManager::MapFile` map regular files; the console's behaviour is not measured. Other descriptors (pipes, sockets, directories, devices) still fail with `EOPNOTSUPP`, and Windows maps no files. - [Host CPU check](../../core/libs/prx/libkernel/System/src/HostCpu.cpp) (libkernel) - when libkernel loads on a Linux or Windows x86-64 host, it logs which of the PS5 CPU's user-mode extensions CPUID reports and throws, naming the host CPU, if any extension is missing that LLVM selects from plain C/C++ for the PS5's Zen 2 (`-march=znver2`, [feature list](https://github.com/llvm/llvm-project/blob/llvmorg-19.1.7/llvm/lib/Target/X86/X86.td#L1459-L1513)): SSE to SSE4.2, SSSE3, POPCNT, LZCNT, BMI1, BMI2, MOVBE, CMPXCHG16B, LAHF/SAHF, AVX, AVX2, FMA, F16C, and the operating system's AVX state in XCR0 (#3719). SSE4A, CLZERO and SHA, which `--to-intel` converts, and AES, PCLMULQDQ, RDRAND, RDSEED, ADX, CLFLUSHOPT, CLWB, RDPID, XSAVEOPT, XSAVEC and PREFETCHW, which compilers emit only for intrinsics or explicit prefetches, are logged but not required: a title that executes one of them on a host without it still stops with an illegal instruction. macOS hosts are not checked, because Rosetta runs AVX2, FMA, BMI1/2, F16C and MOVBE without reporting them through CPUID -- [hw.model](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports the [host CPU's name](../../core/libs/prx/libkernel/System/src/HostCpu.cpp), built as FreeBSD 11 builds `hw.model`: the CPUID brand string (leaves 0x80000002 to 0x80000004) without leading spaces ([identcpu.c](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/x86/x86/identcpu.c#L683-L691)). Trailing padding stays, as it does there, so an AMD host's name ends in spaces. The name a PS5 reports is unknown. A write returns -1 with `EPERM`. A host without an x86 CPUID brand string, such as an Apple Silicon Mac, throws. PPSA99203 only prints it (`[console] hw.model: %s`) +- [hw.model](../../core/libs/prx/libkernel/System/src/SystemConfiguration.cpp) (libkernel) reports the [host CPU's name](../../core/libs/prx/libkernel/System/src/HostCpu.cpp), built as FreeBSD 11 builds `hw.model`: the CPUID brand string (leaves 0x80000002 to 0x80000004) without leading spaces ([identcpu.c](https://github.com/freebsd/freebsd-src/blob/release/11.0.0/sys/x86/x86/identcpu.c#L683-L691)). Trailing padding stays, as it does there, so an AMD host's name ends in spaces. The name a PS5 reports is unknown. A write returns -1 with `EPERM`. A host without an x86 CPUID brand string, such as an Apple Silicon Mac, throws. Another title only prints it (`[console] hw.model: %s`) - [pthread_kill](../../core/libs/prx/libkernel/System/src/Signals.cpp) (libkernel) returns the error number like FreeBSD's `pthread_kill`: `EINVAL` for signals outside 0 to 128 and `ESRCH` for a null thread. Signal 0 reports any other thread handle as existing, without checking that the thread is still alive. A signal to the calling thread goes through `raise`, so it shares `raise`'s limits; a signal to another thread throws, since guest signals are not delivered to a chosen thread - [select](../../core/libs/prx/libkernel/Socket/src/Socket.cpp) (libkernel) validates `tv_usec` but saturates a valid timeout beyond the remaining `steady_clock` range at `time_point::max()`, so the wait can continue effectively indefinitely. The console's behavior for a valid timeout outside the host clock's range is unknown. - [AJM](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp), [APR](../../core/libs/prx/libkernel/Apr/src/Apr.cpp) and [NGS2](../../core/libs/prx/libSceNgs2.native/src/System.cpp) state is allocated with `new` and never freed on purpose: title threads still call into these libraries while `std::exit` runs static destructors, so ordinary statics would be destroyed under them. Keep them leaked; `guest_ajm_teardown` covers the AJM case on Unix. @@ -703,7 +703,7 @@ Throughout the project, every function at every stage either **does exactly what - PPSA07411 PS VR2 imports declared without parameters, signatures unknown, added without an implementation because the title fails to load without them: [sceHmd2GetDeviceInformationByHandle, sceHmd2GetFieldOfView and sceHmd2Terminate](../../core/libs/prx/libSceHmd2/Export.cpp) (libSceHmd2), [scePadVrControllerSetVibration, scePadVrControllerSetVibrationMode and scePadVrControllerReadCombinedState](../../core/libs/prx/libScePad/Export.cpp) (libScePad) and [sceVrTracker2ResetLocalCoordinate](../../core/libs/prx/libSceVrTracker2/Export.cpp) (libSceVrTracker2) - [Descriptor pool recycling](../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) avoids individually freed sets: [RADV 26.2.2](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-26.2.2/src/amd/vulkan/radv_descriptor_pool.c) initializes its free-set heap with 32 bytes beyond the backing allocation. An allocation-only RX 6600 test reproduces acceptance of a 4,128-byte set in a 4,096-byte pool; the path without individual frees rejects it. Pools reset after their last set is released. A cached set can retain unused slots in an exhausted pool until eviction; peak gameplay pool memory remains unmeasured. - [_fstatfs](../../core/libs/prx/libkernel/File/src/Stdio.cpp) (libkernel) fills the FreeBSD 11 `struct statfs` of the PS5 payload SDK with the host volume that holds the file: block size, transfer size, total, free and available blocks, maximum name length and the read-only, `nosuid` and `noexec` flags (on Windows only read-only, and `f_files` and `f_ffree` are 0, as NTFS has no fixed number of files). The filesystem type number and name, mount paths, owner, filesystem id and I/O counters are left 0 or empty, since they would describe a host mount, not a console one. Sockets and pipes return `EINVAL`, as FreeBSD's `getvnode` does; a Windows descriptor that is neither a file nor a pipe throws. Stremio Plus (PPSA74126) reads the free space before a download and only logs the other fields -- [sceKernelGetPageTableStats](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) reports page-table entries over the recorded protection ranges (committed mappings; reservations are not recorded): each range charges one entry per 2 MiB granule it spans to the cpu pool when it has CPU access bits (0x7) and to the gpu pool when it has GPU access bits (0x30), so a range with both counts in both and two ranges sharing one granule charge it once each, as KytyPS5 sums per committed range. Mappings with no access bits, such as PROT_NONE or ACP-only protections, charge neither pool. The 2048-entry budget per side, its constants, and whether the console counts reservations or guest image segments are unverified. Resonance: A Plague Tale Legacy (PPSA30601) reaches this call after the other missing exports of its start-up are provided +- [sceKernelGetPageTableStats](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) reports page-table entries over the recorded protection ranges (committed mappings; reservations are not recorded): each range charges one entry per 2 MiB granule it spans to the cpu pool when it has CPU access bits (0x7) and to the gpu pool when it has GPU access bits (0x30), so a range with both counts in both and two ranges sharing one granule charge it once each, as KytyPS5 sums per committed range. Mappings with no access bits, such as PROT_NONE or ACP-only protections, charge neither pool. The 2048-entry budget per side, its constants, and whether the console counts reservations or guest image segments are unverified. A title reaches this call after the other missing exports of its start-up are provided - [fstatvfs](../../core/libs/prx/libSceLibcInternal/FilesystemStatistics.cpp) (libSceLibcInternal) converts `_fstatfs` to the 88-byte `struct statvfs` as FreeBSD 9.2's `sfs2svfs` does (`f_bsize` from the transfer size, `f_frsize` from the block size, `f_favail` equal to `f_ffree`, `f_fsid` 0, `ST_RDONLY` and `ST_NOSUID` only). Differences: `f_namemax` is the `statfs` value, not `fpathconf(_PC_NAME_MAX)`; negative `f_bavail` and `f_ffree` wrap to unsigned without `EOVERFLOW`, as the same-width copy in FreeBSD does; inode counts are 0 on Windows, inherited from `_fstatfs`; a null output returns `EFAULT` after the descriptor is validated, where FreeBSD would fault. Layout and conversion are unverified against the PS5 library (PS5MC imports `fstatvfs` but was not run) - [sceVoiceQoSEnd](../../core/libs/prx/libSceVoiceQoS/Export.cpp) (libSceVoiceQoS) - `0x804E0901` (not initialized) before any initialization was measured on a PS5 (firmware 13.60, #1407); ending an initialized library was not, because a valid `sceVoiceQoSInit` never returns inside a homebrew payload. PPSA14632 calls it at shutdown and PPSA26344 after a nonzero `sceVoiceQoSInit`. After an initialization it returns 0 and clears the init flag, so the library can be initialized again. Whether the console also ends the libSceVoice instance that its `sceVoiceQoSInit` starts ([prosper](https://github.com/mattias800/prosper)'s reading of the module), and what it answers while endpoints exist, is unknown; no endpoint is implemented - [sceSharePlayGetCurrentConnectionInfoA](../../core/libs/prx/libSceSharePlay/Export.cpp) (libSceSharePlay) - reports no Share Play session, as the library keeps none: status 0 (DORMANT), mode 0, empty online IDs, account IDs 0 and both user IDs -1 (`SCE_USER_SERVICE_USER_ID_INVALID`). A null pointer returns `SCE_SHARE_PLAY_ERROR_INVALID_ARGS` (0x810E0001). The 72-byte `SceSharePlayConnectionInfoA` layout and the error code follow [KytyPS5](https://github.com/KytyPS5/KytyPS5/blob/main/src/libs/libNet.cpp) and [fpPS4](https://github.com/red-prig/fpPS4/blob/trunk/src/ps4_libsceshareplay.pas), which agree on both; KytyPS5 sets the user IDs to -1 and fpPS4 leaves them 0, and which one the console returns is not verified. KytyPS5 also returns `SCE_SHARE_PLAY_ERROR_NOT_INITIALIZED` before `sceSharePlayInitialize`; this library keeps no initialization state and does not.