#include "prx/libc/include/Api.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 #include #endif #include "prx/libc/include/General.hpp" #include "prx/libc/include/GuestArena.hpp" #include "prx/libc/include/SonyCrt.hpp" #include "prx/libc/include/specifics/gcc/AtomicOps.hpp" #include "prx/libc/include/FileStream.hpp" #include "prx/libc/include/HostEntropy.hpp" namespace { struct ErrnoGuard { int savedErrno = errno; ~ErrnoGuard() noexcept { errno = savedErrno; } }; bool ValidSpan(const void* pointer, std::size_t bytes) { if (bytes == 0) return true; if (!pointer) return false; const auto address = reinterpret_cast(pointer); return bytes - 1 <= std::numeric_limits::max() - address; } bool CopyInBytes(void* destination, const void* source, std::size_t bytes) { if (bytes == 0) return true; if (!ValidSpan(source, bytes)) return false; const ErrnoGuard savedErrno; return GuestCopyIn_nid_no_patch(destination, source, bytes); } bool CopyInOffset(void* destination, const void* base, std::size_t offset, std::size_t bytes) { if (!base) return false; const auto baseAddress = reinterpret_cast(base); if (offset > std::numeric_limits::max() - baseAddress) return false; return CopyInBytes(destination, reinterpret_cast(baseAddress + offset), bytes); } struct CheckedWrite { void* destination = nullptr; std::size_t bytes = 0; std::optional guard; bool Open(void* address, std::size_t size) { if (!ValidSpan(address, size)) return false; destination = address; bytes = size; if (bytes == 0) return true; const ErrnoGuard savedErrno; guard.emplace(destination, bytes); return guard->Open() && GuestWritable_nid_no_patch(destination, bytes); } bool Write(const void* source) const { if (bytes == 0) return true; if (!destination || !guard || !guard->Open()) return false; const ErrnoGuard savedErrno; return GuestCopyOut_nid_no_patch(destination, source, bytes); } }; std::recursive_mutex g_sysLock; struct ExitDestructor { void (APS5_VABI *func)(void*); void* arg; void* dsoHandle; }; std::mutex g_exitMutex; std::vector g_exitDestructors; bool g_exitRunnerRegistered = false; #ifdef _WIN32 struct UcrtStream { char* pointer; char* base; int count; long flags; long file; int charBuffer; int bufferSize; char* temporaryName; CRITICAL_SECTION lock; }; #endif } extern "C" { FileStream _Stderr_nid_postfix{stderr}; FileStream _Stdout_nid_postfix{stdout}; FileStream _Stdin_nid_postfix{stdin}; std::FILE* GuestStandardOutputFile_nid_no_patch() { return GetNativeStream(&_Stdout_nid_postfix); } std::FILE* GuestStandardOutputForWriting_nid_no_patch() { auto* native = GetNativeStream(&_Stdout_nid_postfix); return _Stdout_nid_postfix.SwitchToWriting() ? native : nullptr; } int APS5_VABI __cxa_atexit_nid_postfix(void (APS5_VABI *func)(void*), void* arg, void* dsoHandle) { std::lock_guard lock(g_exitMutex); g_exitDestructors.push_back({func, arg, dsoHandle}); if (!g_exitRunnerRegistered) { g_exitRunnerRegistered = true; std::atexit([] { CxaFinalize_nid_no_patch(nullptr); }); } return 0; } void CxaFinalize_nid_no_patch(void* dsoHandle) { for (;;) { ExitDestructor destructor{}; { std::lock_guard lock(g_exitMutex); const auto found = std::find_if(g_exitDestructors.rbegin(), g_exitDestructors.rend(), [&](const ExitDestructor& entry) { return dsoHandle == nullptr || entry.dsoHandle == dsoHandle; }); if (found == g_exitDestructors.rend()) return; destructor = *found; g_exitDestructors.erase(std::next(found).base()); } destructor.func(destructor.arg); } } int APS5_VABI cxa_atexit_nid_postfix(void (APS5_VABI *func)(void*), void* arg, void* dsoHandle) { return __cxa_atexit_nid_postfix(func, arg, dsoHandle); } void APS5_VABI cxa_finalize_nid_postfix(void* dsoHandle) { CxaFinalize_nid_no_patch(dsoHandle); } void APS5_VABI _Vacopy_nid_postfix(unsigned char* destination, const unsigned char* source) { constexpr std::size_t VaListBytes = 24; unsigned char buffer[VaListBytes]; if (!CopyInBytes(buffer, source, VaListBytes)) { throw std::invalid_argument("_Vacopy: unreadable source"); } CheckedWrite writeGuard; if (!writeGuard.Open(destination, VaListBytes) || !writeGuard.Write(buffer)) { throw std::invalid_argument("_Vacopy: unwritable destination"); } } unsigned int APS5_VABI _Atomic_fetch_add_4_nid_postfix(volatile unsigned int* target, unsigned int value, int memoryOrder) { (void)memoryOrder; return GccAtomicFetchAdd(target, value); } unsigned int APS5_VABI _Atomic_fetch_sub_4_nid_postfix(volatile unsigned int* target, unsigned int value, int memoryOrder) { (void)memoryOrder; return GccAtomicFetchSub(target, value); } int APS5_VABI _Atomic_compare_exchange_weak_4_nid_postfix(volatile unsigned int* target, unsigned int* expected, unsigned int desired, int successOrder, int failureOrder) { (void)successOrder; (void)failureOrder; return GccAtomicCompareExchangeWeak(target, expected, desired) ? 1 : 0; } unsigned int APS5_VABI _Atomic_load_4_nid_postfix(volatile unsigned int* target, int memoryOrder) { (void)memoryOrder; return GccAtomicLoad(target); } std::intmax_t APS5_VABI strtoimax_nid_postfix(const char* str, char** endptr, int base) { if (RejectIntegerBase_nid_no_patch(str, endptr, base, false) || StopAtPrefixLetter_nid_no_patch(str, endptr, base)) return 0; return ParseInteger(str, endptr, base, std::strtoimax); } std::uintmax_t APS5_VABI strtoumax_nid_postfix(const char* str, char** endptr, int base) { if (RejectIntegerBase_nid_no_patch(str, endptr, base, false) || StopAtPrefixLetter_nid_no_patch(str, endptr, base)) return 0; return ParseInteger(str, endptr, base, std::strtoumax); } unsigned int APS5_VABI _ZSt14_Random_devicev_nid_postfix() { unsigned int value = 0; HostEntropy_nid_no_patch(&value, sizeof(value)); return value; } static constexpr int ThrdNomem = 1; static constexpr int ThrdTimedout = 2; static constexpr int ThrdBusy = 3; static constexpr int ThrdError = 4; static constexpr int ThrdPermission = 5; static constexpr int CppDeviceOrResourceBusy = 0; static constexpr int CppInvalidArgument = 1; static constexpr int CppOperationNotPermitted = 4; static constexpr int CppResourceUnavailableTryAgain = 6; [[noreturn]] void ThrowCppError_nid_no_patch(int code); void APS5_VABI _ZSt14_Throw_C_errori_nid_postfix(int code) { switch (code) { case ThrdNomem: case ThrdTimedout: ThrowCppError_nid_no_patch(CppResourceUnavailableTryAgain); case ThrdBusy: ThrowCppError_nid_no_patch(CppDeviceOrResourceBusy); case ThrdError: ThrowCppError_nid_no_patch(CppInvalidArgument); case ThrdPermission: ThrowCppError_nid_no_patch(CppOperationNotPermitted); default: return; } } namespace { std::mutex& ExplicitNativeLocksMutex_nid_no_patch() { static std::mutex mutex; return mutex; } std::unordered_map& ExplicitNativeLocks_nid_no_patch() { static std::unordered_map locks; return locks; } void LockNative_nid_no_patch(std::FILE* native) { #ifdef _WIN32 _lock_file(native); #else flockfile(native); #endif } void UnlockNative_nid_no_patch(std::FILE* native) { #ifdef _WIN32 _unlock_file(native); #else funlockfile(native); #endif } } void NoteExplicitNativeLock_nid_no_patch(std::FILE* native) { std::lock_guard lock(ExplicitNativeLocksMutex_nid_no_patch()); auto& count = ExplicitNativeLocks_nid_no_patch()[native]; if (count == std::numeric_limits::max()) throw std::overflow_error("FileStream: explicit lock count overflow"); ++count; } bool ForgetExplicitNativeLock_nid_no_patch(std::FILE* native) { std::lock_guard lock(ExplicitNativeLocksMutex_nid_no_patch()); auto& locks = ExplicitNativeLocks_nid_no_patch(); const auto found = locks.find(native); if (found == locks.end() || found->second == 0) return false; if (--found->second == 0) locks.erase(found); return true; } void ReleaseExplicitNativeLocks_nid_no_patch(std::FILE* native) { std::uint32_t held = 0; { std::lock_guard lock(ExplicitNativeLocksMutex_nid_no_patch()); auto& locks = ExplicitNativeLocks_nid_no_patch(); const auto found = locks.find(native); if (found == locks.end()) return; held = found->second; locks.erase(found); } for (; held > 0; --held) UnlockNative_nid_no_patch(native); } std::uint32_t SuspendExplicitNativeLocks_nid_no_patch(std::FILE* native) { std::lock_guard lock(ExplicitNativeLocksMutex_nid_no_patch()); auto& locks = ExplicitNativeLocks_nid_no_patch(); const auto found = locks.find(native); return found == locks.end() ? 0 : std::exchange(found->second, 0); } void ResumeExplicitNativeLocks_nid_no_patch(std::FILE* native, std::uint32_t held) { if (held == 0) return; std::lock_guard lock(ExplicitNativeLocksMutex_nid_no_patch()); auto& count = ExplicitNativeLocks_nid_no_patch()[native]; if (count > std::numeric_limits::max() - held) throw std::overflow_error("FileStream: explicit lock count overflow"); count += held; } void DropIdleExplicitNativeLocks_nid_no_patch(std::FILE* native) { std::lock_guard lock(ExplicitNativeLocksMutex_nid_no_patch()); auto& locks = ExplicitNativeLocks_nid_no_patch(); const auto found = locks.find(native); if (found != locks.end() && found->second == 0) locks.erase(found); } int CloseNativeReleasingExplicitLocks_nid_no_patch(std::FILE* native) { ReleaseExplicitNativeLocks_nid_no_patch(native); return std::fclose(native); } void APS5_VABI _Lockfilelock_nid_postfix(FileStream* stream) { if (stream == nullptr) throw std::invalid_argument("_Lockfilelock: null stream"); auto gate = PinFileStreamIfValid_nid_no_patch(stream); if (!gate) { errno = 9; throw std::runtime_error("_Lockfilelock: closed stream"); } gate->lock(); try { std::FILE* const native = stream->RawHandle_nid_no_patch(); if (!native) throw std::runtime_error("_Lockfilelock: closed stream"); NoteExplicitNativeLock_nid_no_patch(native); LockNative_nid_no_patch(native); } catch (...) { gate->unlock(); UnpinFileStream_nid_no_patch(stream); throw; } } void APS5_VABI _Unlockfilelock_nid_postfix(FileStream* stream) { if (stream == nullptr) throw std::invalid_argument("_Unlockfilelock: null stream"); auto gate = stream->GatePtr_nid_no_patch(); if (!gate) throw std::runtime_error("_Unlockfilelock: stream has no gate"); std::FILE* const native = stream->RawHandle_nid_no_patch(); if (native && ForgetExplicitNativeLock_nid_no_patch(native)) UnlockNative_nid_no_patch(native); gate->unlock(); UnpinFileStream_nid_no_patch(stream); } void APS5_VABI flockfile_nid_postfix(FileStream* stream) { _Lockfilelock_nid_postfix(stream); } void APS5_VABI funlockfile_nid_postfix(FileStream* stream) { _Unlockfilelock_nid_postfix(stream); } int APS5_VABI ftrylockfile_nid_postfix(FileStream* stream) { if (stream == nullptr) throw std::invalid_argument("ftrylockfile: null stream"); auto gate = PinFileStreamIfValid_nid_no_patch(stream); if (!gate) { errno = 9; throw std::runtime_error("ftrylockfile: closed stream"); } if (!gate->try_lock()) { UnpinFileStream_nid_no_patch(stream); return -1; } std::FILE* const native = stream->RawHandle_nid_no_patch(); bool nativeOk; try { if (!native) throw std::runtime_error("ftrylockfile: closed stream"); else { #ifdef _WIN32 nativeOk = TryEnterCriticalSection(&reinterpret_cast(native)->lock); #else nativeOk = ftrylockfile(native) == 0; #endif } } catch (...) { gate->unlock(); UnpinFileStream_nid_no_patch(stream); throw; } if (!nativeOk) { gate->unlock(); UnpinFileStream_nid_no_patch(stream); return -1; } try { NoteExplicitNativeLock_nid_no_patch(native); } catch (...) { UnlockNative_nid_no_patch(native); gate->unlock(); UnpinFileStream_nid_no_patch(stream); throw; } return 0; } std::uint64_t APS5_VABI _Stoul_nid_postfix(const char* str, char** endptr, int base) { if (RejectIntegerBase_nid_no_patch(str, endptr, base, false) || StopAtPrefixLetter_nid_no_patch(str, endptr, base)) return 0; return ParseInteger(str, endptr, base, std::strtoull); } void APS5_VABI _Locksyslock_nid_postfix() { g_sysLock.lock(); } void APS5_VABI _Unlocksyslock_nid_postfix() { g_sysLock.unlock(); } __int128 APS5_VABI __divti3_nid_postfix(__int128 dividend, __int128 divisor) { return SonyDivti3(dividend, divisor); } unsigned __int128 APS5_VABI __udivti3_nid_postfix(unsigned __int128 dividend, unsigned __int128 divisor) { return SonyUdivti3(dividend, divisor); } unsigned __int128 APS5_VABI __umodti3_nid_postfix(unsigned __int128 dividend, unsigned __int128 divisor) { return SonyUmodti3(dividend, divisor); } __int128 APS5_VABI __modti3_nid_postfix(__int128 dividend, __int128 divisor) { return SonyModti3(dividend, divisor); } namespace { struct CrtSetupTable { std::uint64_t size; std::uintptr_t unknown; std::uintptr_t primary[8]; std::uintptr_t extended[4]; std::uintptr_t trailing[10]; }; std::uintptr_t g_crtPrimarySlots[8] {}; std::uintptr_t g_crtExtendedSlots[4] {}; std::uintptr_t g_crtTrailingSlots[10] {}; bool SlotGroupIsUniform(const std::uintptr_t* slots, std::size_t count) { std::size_t filled = 0; for (std::size_t index = 0; index < count; ++index) filled += slots[index] == 0 ? 0 : 1; return filled == 0 || filled == count; } void CopySlots(const std::uintptr_t* source, std::uintptr_t* destination, std::size_t count) { for (std::size_t index = 0; index < count; ++index) destination[index] = source[index]; } } int CrtNewSetup_nid_no_patch(const void* table) { constexpr std::uint64_t primaryTableBytes = 0x50; constexpr std::uint64_t extendedTableBytes = 0x70; constexpr std::uint64_t trailingTableBytes = 0xc0; if (table == nullptr) return 0; std::uint64_t size = 0; if (!CopyInOffset(&size, table, offsetof(CrtSetupTable, size), sizeof(size))) { throw std::invalid_argument("_new_setup: unreadable table"); } if (size < primaryTableBytes) return 1; std::uintptr_t primary[8]{}; if (!CopyInOffset(primary, table, offsetof(CrtSetupTable, primary), sizeof(primary))) { throw std::invalid_argument("_new_setup: unreadable primary slots"); } if (!SlotGroupIsUniform(primary, 8)) return 1; const bool hasExtended = size >= extendedTableBytes; std::uintptr_t extended[4]{}; if (hasExtended && !CopyInOffset(extended, table, offsetof(CrtSetupTable, extended), sizeof(extended))) { throw std::invalid_argument("_new_setup: unreadable extended slots"); } const bool hasTrailing = size >= trailingTableBytes; std::uintptr_t trailing[10]{}; if (hasTrailing && !CopyInOffset(trailing, table, offsetof(CrtSetupTable, trailing), sizeof(trailing))) { throw std::invalid_argument("_new_setup: unreadable trailing slots"); } const bool primaryPresent = primary[0] != 0; if (primaryPresent) CopySlots(primary, g_crtPrimarySlots, 8); if (!hasExtended) return 0; if (primaryPresent) { for (std::size_t index = 0; index < 4; ++index) { if (extended[index] != 0) g_crtExtendedSlots[index] = extended[index]; } } if (!hasTrailing) return 0; if (!SlotGroupIsUniform(trailing, 10)) return 1; if (trailing[0] != 0) CopySlots(trailing, g_crtTrailingSlots, 10); return 0; } int APS5_VABI _new_setup_nid_postfix(const void* table) { return CrtNewSetup_nid_no_patch(table); } }