diff --git a/core/libs/prx/libc/src/AppArchiveBacking.cpp b/core/libs/prx/libc/src/AppArchiveBacking.cpp index ebd1fcb99e79..fbfeeb6dbbb0 100644 --- a/core/libs/prx/libc/src/AppArchiveBacking.cpp +++ b/core/libs/prx/libc/src/AppArchiveBacking.cpp @@ -101,7 +101,8 @@ class TemporaryBacking { int ReadOnlyDescriptor() { #ifdef _WIN32 - const HANDLE reader = ReOpenFile(writer, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0); + HANDLE reader = ReOpenFile(writer, GENERIC_READ | GENERIC_EXECUTE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0); + if (reader == INVALID_HANDLE_VALUE && GetLastError() == ERROR_ACCESS_DENIED) reader = ReOpenFile(writer, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0); if (reader == INVALID_HANDLE_VALUE) Fail(GetLastError()); const int descriptor = _open_osfhandle(reinterpret_cast(reader), _O_RDONLY | _O_BINARY | _O_NOINHERIT); if (descriptor < 0) { diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp index 558b2f6015f3..f7c3e5f086c8 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp @@ -1565,7 +1565,8 @@ int DoMapFileBacked_nid_no_patch(void** addr, size_t len, int prot, int flags, i if (access == 0 && (prot & PROT_WRITE) != 0) throw std::system_error(EACCES, std::generic_category(), "map file: a writable shared mapping of a read-only descriptor"); const bool execute = (prot & PROT_EXEC) != 0; const DWORD viewProtection = execute ? (access == 2 ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ) : (access == 2 ? PAGE_READWRITE : PAGE_READONLY); - const HANDLE source = execute ? ReOpenFile(file, GENERIC_READ | GENERIC_EXECUTE | (access == 2 ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0) : file; + const bool reopen = execute && (WindowsHandleAccess_nid_no_patch(file, descriptor, "mmap") & FILE_EXECUTE) == 0; + const HANDLE source = reopen ? ReOpenFile(file, GENERIC_READ | GENERIC_EXECUTE | (access == 2 ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0) : file; if (source == INVALID_HANDLE_VALUE) { const DWORD error = GetLastError(); throw std::system_error(error == ERROR_ACCESS_DENIED ? EACCES : EIO, std::generic_category(), "map file: reopen the file with execute access"); diff --git a/core/libs/tests/GuestKernelAppArchive.cpp b/core/libs/tests/GuestKernelAppArchive.cpp index 9037044a3620..3a0464bab024 100644 --- a/core/libs/tests/GuestKernelAppArchive.cpp +++ b/core/libs/tests/GuestKernelAppArchive.cpp @@ -37,7 +37,10 @@ #include #ifdef _WIN32 +#include "prx/libc/include/WindowsDescriptor.hpp" +#include #include +#include #include #elif defined(__linux__) #include @@ -560,7 +563,10 @@ void MappingBackingWindows() { const auto available = offset < BigSize ? std::min(length, BigSize - offset) : 0; #ifdef _WIN32 LARGE_INTEGER size{}; - Check(GetFileSizeEx(reinterpret_cast(_get_osfhandle(backing)), &size) && size.QuadPart == static_cast(available)); + const auto handle = reinterpret_cast(_get_osfhandle(backing)); + Check(GetFileSizeEx(handle, &size) && size.QuadPart == static_cast(available)); + const ACCESS_MASK access = WindowsHandleAccess_nid_no_patch(handle, backing, "MappingBackingWindows"); + Check((access & (FILE_READ_DATA | FILE_EXECUTE)) == (FILE_READ_DATA | FILE_EXECUTE) && (access & (FILE_WRITE_DATA | FILE_APPEND_DATA)) == 0); #else struct stat size{}; Check(fstat(backing, &size) == 0 && size.st_size == static_cast(available)); @@ -1104,6 +1110,66 @@ void MappingEndOfFile(const char* directory) { Check(sceKernelClose(fd) == 0); } +#ifdef _WIN32 +void MappingBackingWithoutExecuteWindows(const std::filesystem::path& root) { + const auto directory = root / "no-execute-temp"; + std::filesystem::create_directories(directory); + PSECURITY_DESCRIPTOR noExecute = nullptr; + Check(ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FRFWSD;;;WD)", SDDL_REVISION_1, &noExecute, nullptr) != 0); + Check(SetFileSecurityW(directory.c_str(), DACL_SECURITY_INFORMATION, noExecute) != 0); + LocalFree(noExecute); + std::vector previous(32768); + const DWORD previousLength = GetEnvironmentVariableW(L"TMP", previous.data(), static_cast(previous.size())); + Check(previousLength < previous.size()); + Check(SetEnvironmentVariableW(L"TMP", (directory.wstring() + L"\\").c_str()) != 0); + const auto path = "/app0/Mapped/" + std::to_string(BigSize) + ".bin"; + const auto expected = AppArchiveFixture::Pattern(BigSize); + const int fd = sceKernelOpen(path.c_str(), SCE_KERNEL_O_RDONLY, 0); + int backing = -1; + const bool mapped = fd >= 0 && AppArchiveMappingDescriptor_nid_no_patch(fd, 0, MapPage, &backing) && backing >= 0; + Check(SetEnvironmentVariableW(L"TMP", previousLength == 0 ? nullptr : previous.data()) != 0); + Check(mapped); + const ACCESS_MASK access = WindowsHandleAccess_nid_no_patch(reinterpret_cast(_get_osfhandle(backing)), backing, "MappingBackingWithoutExecuteWindows"); + Check((access & FILE_READ_DATA) != 0 && (access & (FILE_EXECUTE | FILE_WRITE_DATA | FILE_APPEND_DATA)) == 0); + std::vector bytes(MapPage); + Check(sceKernelPread(backing, bytes.data(), bytes.size(), 0) == static_cast(MapPage)); + Check(std::memcmp(bytes.data(), expected.data(), MapPage) == 0); + Check(_close(backing) == 0 && sceKernelClose(fd) == 0); + std::filesystem::remove_all(directory); +} + +void MappingExecutableHandleWindows(const std::filesystem::path& root) { + const auto path = root / "executable-handle.bin"; + const auto expected = AppArchiveFixture::Pattern(MapPage); + { + std::ofstream file(path, std::ios::binary); + file.write(expected.data(), static_cast(expected.size())); + Check(static_cast(file)); + } + constexpr DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; + const HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_EXECUTE, share, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + Check(handle != INVALID_HANDLE_VALUE); + PSECURITY_DESCRIPTOR readOnly = nullptr; + Check(ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;FRSD;;;WD)", SDDL_REVISION_1, &readOnly, nullptr) != 0); + Check(SetFileSecurityW(path.c_str(), DACL_SECURITY_INFORMATION, readOnly) != 0); + LocalFree(readOnly); + const HANDLE reopened = ReOpenFile(handle, GENERIC_READ | GENERIC_EXECUTE, share, 0); + Check(reopened == INVALID_HANDLE_VALUE && GetLastError() == ERROR_ACCESS_DENIED); + const int fd = _open_osfhandle(reinterpret_cast(handle), _O_RDONLY | _O_BINARY); + Check(fd >= 0); + for (const int protection : {4, 5}) { + const auto mapping = TryMapping(fd, MapPage, protection, 1, 0); + Check(mapping.address != MapFailed && mapping.error == 0); + Check(mprotect_nid_postfix(mapping.address, MapPage, 1) == 0); + Check(std::memcmp(mapping.address, expected.data(), MapPage) == 0); + Check(munmap_nid_postfix(mapping.address, MapPage) == 0); + } + Check(TryMapping(fd, MapPage, 3, 1, 0).error == 13); + Check(_close(fd) == 0); + Check(DeleteFileW(path.c_str()) != 0); +} +#endif + void MappingConcurrent() { const int fd = sceKernelOpen(("/app0/Mapped/" + std::to_string(BigSize) + ".bin").c_str(), SCE_KERNEL_O_RDONLY, 0); Check(fd >= 0); @@ -1136,6 +1202,10 @@ void Mappings(const std::filesystem::path& root) { MappingConcurrent(); MappingRanges(); MappingProtections(); +#ifdef _WIN32 + MappingExecutableHandleWindows(root); + MappingBackingWithoutExecuteWindows(root); +#endif #if defined(__linux__) || defined(_WIN32) const auto archivePartial = MappingPartialRead(("/app0/Mapped/" + std::to_string(BigSize) + ".bin").c_str()); const auto plainPartial = MappingPartialRead(("/app0/Reference/" + std::to_string(BigSize) + ".bin").c_str()); diff --git a/docs/dev/debt/changes/fix-libkernel-app-archive-exec-map.md b/docs/dev/debt/changes/fix-libkernel-app-archive-exec-map.md new file mode 100644 index 000000000000..596ee8abb97e --- /dev/null +++ b/docs/dev/debt/changes/fix-libkernel-app-archive-exec-map.md @@ -0,0 +1,5 @@ +# libkernel + +## change [Regular file mappings] + +- [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`) in Dusklight PPSA99305 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`. On Windows a shared mapping is a view of a file section (`CreateFileMappingW` on the descriptor's handle, read-write when the descriptor is, otherwise read-only), so writes through the descriptor and the mapping see each other. This also maps anonymous `shm_open` objects and JIT shared memory descriptors, which are temporary files on Windows. A shared mapping may end inside the 16 KiB page that holds the end of the file, as POSIX [`mmap`](https://pubs.opengroup.org/onlinepubs/9799919799/functions/mmap.html) allows (llama.cpp in PS5LM Plus PPSA99581 maps a whole model file this way): the section keeps the file's size, so the file never grows, the view ends with the 4 KiB host page that holds the end of the file, which Windows fills with zeros past it, and the rest of the guest page is private zero pages. As POSIX requires, the bytes past the end read zero and are never written to the file; bytes written to those private pages are seen only through that mapping, not through other mappings of the file, and a file that grows later does not show its new bytes there. A shared mapping that reaches a whole page past the end of the file fails with `EOPNOTSUPP`, where POSIX maps it and delivers `SIGBUS` on access, as does a write-only descriptor; FreeBSD 11.4's `vn_mmap` maps a write-only descriptor without `PROT_READ`, and Linux refuses it with `EACCES`. A `PROT_EXEC` mapping is a view of a section created on the descriptor's handle when that handle grants execute access, as the backing of an app0.zar file does; otherwise it is created on a second handle that `ReOpenFile` opens with execute access, so a file whose ACL does not grant the user execute fails with `EACCES`, where FreeBSD maps it unless the file system is mounted `noexec`. When the ACL of the temporary directory does not grant execute, the backing of an app0.zar file is opened for reading only, so its `PROT_EXEC` mappings fail the same way. A read-write alias (`GuestArenaMapAlias`) of a mapped page that holds the end of the file throws. `mprotect` above the view's protection (writing through a read-only descriptor, or adding `PROT_EXEC`) fails with `EACCES` before anything changes; FreeBSD allows `PROT_EXEC` on a readable descriptor. Shrinking the file with `ftruncate` fails with `EINVAL` while any shared mapping of it exists, even one that does not cover the removed part, because the section keeps the file's size at `mmap`; FreeBSD truncates. A read-write alias of a view (`GuestArenaMapAlias`, used when the GPU imports guest memory) of a read-only file section fails, as the alias is mapped `PAGE_READWRITE`. Views of the same file made by separate `mmap` calls are separate sections, so write tracking does not treat them as aliases of each other. A private mapping on Windows is a copy of the file read at `mmap`, which POSIX allows (later changes to the file need not show); pages wholly past the end of the file fail with `EOPNOTSUPP` instead of faulting on access, and a write-only descriptor fails with `EOPNOTSUPP`.