Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions core/libs/prx/libkernel/DirectMemory/Export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,32 @@ bool UndefinedProtection(int prot) {
return (prot & ~0x3F7) != 0;
}

bool RefusedFlexibleFlag(int flags) {
switch (flags) {
case 0x1:
case 0x2:
case 0x4:
case 0x8:
case 0x20:
case 0x40:
case 0x100:
case 0x200:
case 0x400:
case 0x800:
case 0x1000:
case 0x2000:
case 0x4000:
case 0x10000:
case 0x20000:
case 0x40000:
case 0x80000:
case 0x100000:
return true;
default:
return false;
}
}

constexpr int PRT_APERTURE_COUNT = 3;

struct PrtAperture {
Expand Down Expand Up @@ -309,7 +335,7 @@ int APS5_VABI sceKernelMapDirectMemory2(void** addr, size_t len, int type, int p
}

int APS5_VABI sceKernelMapFlexibleMemory(void** addr_in_out, size_t len, int prot, int flags) {
if (UndefinedProtection(prot)) return SCE_KERNEL_ERROR_EINVAL;
if (UndefinedProtection(prot) || RefusedFlexibleFlag(flags)) return SCE_KERNEL_ERROR_EINVAL;
constexpr int IgnoredHeapFlag = 0x8000;
return _mapFlexible(addr_in_out, len, prot, flags & ~IgnoredHeapFlag);
}
Expand All @@ -323,7 +349,7 @@ int APS5_VABI sceKernelMapNamedDirectMemory(void** addr, size_t len, int prot, i
}

int32_t APS5_VABI sceKernelMapNamedFlexibleMemory(void** addr_in_out, size_t len, int prot, int flags, const char* name) {
if (UndefinedProtection(prot)) return SCE_KERNEL_ERROR_EINVAL;
if (UndefinedProtection(prot) || flags == 0x8000) return SCE_KERNEL_ERROR_EINVAL;
const int result = _mapFlexible(addr_in_out, len, prot, flags);
if (result == 0 && name) sceKernelSetVirtualRangeName(*addr_in_out, len, name);
return result;
Expand Down
23 changes: 18 additions & 5 deletions core/libs/tests/GuestMemory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,6 @@ static void CheckFlexibleMappingIgnoresFlag8000() {
Require(static_cast<volatile unsigned char*>(again)[length - 1] == 0);
Require(sceKernelMunmap(reinterpret_cast<std::uint64_t>(again), length) == 0);
Require(sceKernelAvailableFlexibleMemorySize(&available) == 0 && available == before);
bool rejected = false;
void* unknown = nullptr;
try { sceKernelMapFlexibleMemory(&unknown, length, 3, 0x20000); } catch (const std::exception&) { rejected = true; }
Require(rejected && unknown == nullptr);
Require(sceKernelAvailableFlexibleMemorySize(&available) == 0 && available == before);
Require(sceKernelAvailableFlexibleMemorySize(nullptr) == SCE_KERNEL_ERROR_EINVAL);
Require(sceKernelAvailableFlexibleMemorySize(reinterpret_cast<std::size_t*>(0x10)) == SCE_KERNEL_ERROR_EFAULT);
std::size_t configured = 0;
Expand All @@ -151,6 +146,23 @@ static void CheckFlexibleMappingIgnoresFlag8000() {
Require(sceKernelConfiguredFlexibleMemorySize(reinterpret_cast<std::size_t*>(0x10)) == SCE_KERNEL_ERROR_EFAULT);
}

static void CheckFlexibleMappingRefusesMeasuredFlags() {
constexpr std::size_t length = 0x10000;
std::size_t before = 0;
std::size_t available = 0;
Require(sceKernelAvailableFlexibleMemorySize(&before) == 0);
for (const int flag : {0x1, 0x2, 0x4, 0x8, 0x20, 0x40, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000}) {
void* mapped = nullptr;
Require(sceKernelMapFlexibleMemory(&mapped, length, 3, flag) == SCE_KERNEL_ERROR_EINVAL && mapped == nullptr);
void* sentinel = reinterpret_cast<void*>(0x1000);
Require(sceKernelMapFlexibleMemory(&sentinel, length, 3, flag) == SCE_KERNEL_ERROR_EINVAL && sentinel == reinterpret_cast<void*>(0x1000));
Require(sceKernelAvailableFlexibleMemorySize(&available) == 0 && available == before);
}
void* named = nullptr;
Require(sceKernelMapNamedFlexibleMemory(&named, length, 3, 0x8000, "flag 8000") == SCE_KERNEL_ERROR_EINVAL && named == nullptr);
Require(sceKernelAvailableFlexibleMemorySize(&available) == 0 && available == before);
}

static void CheckPageTableStats() {
int cpuTotal = -1, cpuAvailable = -1, gpuTotal = -1, gpuAvailable = -1;
Require(sceKernelGetPageTableStats(&cpuTotal, &cpuAvailable, &gpuTotal, &gpuAvailable) == 0);
Expand Down Expand Up @@ -4171,6 +4183,7 @@ int main(int argc, char** argv) {
CheckMemoryPoolBlockStats();
CheckReleaseFlexibleMemory();
CheckFlexibleMappingIgnoresFlag8000();
CheckFlexibleMappingRefusesMeasuredFlags();
CheckPrtApertures();
CheckSceKernelMmap();
CheckInternalMemoryAvailableSize();
Expand Down
2 changes: 1 addition & 1 deletion docs/dev/debt/libkernel.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
- [sceKernelGetCurrentCpu](../../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - guest affinities are not applied to host threads, so the host CPU index is mapped into the calling thread's affinity clipped to `sceKernelGetAvailableCpumask` (the available mask when they do not overlap): host CPU n reports the (n modulo the CPU count)-th CPU of that mask, so a thread pinned to one CPU reports that CPU, as a FreeBSD `cpuset` guarantees on the console. Which CPU the console reports for a thread allowed on several is not known; shadPS4 returns 0
- [pthread_attr_setsolosched_np](../../../core/libs/prx/libkernel/Pthread/Posix/Attr.cpp) (libkernel) takes `(attr, int)` and stores the value through `scePthreadAttrSetsolosched`, returning `EINVAL` (22) for a null or uninitialized attribute like the other POSIX attribute setters. Only the name is public (aerolib `2+pVfgiEd7A`); the signature and behaviour follow the SCE twin, which [KytyPS5](https://github.com/KytyPS5/KytyPS5/blob/947627d10d4ef4b68ba3c0189aab6c368e70a8d2/src/kernel/pthread.cpp#L2188-L2199) and [sharpemu](https://github.com/sharpemu/sharpemu/blob/a2983692930564815a77f81e74c151268f5b935f/src/SharpEmu.Libs/Kernel/KernelPthreadExtendedCompatExports.cs#L891-L913) store as an `int` without a range check, and [PS5PCEM](https://github.com/iStark/PS5PCEM/blob/71de7681f06c5db59a1120a3bb554c86780c3f5f/src/hle/libs/kernel_threading.zig#L1396-L1398) implements this alias over it. On a PS5 (firmware 13.60) only 0 and 16 are accepted; every other value returns `ENOTSUP` (45, `0x8002002D` from the SCE call) and keeps the stored one, and the SCE calls return `EINVAL` for a null or uninitialized attribute. PPSA15878 passes 16. Threads created from the attribute are not scheduled differently; what solo scheduling does on the console is unknown. Returnal (PPSA01285 v03.000.005) stopped on it with `what(): pthread_attr_setsolosched_np_nid_postfix not implemented` (#2872, #1155); LEGO Horizon Adventures (PPSA14632, #734) and Palworld (PPSA23126, #2598) import it
- [pthread_main_np and scePthreadMain](../../../core/libs/prx/libkernel/Pthread/src/Thread.cpp) (libkernel_sys) - console behaviour is unmeasured. Linux identifies the process initial thread by kernel TID/PID equality, including worker-first loading. Other hosts identify the thread that initialized libkernel; loading it first from a worker can misidentify the initial thread. The pre-initialization -1 state is not exposed.
- [sceKernelMapFlexibleMemory / sceKernelMapNamedFlexibleMemoryInternal](../../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 is accepted and ignored by both, as KytyPS5 (`GUEST_MAP_UNKNOWN_8000`) and sharpemu do; its meaning is unknown. In a PS5 (firmware 13.60) payload process the Internal variant accepted it with the address, `sceKernelVirtualQuery` record and protection unchanged; `sceKernelMapFlexibleMemory` and `sceKernelMapNamedFlexibleMemory` failed it with `EINVAL`, and the first failed every other single flag from 0x1 to 0x100000 except 0x80 (0x10 untried). Here those flags, and 0x8000 in `sceKernelMapNamedFlexibleMemory`, throw; the other two accept 0x8000 because PPSA22520 passes it to the first. Every known caller is an SDK 9 `libc.prx` heap passing it with read/write protection and using the mapping as older ones use `sceKernelMapNamedFlexibleMemory` with flags 0 (Internal in PPSA21564, `sceKernelMapFlexibleMemory` in PPSA22520)
- [sceKernelMapFlexibleMemory / sceKernelMapNamedFlexibleMemoryInternal](../../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 is accepted and ignored by both, as KytyPS5 (`GUEST_MAP_UNKNOWN_8000`) and sharpemu do; its meaning is unknown. In a PS5 (firmware 13.60) payload process the Internal variant accepted it with the address, `sceKernelVirtualQuery` record and protection unchanged; `sceKernelMapFlexibleMemory` and `sceKernelMapNamedFlexibleMemory` failed it with `EINVAL`, and the first failed every other single flag from 0x1 to 0x100000 except 0x80 (0x10 untried). Here `sceKernelMapFlexibleMemory` and the Internal variant accept 0x8000 because PPSA22520 passes it to the first; the other measured single flags, and 0x8000 in `sceKernelMapNamedFlexibleMemory`, return `EINVAL`; flag sets of several bits and other `sceKernelMapNamedFlexibleMemory` flags throw. Every known caller is an SDK 9 `libc.prx` heap passing it with read/write protection and using the mapping as older ones use `sceKernelMapNamedFlexibleMemory` with flags 0 (Internal in PPSA21564, `sceKernelMapFlexibleMemory` in PPSA22520)

Check warning on line 113 in docs/dev/debt/libkernel.md

View workflow job for this annotation

GitHub Actions / conventions

debt-length

Technical debt entry over 1000 characters: state the gap first (what differs from the console, what is unverified, what throws) and keep only the behaviour it needs: 1140 characters

Check warning on line 113 in docs/dev/debt/libkernel.md

View workflow job for this annotation

GitHub Actions / conventions

debt-length

Technical debt entry over 1000 characters: state the gap first (what differs from the console, what is unverified, what throws) and keep only the behaviour it needs: 1140 characters
- [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. With `MAP_FIXED`, `MAP_EXCL` is accepted and ignored, so an occupied range or a reservation is replaced as without it. This is reported by Prospero Win (PPSA99995), not measured here: its [patch 0570](https://github.com/mpereiraesaa/prospero-win/blob/59c48117119fd57cd33e7bc91c11fa0c8ebf8b3d/wine/patches/0570-ntdll-ps5-reserve-virtual-range.patch#L7-L10) says that on firmware 12.02 `MAP_FIXED | MAP_EXCL | MAP_PRIVATE | MAP_ANON` over an existing mapping replaces it without error, where FreeBSD fails with `ENOMEM`. Without `MAP_FIXED` it is `EINVAL`, following FreeBSD; that case is not measured. Lengths are rounded to 16 KiB and fixed addresses must be aligned. The complete rounded range must lie inside the guest arena or, for POSIX fixed anonymous `mmap` on Windows, one current or registered native thread stack; other mapping APIs do not opt into stack replacement. Native stack replacement keeps the reservation, decommits and recommits fresh pages, and rejects foreign allocations, ranges spanning reservations and host `PAGE_GUARD` pages before mutation. Current-stack ranges must end at least 64 KiB below the active host frame; callers replacing another thread's stack must coordinate with that thread. If recommitting fails, the call returns `ENOMEM` with the range still reserved; thread cleanup attempts to recommit it before restoring write access. 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. Linux and Windows accept addresses from 64 KiB that no host mapping occupies, such as the 0x400000 imported by PICO-8 PPSA99808; macOS keeps the 0x200000000 start. Non-fixed private anonymous mappings keep their hint; null hints still use the 8 GiB area. On Windows the host's `KUSER_SHARED_DATA` always occupies 0x7ffe0000, so Wine's shared user data page (Forever Launcher PPSA99030) cannot be placed there. 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.
Expand Down
Loading