fix(libc): route guest allocations through application heap

This commit is contained in:
boykopovar
2026-09-24 06:53:12 +03:00
parent 7ed9ef1e9b
commit 9f2b41b9a1
12 changed files with 440 additions and 9 deletions
+4
View File
@@ -103,6 +103,10 @@ endforeach()
add_custom_target(libs DEPENDS ${PATCHED_OUTPUTS})
add_executable(application_heap_tests EXCLUDE_FROM_ALL tests/ApplicationHeap.cpp prx/libc/src/ApplicationHeap.cpp)
target_include_directories(application_heap_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(application_heap_tests PROPERTIES CXX_EXTENSIONS OFF)
if(MINGW)
foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
+2
View File
@@ -9,6 +9,8 @@ target_sources(libc PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src/FileAndHeap.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/GuestAllocations.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/GuestHeap.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/ApplicationHeap.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/ApplicationProcessParameters.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/JumpBuffer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/Formatting.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/RuntimeSupport.cpp
@@ -0,0 +1,20 @@
#ifndef CORE_LIBS_PRX_LIBC_INCLUDE_APPLICATIONHEAP_HPP
#define CORE_LIBS_PRX_LIBC_INCLUDE_APPLICATIONHEAP_HPP
#include <cstddef>
extern "C" {
const void* ApplicationProcessParameters_nid_no_patch();
void ApplicationHeapInitialize_nid_no_patch(const void* processParameters);
void ApplicationHeapRegister_nid_no_patch(void* const* api);
void* ApplicationHeapAllocate_nid_no_patch(std::size_t bytes);
void ApplicationHeapFree_nid_no_patch(void* pointer);
void* ApplicationHeapReallocate_nid_no_patch(void* pointer, std::size_t bytes);
void* ApplicationHeapAlign_nid_no_patch(std::size_t alignment, std::size_t bytes);
void* ApplicationHeapCalloc_nid_no_patch(std::size_t count, std::size_t bytes);
int ApplicationHeapPosixAlign_nid_no_patch(void** pointer, std::size_t alignment, std::size_t bytes);
}
#endif
+178
View File
@@ -0,0 +1,178 @@
#include "prx/libc/include/ApplicationHeap.hpp"
#include "prx/libc/include/general/VabiMacros.hpp"
#include <array>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <mutex>
#include <new>
#include <stdexcept>
namespace {
using Allocate = void* (APS5_VABI *)(std::size_t);
using Free = void (APS5_VABI *)(void*);
using Reallocate = void* (APS5_VABI *)(void*, std::size_t);
using Calloc = void* (APS5_VABI *)(std::size_t, std::size_t);
using Align = void* (APS5_VABI *)(std::size_t, std::size_t);
using PosixAlign = int (APS5_VABI *)(void**, std::size_t, std::size_t);
using Initialize = void (APS5_VABI *)();
std::mutex heapMutex;
std::array<void*, 10> heapApi{};
std::once_flag heapInitialization;
std::exception_ptr heapFailure;
Initialize heapFinalize = nullptr;
bool heapFinalized = false;
thread_local bool heapCallbackActive = false;
class CallbackScope {
public:
CallbackScope() {
if (heapCallbackActive) throw std::runtime_error("application heap: recursive libc allocator callback");
heapCallbackActive = true;
}
~CallbackScope() { heapCallbackActive = false; }
CallbackScope(const CallbackScope&) = delete;
CallbackScope& operator=(const CallbackScope&) = delete;
};
template<typename TValue>
TValue read(const void* pointer, std::size_t offset) {
if (pointer == nullptr) throw std::invalid_argument("application heap: null metadata");
TValue value;
std::memcpy(&value, static_cast<const std::byte*>(pointer) + offset, sizeof(value));
return value;
}
template<typename TCallback>
TCallback callback(std::size_t index) {
std::lock_guard lock(heapMutex);
if (heapFailure) std::rethrow_exception(heapFailure);
if (heapFinalized) throw std::runtime_error("application heap: allocator has been finalized");
if (heapApi[index] == nullptr) throw std::runtime_error("application heap: allocator API is not registered");
static_assert(sizeof(TCallback) == sizeof(void*));
TCallback result;
std::memcpy(&result, &heapApi[index], sizeof(result));
return result;
}
void* requireAllocation(void* pointer) {
if (pointer == nullptr) throw std::bad_alloc();
return pointer;
}
void requireAlignment(std::size_t alignment) {
if (alignment == 0 || (alignment & (alignment - 1)) != 0) throw std::invalid_argument("application heap: invalid alignment");
}
void finalize() {
Initialize finalizeCallback;
{
std::lock_guard lock(heapMutex);
if (heapFailure) std::rethrow_exception(heapFailure);
if (heapFinalized) throw std::runtime_error("application heap: duplicate finalization");
finalizeCallback = heapFinalize;
}
if (finalizeCallback != nullptr) finalizeCallback();
std::lock_guard lock(heapMutex);
heapFinalized = true;
}
}
void ApplicationHeapRegister_nid_no_patch(void* const* api) {
if (api == nullptr) throw std::invalid_argument("application heap: null allocator API");
std::array<void*, 10> replacement;
std::memcpy(replacement.data(), api, sizeof(replacement));
for (std::size_t index = 0; index < 7; ++index) {
if (replacement[index] == nullptr) throw std::invalid_argument("application heap: incomplete allocator API");
}
std::lock_guard lock(heapMutex);
if (heapFailure) std::rethrow_exception(heapFailure);
if (heapFinalized) throw std::runtime_error("application heap: allocator has been finalized");
if (heapApi[0] != nullptr && heapApi != replacement) throw std::runtime_error("application heap: cannot replace an active allocator");
heapApi = replacement;
}
void ApplicationHeapInitialize_nid_no_patch(const void* processParameters) {
std::call_once(heapInitialization, [processParameters] {
try {
if (read<std::uint64_t>(processParameters, 0) < 0x40 || read<std::uint32_t>(processParameters, 8) != 0x4942524f) throw std::runtime_error("application heap: invalid process parameters");
const auto* libcParameters = read<const void*>(processParameters, 0x38);
if (read<std::uint64_t>(libcParameters, 0) < 0x38) throw std::runtime_error("application heap: invalid libc parameters");
const auto* replacement = read<const void*>(libcParameters, 0x30);
if (read<std::uint64_t>(replacement, 0) != 0x78 || read<std::uint64_t>(replacement, 8) != 2) throw std::runtime_error("application heap: unsupported allocator replacement table");
std::array<void*, 10> api;
std::memcpy(api.data(), static_cast<const std::byte*>(replacement) + 0x20, sizeof(api));
ApplicationHeapRegister_nid_no_patch(api.data());
const auto initialize = read<Initialize>(replacement, 0x10);
if (initialize != nullptr) initialize();
{
std::lock_guard lock(heapMutex);
heapFinalize = read<Initialize>(replacement, 0x18);
}
if (std::atexit(finalize) != 0) throw std::runtime_error("application heap: cannot register finalization");
} catch (...) {
std::lock_guard lock(heapMutex);
heapFailure = std::current_exception();
}
});
std::lock_guard lock(heapMutex);
if (heapFailure) std::rethrow_exception(heapFailure);
}
void* ApplicationHeapAllocate_nid_no_patch(std::size_t bytes) {
const auto allocate = callback<Allocate>(0);
CallbackScope scope;
return requireAllocation(allocate(bytes));
}
void ApplicationHeapFree_nid_no_patch(void* pointer) {
if (pointer == nullptr) return;
const auto free = callback<Free>(1);
CallbackScope scope;
free(pointer);
}
void* ApplicationHeapReallocate_nid_no_patch(void* pointer, std::size_t bytes) {
if (bytes == 0) {
ApplicationHeapFree_nid_no_patch(pointer);
return nullptr;
}
const auto reallocate = callback<Reallocate>(2);
CallbackScope scope;
return requireAllocation(reallocate(pointer, bytes));
}
void* ApplicationHeapAlign_nid_no_patch(std::size_t alignment, std::size_t bytes) {
requireAlignment(alignment);
const auto align = callback<Align>(4);
CallbackScope scope;
void* pointer = requireAllocation(align(alignment, bytes));
if (reinterpret_cast<std::uintptr_t>(pointer) % alignment != 0) throw std::runtime_error("application heap: allocator returned a misaligned pointer");
return pointer;
}
void* ApplicationHeapCalloc_nid_no_patch(std::size_t count, std::size_t bytes) {
if (bytes != 0 && count > std::numeric_limits<std::size_t>::max() / bytes) throw std::length_error("application heap: calloc size overflow");
const auto calloc = callback<Calloc>(3);
CallbackScope scope;
return requireAllocation(calloc(count, bytes));
}
int ApplicationHeapPosixAlign_nid_no_patch(void** pointer, std::size_t alignment, std::size_t bytes) {
if (pointer == nullptr) throw std::invalid_argument("application heap: null allocation output");
requireAlignment(alignment);
if (alignment < sizeof(void*)) throw std::invalid_argument("application heap: invalid POSIX alignment");
const auto align = callback<PosixAlign>(6);
CallbackScope scope;
void* result = nullptr;
if (align(&result, alignment, bytes) != 0) throw std::runtime_error("application heap: posix_memalign failed");
requireAllocation(result);
if (reinterpret_cast<std::uintptr_t>(result) % alignment != 0) throw std::runtime_error("application heap: allocator returned a misaligned pointer");
*pointer = result;
return 0;
}
@@ -0,0 +1,74 @@
#include "prx/libc/include/ApplicationHeap.hpp"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#elif defined(__linux__)
#include "prx/libc/include/specifics/linux/ElfTypes.hpp"
#endif
const void* ApplicationProcessParameters_nid_no_patch() {
#ifdef _WIN32
const auto* image = reinterpret_cast<const std::byte*>(GetModuleHandleW(nullptr));
if (image == nullptr) throw std::runtime_error("application heap: main image is unavailable");
const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(image);
if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0) throw std::runtime_error("application heap: invalid DOS header");
const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(image + dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) throw std::runtime_error("application heap: invalid PE header");
const auto* sections = IMAGE_FIRST_SECTION(nt);
const auto imageSize = nt->OptionalHeader.SizeOfImage;
const void* result = nullptr;
for (unsigned index = 0; index < nt->FileHeader.NumberOfSections; ++index) {
const auto& section = sections[index];
if (std::memcmp(section.Name, ".procpar", 8) != 0) continue;
if (result != nullptr) throw std::runtime_error("application heap: duplicate process metadata");
if (section.Misc.VirtualSize != 8 || section.VirtualAddress > imageSize || 8 > imageSize - section.VirtualAddress) throw std::runtime_error("application heap: invalid process metadata section");
std::uint32_t address;
std::uint32_t size;
std::memcpy(&address, image + section.VirtualAddress, sizeof(address));
std::memcpy(&size, image + section.VirtualAddress + 4, sizeof(size));
if (size < 0x40 || address > imageSize || size > imageSize - address) throw std::runtime_error("application heap: process parameters exceed the image");
result = image + address;
}
if (result == nullptr) throw std::runtime_error("application heap: process metadata is missing; relink the executable");
return result;
#elif defined(__linux__)
struct Search {
const void* parameters = nullptr;
bool invalid = false;
} search;
dl_iterate_phdr([](dl_phdr_info* image, std::size_t, void* data) {
auto& result = *static_cast<Search*>(data);
if (image->dlpi_name != nullptr && image->dlpi_name[0] != '\0') return 0;
for (std::uint16_t index = 0; index < image->dlpi_phnum; ++index) {
const auto& header = image->dlpi_phdr[index];
if (header.p_type != 0x61000001) continue;
if (result.parameters != nullptr || header.p_filesz < 0x40) {
result.invalid = true;
return 1;
}
bool mapped = false;
for (std::uint16_t loadIndex = 0; loadIndex < image->dlpi_phnum; ++loadIndex) {
const auto& load = image->dlpi_phdr[loadIndex];
if (load.p_type == PT_LOAD && header.p_vaddr >= load.p_vaddr && header.p_vaddr - load.p_vaddr <= load.p_memsz && header.p_filesz <= load.p_memsz - (header.p_vaddr - load.p_vaddr)) mapped = true;
}
if (!mapped) {
result.invalid = true;
return 1;
}
result.parameters = reinterpret_cast<const void*>(image->dlpi_addr + header.p_vaddr);
}
return 1;
}, &search);
if (search.invalid || search.parameters == nullptr) throw std::runtime_error("application heap: invalid or missing process parameters");
return search.parameters;
#else
throw std::runtime_error("application heap: unsupported executable format");
#endif
}
+13 -5
View File
@@ -8,7 +8,7 @@
#include <utility>
#include "prx/libc/include/FileStream.hpp"
#include "prx/libc/include/GuestHeap.hpp"
#include "prx/libc/include/ApplicationHeap.hpp"
#include "prx/libc/include/General.hpp"
extern "C" {
@@ -93,19 +93,27 @@ int APS5_VABI fflush_nid_postfix(FileStream* stream) {
}
void* APS5_VABI malloc_nid_postfix(size_t size) {
return GuestHeap::GuestHeapAllocate_nid_postfix(size);
return ApplicationHeapAllocate_nid_no_patch(size);
}
void APS5_VABI free_nid_postfix(void* ptr) {
GuestHeap::GuestHeapFree_nid_postfix(ptr);
ApplicationHeapFree_nid_no_patch(ptr);
}
void* APS5_VABI realloc_nid_postfix(void* ptr, size_t newSize) {
return GuestHeap::GuestHeapReallocate_nid_postfix(ptr, newSize);
return ApplicationHeapReallocate_nid_no_patch(ptr, newSize);
}
void* APS5_VABI memalign_nid_postfix(size_t alignment, size_t size) {
return GuestHeap::GuestHeapAlign_nid_postfix(alignment, size);
return ApplicationHeapAlign_nid_no_patch(alignment, size);
}
void* APS5_VABI calloc_nid_postfix(size_t count, size_t size) {
return ApplicationHeapCalloc_nid_no_patch(count, size);
}
int APS5_VABI posix_memalign_nid_postfix(void** pointer, size_t alignment, size_t size) {
return ApplicationHeapPosixAlign_nid_no_patch(pointer, alignment, size);
}
void APS5_VABI qsort_nid_postfix(void* base, size_t count, size_t size, int (APS5_VABI *compare)(const void*, const void*)) {
+2
View File
@@ -7,6 +7,7 @@
#include <mutex>
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/ApplicationHeap.hpp"
namespace {
@@ -135,6 +136,7 @@ wint_t APS5_VABI _Towctrans_nid_postfix(wint_t c, wctrans_t desc) {
}
void APS5_VABI _init_env_nid_postfix() {
ApplicationHeapInitialize_nid_no_patch(ApplicationProcessParameters_nid_no_patch());
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
#include "prx/libc/include/GuestHeap.hpp"
#include "prx/libc/include/ApplicationHeap.hpp"
#include <cstddef>
#include <cstring>
#include <cstdlib>
@@ -145,7 +145,7 @@ int APS5_VABI strncasecmp_nid_postfix(const char* s1, const char* s2, size_t n)
char* APS5_VABI strdup_nid_postfix(const char* s) {
std::size_t len = std::strlen(s) + 1;
char* copy = static_cast<char*>(GuestHeap::GuestHeapAllocate_nid_postfix(len));
char* copy = static_cast<char*>(ApplicationHeapAllocate_nid_no_patch(len));
std::memcpy(copy, s, len);
return copy;
}
+2 -2
View File
@@ -2,12 +2,12 @@
#include <cstddef>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/ApplicationHeap.hpp"
extern "C" {
void APS5_VABI sceKernelRtldSetApplicationHeapAPI(void* api[]) {
(void)api;
NotImplemented_nid_no_patch(__func__);
ApplicationHeapRegister_nid_no_patch(api);
}
int APS5_VABI sceKernelRtldThreadAtexitDecrement(uint64_t* c) {
+131
View File
@@ -0,0 +1,131 @@
#include "prx/libc/include/ApplicationHeap.hpp"
#include "prx/libc/include/general/VabiMacros.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <stdexcept>
namespace {
alignas(64) std::array<std::byte, 256> storage{};
std::size_t lastSize = 0;
std::size_t lastAlignment = 0;
unsigned initializes = 0;
unsigned frees = 0;
bool fail = false;
bool recurse = false;
void require(bool condition) {
if (!condition) throw std::runtime_error("application heap test failed");
}
template<typename TAction>
void reject(TAction action) {
bool rejected = false;
try { action(); } catch (const std::exception&) { rejected = true; }
require(rejected);
}
void APS5_VABI initialize() { ++initializes; }
void APS5_VABI finalize() { require(initializes == 1); }
void* APS5_VABI allocate(std::size_t bytes) {
lastSize = bytes;
if (recurse) return ApplicationHeapAllocate_nid_no_patch(bytes);
return fail ? nullptr : storage.data();
}
void APS5_VABI release(void* pointer) {
require(pointer == storage.data());
++frees;
}
void* APS5_VABI reallocate(void* pointer, std::size_t bytes) {
require(pointer == storage.data());
return allocate(bytes);
}
void* APS5_VABI allocateZeroed(std::size_t count, std::size_t bytes) {
return allocate(count * bytes);
}
void* APS5_VABI align(std::size_t alignment, std::size_t bytes) {
lastAlignment = alignment;
return allocate(bytes);
}
int APS5_VABI posixAlign(void** pointer, std::size_t alignment, std::size_t bytes) {
if (fail) return 12;
*pointer = align(alignment, bytes);
return 0;
}
template<typename TValue, std::size_t TSize>
void write(std::array<std::byte, TSize>& data, std::size_t offset, TValue value) {
require(offset <= data.size() && sizeof(value) <= data.size() - offset);
std::memcpy(data.data() + offset, &value, sizeof(value));
}
}
int main(int argc, char**) {
reject([] { ApplicationHeapAllocate_nid_no_patch(64); });
reject([] { ApplicationHeapRegister_nid_no_patch(nullptr); });
std::array<std::byte, 0x40> process{};
std::array<std::byte, 0x38> libc{};
std::array<std::byte, 0x78> replacement{};
write(process, 0, std::uint64_t{0x40});
write(process, 8, std::uint32_t{0x4942524f});
write(process, 0x38, libc.data());
write(libc, 0, std::uint64_t{0x38});
write(libc, 0x30, replacement.data());
write(replacement, 0, std::uint64_t{0x78});
write(replacement, 8, std::uint64_t{2});
write(replacement, 0x10, &initialize);
write(replacement, 0x18, &finalize);
write(replacement, 0x20, &allocate);
write(replacement, 0x28, &release);
write(replacement, 0x30, &reallocate);
write(replacement, 0x38, &allocateZeroed);
write(replacement, 0x40, &align);
write(replacement, 0x48, &reallocate);
write(replacement, 0x50, &posixAlign);
if (argc > 1) {
write(replacement, 8, std::uint64_t{99});
reject([&] { ApplicationHeapInitialize_nid_no_patch(process.data()); });
write(replacement, 8, std::uint64_t{2});
reject([&] { ApplicationHeapInitialize_nid_no_patch(process.data()); });
reject([] { ApplicationHeapAlign_nid_no_patch(4, 64); });
require(initializes == 0);
return 0;
}
ApplicationHeapInitialize_nid_no_patch(process.data());
ApplicationHeapInitialize_nid_no_patch(process.data());
require(initializes == 1);
void* pointer = ApplicationHeapAlign_nid_no_patch(4, 64);
require(pointer == storage.data() && lastAlignment == 4 && lastSize == 64);
release(pointer);
require(frees == 1);
pointer = ApplicationHeapAllocate_nid_no_patch(32);
require(pointer == storage.data() && lastSize == 32);
require(ApplicationHeapReallocate_nid_no_patch(pointer, 96) == storage.data() && lastSize == 96);
ApplicationHeapFree_nid_no_patch(pointer);
require(frees == 2);
require(ApplicationHeapCalloc_nid_no_patch(3, 16) == storage.data() && lastSize == 48);
require(ApplicationHeapPosixAlign_nid_no_patch(&pointer, 64, 128) == 0 && pointer == storage.data() && lastAlignment == 64);
reject([] { ApplicationHeapAlign_nid_no_patch(3, 64); });
reject([] { ApplicationHeapCalloc_nid_no_patch(2, std::numeric_limits<std::size_t>::max()); });
fail = true;
reject([] { ApplicationHeapAlign_nid_no_patch(4, 64); });
reject([] { ApplicationHeapAllocate_nid_no_patch(64); });
void* unchanged = storage.data();
reject([&] { ApplicationHeapPosixAlign_nid_no_patch(&unchanged, 64, 64); });
require(unchanged == storage.data());
fail = false;
recurse = true;
reject([] { ApplicationHeapAllocate_nid_no_patch(64); });
recurse = false;
require(ApplicationHeapAllocate_nid_no_patch(64) == storage.data());
}
@@ -11,6 +11,7 @@ bool SegmentFilter::_isSceSpecificSegment(const std::uint32_t type) const {
}
bool SegmentFilter::ShouldSkip(const Domain::ProgramHeader& ph) const {
if (ph.Type == PT_OS_PROCPARAM) return false;
if (_isSceSpecificSegment(ph.Type)) return true;
if (ph.Type == PT_DYNAMIC) return true;
if (ph.Type == PT_NOTE && ph.MappedAddress == 0 && ph.FileSize > 0) return true;
@@ -32,6 +32,17 @@ std::vector<std::uint8_t> WindowsPePatcher::Patch(const std::vector<std::uint8_t
auto sections = image.BuildSections();
std::array<PeDirectory, 16> directories{};
auto nextRva = image.GetEndRva();
bool hasProcessParameters = false;
for (const auto& header : originalHeaders) {
if (header.Type != 0x61000001) continue;
if (hasProcessParameters || header.FileSize < 0x40) throw Domain::RelinkerException("Invalid process parameter segment");
hasProcessParameters = true;
std::vector<std::uint8_t> metadata(8);
Io::WriteU32(metadata, 0, image.GetRva(header.MappedAddress, header.FileSize));
Io::WriteU32(metadata, 4, CheckedRva(header.FileSize));
sections.push_back({".procpar", nextRva, SectionRead | 0x40u, std::move(metadata)});
nextRva = AlignRva(nextRva + sections.back().Data.size());
}
for (const auto& header : originalHeaders) {
if (header.Type != 0x6474e550) continue;
std::vector<std::uint8_t> metadata(4);