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
6 changes: 3 additions & 3 deletions core/libs/prx/libc/include/GuestArena.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ 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 GuestArenaSetProtection_nid_postfix(std::uintptr_t address, std::size_t bytes, std::uint32_t protection);
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);
#ifdef _WIN32
bool GuestArenaHandleWrite_nid_postfix(std::uintptr_t address);
void GuestArenaPinWritable_nid_postfix(const void* pointer, std::size_t bytes);
void GuestArenaUnpinWritable_nid_postfix(const void* pointer, std::size_t bytes);
Expand All @@ -34,8 +36,6 @@ bool GuestArenaCollectWrites_nid_postfix(std::uintptr_t address, std::size_t byt
bool GuestArenaHostRegionOverlaps_nid_postfix(std::uintptr_t address, std::size_t bytes);
std::uint64_t GuestArenaCommitGeneration_nid_postfix();
void GuestArenaSetPrivateMappingObserver_nid_postfix(void (*callback)(std::uintptr_t address, std::size_t bytes, std::uint64_t generation));
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);
void* GuestArenaMapAlias_nid_postfix(std::uintptr_t address, std::size_t bytes);
void GuestArenaUnmapAlias_nid_postfix(void* alias);
Expand Down
153 changes: 142 additions & 11 deletions core/libs/prx/libc/src/GuestArena.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
#include <algorithm>
#include <atomic>
#include <cstdint>
#ifndef _WIN32
#include <cerrno>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/mman.h>
#endif
#include <cstdio>
#include <iterator>
#include <map>
Expand Down Expand Up @@ -72,6 +79,22 @@ class Arena {
return reinterpret_cast<void*>(candidate);
}

bool MarkUsedForCommit(const void* pointer, std::size_t bytes) {
std::lock_guard lock(_lock);
const auto start = reinterpret_cast<std::uintptr_t>(pointer);
const auto end = start + bytes;
const auto exact = _used.find(start);
if (exact != _used.end() && exact->second >= end) return false;
const auto next = _used.lower_bound(start);
if ((next != _used.end() && next->first < end) || (next != _used.begin() && std::prev(next)->second > start)) {
char message[160];
std::snprintf(message, sizeof(message), "guest arena commit 0x%llx+0x%zx overlaps a used range", static_cast<unsigned long long>(start), bytes);
throw std::runtime_error(message);
}
_used.emplace(start, end);
return true;
}

void MarkUsed(const void* pointer, std::size_t bytes) {
std::lock_guard lock(_lock);
const auto start = reinterpret_cast<std::uintptr_t>(pointer);
Expand Down Expand Up @@ -108,7 +131,9 @@ class Arena {

private:
Arena() {
#ifdef _WIN32
#if defined(__linux__)
SeedLinuxUsedRanges();
#elif defined(_WIN32)
_writeWatched = std::getenv("APS5_NO_WRITE_WATCH") == nullptr;
SYSTEM_INFO system{};
GetSystemInfo(&system);
Expand Down Expand Up @@ -139,6 +164,66 @@ class Arena {
#endif
}

#if defined(__linux__)
void SeedLinuxUsedRanges() {
std::ifstream maps("/proc/self/maps");
if (!maps.is_open()) throw std::runtime_error("guest arena: cannot open /proc/self/maps");
std::string line;
while (std::getline(maps, line)) {
std::istringstream fields(line);
std::uintptr_t begin = 0, end = 0;
char dash = 0;
if (!(fields >> std::hex >> begin >> dash >> end) || dash != '-' || end <= begin) throw std::runtime_error("guest arena: malformed /proc/self/maps line: " + line);
if (end <= ArenaStart || begin >= ApplicationAreaEnd) continue;
const auto first = std::max(begin, ArenaStart);
const auto last = std::min(end, ApplicationAreaEnd);
_used.emplace(first, last);
_hostRegions.emplace_back(first, last);
}
_used.emplace(SystemReservedStart, SystemReservedEnd);
_hostRegions.emplace_back(SystemReservedStart, SystemReservedEnd);
ReserveFreeRanges();
_base = ArenaStart;
_end = ApplicationAreaEnd;
}

static void TryReserve(std::vector<std::pair<std::uintptr_t, std::uintptr_t>>& occupied, std::uintptr_t from, std::uintptr_t to) {
constexpr std::uintptr_t kChunk = 1ULL << 30;
for (std::uintptr_t cursor = from; cursor < to; cursor += kChunk) {
const auto end = std::min(cursor + kChunk, to);
void* const wanted = reinterpret_cast<void*>(cursor);
void* const placed = mmap(wanted, end - cursor, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0);
if (placed == wanted) continue;
const int failed = placed == MAP_FAILED ? errno : EINVAL;
if (placed != MAP_FAILED) munmap(placed, end - cursor);
if (failed != EEXIST) {
char message[128];
std::snprintf(message, sizeof(message), "guest arena: cannot reserve 0x%llx+0x%llx",
static_cast<unsigned long long>(cursor), static_cast<unsigned long long>(end - cursor));
throw std::system_error(failed, std::system_category(), message);
}
occupied.emplace_back(cursor, end);
}
}

void ReserveFreeRanges() {
std::vector<std::pair<std::uintptr_t, std::uintptr_t>> occupied;
std::uintptr_t cursor = ArenaStart;
for (const auto& [usedStart, usedEnd] : _used) {
if (usedStart > ApplicationAreaEnd) break;
if (usedStart > cursor) TryReserve(occupied, cursor, std::min(usedStart, ApplicationAreaEnd));
if (usedEnd > cursor) cursor = usedEnd;
if (cursor >= ApplicationAreaEnd) break;
}
if (cursor < ApplicationAreaEnd) TryReserve(occupied, cursor, ApplicationAreaEnd);
for (const auto& [from, to] : occupied) {
_used.emplace(from, to);
_hostRegions.emplace_back(from, to);
}
}
#endif

std::mutex _lock;
std::map<std::uintptr_t, std::uintptr_t> _used;
std::vector<std::pair<std::uintptr_t, std::uintptr_t>> _holes;
Expand Down Expand Up @@ -192,6 +277,16 @@ void GuestArenaRange_nid_postfix(std::uintptr_t* base, std::size_t* bytes) {
*bytes = Arena::Get().Size();
}

namespace {

std::invalid_argument OutsideArena(const char* operation, const void* pointer, std::size_t bytes) {
char message[128];
std::snprintf(message, sizeof(message), "%s 0x%llx+0x%zx outside the guest arena", operation, static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(pointer)), bytes);
return std::invalid_argument(message);
}

}

#ifdef _WIN32
void GuestArenaSetProtection_nid_postfix(std::uintptr_t address, std::size_t bytes, std::uint32_t protection) {
WindowsMappings::Get().SetProtection(address, bytes, protection);
Expand Down Expand Up @@ -223,16 +318,6 @@ bool GuestArenaHostRegionOverlaps_nid_postfix(std::uintptr_t address, std::size_
return Arena::Get().OverlapsHostRegion(address, bytes);
}

namespace {

std::invalid_argument OutsideArena(const char* operation, const void* pointer, std::size_t bytes) {
char message[128];
std::snprintf(message, sizeof(message), "%s 0x%llx+0x%zx outside the guest arena", operation, static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(pointer)), bytes);
return std::invalid_argument(message);
}

}

std::uint64_t GuestArenaCommitGeneration_nid_postfix() {
return commitGeneration.load(std::memory_order_acquire);
}
Expand Down Expand Up @@ -269,6 +354,52 @@ void GuestArenaUnmapAlias_nid_postfix(void* alias) {
}
#endif

#if defined(__linux__)
namespace {
int PosixProtection(std::uint32_t windowsProtection) {
switch (windowsProtection) {
case 0x01: return PROT_NONE;
case 0x02: return PROT_READ;
case 0x04: return PROT_READ | PROT_WRITE;
case 0x08: return PROT_READ | PROT_WRITE;
case 0x10: return PROT_EXEC;
case 0x20: return PROT_READ | PROT_EXEC;
case 0x40: return PROT_READ | PROT_WRITE | PROT_EXEC;
default: throw std::runtime_error("guest arena: unmapped protection value");
}
}

void* PlaceAt(void* pointer, std::size_t bytes, std::uint32_t protection) {
return mmap(pointer, bytes, PosixProtection(protection), MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
}
}
#endif

#if defined(__linux__)
void GuestArenaSetProtection_nid_postfix(std::uintptr_t address, std::size_t bytes, std::uint32_t protection) {
if (!Arena::Get().Contains(reinterpret_cast<void*>(address), bytes)) throw OutsideArena("set protection", reinterpret_cast<void*>(address), bytes);
if (mprotect(reinterpret_cast<void*>(address), bytes, PosixProtection(protection)) != 0)
throw std::system_error(errno, std::generic_category(), "guest arena protection failed");
}

void GuestArenaCommit_nid_postfix(void* pointer, std::size_t bytes, std::uint32_t protection, std::size_t granule) {
(void)granule;
if (!Arena::Get().Contains(pointer, bytes)) throw OutsideArena("commit", pointer, bytes);
const bool marked = Arena::Get().MarkUsedForCommit(pointer, bytes);
try {
if (PlaceAt(pointer, bytes, protection) == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "guest arena commit failed");
} catch (...) {
if (marked) Arena::Get().Release(pointer, bytes);
throw;
}
}

void GuestArenaReset_nid_postfix(void* pointer, std::size_t bytes) {
if (!Arena::Get().Contains(pointer, bytes)) throw OutsideArena("reset", pointer, bytes);
if (PlaceAt(pointer, bytes, 0x01) == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "guest arena reset failed");
}
#endif

bool GuestArenaWriteWatched_nid_postfix() {
return Arena::Get().WriteWatched();
}
Expand Down
11 changes: 3 additions & 8 deletions core/libs/prx/libc/src/GuestHeap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
namespace GuestHeap {
namespace {

constexpr std::uint32_t ReadWriteProtection = 0x04;

// Each block is preceded by a header holding the raw block address and its size in bytes.
constexpr std::size_t HeaderBytes = 2 * sizeof(void*);
constexpr std::size_t RawAlignment = 16;
Expand Down Expand Up @@ -110,12 +112,7 @@ class ArenaHeap {
}

static void commit(void* pointer, std::size_t bytes) {
#ifdef _WIN32
GuestArena::GuestArenaCommit_nid_postfix(pointer, bytes, PAGE_READWRITE, bytes);
#else
(void)pointer;
(void)bytes;
#endif
GuestArena::GuestArenaCommit_nid_postfix(pointer, bytes, ReadWriteProtection, bytes);
}

// Freed large blocks stay committed and are handed out again for the same block size: the game
Expand Down Expand Up @@ -168,10 +165,8 @@ class ArenaHeap {
}

static void release(void* raw, std::size_t bytes) {
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(raw, bytes);
GuestAllocations::GuestAllocationsInvalidate_nid_postfix(reinterpret_cast<std::uintptr_t>(raw), bytes);
#endif
GuestArena::GuestArenaRelease_nid_postfix(raw, bytes);
}

Expand Down
40 changes: 39 additions & 1 deletion core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,24 @@ bool RemapFixedIntoRegistered(GuestAllocations::Mutation& mutation, void* addr,
return true;
}

#if defined(__linux__)
bool ArenaAvailable() { return GuestArena::GuestArenaAvailable_nid_postfix(); }

void* ArenaCommit(void* addr, size_t len, int prot) {
return mmap(addr, len, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
}

void ArenaForget(void* addr, size_t len) {
if (GuestArena::GuestArenaContains_nid_postfix(addr, len)) GuestArena::GuestArenaRelease_nid_postfix(addr, len);
}
#endif

void Unmap(void* addr, size_t len) {
#if defined(__linux__)
if (munmap(addr, len) != 0) throw std::system_error(errno, std::generic_category(), "munmap failed");
if (ArenaAvailable() && GuestArena::GuestArenaContains_nid_postfix(addr, len))
GuestArena::GuestArenaReset_nid_postfix(addr, len);
else if (munmap(addr, len) != 0) throw std::system_error(errno, std::generic_category(), "munmap failed");
ArenaForget(addr, len);
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(addr, len);
#else
if (KernelArena::Get().Contains(addr, len)) munmap(addr, len);
Expand Down Expand Up @@ -565,6 +580,14 @@ void* MapPlaced(void* addr, size_t len, int prot, int flags, size_t alignment) {
}
#endif
#if defined(__linux__)
if (ArenaAvailable() && !GuestArena::GuestArenaContains_nid_postfix(addr, len))
throw std::invalid_argument("fixed mapping is outside the guest address space arena");
if (ArenaAvailable()) {
GuestArena::GuestArenaMarkUsed_nid_postfix(addr, len);
if (void* placed = ArenaCommit(addr, len, prot); placed != MAP_FAILED) return placed;
GuestArena::GuestArenaRelease_nid_postfix(addr, len);
throw std::system_error(errno, std::generic_category(), "Arena mapping failed");
}
const int placement = (flags & GuestMapNoOverwrite) != 0 ? MAP_FIXED_NOREPLACE : MAP_FIXED;
#else
const int placement = MAP_FIXED;
Expand All @@ -578,13 +601,28 @@ void* MapPlaced(void* addr, size_t len, int prot, int flags, size_t alignment) {
}
if (addr) {
#if defined(__linux__)
if (ArenaAvailable()) {
void* placed = GuestArena::GuestArenaAllocateAtOrAbove_nid_postfix(
reinterpret_cast<std::uintptr_t>(addr), len, alignment);
if (void* committed = ArenaCommit(placed, len, prot); committed != MAP_FAILED) return committed;
ArenaForget(placed, len);
throw std::system_error(errno, std::generic_category(), "Arena mapping failed");
}
return MapAtOrAbove(reinterpret_cast<std::uintptr_t>(addr), len, prot, alignment);
#else
return mmap_aligned(len, prot, alignment, reinterpret_cast<std::uintptr_t>(addr));
#endif
}
#ifdef _WIN32
return mmap_aligned(len, prot, alignment);
#endif
#if defined(__linux__)
if (ArenaAvailable()) {
void* placed = GuestArena::GuestArenaAllocate_nid_postfix(len, alignment);
if (void* committed = ArenaCommit(placed, len, prot); committed != MAP_FAILED) return committed;
ArenaForget(placed, len);
throw std::system_error(errno, std::generic_category(), "Arena mapping failed");
}
#endif
if (len > std::numeric_limits<size_t>::max() - alignment) {
throw std::overflow_error("Aligned mapping size overflow");
Expand Down
1 change: 1 addition & 0 deletions core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@ int DoMunmap(void* addr, size_t len);
int DoReserveVirtual(void** addr, size_t len, int flags, size_t alignment);
bool GuestProtection(uintptr_t addr, int* prot);
bool GuestReservation(std::uintptr_t addr, std::uintptr_t* start, std::uintptr_t* end);
bool GuestRangeMapped(std::uintptr_t start, std::uintptr_t end);

#endif
11 changes: 11 additions & 0 deletions core/libs/prx/libkernel/DirectMemory/Export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,16 @@ int APS5_VABI sceKernelBatchMap2(KernelBatchMapEntry* entries, int num_entries,

}

bool GuestRangeMapped(std::uintptr_t start, std::uintptr_t end) {
for (auto cursor = start; cursor < end;) {
VirtualQueryInfo info{};
if (sceKernelVirtualQuery(reinterpret_cast<const void*>(cursor), 0, &info, sizeof(info)) != 0) return false;
if (info.end <= cursor) return false;
cursor = info.end;
}
return true;
}

namespace {

bool PageRange(void* address, std::uint64_t length, std::uintptr_t& start, std::uintptr_t& end) {
Expand Down Expand Up @@ -561,6 +571,7 @@ int LockHostPages(std::uintptr_t start, std::uintptr_t end) {
}

int UnlockHostPages(std::uintptr_t start, std::uintptr_t end) {
if (!GuestRangeMapped(start, end)) return SCE_KERNEL_ERROR_ENOMEM;
if (::munlock(reinterpret_cast<void*>(start), end - start) == 0) return 0;
const int error = errno;
if (error == ENOMEM) return SCE_KERNEL_ERROR_ENOMEM;
Expand Down
12 changes: 1 addition & 11 deletions core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,6 @@ bool Mapped(std::uintptr_t address) {
VirtualQueryInfo info{};
return sceKernelVirtualQuery(reinterpret_cast<const void*>(address), 0, &info, sizeof(info)) == 0;
}

bool RangeMapped(std::uintptr_t start, std::uintptr_t end) {
for (auto cursor = start; cursor < end;) {
VirtualQueryInfo info{};
if (sceKernelVirtualQuery(reinterpret_cast<const void*>(cursor), 0, &info, sizeof(info)) != 0) return false;
if (info.end <= cursor) return false;
cursor = info.end;
}
return true;
}
}

extern "C" {
Expand Down Expand Up @@ -150,7 +140,7 @@ int APS5_VABI msync_nid_postfix(void* address, std::size_t length, int flags) {
const auto end = start + size;
if (end < start) return failed(GuestInvalid);
if ((flags & (GuestSyncAsync | GuestSyncInvalidate)) == (GuestSyncAsync | GuestSyncInvalidate)) return failed(GuestInvalid);
if (start == end ? !Mapped(start) : !RangeMapped(start, end)) return failed(GuestNoMemory);
if (start == end ? !Mapped(start) : !GuestRangeMapped(start, end)) return failed(GuestNoMemory);
if ((flags & GuestSyncInvalidate) != 0) throw std::runtime_error("msync: MS_INVALIDATE is not implemented");
return 0;
}
Expand Down
Loading
Loading