mirror of
https://github.com/boykopovar/AnyPS5.git
synced 2026-10-10 01:28:44 +02:00
fix(kernel): share direct memory mappings and track physical offsets
This commit is contained in:
@@ -40,7 +40,7 @@ void heapMirrorTests(const Context& context, const BdaTestAccess& access) {
|
||||
constexpr std::size_t bytes = 2 * 65536;
|
||||
void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536);
|
||||
#ifdef _WIN32
|
||||
Require(VirtualAlloc(block, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the heap mirror block");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
|
||||
#endif
|
||||
auto* guest = static_cast<std::uint8_t*>(block);
|
||||
std::memset(block, 0x11, bytes);
|
||||
@@ -108,7 +108,7 @@ void heapMirrorTests(const Context& context, const BdaTestAccess& access) {
|
||||
{
|
||||
constexpr std::size_t half = 2 * 65536;
|
||||
void* pair = GuestArena::GuestArenaAllocate_nid_postfix(2 * half, 65536);
|
||||
Require(VirtualAlloc(pair, 2 * half, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the heap mirror pair");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(pair, 2 * half, PAGE_READWRITE, 2 * half);
|
||||
std::memset(pair, 0x11, 2 * half);
|
||||
auto* first = static_cast<std::uint8_t*>(pair);
|
||||
auto* second = first + half;
|
||||
@@ -150,7 +150,7 @@ void heapMirrorTests(const Context& context, const BdaTestAccess& access) {
|
||||
Require(firstDevice() == device && access.addressBytes(device)[5] == std::byte{0x66}, "an interrupted build left a changed heap block marked current");
|
||||
registerPair(false);
|
||||
sweep();
|
||||
VirtualFree(pair, 2 * half, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(pair, 2 * half);
|
||||
GuestArena::GuestArenaRelease_nid_postfix(pair, 2 * half);
|
||||
}
|
||||
#endif
|
||||
@@ -158,7 +158,7 @@ void heapMirrorTests(const Context& context, const BdaTestAccess& access) {
|
||||
{
|
||||
constexpr std::size_t size = 2 * 65536;
|
||||
void* raw = GuestArena::GuestArenaAllocate_nid_postfix(size, 65536);
|
||||
Require(VirtualAlloc(raw, size, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the aliased range");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(raw, size, PAGE_READWRITE, size);
|
||||
auto* bytes8 = static_cast<std::uint8_t*>(raw);
|
||||
std::memset(raw, 0x11, size);
|
||||
const auto base = reinterpret_cast<std::uintptr_t>(raw);
|
||||
@@ -209,12 +209,12 @@ void heapMirrorTests(const Context& context, const BdaTestAccess& access) {
|
||||
sweep();
|
||||
Require(VirtualProtect(reinterpret_cast<void*>(page), 4096, PAGE_READWRITE, &previous) != 0, "cannot restore the aliased page");
|
||||
GuestAllocations::GuestAllocationsInvalidate_nid_postfix(page, 4096);
|
||||
VirtualFree(raw, size, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(raw, size);
|
||||
GuestArena::GuestArenaRelease_nid_postfix(raw, size);
|
||||
}
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
VirtualFree(block, bytes, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(block, bytes);
|
||||
#endif
|
||||
GuestArena::GuestArenaRelease_nid_postfix(block, bytes);
|
||||
}
|
||||
|
||||
@@ -343,7 +343,7 @@ void unchangedSinceTests() {
|
||||
constexpr std::size_t bytes = 65536;
|
||||
void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, bytes);
|
||||
#ifdef _WIN32
|
||||
Require(VirtualAlloc(block, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the arena block");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
|
||||
#endif
|
||||
auto* words = static_cast<volatile std::uint32_t*>(block);
|
||||
const auto address = reinterpret_cast<std::uint64_t>(block);
|
||||
@@ -371,7 +371,7 @@ void unchangedSinceTests() {
|
||||
CollectWritesUncached(address, 4);
|
||||
Require(!UnchangedSinceCollected(address, 4, generation3), "(6) a CPU write collected by another caller is not seen");
|
||||
#ifdef _WIN32
|
||||
VirtualFree(block, bytes, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(block, bytes);
|
||||
#endif
|
||||
GuestArena::GuestArenaRelease_nid_postfix(block, bytes);
|
||||
}
|
||||
@@ -389,13 +389,13 @@ void keyProofTests(const Device& device, Recorder& recorder) {
|
||||
constexpr std::size_t bytes = 65536;
|
||||
void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, bytes);
|
||||
#ifdef _WIN32
|
||||
Require(VirtualAlloc(block, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the arena block");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
|
||||
#endif
|
||||
struct Release {
|
||||
void* block;
|
||||
~Release() {
|
||||
#ifdef _WIN32
|
||||
VirtualFree(block, bytes, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(block, bytes);
|
||||
#endif
|
||||
GuestArena::GuestArenaRelease_nid_postfix(block, bytes);
|
||||
}
|
||||
@@ -476,7 +476,7 @@ void closeRaceTests(const Device& device, Recorder& recorder) {
|
||||
constexpr std::size_t bytes = 1u << 20;
|
||||
void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536);
|
||||
#ifdef _WIN32
|
||||
Require(VirtualAlloc(block, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the arena block");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
|
||||
#endif
|
||||
const auto base = reinterpret_cast<std::uint64_t>(block);
|
||||
// Late in the range, so the walker is usually still ahead of the page when the store lands.
|
||||
@@ -510,7 +510,7 @@ void closeRaceTests(const Device& device, Recorder& recorder) {
|
||||
recorder.Sync();
|
||||
Require(!Recorder::LookupLabel(label, 4, 5).has_value(), "(8) the entry outlived its batch");
|
||||
#ifdef _WIN32
|
||||
VirtualFree(block, bytes, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(block, bytes);
|
||||
#endif
|
||||
GuestArena::GuestArenaRelease_nid_postfix(block, bytes);
|
||||
}
|
||||
@@ -722,13 +722,13 @@ void unitShadowTests(const Device& device, Recorder& recorder) {
|
||||
void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536);
|
||||
Require(block != nullptr, "cannot allocate the shadow test block");
|
||||
#ifdef _WIN32
|
||||
Require(VirtualAlloc(block, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr, "cannot commit the shadow test block");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
|
||||
#endif
|
||||
struct Release {
|
||||
void* block;
|
||||
~Release() {
|
||||
#ifdef _WIN32
|
||||
VirtualFree(block, bytes, MEM_DECOMMIT);
|
||||
GuestArena::GuestArenaReset_nid_postfix(block, bytes);
|
||||
#endif
|
||||
GuestArena::GuestArenaRelease_nid_postfix(block, bytes);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,11 @@ void GuestArenaRelease_nid_postfix(const void* pointer, std::size_t bytes);
|
||||
// The reserved range, and whether it was reserved with page write watching (Windows MEM_WRITE_WATCH).
|
||||
void GuestArenaRange_nid_postfix(std::uintptr_t* base, std::size_t* bytes);
|
||||
bool GuestArenaWriteWatched_nid_postfix();
|
||||
#ifdef _WIN32
|
||||
void GuestArenaCommit_nid_postfix(void* pointer, std::size_t bytes, std::uint32_t protection, std::size_t granule);
|
||||
void GuestArenaReset_nid_postfix(void* pointer, std::size_t bytes);
|
||||
void GuestArenaMap_nid_postfix(void* pointer, std::size_t bytes, void* section, std::uint64_t offset, std::uint32_t protection);
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
#ifndef CORE_LIBS_PRX_LIBC_INCLUDE_WINDOWSMAPPINGS_HPP
|
||||
#define CORE_LIBS_PRX_LIBC_INCLUDE_WINDOWSMAPPINGS_HPP
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
|
||||
namespace GuestArena {
|
||||
|
||||
class WindowsMappings {
|
||||
public:
|
||||
static WindowsMappings& Get() {
|
||||
static WindowsMappings mappings;
|
||||
return mappings;
|
||||
}
|
||||
|
||||
void* Reserve(void* address, std::size_t bytes) {
|
||||
return allocate(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0);
|
||||
}
|
||||
|
||||
void Commit(void* address, std::size_t bytes, DWORD protection, std::size_t granule, bool watched) {
|
||||
std::lock_guard lock(mutex);
|
||||
const auto end = reinterpret_cast<std::uintptr_t>(address) + bytes;
|
||||
for (auto cursor = reinterpret_cast<std::uintptr_t>(address); cursor < end;) {
|
||||
const auto memory = query(cursor);
|
||||
const auto stop = std::min(end, reinterpret_cast<std::uintptr_t>(memory.BaseAddress) + memory.RegionSize);
|
||||
if (memory.State == MEM_RESERVE) {
|
||||
const auto limit = std::min(end, cursor + granule);
|
||||
auto placeholderEnd = stop;
|
||||
while (placeholderEnd < limit) {
|
||||
const auto next = query(placeholderEnd);
|
||||
if (next.State != MEM_RESERVE) break;
|
||||
placeholderEnd = reinterpret_cast<std::uintptr_t>(next.BaseAddress) + next.RegionSize;
|
||||
}
|
||||
const auto size = std::min(limit, placeholderEnd) - cursor;
|
||||
reset(cursor, size);
|
||||
const DWORD flags = MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER | (watched ? MEM_WRITE_WATCH : 0);
|
||||
if (!allocate(GetCurrentProcess(), reinterpret_cast<void*>(cursor), size, flags, protection, nullptr, 0)) fail("replace guest placeholder with private memory");
|
||||
cursor += size;
|
||||
} else {
|
||||
if (memory.State != MEM_COMMIT) throw std::runtime_error("guest memory is not committed");
|
||||
DWORD previous;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(cursor), stop - cursor, protection, &previous)) fail("protect guest memory");
|
||||
cursor = stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Reset(void* address, std::size_t bytes) {
|
||||
std::lock_guard lock(mutex);
|
||||
reset(reinterpret_cast<std::uintptr_t>(address), bytes);
|
||||
}
|
||||
|
||||
void Map(void* address, std::size_t bytes, HANDLE section, std::uint64_t offset, DWORD protection) {
|
||||
std::lock_guard lock(mutex);
|
||||
auto cursor = reinterpret_cast<std::uintptr_t>(address);
|
||||
reset(cursor, bytes);
|
||||
for (std::size_t done = 0; done < bytes; done += pageBytes) {
|
||||
split(cursor + done, pageBytes);
|
||||
void* page = reinterpret_cast<void*>(cursor + done);
|
||||
if (!map(section, GetCurrentProcess(), page, offset + done, pageBytes, MEM_REPLACE_PLACEHOLDER, PAGE_EXECUTE_READWRITE, nullptr, 0)) fail("map shared guest page");
|
||||
DWORD previous;
|
||||
if (!VirtualProtect(page, pageBytes, protection, &previous)) fail("protect shared guest page");
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr std::size_t pageBytes = 0x4000;
|
||||
using AllocateFunction = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using MapFunction = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using UnmapFunction = BOOL (WINAPI*)(HANDLE, PVOID, ULONG);
|
||||
|
||||
WindowsMappings() {
|
||||
const auto module = GetModuleHandleW(L"KernelBase.dll");
|
||||
if (!module) fail("load Windows memory API");
|
||||
allocate = reinterpret_cast<AllocateFunction>(GetProcAddress(module, "VirtualAlloc2"));
|
||||
map = reinterpret_cast<MapFunction>(GetProcAddress(module, "MapViewOfFile3"));
|
||||
unmap = reinterpret_cast<UnmapFunction>(GetProcAddress(module, "UnmapViewOfFile2"));
|
||||
if (!allocate || !map || !unmap) throw std::runtime_error("Windows placeholder memory APIs are required");
|
||||
}
|
||||
|
||||
[[noreturn]] static void fail(const char* operation) {
|
||||
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), operation);
|
||||
}
|
||||
|
||||
static MEMORY_BASIC_INFORMATION query(std::uintptr_t address) {
|
||||
MEMORY_BASIC_INFORMATION memory{};
|
||||
if (VirtualQuery(reinterpret_cast<void*>(address), &memory, sizeof(memory)) != sizeof(memory)) fail("query guest memory");
|
||||
return memory;
|
||||
}
|
||||
|
||||
static void split(std::uintptr_t address, std::size_t bytes) {
|
||||
auto memory = query(address);
|
||||
memory = query(reinterpret_cast<std::uintptr_t>(memory.AllocationBase));
|
||||
if (memory.State != MEM_RESERVE) throw std::runtime_error("guest mapping requires a placeholder");
|
||||
const auto base = reinterpret_cast<std::uintptr_t>(memory.BaseAddress);
|
||||
if (address != base) {
|
||||
if (!VirtualFree(reinterpret_cast<void*>(base), address - base, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("split guest placeholder prefix");
|
||||
memory = query(address);
|
||||
}
|
||||
if (memory.RegionSize < bytes) throw std::runtime_error("guest placeholder is too small");
|
||||
if (memory.RegionSize != bytes && !VirtualFree(reinterpret_cast<void*>(address), bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("split guest placeholder suffix");
|
||||
}
|
||||
|
||||
void reset(std::uintptr_t address, std::size_t bytes) {
|
||||
const auto end = address + bytes;
|
||||
for (auto cursor = address; cursor < end;) {
|
||||
const auto memory = query(cursor);
|
||||
if (memory.State == MEM_RESERVE) {
|
||||
cursor = std::min(end, reinterpret_cast<std::uintptr_t>(memory.BaseAddress) + memory.RegionSize);
|
||||
continue;
|
||||
}
|
||||
if (reinterpret_cast<std::uintptr_t>(memory.AllocationBase) != cursor) throw std::runtime_error("cannot release part of a host allocation");
|
||||
auto allocationEnd = cursor;
|
||||
do {
|
||||
const auto part = query(allocationEnd);
|
||||
if (part.AllocationBase != memory.AllocationBase) break;
|
||||
allocationEnd = reinterpret_cast<std::uintptr_t>(part.BaseAddress) + part.RegionSize;
|
||||
} while (allocationEnd < end);
|
||||
if (allocationEnd > end || query(allocationEnd).AllocationBase == memory.AllocationBase) throw std::runtime_error("guest release truncates a host allocation");
|
||||
if (memory.Type == MEM_MAPPED) {
|
||||
if (!unmap(GetCurrentProcess(), reinterpret_cast<void*>(cursor), MEM_PRESERVE_PLACEHOLDER)) fail("unmap shared guest page");
|
||||
} else if (memory.Type == MEM_PRIVATE) {
|
||||
if (!VirtualFree(reinterpret_cast<void*>(cursor), allocationEnd - cursor, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("release private guest memory");
|
||||
} else {
|
||||
throw std::runtime_error("unsupported guest mapping type");
|
||||
}
|
||||
cursor = allocationEnd;
|
||||
}
|
||||
const auto last = query(reinterpret_cast<std::uintptr_t>(query(end - 1).AllocationBase));
|
||||
const auto lastBase = reinterpret_cast<std::uintptr_t>(last.BaseAddress);
|
||||
if (lastBase + last.RegionSize > end) split(lastBase, end - lastBase);
|
||||
const auto first = query(address);
|
||||
split(address, std::min(bytes, reinterpret_cast<std::uintptr_t>(first.BaseAddress) + first.RegionSize - address));
|
||||
if (query(address).RegionSize != bytes && !VirtualFree(reinterpret_cast<void*>(address), bytes, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) fail("coalesce guest placeholders");
|
||||
}
|
||||
|
||||
std::mutex mutex;
|
||||
AllocateFunction allocate = nullptr;
|
||||
MapFunction map = nullptr;
|
||||
UnmapFunction unmap = nullptr;
|
||||
};
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "prx/libc/include/GuestArena.hpp"
|
||||
#include "prx/libc/include/WindowsMappings.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
@@ -91,13 +92,8 @@ private:
|
||||
for (std::uintptr_t base = PreferredBase; base + MinimumSize <= MapAreaEnd; base += MinimumSize) {
|
||||
for (std::size_t size = MaximumSize; size >= MinimumSize; size /= 2) {
|
||||
if (base + size > MapAreaEnd) continue;
|
||||
// Write watching lets the GPU driver learn which pages the CPU wrote instead of comparing
|
||||
// whole resources; the plain reservation is the fallback. Debug aid: APS5_NO_WRITE_WATCH=1
|
||||
// skips it, to measure what the write faults it re-arms cost the game's threads.
|
||||
static const bool noWriteWatch = std::getenv("APS5_NO_WRITE_WATCH") != nullptr;
|
||||
void* reserved = noWriteWatch ? nullptr : VirtualAlloc(reinterpret_cast<void*>(base), size, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_NOACCESS);
|
||||
_writeWatched = reserved != nullptr;
|
||||
if (!reserved) reserved = VirtualAlloc(reinterpret_cast<void*>(base), size, MEM_RESERVE, PAGE_NOACCESS);
|
||||
_writeWatched = std::getenv("APS5_NO_WRITE_WATCH") == nullptr;
|
||||
void* reserved = WindowsMappings::Get().Reserve(reinterpret_cast<void*>(base), size);
|
||||
if (!reserved) continue;
|
||||
_base = reinterpret_cast<std::uintptr_t>(reserved);
|
||||
_end = _base + size;
|
||||
@@ -150,6 +146,23 @@ void GuestArenaRange_nid_postfix(std::uintptr_t* base, std::size_t* bytes) {
|
||||
*bytes = Arena::Get().Size();
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
void GuestArenaCommit_nid_postfix(void* pointer, std::size_t bytes, std::uint32_t protection, std::size_t granule) {
|
||||
if (!Arena::Get().Contains(pointer, bytes)) throw std::invalid_argument("commit outside the guest arena");
|
||||
WindowsMappings::Get().Commit(pointer, bytes, protection, granule, Arena::Get().WriteWatched());
|
||||
}
|
||||
|
||||
void GuestArenaReset_nid_postfix(void* pointer, std::size_t bytes) {
|
||||
if (!Arena::Get().Contains(pointer, bytes)) throw std::invalid_argument("reset outside the guest arena");
|
||||
WindowsMappings::Get().Reset(pointer, bytes);
|
||||
}
|
||||
|
||||
void GuestArenaMap_nid_postfix(void* pointer, std::size_t bytes, void* section, std::uint64_t offset, std::uint32_t protection) {
|
||||
if (!Arena::Get().Contains(pointer, bytes)) throw std::invalid_argument("shared mapping outside the guest arena");
|
||||
WindowsMappings::Get().Map(pointer, bytes, section, offset, protection);
|
||||
}
|
||||
#endif
|
||||
|
||||
bool GuestArenaWriteWatched_nid_postfix() {
|
||||
return Arena::Get().WriteWatched();
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ private:
|
||||
|
||||
static void commit(void* pointer, std::size_t bytes) {
|
||||
#ifdef _WIN32
|
||||
if (!VirtualAlloc(pointer, bytes, MEM_COMMIT, PAGE_READWRITE)) throw std::bad_alloc();
|
||||
GuestArena::GuestArenaCommit_nid_postfix(pointer, bytes, PAGE_READWRITE, bytes);
|
||||
#else
|
||||
(void)pointer;
|
||||
(void)bytes;
|
||||
@@ -165,7 +165,7 @@ private:
|
||||
|
||||
static void release(void* raw, std::size_t bytes) {
|
||||
#ifdef _WIN32
|
||||
if (!VirtualFree(raw, bytes, MEM_DECOMMIT)) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "guest heap decommit failed");
|
||||
GuestArena::GuestArenaReset_nid_postfix(raw, bytes);
|
||||
GuestAllocations::GuestAllocationsInvalidate_nid_postfix(reinterpret_cast<std::uintptr_t>(raw), bytes);
|
||||
#endif
|
||||
GuestArena::GuestArenaRelease_nid_postfix(raw, bytes);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#include "DirectMemory.hpp"
|
||||
#include "prx/libkernel/DirectMemory/DirectMemory.hpp"
|
||||
#include "prx/libc/include/GuestAllocations.hpp"
|
||||
#include "prx/libc/include/GuestArena.hpp"
|
||||
#include <algorithm>
|
||||
@@ -6,7 +6,6 @@
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -19,6 +18,7 @@
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -57,8 +57,7 @@ struct KernelArena {
|
||||
};
|
||||
|
||||
static void CommitArenaRange(void* addr, size_t len, DWORD winProt) {
|
||||
if (!VirtualAlloc(addr, len, MEM_COMMIT, winProt))
|
||||
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualAlloc commit failed");
|
||||
GuestArena::GuestArenaCommit_nid_postfix(addr, len, winProt, PS5_PAGE_SIZE);
|
||||
}
|
||||
|
||||
static void* mmap_aligned(size_t len, int prot, size_t alignment) {
|
||||
@@ -99,9 +98,9 @@ static void* mmap(void* addr, size_t len, int prot, int flags, int, int) {
|
||||
}
|
||||
|
||||
static int munmap(void* addr, size_t len) {
|
||||
if (!VirtualFree(addr, len, MEM_DECOMMIT))
|
||||
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualFree decommit failed");
|
||||
auto& arena = KernelArena::Get();
|
||||
if (arena.Contains(addr, len)) GuestArena::GuestArenaReset_nid_postfix(addr, len);
|
||||
else if (!VirtualFree(addr, len, MEM_DECOMMIT)) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualFree decommit failed");
|
||||
if (arena.Contains(addr, len)) arena.Release(addr, len);
|
||||
return 0;
|
||||
}
|
||||
@@ -219,114 +218,108 @@ void Trace(const char* format, ...) {
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
class PhysicalBacking {
|
||||
public:
|
||||
explicit PhysicalBacking(std::size_t bytes, int memoryType) : memoryType(memoryType) {
|
||||
#ifdef _WIN32
|
||||
const auto size = static_cast<std::uint64_t>(bytes);
|
||||
section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_EXECUTE_READWRITE, static_cast<DWORD>(size >> 32), static_cast<DWORD>(size), nullptr);
|
||||
if (!section) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "create direct memory backing");
|
||||
#else
|
||||
file = std::tmpfile();
|
||||
if (!file) throw std::system_error(errno, std::generic_category(), "create direct memory backing");
|
||||
if (ftruncate(fileno(file), static_cast<off_t>(bytes)) != 0) {
|
||||
const int error = errno;
|
||||
std::fclose(file);
|
||||
throw std::system_error(error, std::generic_category(), "size direct memory backing");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
int MemoryType() const { return memoryType; }
|
||||
|
||||
~PhysicalBacking() {
|
||||
#ifdef _WIN32
|
||||
CloseHandle(section);
|
||||
#else
|
||||
std::fclose(file);
|
||||
#endif
|
||||
}
|
||||
|
||||
PhysicalBacking(const PhysicalBacking&) = delete;
|
||||
PhysicalBacking& operator=(const PhysicalBacking&) = delete;
|
||||
|
||||
void Map(std::uintptr_t address, std::size_t bytes, std::uint64_t offset, int protection) const {
|
||||
#ifdef _WIN32
|
||||
GuestArena::GuestArenaMap_nid_postfix(reinterpret_cast<void*>(address), bytes, section, offset, WinProtFromPosix(protection));
|
||||
#else
|
||||
if (::mmap(reinterpret_cast<void*>(address), bytes, protection, MAP_SHARED | MAP_FIXED, fileno(file), static_cast<off_t>(offset)) == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "map direct memory backing");
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
int memoryType;
|
||||
#ifdef _WIN32
|
||||
HANDLE section = nullptr;
|
||||
#else
|
||||
std::FILE* file = nullptr;
|
||||
#endif
|
||||
};
|
||||
|
||||
struct PhysicalPage {
|
||||
std::shared_ptr<PhysicalBacking> backing;
|
||||
std::uint64_t offset;
|
||||
};
|
||||
|
||||
std::mutex g_directLock;
|
||||
std::map<std::uint64_t, PhysicalPage> g_physPages;
|
||||
|
||||
struct DirectMapping {
|
||||
std::uintptr_t end;
|
||||
std::uint64_t phys;
|
||||
int memoryType;
|
||||
};
|
||||
std::mutex g_directLock;
|
||||
|
||||
std::map<std::uintptr_t, DirectMapping> g_directMappings;
|
||||
std::map<std::uint64_t, std::unique_ptr<unsigned char[]>> g_physPages;
|
||||
|
||||
void ProtectOrThrow(std::uintptr_t address, std::size_t len, int nativeProt) {
|
||||
if (mprotect(reinterpret_cast<void*>(address), len, nativeProt) != 0) throw std::system_error(errno, std::generic_category(), "mprotect failed");
|
||||
}
|
||||
|
||||
void SaveContents(std::uintptr_t address, std::size_t len, std::uint64_t phys) {
|
||||
static const unsigned char zero[PS5_PAGE_SIZE] = {};
|
||||
ProtectOrThrow(address, len, PROT_READ);
|
||||
for (std::size_t offset = 0; offset < len; offset += PS5_PAGE_SIZE) {
|
||||
const auto* page = reinterpret_cast<const unsigned char*>(address + offset);
|
||||
if (std::memcmp(page, zero, PS5_PAGE_SIZE) == 0) continue;
|
||||
auto& copy = g_physPages[phys + offset];
|
||||
copy.reset(new unsigned char[PS5_PAGE_SIZE]);
|
||||
std::memcpy(copy.get(), page, PS5_PAGE_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
std::set<std::uintptr_t> g_shared;
|
||||
|
||||
std::vector<std::uintptr_t> Views(std::uint64_t physPage) {
|
||||
std::vector<std::uintptr_t> views;
|
||||
for (const auto& [base, mapping] : g_directMappings) {
|
||||
if (physPage >= mapping.phys && physPage < mapping.phys + (mapping.end - base)) views.push_back(base + (physPage - mapping.phys));
|
||||
}
|
||||
return views;
|
||||
}
|
||||
|
||||
int NativeProtection(std::uintptr_t view) {
|
||||
int prot = 0;
|
||||
if (!GuestProtection(view, &prot)) throw std::runtime_error("direct memory view has no recorded protection");
|
||||
return LinuxProtFromSce(prot);
|
||||
}
|
||||
|
||||
int SharedProtection(int nativeProt) {
|
||||
return nativeProt & ~PROT_WRITE;
|
||||
}
|
||||
|
||||
void Unshare(std::uintptr_t page, std::uint64_t physPage) {
|
||||
const auto others = Views(physPage);
|
||||
if (others.empty()) throw std::runtime_error("shared direct memory page has no other view");
|
||||
ProtectOrThrow(page, PS5_PAGE_SIZE, PROT_READ);
|
||||
ProtectOrThrow(others.front(), PS5_PAGE_SIZE, PROT_READ);
|
||||
if (std::memcmp(reinterpret_cast<const void*>(page), reinterpret_cast<const void*>(others.front()), PS5_PAGE_SIZE) != 0) {
|
||||
char message[160];
|
||||
std::snprintf(message, sizeof(message), "direct memory 0x%llx mapped at 0x%llx and 0x%llx was written through one view; aliased writes are not implemented", static_cast<unsigned long long>(physPage),
|
||||
static_cast<unsigned long long>(page), static_cast<unsigned long long>(others.front()));
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
const bool last = others.size() == 1;
|
||||
if (last) g_shared.erase(others.front());
|
||||
const auto prot = NativeProtection(others.front());
|
||||
ProtectOrThrow(others.front(), PS5_PAGE_SIZE, last ? prot : SharedProtection(prot));
|
||||
}
|
||||
|
||||
void EraseMappings(std::uintptr_t start, std::uintptr_t end, bool save) {
|
||||
void EraseMappings(std::uintptr_t start, std::uintptr_t end) {
|
||||
auto it = g_directMappings.lower_bound(start);
|
||||
if (it != g_directMappings.begin() && std::prev(it)->second.end > start) --it;
|
||||
while (it != g_directMappings.end() && it->first < end) {
|
||||
const auto base = it->first;
|
||||
const auto mapping = it->second;
|
||||
it = g_directMappings.erase(it);
|
||||
const auto cutStart = std::max(base, start);
|
||||
const auto cutEnd = std::min(mapping.end, end);
|
||||
if (base < start) g_directMappings.emplace(base, DirectMapping{start, mapping.phys});
|
||||
if (mapping.end > end) it = g_directMappings.emplace(end, DirectMapping{mapping.end, mapping.phys + (end - base)}).first;
|
||||
if (g_shared.empty()) {
|
||||
if (save) SaveContents(cutStart, cutEnd - cutStart, mapping.phys + (cutStart - base));
|
||||
continue;
|
||||
}
|
||||
for (auto page = cutStart; page < cutEnd; page += PS5_PAGE_SIZE) {
|
||||
const auto physPage = mapping.phys + (page - base);
|
||||
if (g_shared.erase(page) != 0) Unshare(page, physPage);
|
||||
else if (save) SaveContents(page, PS5_PAGE_SIZE, physPage);
|
||||
if (base < start) g_directMappings.emplace(base, DirectMapping{start, mapping.phys, mapping.memoryType});
|
||||
if (mapping.end > end) it = g_directMappings.emplace(end, DirectMapping{mapping.end, mapping.phys + end - base, mapping.memoryType}).first;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void ValidatePhysicalRange(std::uint64_t phys, std::size_t len) {
|
||||
for (std::size_t offset = 0; offset < len; offset += PS5_PAGE_SIZE) {
|
||||
if (!g_physPages.contains(phys + offset)) {
|
||||
char message[160];
|
||||
std::snprintf(message, sizeof(message), "direct memory range 0x%llx+0x%zx references unallocated physical page 0x%llx", static_cast<unsigned long long>(phys), len, static_cast<unsigned long long>(phys + offset));
|
||||
throw std::invalid_argument(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AddMapping(std::uintptr_t address, std::size_t len, std::uint64_t phys, int nativeProt) {
|
||||
std::vector<std::pair<std::size_t, std::uintptr_t>> shared;
|
||||
for (const auto& [base, mapping] : g_directMappings) {
|
||||
const auto physEnd = std::min(phys + len, mapping.phys + (mapping.end - base));
|
||||
for (auto page = std::max(phys, mapping.phys); page < physEnd; page += PS5_PAGE_SIZE) shared.emplace_back(page - phys, base + (page - mapping.phys));
|
||||
ValidatePhysicalRange(phys, len);
|
||||
EraseMappings(address, address + len);
|
||||
for (std::size_t offset = 0; offset < len;) {
|
||||
const auto& page = g_physPages.at(phys + offset);
|
||||
std::size_t bytes = PS5_PAGE_SIZE;
|
||||
while (offset + bytes < len) {
|
||||
const auto& next = g_physPages.at(phys + offset + bytes);
|
||||
if (next.backing != page.backing || next.offset != page.offset + bytes) break;
|
||||
bytes += PS5_PAGE_SIZE;
|
||||
}
|
||||
page.backing->Map(address + offset, bytes, page.offset, nativeProt);
|
||||
g_directMappings.emplace(address + offset, DirectMapping{address + offset + bytes, phys + offset, page.backing->MemoryType()});
|
||||
offset += bytes;
|
||||
}
|
||||
g_directMappings.emplace(address, DirectMapping{address + len, phys});
|
||||
auto it = g_physPages.lower_bound(phys);
|
||||
const auto last = g_physPages.lower_bound(phys + len);
|
||||
if (it == last && shared.empty()) return;
|
||||
ProtectOrThrow(address, len, PROT_READ | PROT_WRITE);
|
||||
for (; it != last; it = g_physPages.erase(it)) std::memcpy(reinterpret_cast<void*>(address + (it->first - phys)), it->second.get(), PS5_PAGE_SIZE);
|
||||
for (const auto& [offset, view] : shared) {
|
||||
ProtectOrThrow(view, PS5_PAGE_SIZE, PROT_READ);
|
||||
std::memcpy(reinterpret_cast<void*>(address + offset), reinterpret_cast<const void*>(view), PS5_PAGE_SIZE);
|
||||
ProtectOrThrow(view, PS5_PAGE_SIZE, SharedProtection(NativeProtection(view)));
|
||||
g_shared.insert(view);
|
||||
}
|
||||
ProtectOrThrow(address, len, nativeProt);
|
||||
for (const auto& [offset, view] : shared) {
|
||||
ProtectOrThrow(address + offset, PS5_PAGE_SIZE, SharedProtection(nativeProt));
|
||||
g_shared.insert(address + offset);
|
||||
}
|
||||
if (!shared.empty()) Trace("alias %p+0x%zx shares %zu physical pages with older views", reinterpret_cast<void*>(address), len, shared.size());
|
||||
}
|
||||
|
||||
bool RemapFixedIntoRegistered(GuestAllocations::Mutation& mutation, void* addr, size_t len, int prot, int flags, int64_t physStart = -1) {
|
||||
@@ -339,15 +332,17 @@ bool RemapFixedIntoRegistered(GuestAllocations::Mutation& mutation, void* addr,
|
||||
mutation.Protect(addr, len, (prot & 3) != 0, (prot & 2) != 0, [&] {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(addr);
|
||||
std::lock_guard lock(g_directLock);
|
||||
EraseMappings(address, address + len, true);
|
||||
if (physStart >= 0) {
|
||||
AddMapping(address, len, static_cast<std::uint64_t>(physStart), nativeProtection);
|
||||
} else {
|
||||
EraseMappings(address, address + len);
|
||||
#ifdef _WIN32
|
||||
if (physStart >= 0 && !VirtualFree(addr, len, MEM_DECOMMIT)) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualFree decommit failed");
|
||||
if (!VirtualAlloc(addr, len, MEM_COMMIT, WinProtFromPosix(nativeProtection))) throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "VirtualAlloc commit failed");
|
||||
GuestArena::GuestArenaReset_nid_postfix(addr, len);
|
||||
if (nativeProtection != PROT_NONE) CommitArenaRange(addr, len, WinProtFromPosix(nativeProtection));
|
||||
#else
|
||||
if (physStart >= 0 && madvise(addr, len, MADV_DONTNEED) != 0) throw std::system_error(errno, std::generic_category(), "madvise failed");
|
||||
if (::mmap(addr, len, nativeProtection, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "remap anonymous memory");
|
||||
#endif
|
||||
if (mprotect(addr, len, nativeProtection) != 0) throw std::system_error(errno, std::generic_category(), "mprotect failed");
|
||||
if (physStart >= 0) AddMapping(address, len, static_cast<std::uint64_t>(physStart), nativeProtection);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -475,11 +470,13 @@ int DoMapDirect(void** addr, size_t len, int prot, int flags, int64_t physStart,
|
||||
}
|
||||
if (*addr != nullptr && (flags & GuestMapFixedFlag) != 0) mutation.RequireAvailable(*addr, len);
|
||||
std::lock_guard lock(g_directLock);
|
||||
void* mapped = MapAligned(*addr, len, LinuxProtFromSce(prot), flags, alignment);
|
||||
ValidatePhysicalRange(static_cast<std::uint64_t>(physStart), len);
|
||||
void* mapped = MapAligned(*addr, len, PROT_NONE, flags, alignment);
|
||||
try {
|
||||
mutation.Add(mapped, len, (prot & 3) != 0, (prot & 2) != 0);
|
||||
AddMapping(reinterpret_cast<std::uintptr_t>(mapped), len, static_cast<std::uint64_t>(physStart), LinuxProtFromSce(prot));
|
||||
mutation.Add(mapped, len, (prot & 3) != 0, (prot & 2) != 0);
|
||||
} catch (...) {
|
||||
EraseMappings(reinterpret_cast<std::uintptr_t>(mapped), reinterpret_cast<std::uintptr_t>(mapped) + len);
|
||||
Unmap(mapped, len);
|
||||
throw;
|
||||
}
|
||||
@@ -535,8 +532,6 @@ int DoMprotect(const void* addr, size_t len, int prot) {
|
||||
#endif
|
||||
mutation.Protect(pointer, bytes, (prot & 3) != 0, (prot & 2) != 0, [&] {
|
||||
if (mprotect(const_cast<void*>(pointer), bytes, nativeProtection) != 0) throw std::system_error(errno, std::generic_category(), "mprotect failed");
|
||||
std::lock_guard lock(g_directLock);
|
||||
for (auto it = g_shared.lower_bound(first); it != g_shared.end() && *it < end; ++it) ProtectOrThrow(*it, PS5_PAGE_SIZE, SharedProtection(nativeProtection));
|
||||
});
|
||||
RecordProtection(pointer, bytes, prot);
|
||||
return 0;
|
||||
@@ -547,11 +542,8 @@ int DoMunmap(void* addr, size_t len) {
|
||||
if (len == 0 || (len & (PS5_PAGE_SIZE - 1)) != 0 || !addr) return SCE_KERNEL_ERROR_EINVAL;
|
||||
GuestAllocations::Mutation mutation;
|
||||
mutation.Unmap(addr, len, [&](const void* allocation, bool last) {
|
||||
{
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(addr);
|
||||
std::lock_guard lock(g_directLock);
|
||||
EraseMappings(address, address + len, true);
|
||||
}
|
||||
std::lock_guard lock(g_directLock);
|
||||
EraseMappings(reinterpret_cast<std::uintptr_t>(addr), reinterpret_cast<std::uintptr_t>(addr) + len);
|
||||
#if defined(__linux__)
|
||||
Unmap(addr, len);
|
||||
#else
|
||||
@@ -580,17 +572,25 @@ int DoReserveVirtual(void** addr, size_t len, size_t alignment) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void CreateDirectMemoryBacking(int64_t start, size_t len, int memoryType) {
|
||||
std::lock_guard lock(g_directLock);
|
||||
const auto first = static_cast<std::uint64_t>(start);
|
||||
for (std::size_t offset = 0; offset < len; offset += PS5_PAGE_SIZE) {
|
||||
if (g_physPages.contains(first + offset)) throw std::runtime_error("physical allocation overlaps live direct memory");
|
||||
}
|
||||
const auto backing = std::make_shared<PhysicalBacking>(len, memoryType);
|
||||
std::map<std::uint64_t, PhysicalPage> pages;
|
||||
for (std::size_t offset = 0; offset < len; offset += PS5_PAGE_SIZE) pages.emplace(first + offset, PhysicalPage{backing, offset});
|
||||
g_physPages.merge(pages);
|
||||
Trace("allocate physical 0x%llx+0x%zx", static_cast<unsigned long long>(first), len);
|
||||
}
|
||||
|
||||
void ForgetDirectMemory(int64_t start, size_t len) {
|
||||
const auto first = static_cast<std::uint64_t>(start);
|
||||
const auto end = first + len;
|
||||
std::lock_guard lock(g_directLock);
|
||||
g_physPages.erase(g_physPages.lower_bound(first), g_physPages.lower_bound(end));
|
||||
std::vector<std::pair<std::uintptr_t, std::uintptr_t>> released;
|
||||
for (const auto& [base, mapping] : g_directMappings) {
|
||||
const auto mappedEnd = mapping.phys + (mapping.end - base);
|
||||
if (mapping.phys < end && first < mappedEnd) released.emplace_back(base + (std::max(first, mapping.phys) - mapping.phys), base + (std::min(end, mappedEnd) - mapping.phys));
|
||||
}
|
||||
for (const auto& [from, to] : released) EraseMappings(from, to, false);
|
||||
ValidatePhysicalRange(first, len);
|
||||
g_physPages.erase(g_physPages.lower_bound(first), g_physPages.lower_bound(first + len));
|
||||
Trace("release physical 0x%llx+0x%zx", static_cast<unsigned long long>(first), len);
|
||||
}
|
||||
|
||||
bool GuestProtection(uintptr_t addr, int* prot) {
|
||||
@@ -602,3 +602,16 @@ bool GuestProtection(uintptr_t addr, int* prot) {
|
||||
*prot = containing->second.prot;
|
||||
return true;
|
||||
}
|
||||
|
||||
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);
|
||||
if (next == g_directMappings.begin()) return false;
|
||||
const auto it = std::prev(next);
|
||||
if (address >= it->second.end) return false;
|
||||
*start = it->first;
|
||||
*end = it->second.end;
|
||||
*offset = it->second.phys;
|
||||
*memoryType = it->second.memoryType;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ static constexpr size_t PS5_PAGE_SIZE = 0x4000;
|
||||
|
||||
int DirectMemoryAlloc(int64_t searchStart, int64_t searchEnd, size_t len, size_t alignment, int memoryType, int64_t* physOut);
|
||||
void DirectMemoryFree(int64_t start, size_t len);
|
||||
void CreateDirectMemoryBacking(int64_t start, size_t len, int memoryType);
|
||||
bool QueryDirectMapping(std::uintptr_t address, std::uintptr_t* start, std::uintptr_t* end, std::uint64_t* offset, int* memoryType);
|
||||
void ForgetDirectMemory(int64_t start, size_t len);
|
||||
bool DirectMemoryFind(int64_t offset, bool findNext, int64_t* start, int64_t* end, int* memoryType);
|
||||
size_t DirectMemoryFreeRun(uint64_t offset, uint64_t limit);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include "SceTypes.hpp"
|
||||
#include "prx/libc/include/General.hpp"
|
||||
#include "prx/libc/include/GuestAllocations.hpp"
|
||||
#include "DirectMemory.hpp"
|
||||
#include "prx/libkernel/DirectMemory/DirectMemory.hpp"
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
@@ -218,9 +218,21 @@ int APS5_VABI sceKernelVirtualQuery(const void* addr, int flags, VirtualQueryInf
|
||||
info->protection = (best->readable ? 1 : 0) | (best->writable ? 2 : 0) | (!best->releasable ? 4 : 0);
|
||||
int recorded = 0;
|
||||
if (GuestProtection(std::max<uintptr_t>(address, info->start), &recorded)) info->protection = recorded;
|
||||
info->is_direct = best->releasable ? 1u : 0u;
|
||||
std::uintptr_t directStart = 0;
|
||||
std::uintptr_t directEnd = 0;
|
||||
std::uint64_t physicalOffset = 0;
|
||||
int memoryType = 0;
|
||||
const bool direct = QueryDirectMapping(std::max<uintptr_t>(address, info->start), &directStart, &directEnd, &physicalOffset, &memoryType);
|
||||
info->is_direct = direct ? 1u : 0u;
|
||||
info->is_flexible = !direct && best->releasable ? 1u : 0u;
|
||||
if (direct) {
|
||||
info->start = std::max(info->start, directStart);
|
||||
info->end = std::min(info->end, directEnd);
|
||||
info->memory_type = memoryType;
|
||||
}
|
||||
info->is_committed = 1;
|
||||
ApplyRangeName(std::max<uintptr_t>(address, info->start), info);
|
||||
if (direct) info->offset = physicalOffset + info->start - directStart;
|
||||
return 0;
|
||||
}
|
||||
// Memory the registry does not know (the title's own heap blocks, stacks): the host's committed
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#define _GLIBCXX_HAS_GTHREADS 0
|
||||
#include "MemoryPool.hpp"
|
||||
#include "DirectMemory.hpp"
|
||||
#include "prx/libkernel/DirectMemory/MemoryPool.hpp"
|
||||
#include "prx/libkernel/DirectMemory/DirectMemory.hpp"
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
@@ -20,6 +19,7 @@ struct PhysicalMemoryPool {
|
||||
uint64_t cur = (start + align - 1) & ~(align - 1);
|
||||
while (cur + len <= end && cur + len <= DIRECT_MEMORY_SIZE) {
|
||||
if (_isFree(cur, len)) {
|
||||
CreateDirectMemoryBacking(static_cast<int64_t>(cur), len, memoryType);
|
||||
_mark(cur, len, true);
|
||||
_blocks[cur] = {cur + len, memoryType};
|
||||
*physOut = static_cast<int64_t>(cur);
|
||||
@@ -32,6 +32,7 @@ struct PhysicalMemoryPool {
|
||||
|
||||
void Free(uint64_t start, size_t len) {
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
ForgetDirectMemory(static_cast<int64_t>(start), len);
|
||||
_mark(start, len, false);
|
||||
const uint64_t end = start + len;
|
||||
auto it = _blocks.upper_bound(start);
|
||||
@@ -99,7 +100,6 @@ int DirectMemoryAlloc(int64_t searchStart, int64_t searchEnd, size_t len, size_t
|
||||
}
|
||||
|
||||
void DirectMemoryFree(int64_t start, size_t len) {
|
||||
ForgetDirectMemory(start, len);
|
||||
PhysicalMemoryPool::Instance().Free(static_cast<uint64_t>(start), len);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "prx/libc/include/general/VabiMacros.hpp"
|
||||
#include "prx/libc/include/GuestAllocations.hpp"
|
||||
#include "prx/libc/include/GuestHeap.hpp"
|
||||
#include "SceTypes.hpp"
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
@@ -20,6 +21,7 @@ int APS5_VABI sceKernelSetVirtualRangeName(const void*, std::uint64_t, const cha
|
||||
int APS5_VABI sceKernelClearVirtualRangeName(const void*, std::uint64_t);
|
||||
int APS5_VABI sceKernelAllocateDirectMemory(std::int64_t, std::int64_t, std::size_t, std::size_t, int, std::int64_t*);
|
||||
int APS5_VABI sceKernelMapDirectMemory(void**, std::size_t, int, int, std::int64_t, std::size_t);
|
||||
int APS5_VABI sceKernelMprotect(const void*, std::size_t, int);
|
||||
int APS5_VABI sceKernelReleaseDirectMemory(std::int64_t, std::size_t);
|
||||
int APS5_VABI sceKernelReserveVirtualRange(void**, std::size_t, int, std::size_t);
|
||||
}
|
||||
@@ -73,6 +75,16 @@ static void CheckDirectMemoryFollowsPhysicalPages() {
|
||||
void* alias = nullptr;
|
||||
Require(sceKernelMapDirectMemory(&alias, page, 3, 0, phys + page, 0) == 0);
|
||||
Require(alias != first && static_cast<unsigned char*>(alias)[5] == 22);
|
||||
static_cast<unsigned char*>(alias)[5] = 37;
|
||||
Require(static_cast<unsigned char*>(first)[page + 5] == 37);
|
||||
static_cast<unsigned char*>(first)[page + 6] = 48;
|
||||
Require(static_cast<unsigned char*>(alias)[6] == 48);
|
||||
Require(sceKernelMprotect(alias, page, 1) == 0);
|
||||
static_cast<unsigned char*>(first)[page + 5] = 59;
|
||||
Require(static_cast<unsigned char*>(alias)[5] == 59);
|
||||
Require(sceKernelMprotect(alias, page, 3) == 0);
|
||||
static_cast<unsigned char*>(alias)[5] = 22;
|
||||
Require(static_cast<unsigned char*>(first)[page + 5] == 22);
|
||||
Require(sceKernelMunmap(alias, page) == 0);
|
||||
static_cast<unsigned char*>(first)[page + 5] = 22;
|
||||
Require(sceKernelMunmap(first, page * 2) == 0);
|
||||
@@ -99,9 +111,90 @@ static void CheckDirectMemoryFollowsPhysicalPages() {
|
||||
Require(sceKernelReleaseDirectMemory(again, page * 2) == 0);
|
||||
}
|
||||
|
||||
static void CheckSharedDirectMemoryLifecycle() {
|
||||
constexpr std::size_t page = 0x4000;
|
||||
std::int64_t phys = 0;
|
||||
Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, page * 3, 0, 0, &phys) == 0);
|
||||
void* first = nullptr;
|
||||
void* second = nullptr;
|
||||
Require(sceKernelMapDirectMemory(&first, page * 3, 3, 0, phys, 0) == 0);
|
||||
Require(sceKernelMapDirectMemory(&second, page * 3, 3, 0, phys, 0) == 0);
|
||||
VirtualQueryInfo info{};
|
||||
Require(sceKernelVirtualQuery(second, 0, &info, sizeof(info)) == 0);
|
||||
Require(info.is_direct && !info.is_flexible && info.offset == static_cast<std::uint64_t>(phys));
|
||||
auto* left = static_cast<unsigned char*>(first);
|
||||
auto* right = static_cast<unsigned char*>(second);
|
||||
left[0] = 31;
|
||||
right[page] = 47;
|
||||
left[page * 2] = 63;
|
||||
Require(right[0] == 31 && left[page] == 47 && right[page * 2] == 63);
|
||||
void* inaccessible = nullptr;
|
||||
Require(sceKernelMapDirectMemory(&inaccessible, page, 0, 0, phys + page, 0) == 0);
|
||||
left[page] = 48;
|
||||
Require(sceKernelMprotect(inaccessible, page, 1) == 0);
|
||||
Require(static_cast<const unsigned char*>(inaccessible)[0] == 48);
|
||||
Require(sceKernelMunmap(inaccessible, page) == 0);
|
||||
Require(sceKernelMunmap(left + page, page) == 0);
|
||||
right[page] = 79;
|
||||
Require(left[0] == 31 && left[page * 2] == 63);
|
||||
void* middle = left + page;
|
||||
Require(sceKernelMapDirectMemory(&middle, page, 3, 0x10, phys + page, 0) == 0);
|
||||
Require(left[page] == 79);
|
||||
Require(sceKernelVirtualQuery(middle, 0, &info, sizeof(info)) == 0);
|
||||
Require(info.offset == static_cast<std::uint64_t>(phys) + page && info.start == reinterpret_cast<std::uintptr_t>(middle));
|
||||
Require(sceKernelMprotect(second, page * 3, 0) == 0);
|
||||
left[page] = 95;
|
||||
Require(sceKernelMprotect(second, page * 3, 1) == 0);
|
||||
Require(right[page] == 95);
|
||||
Require(sceKernelMunmap(first, page) == 0);
|
||||
Require(sceKernelMunmap(left + page * 2, page) == 0);
|
||||
Require(sceKernelMunmap(middle, page) == 0);
|
||||
Require(sceKernelMprotect(second, page * 3, 3) == 0);
|
||||
right[page * 2] = 111;
|
||||
void* reserved = nullptr;
|
||||
Require(sceKernelReserveVirtualRange(&reserved, page * 3, 0, 0) == 0);
|
||||
void* fixed = static_cast<unsigned char*>(reserved) + page;
|
||||
Require(sceKernelMapDirectMemory(&fixed, page, 3, 0x10, phys + page * 2, 0) == 0);
|
||||
Require(static_cast<unsigned char*>(fixed)[0] == 111);
|
||||
static_cast<unsigned char*>(fixed)[0] = 127;
|
||||
Require(right[page * 2] == 127);
|
||||
Require(sceKernelMapFlexibleMemory(&fixed, page, 3, 0x10) == 0);
|
||||
Require(static_cast<unsigned char*>(fixed)[0] == 0);
|
||||
Require(sceKernelVirtualQuery(fixed, 0, &info, sizeof(info)) == 0);
|
||||
Require(!info.is_direct && info.is_flexible && info.offset == 0);
|
||||
static_cast<unsigned char*>(fixed)[0] = 143;
|
||||
Require(right[page * 2] == 127);
|
||||
Require(sceKernelMunmap(reserved, page * 3) == 0);
|
||||
Require(sceKernelMunmap(second, page * 3) == 0);
|
||||
Require(sceKernelReleaseDirectMemory(phys + page, page) == 0);
|
||||
std::int64_t replacement = 0;
|
||||
Require(sceKernelAllocateDirectMemory(phys + page, phys + page * 2, page, 0, 0, &replacement) == 0);
|
||||
Require(replacement == phys + page);
|
||||
void* mixed = nullptr;
|
||||
Require(sceKernelMapDirectMemory(&mixed, page * 3, 3, 0, phys, 0) == 0);
|
||||
const auto* data = static_cast<const unsigned char*>(mixed);
|
||||
Require(data[0] == 31 && data[page] == 0 && data[page * 2] == 127);
|
||||
Require(sceKernelMunmap(mixed, page * 3) == 0);
|
||||
Require(sceKernelReleaseDirectMemory(phys, page * 3) == 0);
|
||||
}
|
||||
|
||||
static void CheckHeapAfterMappingReuse() {
|
||||
constexpr std::size_t bytes = 0x30000;
|
||||
auto* pointer = static_cast<unsigned char*>(GuestHeap::GuestHeapAllocate_nid_postfix(bytes));
|
||||
std::memset(pointer, 0x5a, bytes);
|
||||
Require(pointer[0] == 0x5a && pointer[bytes - 1] == 0x5a);
|
||||
GuestHeap::GuestHeapFree_nid_postfix(pointer);
|
||||
pointer = static_cast<unsigned char*>(GuestHeap::GuestHeapAllocate_nid_postfix(bytes));
|
||||
std::memset(pointer, 0xa5, bytes);
|
||||
Require(pointer[0] == 0xa5 && pointer[bytes - 1] == 0xa5);
|
||||
GuestHeap::GuestHeapFree_nid_postfix(pointer);
|
||||
}
|
||||
|
||||
int main() {
|
||||
CheckNamedAndHintedMappings();
|
||||
CheckDirectMemoryFollowsPhysicalPages();
|
||||
CheckSharedDirectMemoryLifecycle();
|
||||
CheckHeapAfterMappingReuse();
|
||||
constexpr std::size_t page = 0x4000;
|
||||
const auto failed = reinterpret_cast<void*>(static_cast<std::uintptr_t>(-1));
|
||||
const auto reject = [&](std::size_t length, int protection, int flags, int fd,
|
||||
|
||||
Reference in New Issue
Block a user