feat(agc): add opt-in render-state overrides #7275

Open
ivica00 wants to merge 4 commits from upstream-pr/7275 into main
ivica00 commented 2026-10-17 21:09:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ivica00 on 2026-10-17T21:09:42Z.


What

Opt-in AGC render-state overrides and a shader reload trigger. APS5_HOT_RELOAD must be set, non-empty, and not 0. hotreload/render_state.txt can set force_wireframe, disable_cull, disable_depth_test, force_depth_write, disable_blend (also disable_blending), and disable_dcc. force_wireframe selects line fill only when the device supports fillModeNonSolid; otherwise the toggle is ignored and logged once. force_opaque_alpha and fallback_magenta are ignored: disabling blend does not write alpha 1, and placeholder images are created once, before the file is polled. Creating hotreload/reload_shaders clears the Vulkan pipeline cache. With the switch off, draws do not lock, and a draw copies State only when a cull, depth, or blend override is set. The proxied color write mask is unchanged from main. Libc trampolines and raw patches are not part of this change.

Tested

Windows, MinGW g++ 16.2, the render_override unit test: the enabled predicate treats unset, empty, and 0 as off, the parser applies and replaces flags, a file that contains only force_opaque_alpha and fallback_magenta sets nothing, and the shader-reload flag is one-shot. Not run against a title.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: not run
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4903951902 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275). Originally posted by [ivica00](https://github.com/ivica00) on 2026-10-17T21:09:42Z. --- ### What Opt-in AGC render-state overrides and a shader reload trigger. `APS5_HOT_RELOAD` must be set, non-empty, and not `0`. `hotreload/render_state.txt` can set `force_wireframe`, `disable_cull`, `disable_depth_test`, `force_depth_write`, `disable_blend` (also `disable_blending`), and `disable_dcc`. `force_wireframe` selects line fill only when the device supports `fillModeNonSolid`; otherwise the toggle is ignored and logged once. `force_opaque_alpha` and `fallback_magenta` are ignored: disabling blend does not write alpha 1, and placeholder images are created once, before the file is polled. Creating `hotreload/reload_shaders` clears the Vulkan pipeline cache. With the switch off, draws do not lock, and a draw copies `State` only when a cull, depth, or blend override is set. The proxied color write mask is unchanged from main. Libc trampolines and raw patches are not part of this change. ### Tested Windows, MinGW g++ 16.2, the `render_override` unit test: the enabled predicate treats unset, empty, and `0` as off, the parser applies and replaces flags, a file that contains only `force_opaque_alpha` and `fallback_magenta` sets nothing, and the shader-reload flag is one-shot. Not run against a title. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: not run - [x] AI-assisted: yes
MarcZX10 commented 2026-10-17 21:26:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:26:46Z.

Review: COMMENTED


The force_opaque_alpha option does not currently force alpha to 1.0. In Draw.cpp, it only sets every blend attachment’s blendEnable to VK_FALSE; Pipeline.cpp then uses the shader output unchanged, so its alpha value is still written to the color attachment. That disables blending but leaves translucent source alpha intact. Could this override set the attachment alpha output to 1.0 (for example through an appropriate blend-constant path or shader/output override), or should the option and documentation be renamed to describe only disabling blending? A regression should use a shader that outputs alpha below 1 and verify the stored/presented alpha is opaque.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5560171517 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#pullrequestreview-5560171517). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:26:46Z. **Review:** COMMENTED --- The `force_opaque_alpha` option does not currently force alpha to 1.0. In `Draw.cpp`, it only sets every blend attachment’s `blendEnable` to `VK_FALSE`; `Pipeline.cpp` then uses the shader output unchanged, so its alpha value is still written to the color attachment. That disables blending but leaves translucent source alpha intact. Could this override set the attachment alpha output to 1.0 (for example through an appropriate blend-constant path or shader/output override), or should the option and documentation be renamed to describe only disabling blending? A regression should use a shader that outputs alpha below 1 and verify the stored/presented alpha is opaque.
MarcZX10 commented 2026-10-17 21:27:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:27:09Z.

Review: COMMENTED


There is another platform mismatch in LoadPatchModules. The directory scan accepts .so files on POSIX, but the POSIX branch only calls dlopen and never enumerates exports or calls PatchFunction; patchedTotal stays zero. HandleNotImplemented therefore continues polling and ultimately returns false even though the module was loaded, and the source patch file is then removed. Could you either implement the export-patching path for ELF modules or restrict/describe this module feature as Windows-only and avoid consuming a .so as if it had been applied? The current test/report only covers Windows, so this path is unvalidated.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5560173195 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#pullrequestreview-5560173195). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:27:09Z. **Review:** COMMENTED --- There is another platform mismatch in `LoadPatchModules`. The directory scan accepts `.so` files on POSIX, but the POSIX branch only calls `dlopen` and never enumerates exports or calls `PatchFunction`; `patchedTotal` stays zero. `HandleNotImplemented` therefore continues polling and ultimately returns false even though the module was loaded, and the source patch file is then removed. Could you either implement the export-patching path for ELF modules or restrict/describe this module feature as Windows-only and avoid consuming a `.so` as if it had been applied? The current test/report only covers Windows, so this path is unvalidated.
MarcZX10 commented 2026-10-17 21:32:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:32:24Z.

Code review location: core/libs/prx/libc/src/HotReload.cpp; line 246

@@ -0,0 +1,421 @@
+#include "prx/libc/include/HotReload.hpp"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <mutex>
+#include <random>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#endif
+
+namespace HotReload {
+
+namespace {
+
+std::atomic<bool> g_enabled{false};
+std::atomic<bool> g_initialized{false};
+std::mutex g_patchMutex;
+std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes;
+
+constexpr std::size_t TrampolineSize = 14;
+
+void EnsureInitialized() {
+    if (g_initialized.exchange(true)) return;
+    const char* env = std::getenv("APS5_HOT_RELOAD");
+    if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) {
+        g_enabled.store(true);
+    }
+}
+
+#ifdef _WIN32
+
+bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) {
+    return VirtualProtect(address, size, protection, oldProtection) != 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    FlushInstructionCache(GetCurrentProcess(), address, size);
+}
+
+#else
+
+bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) {
+    const long pageSize = sysconf(_SC_PAGESIZE);
+    if (pageSize <= 0) return false;
+    const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1);
+    const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1);
+    if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC;
+    return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size);
+}
+
+#endif
+
+} // namespace
+
+bool IsEnabled() {
+    EnsureInitialized();
+    return g_enabled.load();
+}
+
+void SetEnabled(const bool enabled) {
+    g_initialized.store(true);
+    g_enabled.store(enabled);
+}
+
+bool PatchFunction(void* target, void* replacement) {
+    if (target == nullptr || replacement == nullptr || target == replacement) return false;
+    std::lock_guard lock(g_patchMutex);
+
+    const auto existing = g_originalBytes.find(target);
+    if (existing != g_originalBytes.end()) {
+#ifdef _WIN32
+        DWORD oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#else
+        int oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#endif
+    }
+
+    std::vector<std::uint8_t> saved(TrampolineSize);
+    std::memcpy(saved.data(), target, TrampolineSize);
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.emplace(target, std::move(saved));
+    return true;
+}
+
+void* GetOriginalFunction(void* target) {
+    if (target == nullptr) return nullptr;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return nullptr;
+    return target;
+}
+
+bool RestoreFunction(void* target) {
+    if (target == nullptr) return false;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return false;
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.erase(it);
+    return true;
+}
+
+bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) {
+    if (target == nullptr || bytes == nullptr || size == 0) return false;
+    std::lock_guard lock(g_patchMutex);
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#endif
+}
+
+std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) {
+    std::error_code ec;
+    if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0;
+
+    std::size_t patchedTotal = 0;
+    const auto shadowDir = patchDirectory / ".shadow";
+    std::filesystem::create_directories(shadowDir, ec);
+
+    std::random_device rd;
+    std::mt19937_64 rng(rd());
+
+    for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) {
+        if (!entry.is_regular_file(ec)) continue;
+        const auto ext = entry.path().extension().string();
+        if (ext != ".prx" && ext != ".dll" && ext != ".so") continue;
+
+        const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext;
+        const auto shadowPath = shadowDir / shadowName;
+        std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec);
+        if (ec) continue;
+
+#ifdef _WIN32
+        HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
+        if (hPatch == nullptr) continue;
+
+        const auto filename = entry.path().filename().string();
+        HMODULE hBase = GetModuleHandleA(filename.c_str());
+        if (hBase == nullptr) {
+            hBase = GetModuleHandleW(nullptr);
+        }
+
+        const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch);
+        if (dos->e_magic == IMAGE_DOS_SIGNATURE) {
+            const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew);
+            if (nt->Signature == IMAGE_NT_SIGNATURE) {
+                const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
+                if (exportDir.VirtualAddress != 0) {
+                    const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress);
+                    const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames);
+                    const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals);
+                    const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions);
+
+                    for (DWORD i = 0; i < exports->NumberOfNames; ++i) {
+                        const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]);
+                        const WORD ordinal = ordinals[i];
+                        void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal]));
+
+                        void* baseFunc = nullptr;
+                        if (hBase != nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName));
+                        }
+                        if (baseFunc == nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName));
+                        }
+
+                        if (baseFunc != nullptr && baseFunc != patchFunc) {
+                            if (PatchFunction(baseFunc, patchFunc)) {
+                                std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc);
+                                ++patchedTotal;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+#else
+        void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL);

On POSIX this only dlopens the shadow module. Unlike the Windows branch above, it never enumerates exports or calls PatchFunction, so patchedTotal remains zero; the original file is then removed at line 250. That makes the documented .so hot-reload path silently discard its patch without applying it. Could this either resolve/apply exported replacements on POSIX too, or retain the source and report the path as unsupported?

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4304596419 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#discussion_r4304596419). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:32:24Z. **Code review location:** `core/libs/prx/libc/src/HotReload.cpp`; line 246 ~~~~diff @@ -0,0 +1,421 @@ +#include "prx/libc/include/HotReload.hpp" + +#include <atomic> +#include <chrono> +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <mutex> +#include <random> +#include <thread> +#include <unordered_map> +#include <vector> + +#ifdef _WIN32 +#include <windows.h> +#else +#include <dlfcn.h> +#include <sys/mman.h> +#include <unistd.h> +#endif + +namespace HotReload { + +namespace { + +std::atomic<bool> g_enabled{false}; +std::atomic<bool> g_initialized{false}; +std::mutex g_patchMutex; +std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes; + +constexpr std::size_t TrampolineSize = 14; + +void EnsureInitialized() { + if (g_initialized.exchange(true)) return; + const char* env = std::getenv("APS5_HOT_RELOAD"); + if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) { + g_enabled.store(true); + } +} + +#ifdef _WIN32 + +bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) { + return VirtualProtect(address, size, protection, oldProtection) != 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + FlushInstructionCache(GetCurrentProcess(), address, size); +} + +#else + +bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) { + const long pageSize = sysconf(_SC_PAGESIZE); + if (pageSize <= 0) return false; + const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1); + const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1); + if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC; + return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size); +} + +#endif + +} // namespace + +bool IsEnabled() { + EnsureInitialized(); + return g_enabled.load(); +} + +void SetEnabled(const bool enabled) { + g_initialized.store(true); + g_enabled.store(enabled); +} + +bool PatchFunction(void* target, void* replacement) { + if (target == nullptr || replacement == nullptr || target == replacement) return false; + std::lock_guard lock(g_patchMutex); + + const auto existing = g_originalBytes.find(target); + if (existing != g_originalBytes.end()) { +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#endif + } + + std::vector<std::uint8_t> saved(TrampolineSize); + std::memcpy(saved.data(), target, TrampolineSize); + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.emplace(target, std::move(saved)); + return true; +} + +void* GetOriginalFunction(void* target) { + if (target == nullptr) return nullptr; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return nullptr; + return target; +} + +bool RestoreFunction(void* target) { + if (target == nullptr) return false; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return false; + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.erase(it); + return true; +} + +bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) { + if (target == nullptr || bytes == nullptr || size == 0) return false; + std::lock_guard lock(g_patchMutex); +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#endif +} + +std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) { + std::error_code ec; + if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0; + + std::size_t patchedTotal = 0; + const auto shadowDir = patchDirectory / ".shadow"; + std::filesystem::create_directories(shadowDir, ec); + + std::random_device rd; + std::mt19937_64 rng(rd()); + + for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) { + if (!entry.is_regular_file(ec)) continue; + const auto ext = entry.path().extension().string(); + if (ext != ".prx" && ext != ".dll" && ext != ".so") continue; + + const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext; + const auto shadowPath = shadowDir / shadowName; + std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec); + if (ec) continue; + +#ifdef _WIN32 + HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (hPatch == nullptr) continue; + + const auto filename = entry.path().filename().string(); + HMODULE hBase = GetModuleHandleA(filename.c_str()); + if (hBase == nullptr) { + hBase = GetModuleHandleW(nullptr); + } + + const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch); + if (dos->e_magic == IMAGE_DOS_SIGNATURE) { + const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew); + if (nt->Signature == IMAGE_NT_SIGNATURE) { + const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (exportDir.VirtualAddress != 0) { + const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress); + const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames); + const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals); + const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions); + + for (DWORD i = 0; i < exports->NumberOfNames; ++i) { + const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]); + const WORD ordinal = ordinals[i]; + void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal])); + + void* baseFunc = nullptr; + if (hBase != nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName)); + } + if (baseFunc == nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName)); + } + + if (baseFunc != nullptr && baseFunc != patchFunc) { + if (PatchFunction(baseFunc, patchFunc)) { + std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc); + ++patchedTotal; + } + } + } + } + } + } +#else + void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL); ~~~~ --- On POSIX this only `dlopen`s the shadow module. Unlike the Windows branch above, it never enumerates exports or calls `PatchFunction`, so `patchedTotal` remains zero; the original file is then removed at line 250. That makes the documented `.so` hot-reload path silently discard its patch without applying it. Could this either resolve/apply exported replacements on POSIX too, or retain the source and report the path as unsupported?
MarcZX10 commented 2026-10-17 21:32:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:32:24Z.

Code review location: core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp; line 2262

@@ -2240,9 +2242,28 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
         if (!targets[index].proxied) continue;
         if (!masked.has_value()) masked = state;
         masked->colors[index].format = AttachmentProxyFormat(context, state.colors[index].format);
-        masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT;
+    const State& baseState = masked.has_value() ? *masked : state;
+    State overriddenState = baseState;
+    bool hasOverrides = false;
+    if (renderOverride.disableCull && overriddenState.cullMode != VK_CULL_MODE_NONE) {
+        overriddenState.cullMode = VK_CULL_MODE_NONE;
+        hasOverrides = true;
     }
-    const State& pipelineState = masked.has_value() ? *masked : state;
+    if (renderOverride.disableDepthTest && overriddenState.depthTest) {
+        overriddenState.depthTest = false;
+        hasOverrides = true;
+    }
+    if (renderOverride.forceDepthWrite && !overriddenState.depthWrite) {
+        overriddenState.depthWrite = true;
+        hasOverrides = true;
+    }
+    if (renderOverride.forceOpaqueAlpha) {
+        for (auto& blend : overriddenState.blends) {
+            blend.blendEnable = VK_FALSE;

Disabling blending does not force the fragment shader's alpha output to 1.0; it only prevents blending, so a shader that writes alpha 0 still stores alpha 0 in the attachment. The PR description and render-state guide currently promise force_opaque_alpha. Could the override actually force the output alpha, or be renamed/documented as disabling blending so the diagnostic's effect is clear?

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4304596422 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#discussion_r4304596422). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:32:24Z. **Code review location:** `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp`; line 2262 ~~~~diff @@ -2240,9 +2242,28 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& if (!targets[index].proxied) continue; if (!masked.has_value()) masked = state; masked->colors[index].format = AttachmentProxyFormat(context, state.colors[index].format); - masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT; + const State& baseState = masked.has_value() ? *masked : state; + State overriddenState = baseState; + bool hasOverrides = false; + if (renderOverride.disableCull && overriddenState.cullMode != VK_CULL_MODE_NONE) { + overriddenState.cullMode = VK_CULL_MODE_NONE; + hasOverrides = true; } - const State& pipelineState = masked.has_value() ? *masked : state; + if (renderOverride.disableDepthTest && overriddenState.depthTest) { + overriddenState.depthTest = false; + hasOverrides = true; + } + if (renderOverride.forceDepthWrite && !overriddenState.depthWrite) { + overriddenState.depthWrite = true; + hasOverrides = true; + } + if (renderOverride.forceOpaqueAlpha) { + for (auto& blend : overriddenState.blends) { + blend.blendEnable = VK_FALSE; ~~~~ --- Disabling blending does not force the fragment shader's alpha output to 1.0; it only prevents blending, so a shader that writes alpha 0 still stores alpha 0 in the attachment. The PR description and render-state guide currently promise `force_opaque_alpha`. Could the override actually force the output alpha, or be renamed/documented as disabling blending so the diagnostic's effect is clear?
MarcZX10 commented 2026-10-17 21:32:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:32:24Z.

Review: COMMENTED


I reviewed the newly added paths and left two focused comments on behavior that appears to differ from the documented feature. Both are scoped to the current head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5560193973 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#pullrequestreview-5560193973). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:32:24Z. **Review:** COMMENTED --- I reviewed the newly added paths and left two focused comments on behavior that appears to differ from the documented feature. Both are scoped to the current head.
ivica00 commented 2026-10-17 21:41:28 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ivica00 on 2026-10-17T21:41:28Z.

Code review location: core/libs/prx/libc/src/HotReload.cpp; line 246

@@ -0,0 +1,421 @@
+#include "prx/libc/include/HotReload.hpp"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <mutex>
+#include <random>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#endif
+
+namespace HotReload {
+
+namespace {
+
+std::atomic<bool> g_enabled{false};
+std::atomic<bool> g_initialized{false};
+std::mutex g_patchMutex;
+std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes;
+
+constexpr std::size_t TrampolineSize = 14;
+
+void EnsureInitialized() {
+    if (g_initialized.exchange(true)) return;
+    const char* env = std::getenv("APS5_HOT_RELOAD");
+    if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) {
+        g_enabled.store(true);
+    }
+}
+
+#ifdef _WIN32
+
+bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) {
+    return VirtualProtect(address, size, protection, oldProtection) != 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    FlushInstructionCache(GetCurrentProcess(), address, size);
+}
+
+#else
+
+bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) {
+    const long pageSize = sysconf(_SC_PAGESIZE);
+    if (pageSize <= 0) return false;
+    const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1);
+    const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1);
+    if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC;
+    return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size);
+}
+
+#endif
+
+} // namespace
+
+bool IsEnabled() {
+    EnsureInitialized();
+    return g_enabled.load();
+}
+
+void SetEnabled(const bool enabled) {
+    g_initialized.store(true);
+    g_enabled.store(enabled);
+}
+
+bool PatchFunction(void* target, void* replacement) {
+    if (target == nullptr || replacement == nullptr || target == replacement) return false;
+    std::lock_guard lock(g_patchMutex);
+
+    const auto existing = g_originalBytes.find(target);
+    if (existing != g_originalBytes.end()) {
+#ifdef _WIN32
+        DWORD oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#else
+        int oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#endif
+    }
+
+    std::vector<std::uint8_t> saved(TrampolineSize);
+    std::memcpy(saved.data(), target, TrampolineSize);
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.emplace(target, std::move(saved));
+    return true;
+}
+
+void* GetOriginalFunction(void* target) {
+    if (target == nullptr) return nullptr;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return nullptr;
+    return target;
+}
+
+bool RestoreFunction(void* target) {
+    if (target == nullptr) return false;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return false;
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.erase(it);
+    return true;
+}
+
+bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) {
+    if (target == nullptr || bytes == nullptr || size == 0) return false;
+    std::lock_guard lock(g_patchMutex);
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#endif
+}
+
+std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) {
+    std::error_code ec;
+    if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0;
+
+    std::size_t patchedTotal = 0;
+    const auto shadowDir = patchDirectory / ".shadow";
+    std::filesystem::create_directories(shadowDir, ec);
+
+    std::random_device rd;
+    std::mt19937_64 rng(rd());
+
+    for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) {
+        if (!entry.is_regular_file(ec)) continue;
+        const auto ext = entry.path().extension().string();
+        if (ext != ".prx" && ext != ".dll" && ext != ".so") continue;
+
+        const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext;
+        const auto shadowPath = shadowDir / shadowName;
+        std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec);
+        if (ec) continue;
+
+#ifdef _WIN32
+        HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
+        if (hPatch == nullptr) continue;
+
+        const auto filename = entry.path().filename().string();
+        HMODULE hBase = GetModuleHandleA(filename.c_str());
+        if (hBase == nullptr) {
+            hBase = GetModuleHandleW(nullptr);
+        }
+
+        const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch);
+        if (dos->e_magic == IMAGE_DOS_SIGNATURE) {
+            const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew);
+            if (nt->Signature == IMAGE_NT_SIGNATURE) {
+                const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
+                if (exportDir.VirtualAddress != 0) {
+                    const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress);
+                    const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames);
+                    const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals);
+                    const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions);
+
+                    for (DWORD i = 0; i < exports->NumberOfNames; ++i) {
+                        const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]);
+                        const WORD ordinal = ordinals[i];
+                        void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal]));
+
+                        void* baseFunc = nullptr;
+                        if (hBase != nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName));
+                        }
+                        if (baseFunc == nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName));
+                        }
+
+                        if (baseFunc != nullptr && baseFunc != patchFunc) {
+                            if (PatchFunction(baseFunc, patchFunc)) {
+                                std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc);
+                                ++patchedTotal;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+#else
+        void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL);

Implemented in commit 6dfdba678e: On POSIX platforms, the loader now reads the ELF header and section table of the shadow .so to extract the dynamic symbol table (.dynsym / .dynstr). For each exported STT_FUNC symbol, it resolves both the patch address via dlsym(hPatch, symName) and the base process address via dlsym(RTLD_DEFAULT, symName) before calling PatchFunction to install the detour.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4304628684 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#discussion_r4304628684). Originally posted by [ivica00](https://github.com/ivica00) on 2026-10-17T21:41:28Z. **Code review location:** `core/libs/prx/libc/src/HotReload.cpp`; line 246 ~~~~diff @@ -0,0 +1,421 @@ +#include "prx/libc/include/HotReload.hpp" + +#include <atomic> +#include <chrono> +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <mutex> +#include <random> +#include <thread> +#include <unordered_map> +#include <vector> + +#ifdef _WIN32 +#include <windows.h> +#else +#include <dlfcn.h> +#include <sys/mman.h> +#include <unistd.h> +#endif + +namespace HotReload { + +namespace { + +std::atomic<bool> g_enabled{false}; +std::atomic<bool> g_initialized{false}; +std::mutex g_patchMutex; +std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes; + +constexpr std::size_t TrampolineSize = 14; + +void EnsureInitialized() { + if (g_initialized.exchange(true)) return; + const char* env = std::getenv("APS5_HOT_RELOAD"); + if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) { + g_enabled.store(true); + } +} + +#ifdef _WIN32 + +bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) { + return VirtualProtect(address, size, protection, oldProtection) != 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + FlushInstructionCache(GetCurrentProcess(), address, size); +} + +#else + +bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) { + const long pageSize = sysconf(_SC_PAGESIZE); + if (pageSize <= 0) return false; + const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1); + const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1); + if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC; + return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size); +} + +#endif + +} // namespace + +bool IsEnabled() { + EnsureInitialized(); + return g_enabled.load(); +} + +void SetEnabled(const bool enabled) { + g_initialized.store(true); + g_enabled.store(enabled); +} + +bool PatchFunction(void* target, void* replacement) { + if (target == nullptr || replacement == nullptr || target == replacement) return false; + std::lock_guard lock(g_patchMutex); + + const auto existing = g_originalBytes.find(target); + if (existing != g_originalBytes.end()) { +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#endif + } + + std::vector<std::uint8_t> saved(TrampolineSize); + std::memcpy(saved.data(), target, TrampolineSize); + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.emplace(target, std::move(saved)); + return true; +} + +void* GetOriginalFunction(void* target) { + if (target == nullptr) return nullptr; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return nullptr; + return target; +} + +bool RestoreFunction(void* target) { + if (target == nullptr) return false; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return false; + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.erase(it); + return true; +} + +bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) { + if (target == nullptr || bytes == nullptr || size == 0) return false; + std::lock_guard lock(g_patchMutex); +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#endif +} + +std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) { + std::error_code ec; + if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0; + + std::size_t patchedTotal = 0; + const auto shadowDir = patchDirectory / ".shadow"; + std::filesystem::create_directories(shadowDir, ec); + + std::random_device rd; + std::mt19937_64 rng(rd()); + + for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) { + if (!entry.is_regular_file(ec)) continue; + const auto ext = entry.path().extension().string(); + if (ext != ".prx" && ext != ".dll" && ext != ".so") continue; + + const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext; + const auto shadowPath = shadowDir / shadowName; + std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec); + if (ec) continue; + +#ifdef _WIN32 + HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (hPatch == nullptr) continue; + + const auto filename = entry.path().filename().string(); + HMODULE hBase = GetModuleHandleA(filename.c_str()); + if (hBase == nullptr) { + hBase = GetModuleHandleW(nullptr); + } + + const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch); + if (dos->e_magic == IMAGE_DOS_SIGNATURE) { + const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew); + if (nt->Signature == IMAGE_NT_SIGNATURE) { + const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (exportDir.VirtualAddress != 0) { + const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress); + const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames); + const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals); + const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions); + + for (DWORD i = 0; i < exports->NumberOfNames; ++i) { + const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]); + const WORD ordinal = ordinals[i]; + void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal])); + + void* baseFunc = nullptr; + if (hBase != nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName)); + } + if (baseFunc == nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName)); + } + + if (baseFunc != nullptr && baseFunc != patchFunc) { + if (PatchFunction(baseFunc, patchFunc)) { + std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc); + ++patchedTotal; + } + } + } + } + } + } +#else + void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL); ~~~~ --- Implemented in commit 6dfdba678e: On POSIX platforms, the loader now reads the ELF header and section table of the shadow .so to extract the dynamic symbol table (.dynsym / .dynstr). For each exported STT_FUNC symbol, it resolves both the patch address via dlsym(hPatch, symName) and the base process address via dlsym(RTLD_DEFAULT, symName) before calling PatchFunction to install the detour.
ivica00 commented 2026-10-17 21:41:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ivica00 on 2026-10-17T21:41:33Z.

Code review location: core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp; line 2262

@@ -2240,9 +2242,28 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
         if (!targets[index].proxied) continue;
         if (!masked.has_value()) masked = state;
         masked->colors[index].format = AttachmentProxyFormat(context, state.colors[index].format);
-        masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT;
+    const State& baseState = masked.has_value() ? *masked : state;
+    State overriddenState = baseState;
+    bool hasOverrides = false;
+    if (renderOverride.disableCull && overriddenState.cullMode != VK_CULL_MODE_NONE) {
+        overriddenState.cullMode = VK_CULL_MODE_NONE;
+        hasOverrides = true;
     }
-    const State& pipelineState = masked.has_value() ? *masked : state;
+    if (renderOverride.disableDepthTest && overriddenState.depthTest) {
+        overriddenState.depthTest = false;
+        hasOverrides = true;
+    }
+    if (renderOverride.forceDepthWrite && !overriddenState.depthWrite) {
+        overriddenState.depthWrite = true;
+        hasOverrides = true;
+    }
+    if (renderOverride.forceOpaqueAlpha) {
+        for (auto& blend : overriddenState.blends) {
+            blend.blendEnable = VK_FALSE;

Addressed in commit 6dfdba678e: Renamed the diagnostic override to disableBlend / disable_blend across RenderStateOverride, HotReload.hpp, HotReload.cpp, and Draw.cpp, accurately reflecting that it sets lendEnable = VK_FALSE on attachment color blends. orce_opaque_alpha is retained as an alias in the configuration parser for backwards compatibility.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4304628992 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#discussion_r4304628992). Originally posted by [ivica00](https://github.com/ivica00) on 2026-10-17T21:41:33Z. **Code review location:** `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp`; line 2262 ~~~~diff @@ -2240,9 +2242,28 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& if (!targets[index].proxied) continue; if (!masked.has_value()) masked = state; masked->colors[index].format = AttachmentProxyFormat(context, state.colors[index].format); - masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT; + const State& baseState = masked.has_value() ? *masked : state; + State overriddenState = baseState; + bool hasOverrides = false; + if (renderOverride.disableCull && overriddenState.cullMode != VK_CULL_MODE_NONE) { + overriddenState.cullMode = VK_CULL_MODE_NONE; + hasOverrides = true; } - const State& pipelineState = masked.has_value() ? *masked : state; + if (renderOverride.disableDepthTest && overriddenState.depthTest) { + overriddenState.depthTest = false; + hasOverrides = true; + } + if (renderOverride.forceDepthWrite && !overriddenState.depthWrite) { + overriddenState.depthWrite = true; + hasOverrides = true; + } + if (renderOverride.forceOpaqueAlpha) { + for (auto& blend : overriddenState.blends) { + blend.blendEnable = VK_FALSE; ~~~~ --- Addressed in commit 6dfdba678e: Renamed the diagnostic override to disableBlend / disable_blend across RenderStateOverride, HotReload.hpp, HotReload.cpp, and Draw.cpp, accurately reflecting that it sets lendEnable = VK_FALSE on attachment color blends. orce_opaque_alpha is retained as an alias in the configuration parser for backwards compatibility.
MarcZX10 commented 2026-10-17 21:45:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:45:27Z.

Code review location: core/libs/prx/libc/src/HotReload.cpp; line 274

@@ -0,0 +1,467 @@
+#include "prx/libc/include/HotReload.hpp"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <mutex>
+#include <random>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#include <elf.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#endif
+
+namespace HotReload {
+
+namespace {
+
+std::atomic<bool> g_enabled{false};
+std::atomic<bool> g_initialized{false};
+std::mutex g_patchMutex;
+std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes;
+
+constexpr std::size_t TrampolineSize = 14;
+
+void EnsureInitialized() {
+    if (g_initialized.exchange(true)) return;
+    const char* env = std::getenv("APS5_HOT_RELOAD");
+    if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) {
+        g_enabled.store(true);
+    }
+}
+
+#ifdef _WIN32
+
+bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) {
+    return VirtualProtect(address, size, protection, oldProtection) != 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    FlushInstructionCache(GetCurrentProcess(), address, size);
+}
+
+#else
+
+bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) {
+    const long pageSize = sysconf(_SC_PAGESIZE);
+    if (pageSize <= 0) return false;
+    const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1);
+    const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1);
+    if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC;
+    return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size);
+}
+
+#endif
+
+} // namespace
+
+bool IsEnabled() {
+    EnsureInitialized();
+    return g_enabled.load();
+}
+
+void SetEnabled(const bool enabled) {
+    g_initialized.store(true);
+    g_enabled.store(enabled);
+}
+
+bool PatchFunction(void* target, void* replacement) {
+    if (target == nullptr || replacement == nullptr || target == replacement) return false;
+    std::lock_guard lock(g_patchMutex);
+
+    const auto existing = g_originalBytes.find(target);
+    if (existing != g_originalBytes.end()) {
+#ifdef _WIN32
+        DWORD oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#else
+        int oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#endif
+    }
+
+    std::vector<std::uint8_t> saved(TrampolineSize);
+    std::memcpy(saved.data(), target, TrampolineSize);
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.emplace(target, std::move(saved));
+    return true;
+}
+
+void* GetOriginalFunction(void* target) {
+    if (target == nullptr) return nullptr;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return nullptr;
+    return target;
+}
+
+bool RestoreFunction(void* target) {
+    if (target == nullptr) return false;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return false;
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.erase(it);
+    return true;
+}
+
+bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) {
+    if (target == nullptr || bytes == nullptr || size == 0) return false;
+    std::lock_guard lock(g_patchMutex);
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#endif
+}
+
+std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) {
+    std::error_code ec;
+    if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0;
+
+    std::size_t patchedTotal = 0;
+    const auto shadowDir = patchDirectory / ".shadow";
+    std::filesystem::create_directories(shadowDir, ec);
+
+    std::random_device rd;
+    std::mt19937_64 rng(rd());
+
+    for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) {
+        if (!entry.is_regular_file(ec)) continue;
+        const auto ext = entry.path().extension().string();
+        if (ext != ".prx" && ext != ".dll" && ext != ".so") continue;
+
+        const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext;
+        const auto shadowPath = shadowDir / shadowName;
+        std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec);
+        if (ec) continue;
+
+#ifdef _WIN32
+        HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
+        if (hPatch == nullptr) continue;
+
+        const auto filename = entry.path().filename().string();
+        HMODULE hBase = GetModuleHandleA(filename.c_str());
+        if (hBase == nullptr) {
+            hBase = GetModuleHandleW(nullptr);
+        }
+
+        const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch);
+        if (dos->e_magic == IMAGE_DOS_SIGNATURE) {
+            const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew);
+            if (nt->Signature == IMAGE_NT_SIGNATURE) {
+                const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
+                if (exportDir.VirtualAddress != 0) {
+                    const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress);
+                    const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames);
+                    const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals);
+                    const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions);
+
+                    for (DWORD i = 0; i < exports->NumberOfNames; ++i) {
+                        const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]);
+                        const WORD ordinal = ordinals[i];
+                        void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal]));
+
+                        void* baseFunc = nullptr;
+                        if (hBase != nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName));
+                        }
+                        if (baseFunc == nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName));
+                        }
+
+                        if (baseFunc != nullptr && baseFunc != patchFunc) {
+                            if (PatchFunction(baseFunc, patchFunc)) {
+                                std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc);
+                                ++patchedTotal;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+#else
+        void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL);
+        if (hPatch == nullptr) continue;
+
+        FILE* elfFile = std::fopen(shadowPath.string().c_str(), "rb");
+        if (elfFile != nullptr) {
+            Elf64_Ehdr ehdr;
+            if (std::fread(&ehdr, 1, sizeof(ehdr), elfFile) == sizeof(ehdr) &&
+                ehdr.e_ident[EI_MAG0] == ELFMAG0 && ehdr.e_ident[EI_MAG1] == ELFMAG1 &&
+                ehdr.e_ident[EI_MAG2] == ELFMAG2 && ehdr.e_ident[EI_MAG3] == ELFMAG3 &&
+                ehdr.e_ident[EI_CLASS] == ELFCLASS64 && ehdr.e_shoff != 0 && ehdr.e_shentsize == sizeof(Elf64_Shdr)) {
+                std::vector<Elf64_Shdr> shdrs(ehdr.e_shnum);
+                std::fseek(elfFile, ehdr.e_shoff, SEEK_SET);
+                if (std::fread(shdrs.data(), sizeof(Elf64_Shdr), ehdr.e_shnum, elfFile) == ehdr.e_shnum) {
+                    for (const auto& shdr : shdrs) {
+                        if (shdr.sh_type == SHT_DYNSYM && shdr.sh_link < shdrs.size()) {
+                            const auto& strShdr = shdrs[shdr.sh_link];
+                            std::vector<char> strtab(strShdr.sh_size);
+                            std::fseek(elfFile, strShdr.sh_offset, SEEK_SET);
+                            if (std::fread(strtab.data(), 1, strShdr.sh_size, elfFile) != strShdr.sh_size) continue;
+
+                            const std::size_t numSyms = shdr.sh_size / sizeof(Elf64_Sym);
+                            std::vector<Elf64_Sym> syms(numSyms);
+                            std::fseek(elfFile, shdr.sh_offset, SEEK_SET);
+                            if (std::fread(syms.data(), sizeof(Elf64_Sym), numSyms, elfFile) != numSyms) continue;
+
+                            for (const auto& sym : syms) {
+                                if (sym.st_name >= strtab.size() || sym.st_shndx == SHN_UNDEF) continue;
+                                const unsigned char bind = ELF64_ST_BIND(sym.st_info);

Could this also require ELF64_ST_TYPE(sym.st_info) == STT_FUNC before calling PatchFunction? The current loop checks only global/weak binding, so an exported STT_OBJECT or other non-function symbol with a matching base-process name also reaches PatchFunction. That writes the 14-byte code trampoline over the data object's storage and can corrupt the process. This API is intended to replace functions, so filtering to function symbols seems necessary.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4304642667 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#discussion_r4304642667). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:45:27Z. **Code review location:** `core/libs/prx/libc/src/HotReload.cpp`; line 274 ~~~~diff @@ -0,0 +1,467 @@ +#include "prx/libc/include/HotReload.hpp" + +#include <atomic> +#include <chrono> +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <mutex> +#include <random> +#include <thread> +#include <unordered_map> +#include <vector> + +#ifdef _WIN32 +#include <windows.h> +#else +#include <dlfcn.h> +#include <elf.h> +#include <sys/mman.h> +#include <unistd.h> +#endif + +namespace HotReload { + +namespace { + +std::atomic<bool> g_enabled{false}; +std::atomic<bool> g_initialized{false}; +std::mutex g_patchMutex; +std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes; + +constexpr std::size_t TrampolineSize = 14; + +void EnsureInitialized() { + if (g_initialized.exchange(true)) return; + const char* env = std::getenv("APS5_HOT_RELOAD"); + if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) { + g_enabled.store(true); + } +} + +#ifdef _WIN32 + +bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) { + return VirtualProtect(address, size, protection, oldProtection) != 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + FlushInstructionCache(GetCurrentProcess(), address, size); +} + +#else + +bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) { + const long pageSize = sysconf(_SC_PAGESIZE); + if (pageSize <= 0) return false; + const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1); + const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1); + if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC; + return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size); +} + +#endif + +} // namespace + +bool IsEnabled() { + EnsureInitialized(); + return g_enabled.load(); +} + +void SetEnabled(const bool enabled) { + g_initialized.store(true); + g_enabled.store(enabled); +} + +bool PatchFunction(void* target, void* replacement) { + if (target == nullptr || replacement == nullptr || target == replacement) return false; + std::lock_guard lock(g_patchMutex); + + const auto existing = g_originalBytes.find(target); + if (existing != g_originalBytes.end()) { +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#endif + } + + std::vector<std::uint8_t> saved(TrampolineSize); + std::memcpy(saved.data(), target, TrampolineSize); + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.emplace(target, std::move(saved)); + return true; +} + +void* GetOriginalFunction(void* target) { + if (target == nullptr) return nullptr; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return nullptr; + return target; +} + +bool RestoreFunction(void* target) { + if (target == nullptr) return false; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return false; + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.erase(it); + return true; +} + +bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) { + if (target == nullptr || bytes == nullptr || size == 0) return false; + std::lock_guard lock(g_patchMutex); +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#endif +} + +std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) { + std::error_code ec; + if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0; + + std::size_t patchedTotal = 0; + const auto shadowDir = patchDirectory / ".shadow"; + std::filesystem::create_directories(shadowDir, ec); + + std::random_device rd; + std::mt19937_64 rng(rd()); + + for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) { + if (!entry.is_regular_file(ec)) continue; + const auto ext = entry.path().extension().string(); + if (ext != ".prx" && ext != ".dll" && ext != ".so") continue; + + const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext; + const auto shadowPath = shadowDir / shadowName; + std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec); + if (ec) continue; + +#ifdef _WIN32 + HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (hPatch == nullptr) continue; + + const auto filename = entry.path().filename().string(); + HMODULE hBase = GetModuleHandleA(filename.c_str()); + if (hBase == nullptr) { + hBase = GetModuleHandleW(nullptr); + } + + const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch); + if (dos->e_magic == IMAGE_DOS_SIGNATURE) { + const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew); + if (nt->Signature == IMAGE_NT_SIGNATURE) { + const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (exportDir.VirtualAddress != 0) { + const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress); + const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames); + const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals); + const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions); + + for (DWORD i = 0; i < exports->NumberOfNames; ++i) { + const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]); + const WORD ordinal = ordinals[i]; + void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal])); + + void* baseFunc = nullptr; + if (hBase != nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName)); + } + if (baseFunc == nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName)); + } + + if (baseFunc != nullptr && baseFunc != patchFunc) { + if (PatchFunction(baseFunc, patchFunc)) { + std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc); + ++patchedTotal; + } + } + } + } + } + } +#else + void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL); + if (hPatch == nullptr) continue; + + FILE* elfFile = std::fopen(shadowPath.string().c_str(), "rb"); + if (elfFile != nullptr) { + Elf64_Ehdr ehdr; + if (std::fread(&ehdr, 1, sizeof(ehdr), elfFile) == sizeof(ehdr) && + ehdr.e_ident[EI_MAG0] == ELFMAG0 && ehdr.e_ident[EI_MAG1] == ELFMAG1 && + ehdr.e_ident[EI_MAG2] == ELFMAG2 && ehdr.e_ident[EI_MAG3] == ELFMAG3 && + ehdr.e_ident[EI_CLASS] == ELFCLASS64 && ehdr.e_shoff != 0 && ehdr.e_shentsize == sizeof(Elf64_Shdr)) { + std::vector<Elf64_Shdr> shdrs(ehdr.e_shnum); + std::fseek(elfFile, ehdr.e_shoff, SEEK_SET); + if (std::fread(shdrs.data(), sizeof(Elf64_Shdr), ehdr.e_shnum, elfFile) == ehdr.e_shnum) { + for (const auto& shdr : shdrs) { + if (shdr.sh_type == SHT_DYNSYM && shdr.sh_link < shdrs.size()) { + const auto& strShdr = shdrs[shdr.sh_link]; + std::vector<char> strtab(strShdr.sh_size); + std::fseek(elfFile, strShdr.sh_offset, SEEK_SET); + if (std::fread(strtab.data(), 1, strShdr.sh_size, elfFile) != strShdr.sh_size) continue; + + const std::size_t numSyms = shdr.sh_size / sizeof(Elf64_Sym); + std::vector<Elf64_Sym> syms(numSyms); + std::fseek(elfFile, shdr.sh_offset, SEEK_SET); + if (std::fread(syms.data(), sizeof(Elf64_Sym), numSyms, elfFile) != numSyms) continue; + + for (const auto& sym : syms) { + if (sym.st_name >= strtab.size() || sym.st_shndx == SHN_UNDEF) continue; + const unsigned char bind = ELF64_ST_BIND(sym.st_info); ~~~~ --- Could this also require `ELF64_ST_TYPE(sym.st_info) == STT_FUNC` before calling `PatchFunction`? The current loop checks only global/weak binding, so an exported `STT_OBJECT` or other non-function symbol with a matching base-process name also reaches `PatchFunction`. That writes the 14-byte code trampoline over the data object's storage and can corrupt the process. This API is intended to replace functions, so filtering to function symbols seems necessary.
MarcZX10 commented 2026-10-17 21:45:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T21:45:27Z.

Review: COMMENTED


Thanks for addressing the two earlier points. I reviewed the POSIX export loop at the updated head and found one additional correctness issue.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5560248373 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#pullrequestreview-5560248373). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T21:45:27Z. **Review:** COMMENTED --- Thanks for addressing the two earlier points. I reviewed the POSIX export loop at the updated head and found one additional correctness issue.
ivica00 commented 2026-10-17 21:55:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ivica00 on 2026-10-17T21:55:58Z.

Code review location: core/libs/prx/libc/src/HotReload.cpp; line 274

@@ -0,0 +1,467 @@
+#include "prx/libc/include/HotReload.hpp"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <mutex>
+#include <random>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#include <elf.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#endif
+
+namespace HotReload {
+
+namespace {
+
+std::atomic<bool> g_enabled{false};
+std::atomic<bool> g_initialized{false};
+std::mutex g_patchMutex;
+std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes;
+
+constexpr std::size_t TrampolineSize = 14;
+
+void EnsureInitialized() {
+    if (g_initialized.exchange(true)) return;
+    const char* env = std::getenv("APS5_HOT_RELOAD");
+    if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) {
+        g_enabled.store(true);
+    }
+}
+
+#ifdef _WIN32
+
+bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) {
+    return VirtualProtect(address, size, protection, oldProtection) != 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    FlushInstructionCache(GetCurrentProcess(), address, size);
+}
+
+#else
+
+bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) {
+    const long pageSize = sysconf(_SC_PAGESIZE);
+    if (pageSize <= 0) return false;
+    const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1);
+    const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1);
+    if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC;
+    return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0;
+}
+
+void FlushInstructionCacheFor(void* address, std::size_t size) {
+    __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size);
+}
+
+#endif
+
+} // namespace
+
+bool IsEnabled() {
+    EnsureInitialized();
+    return g_enabled.load();
+}
+
+void SetEnabled(const bool enabled) {
+    g_initialized.store(true);
+    g_enabled.store(enabled);
+}
+
+bool PatchFunction(void* target, void* replacement) {
+    if (target == nullptr || replacement == nullptr || target == replacement) return false;
+    std::lock_guard lock(g_patchMutex);
+
+    const auto existing = g_originalBytes.find(target);
+    if (existing != g_originalBytes.end()) {
+#ifdef _WIN32
+        DWORD oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#else
+        int oldProtect = 0;
+        if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+        std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement));
+        SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect);
+        FlushInstructionCacheFor(target, TrampolineSize);
+        return true;
+#endif
+    }
+
+    std::vector<std::uint8_t> saved(TrampolineSize);
+    std::memcpy(saved.data(), target, TrampolineSize);
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00};
+    std::memcpy(trampoline + 6, &replacement, sizeof(replacement));
+    std::memcpy(target, trampoline, TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.emplace(target, std::move(saved));
+    return true;
+}
+
+void* GetOriginalFunction(void* target) {
+    if (target == nullptr) return nullptr;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return nullptr;
+    return target;
+}
+
+bool RestoreFunction(void* target) {
+    if (target == nullptr) return false;
+    std::lock_guard lock(g_patchMutex);
+    const auto it = g_originalBytes.find(target);
+    if (it == g_originalBytes.end()) return false;
+
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, it->second.data(), TrampolineSize);
+    SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, TrampolineSize);
+#endif
+
+    g_originalBytes.erase(it);
+    return true;
+}
+
+bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) {
+    if (target == nullptr || bytes == nullptr || size == 0) return false;
+    std::lock_guard lock(g_patchMutex);
+#ifdef _WIN32
+    DWORD oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#else
+    int oldProtect = 0;
+    if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false;
+    std::memcpy(target, bytes, size);
+    SetMemoryProtection(target, size, oldProtect, &oldProtect);
+    FlushInstructionCacheFor(target, size);
+    return true;
+#endif
+}
+
+std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) {
+    std::error_code ec;
+    if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0;
+
+    std::size_t patchedTotal = 0;
+    const auto shadowDir = patchDirectory / ".shadow";
+    std::filesystem::create_directories(shadowDir, ec);
+
+    std::random_device rd;
+    std::mt19937_64 rng(rd());
+
+    for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) {
+        if (!entry.is_regular_file(ec)) continue;
+        const auto ext = entry.path().extension().string();
+        if (ext != ".prx" && ext != ".dll" && ext != ".so") continue;
+
+        const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext;
+        const auto shadowPath = shadowDir / shadowName;
+        std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec);
+        if (ec) continue;
+
+#ifdef _WIN32
+        HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
+        if (hPatch == nullptr) continue;
+
+        const auto filename = entry.path().filename().string();
+        HMODULE hBase = GetModuleHandleA(filename.c_str());
+        if (hBase == nullptr) {
+            hBase = GetModuleHandleW(nullptr);
+        }
+
+        const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch);
+        if (dos->e_magic == IMAGE_DOS_SIGNATURE) {
+            const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew);
+            if (nt->Signature == IMAGE_NT_SIGNATURE) {
+                const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
+                if (exportDir.VirtualAddress != 0) {
+                    const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress);
+                    const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames);
+                    const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals);
+                    const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions);
+
+                    for (DWORD i = 0; i < exports->NumberOfNames; ++i) {
+                        const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]);
+                        const WORD ordinal = ordinals[i];
+                        void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal]));
+
+                        void* baseFunc = nullptr;
+                        if (hBase != nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName));
+                        }
+                        if (baseFunc == nullptr) {
+                            baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName));
+                        }
+
+                        if (baseFunc != nullptr && baseFunc != patchFunc) {
+                            if (PatchFunction(baseFunc, patchFunc)) {
+                                std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc);
+                                ++patchedTotal;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+#else
+        void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL);
+        if (hPatch == nullptr) continue;
+
+        FILE* elfFile = std::fopen(shadowPath.string().c_str(), "rb");
+        if (elfFile != nullptr) {
+            Elf64_Ehdr ehdr;
+            if (std::fread(&ehdr, 1, sizeof(ehdr), elfFile) == sizeof(ehdr) &&
+                ehdr.e_ident[EI_MAG0] == ELFMAG0 && ehdr.e_ident[EI_MAG1] == ELFMAG1 &&
+                ehdr.e_ident[EI_MAG2] == ELFMAG2 && ehdr.e_ident[EI_MAG3] == ELFMAG3 &&
+                ehdr.e_ident[EI_CLASS] == ELFCLASS64 && ehdr.e_shoff != 0 && ehdr.e_shentsize == sizeof(Elf64_Shdr)) {
+                std::vector<Elf64_Shdr> shdrs(ehdr.e_shnum);
+                std::fseek(elfFile, ehdr.e_shoff, SEEK_SET);
+                if (std::fread(shdrs.data(), sizeof(Elf64_Shdr), ehdr.e_shnum, elfFile) == ehdr.e_shnum) {
+                    for (const auto& shdr : shdrs) {
+                        if (shdr.sh_type == SHT_DYNSYM && shdr.sh_link < shdrs.size()) {
+                            const auto& strShdr = shdrs[shdr.sh_link];
+                            std::vector<char> strtab(strShdr.sh_size);
+                            std::fseek(elfFile, strShdr.sh_offset, SEEK_SET);
+                            if (std::fread(strtab.data(), 1, strShdr.sh_size, elfFile) != strShdr.sh_size) continue;
+
+                            const std::size_t numSyms = shdr.sh_size / sizeof(Elf64_Sym);
+                            std::vector<Elf64_Sym> syms(numSyms);
+                            std::fseek(elfFile, shdr.sh_offset, SEEK_SET);
+                            if (std::fread(syms.data(), sizeof(Elf64_Sym), numSyms, elfFile) != numSyms) continue;
+
+                            for (const auto& sym : syms) {
+                                if (sym.st_name >= strtab.size() || sym.st_shndx == SHN_UNDEF) continue;
+                                const unsigned char bind = ELF64_ST_BIND(sym.st_info);

The POSIX loader now requires ELF64_ST_TYPE(sym.st_info) == STT_FUNC after the global/weak binding check, so an exported STT_OBJECT or other non-function symbol is skipped and PatchFunction is not called for it. Pushed in 3217ec1d1.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4304674814 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#discussion_r4304674814). Originally posted by [ivica00](https://github.com/ivica00) on 2026-10-17T21:55:58Z. **Code review location:** `core/libs/prx/libc/src/HotReload.cpp`; line 274 ~~~~diff @@ -0,0 +1,467 @@ +#include "prx/libc/include/HotReload.hpp" + +#include <atomic> +#include <chrono> +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <mutex> +#include <random> +#include <thread> +#include <unordered_map> +#include <vector> + +#ifdef _WIN32 +#include <windows.h> +#else +#include <dlfcn.h> +#include <elf.h> +#include <sys/mman.h> +#include <unistd.h> +#endif + +namespace HotReload { + +namespace { + +std::atomic<bool> g_enabled{false}; +std::atomic<bool> g_initialized{false}; +std::mutex g_patchMutex; +std::unordered_map<void*, std::vector<std::uint8_t>> g_originalBytes; + +constexpr std::size_t TrampolineSize = 14; + +void EnsureInitialized() { + if (g_initialized.exchange(true)) return; + const char* env = std::getenv("APS5_HOT_RELOAD"); + if (env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0) { + g_enabled.store(true); + } +} + +#ifdef _WIN32 + +bool SetMemoryProtection(void* address, std::size_t size, DWORD protection, DWORD* oldProtection) { + return VirtualProtect(address, size, protection, oldProtection) != 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + FlushInstructionCache(GetCurrentProcess(), address, size); +} + +#else + +bool SetMemoryProtection(void* address, std::size_t size, int protection, int* oldProtection) { + const long pageSize = sysconf(_SC_PAGESIZE); + if (pageSize <= 0) return false; + const std::uintptr_t start = reinterpret_cast<std::uintptr_t>(address) & ~(pageSize - 1); + const std::uintptr_t end = (reinterpret_cast<std::uintptr_t>(address) + size + pageSize - 1) & ~(pageSize - 1); + if (oldProtection != nullptr) *oldProtection = PROT_READ | PROT_EXEC; + return mprotect(reinterpret_cast<void*>(start), end - start, protection) == 0; +} + +void FlushInstructionCacheFor(void* address, std::size_t size) { + __builtin___clear_cache(reinterpret_cast<char*>(address), reinterpret_cast<char*>(address) + size); +} + +#endif + +} // namespace + +bool IsEnabled() { + EnsureInitialized(); + return g_enabled.load(); +} + +void SetEnabled(const bool enabled) { + g_initialized.store(true); + g_enabled.store(enabled); +} + +bool PatchFunction(void* target, void* replacement) { + if (target == nullptr || replacement == nullptr || target == replacement) return false; + std::lock_guard lock(g_patchMutex); + + const auto existing = g_originalBytes.find(target); + if (existing != g_originalBytes.end()) { +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(reinterpret_cast<std::uint8_t*>(target) + 6, &replacement, sizeof(replacement)); + SetMemoryProtection(reinterpret_cast<std::uint8_t*>(target) + 6, sizeof(void*), oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); + return true; +#endif + } + + std::vector<std::uint8_t> saved(TrampolineSize); + std::memcpy(saved.data(), target, TrampolineSize); + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::uint8_t trampoline[TrampolineSize] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; + std::memcpy(trampoline + 6, &replacement, sizeof(replacement)); + std::memcpy(target, trampoline, TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.emplace(target, std::move(saved)); + return true; +} + +void* GetOriginalFunction(void* target) { + if (target == nullptr) return nullptr; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return nullptr; + return target; +} + +bool RestoreFunction(void* target) { + if (target == nullptr) return false; + std::lock_guard lock(g_patchMutex); + const auto it = g_originalBytes.find(target); + if (it == g_originalBytes.end()) return false; + +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, TrampolineSize, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, it->second.data(), TrampolineSize); + SetMemoryProtection(target, TrampolineSize, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, TrampolineSize); +#endif + + g_originalBytes.erase(it); + return true; +} + +bool ApplyRawPatch(void* target, const void* bytes, const std::size_t size) { + if (target == nullptr || bytes == nullptr || size == 0) return false; + std::lock_guard lock(g_patchMutex); +#ifdef _WIN32 + DWORD oldProtect = 0; + if (!SetMemoryProtection(target, size, PAGE_EXECUTE_READWRITE, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#else + int oldProtect = 0; + if (!SetMemoryProtection(target, size, PROT_READ | PROT_WRITE | PROT_EXEC, &oldProtect)) return false; + std::memcpy(target, bytes, size); + SetMemoryProtection(target, size, oldProtect, &oldProtect); + FlushInstructionCacheFor(target, size); + return true; +#endif +} + +std::size_t LoadPatchModules(const std::filesystem::path& patchDirectory) { + std::error_code ec; + if (!std::filesystem::exists(patchDirectory, ec) || !std::filesystem::is_directory(patchDirectory, ec)) return 0; + + std::size_t patchedTotal = 0; + const auto shadowDir = patchDirectory / ".shadow"; + std::filesystem::create_directories(shadowDir, ec); + + std::random_device rd; + std::mt19937_64 rng(rd()); + + for (const auto& entry : std::filesystem::directory_iterator(patchDirectory, ec)) { + if (!entry.is_regular_file(ec)) continue; + const auto ext = entry.path().extension().string(); + if (ext != ".prx" && ext != ".dll" && ext != ".so") continue; + + const auto shadowName = entry.path().stem().string() + "_" + std::to_string(rng()) + ext; + const auto shadowPath = shadowDir / shadowName; + std::filesystem::copy_file(entry.path(), shadowPath, std::filesystem::copy_options::overwrite_existing, ec); + if (ec) continue; + +#ifdef _WIN32 + HMODULE hPatch = LoadLibraryExW(shadowPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (hPatch == nullptr) continue; + + const auto filename = entry.path().filename().string(); + HMODULE hBase = GetModuleHandleA(filename.c_str()); + if (hBase == nullptr) { + hBase = GetModuleHandleW(nullptr); + } + + const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(hPatch); + if (dos->e_magic == IMAGE_DOS_SIGNATURE) { + const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(reinterpret_cast<const std::uint8_t*>(hPatch) + dos->e_lfanew); + if (nt->Signature == IMAGE_NT_SIGNATURE) { + const auto& exportDir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (exportDir.VirtualAddress != 0) { + const auto* exports = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exportDir.VirtualAddress); + const auto* names = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNames); + const auto* ordinals = reinterpret_cast<const WORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfNameOrdinals); + const auto* functions = reinterpret_cast<const DWORD*>(reinterpret_cast<const std::uint8_t*>(hPatch) + exports->AddressOfFunctions); + + for (DWORD i = 0; i < exports->NumberOfNames; ++i) { + const char* exportName = reinterpret_cast<const char*>(reinterpret_cast<const std::uint8_t*>(hPatch) + names[i]); + const WORD ordinal = ordinals[i]; + void* patchFunc = const_cast<void*>(reinterpret_cast<const void*>(reinterpret_cast<const std::uint8_t*>(hPatch) + functions[ordinal])); + + void* baseFunc = nullptr; + if (hBase != nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(hBase, exportName)); + } + if (baseFunc == nullptr) { + baseFunc = reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), exportName)); + } + + if (baseFunc != nullptr && baseFunc != patchFunc) { + if (PatchFunction(baseFunc, patchFunc)) { + std::fprintf(stderr, "[HOT-RELOAD] Patched export %s: %p -> %p\n", exportName, baseFunc, patchFunc); + ++patchedTotal; + } + } + } + } + } + } +#else + void* hPatch = dlopen(shadowPath.c_str(), RTLD_NOW | RTLD_LOCAL); + if (hPatch == nullptr) continue; + + FILE* elfFile = std::fopen(shadowPath.string().c_str(), "rb"); + if (elfFile != nullptr) { + Elf64_Ehdr ehdr; + if (std::fread(&ehdr, 1, sizeof(ehdr), elfFile) == sizeof(ehdr) && + ehdr.e_ident[EI_MAG0] == ELFMAG0 && ehdr.e_ident[EI_MAG1] == ELFMAG1 && + ehdr.e_ident[EI_MAG2] == ELFMAG2 && ehdr.e_ident[EI_MAG3] == ELFMAG3 && + ehdr.e_ident[EI_CLASS] == ELFCLASS64 && ehdr.e_shoff != 0 && ehdr.e_shentsize == sizeof(Elf64_Shdr)) { + std::vector<Elf64_Shdr> shdrs(ehdr.e_shnum); + std::fseek(elfFile, ehdr.e_shoff, SEEK_SET); + if (std::fread(shdrs.data(), sizeof(Elf64_Shdr), ehdr.e_shnum, elfFile) == ehdr.e_shnum) { + for (const auto& shdr : shdrs) { + if (shdr.sh_type == SHT_DYNSYM && shdr.sh_link < shdrs.size()) { + const auto& strShdr = shdrs[shdr.sh_link]; + std::vector<char> strtab(strShdr.sh_size); + std::fseek(elfFile, strShdr.sh_offset, SEEK_SET); + if (std::fread(strtab.data(), 1, strShdr.sh_size, elfFile) != strShdr.sh_size) continue; + + const std::size_t numSyms = shdr.sh_size / sizeof(Elf64_Sym); + std::vector<Elf64_Sym> syms(numSyms); + std::fseek(elfFile, shdr.sh_offset, SEEK_SET); + if (std::fread(syms.data(), sizeof(Elf64_Sym), numSyms, elfFile) != numSyms) continue; + + for (const auto& sym : syms) { + if (sym.st_name >= strtab.size() || sym.st_shndx == SHN_UNDEF) continue; + const unsigned char bind = ELF64_ST_BIND(sym.st_info); ~~~~ --- The POSIX loader now requires `ELF64_ST_TYPE(sym.st_info) == STT_FUNC` after the global/weak binding check, so an exported `STT_OBJECT` or other non-function symbol is skipped and `PatchFunction` is not called for it. Pushed in 3217ec1d1.
oneandonlydean commented 2026-10-17 22:09:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T22:09:50Z.


@ivica00 thanks for this. We'd like the live render-state toggles, but only those, so could you split them into an AGC-only PR?

In scope: the hotreload/render_state.txt overrides (wireframe, no cull, no depth test, forced depth writes, no blending, magenta fallback, no DCC) and the shader reload trigger.

Out of scope for this PR: the libc parts, i.e. the module loader and trampolines (LoadPatchModules, HandleNotImplemented) and the raw byte patches from hotreload/patches.txt. Writing arbitrary bytes into the running process is a separate design question for the maintainers, and libc isn't the place for it. Please leave them out rather than moving them.

Two changes for the AGC PR:

  1. No cost when it's off. At 3217ec1d1 every draw calls GetRenderStateOverride(), which takes g_overrideMutex, and Draw copies the whole State (State overriddenState = baseState;) whether or not an override is active. Please check a cached "enabled" flag first and return before any locking, and copy State only when at least one override is set. The same goes for the getter calls in Pipeline.cpp and PlaceholderImages.cpp. Also, Presentation.cpp treats APS5_HOT_RELOAD as on whenever it's set, even to 0; please use one definition of "enabled" everywhere.

  2. Restore the proxied write mask. The change in the proxied-target loop in Draw.cpp removes masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT;. That changes rendering on the default path with hot reload off. Please keep that line exactly as on main.

We'll test the new version on our side once it's up.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6241981912 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6241981912). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-17T22:09:50Z. --- @ivica00 thanks for this. We'd like the live render-state toggles, but only those, so could you split them into an AGC-only PR? **In scope:** the `hotreload/render_state.txt` overrides (wireframe, no cull, no depth test, forced depth writes, no blending, magenta fallback, no DCC) and the shader reload trigger. **Out of scope for this PR:** the libc parts, i.e. the module loader and trampolines (`LoadPatchModules`, `HandleNotImplemented`) and the raw byte patches from `hotreload/patches.txt`. Writing arbitrary bytes into the running process is a separate design question for the maintainers, and libc isn't the place for it. Please leave them out rather than moving them. Two changes for the AGC PR: 1. **No cost when it's off.** At 3217ec1d1 every draw calls `GetRenderStateOverride()`, which takes `g_overrideMutex`, and `Draw` copies the whole `State` (`State overriddenState = baseState;`) whether or not an override is active. Please check a cached "enabled" flag first and return before any locking, and copy `State` only when at least one override is set. The same goes for the getter calls in `Pipeline.cpp` and `PlaceholderImages.cpp`. Also, `Presentation.cpp` treats `APS5_HOT_RELOAD` as on whenever it's set, even to `0`; please use one definition of "enabled" everywhere. 2. **Restore the proxied write mask.** The change in the proxied-target loop in `Draw.cpp` removes `masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT;`. That changes rendering on the default path with hot reload off. Please keep that line exactly as on main. We'll test the new version on our side once it's up.
oneandonlydean commented 2026-10-17 22:19:19 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-17T22:19:19Z.


Two more things on 3217ec1d1, in addition to the scope note above:

  • It still doesn't build. Presentation.cpp:230 calls ShaderRecompiler::ResetRecompilerCaches(), which doesn't exist anywhere in the tree (the PR-event CI doesn't build the AGC driver, so the checks show green). The AGC-only PR will need the reload path to call something that exists, or to clear only the pipeline cache.
  • It conflicts with main in docs/dev/debt/libc.md. That file drops out once the libc half is gone, so a fresh AGC-only branch from current main avoids it.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6242114803 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6242114803). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-17T22:19:19Z. --- Two more things on 3217ec1d1, in addition to the scope note above: - **It still doesn't build.** `Presentation.cpp:230` calls `ShaderRecompiler::ResetRecompilerCaches()`, which doesn't exist anywhere in the tree (the PR-event CI doesn't build the AGC driver, so the checks show green). The AGC-only PR will need the reload path to call something that exists, or to clear only the pipeline cache. - **It conflicts with main** in `docs/dev/debt/libc.md`. That file drops out once the libc half is gone, so a fresh AGC-only branch from current main avoids it.
ivica00 commented 2026-10-17 22:32:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ivica00 on 2026-10-17T22:32:15Z.


Thanks. The branch is now AGC-only, rebuilt on current main (eabb717bb).

  • The libc loader, trampolines, and hotreload/patches.txt are gone, not moved. docs/dev/debt/libc.md is no longer in the diff.
  • Shader reload no longer calls ShaderRecompiler::ResetRecompilerCaches. That function is not in the tree. hotreload/reload_shaders and a render-state change only wait for the device and call Graphics::ClearCachedPipelines.
  • Enabled means APS5_HOT_RELOAD is set, non-empty, and not 0. That check is cached. CurrentRenderOverride returns before the mutex when it is off, including the calls in Draw, Pipeline, and PlaceholderImages. Presentation uses the same check, so 0 is off there too.
  • Draw copies State only when disable_cull, disable_depth_test, force_depth_write, or disable_blend is set. Wireframe, magenta placeholders, and disable_dcc do not need that copy.
  • The proxied-target line masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT is back, unchanged from main.

The render_override unit test covers the enabled predicate, the render_state.txt parser (including the force_opaque_alpha alias), and the one-shot shader-reload flag. I have not run it against a title.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6242329289 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6242329289). Originally posted by [ivica00](https://github.com/ivica00) on 2026-10-17T22:32:15Z. --- Thanks. The branch is now AGC-only, rebuilt on current main (eabb717bb). - The libc loader, trampolines, and hotreload/patches.txt are gone, not moved. docs/dev/debt/libc.md is no longer in the diff. - Shader reload no longer calls ShaderRecompiler::ResetRecompilerCaches. That function is not in the tree. hotreload/reload_shaders and a render-state change only wait for the device and call Graphics::ClearCachedPipelines. - Enabled means APS5_HOT_RELOAD is set, non-empty, and not 0. That check is cached. CurrentRenderOverride returns before the mutex when it is off, including the calls in Draw, Pipeline, and PlaceholderImages. Presentation uses the same check, so 0 is off there too. - Draw copies State only when disable_cull, disable_depth_test, force_depth_write, or disable_blend is set. Wireframe, magenta placeholders, and disable_dcc do not need that copy. - The proxied-target line masked->blends.at(state.colors[index].exportIndex).colorWriteMask &= VK_COLOR_COMPONENT_R_BIT is back, unchanged from main. The render_override unit test covers the enabled predicate, the render_state.txt parser (including the force_opaque_alpha alias), and the one-shot shader-reload flag. I have not run it against a title.
MarcZX10 commented 2026-10-17 22:48:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-17T22:48:51Z.


I built and ran the graphics validation suite at the current head eabb717bb56ab97c196e7b8aca67d3afd44f1e15; it completed with Graphics validation tests passed (exit 0). This includes the new render_override unit coverage, but is not a title/runtime validation.

For this local Linux run I made two temporary, uncommitted environment-only workarounds: added the template keyword to an unrelated existing SrtDescriptorEvaluation.cpp call so GCC could compile it, and bypassed the project’s old-host-CPU test guard (APS5_ALLOW_OLD_TEST_CPU=1) for this Xeon. Neither workaround is part of the PR or the reported test result.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6242566222 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6242566222). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-17T22:48:51Z. --- I built and ran the graphics validation suite at the current head `eabb717bb56ab97c196e7b8aca67d3afd44f1e15`; it completed with `Graphics validation tests passed` (exit 0). This includes the new `render_override` unit coverage, but is not a title/runtime validation. For this local Linux run I made two temporary, uncommitted environment-only workarounds: added the `template` keyword to an unrelated existing `SrtDescriptorEvaluation.cpp` call so GCC could compile it, and bypassed the project’s old-host-CPU test guard (`APS5_ALLOW_OLD_TEST_CPU=1`) for this Xeon. Neither workaround is part of the PR or the reported test result.
oneandonlydean commented 2026-10-18 10:21:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T10:21:56Z.


Thanks, this is the scope we asked for: AGC only, the loader and byte patcher gone, the flag cached and the State copy only when an override is set, and the colorWriteMask line back. It compiles against current main. Two toggles don't work yet:

  1. fallback_magenta: PlaceholderImages reads the override in its constructor, which runs when the context is created, before the first Present has read hotreload/render_state.txt. Changing the file later doesn't rebuild the placeholder images, because HotReloadShaders only clears pipelines. So the toggle never takes effect. Could you poll before creating them and recreate them when the toggle changes, or leave this toggle out?
  2. force_wireframe sets VK_POLYGON_MODE_LINE, but the device never enables fillModeNonSolid, so this is invalid usage and the result depends on the driver. Please enable the feature when it's supported, and ignore the toggle with a log line when it isn't.

Small things: force_opaque_alpha only disables blending (alpha isn't forced to 1), so it's clearer without that alias. And std::optional<State> would avoid default-constructing a State on every draw when overrides are off.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6248703101 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6248703101). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-18T10:21:56Z. --- Thanks, this is the scope we asked for: AGC only, the loader and byte patcher gone, the flag cached and the State copy only when an override is set, and the colorWriteMask line back. It compiles against current main. Two toggles don't work yet: 1. `fallback_magenta`: `PlaceholderImages` reads the override in its constructor, which runs when the context is created, before the first Present has read `hotreload/render_state.txt`. Changing the file later doesn't rebuild the placeholder images, because `HotReloadShaders` only clears pipelines. So the toggle never takes effect. Could you poll before creating them and recreate them when the toggle changes, or leave this toggle out? 2. `force_wireframe` sets `VK_POLYGON_MODE_LINE`, but the device never enables `fillModeNonSolid`, so this is invalid usage and the result depends on the driver. Please enable the feature when it's supported, and ignore the toggle with a log line when it isn't. Small things: `force_opaque_alpha` only disables blending (alpha isn't forced to 1), so it's clearer without that alias. And `std::optional<State>` would avoid default-constructing a State on every draw when overrides are off.
oneandonlydean commented 2026-10-18 10:52:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-18T10:52:04Z.


Windows CI fails at link time for the new test: tests/render_override_tests.exe has an undefined reference to __gxx_personality_v0 (from both RenderOverride.cpp.obj files). Linux is green and main is green, so this comes from the new target.

Cause: on MinGW, core/libs/CMakeLists.txt adds -fno-asynchronous-unwind-tables to everything in that directory (line 44), so these objects use DWARF unwinding and need __gxx_personality_v0. In this tree that symbol comes from libc.prx. Every test there that calls configure_windows_unwind also links libc. render_override_tests is a host-only test that doesn't link libc, and the host libstdc++ (SEH) doesn't provide the DWARF personality.

Host-only tests in the same file already handle this the way you'd expect (nid_buffer_validation_tests, crash_text_tests). Something like:

add_test_executable(render_override_tests prx/libSceAgcDriver/tests/RenderOverride.cpp prx/libSceAgcDriver/Graphics/src/RenderOverride.cpp)
target_include_directories(render_override_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
if(MINGW)
    target_compile_options(render_override_tests PRIVATE -fasynchronous-unwind-tables)
endif()
add_test(NAME render_override COMMAND render_override_tests)

and drop configure_windows_unwind(render_override_tests), since the test doesn't use the guest DWARF unwinder. Could you push that? We'll rerun full CI on the new head.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6248959307 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6248959307). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-18T10:52:04Z. --- Windows CI fails at link time for the new test: `tests/render_override_tests.exe` has an undefined reference to `__gxx_personality_v0` (from both `RenderOverride.cpp.obj` files). Linux is green and main is green, so this comes from the new target. Cause: on MinGW, `core/libs/CMakeLists.txt` adds `-fno-asynchronous-unwind-tables` to everything in that directory (line 44), so these objects use DWARF unwinding and need `__gxx_personality_v0`. In this tree that symbol comes from `libc.prx`. Every test there that calls `configure_windows_unwind` also links `libc`. `render_override_tests` is a host-only test that doesn't link `libc`, and the host libstdc++ (SEH) doesn't provide the DWARF personality. Host-only tests in the same file already handle this the way you'd expect (`nid_buffer_validation_tests`, `crash_text_tests`). Something like: ```cmake add_test_executable(render_override_tests prx/libSceAgcDriver/tests/RenderOverride.cpp prx/libSceAgcDriver/Graphics/src/RenderOverride.cpp) target_include_directories(render_override_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) if(MINGW) target_compile_options(render_override_tests PRIVATE -fasynchronous-unwind-tables) endif() add_test(NAME render_override COMMAND render_override_tests) ``` and drop `configure_windows_unwind(render_override_tests)`, since the test doesn't use the guest DWARF unwinder. Could you push that? We'll rerun full CI on the new head.
ivica00 commented 2026-10-18 12:14:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ivica00 on 2026-10-18T12:14:44Z.


Addressed on 2934c1bf9.

  • fallback_magenta is removed. Placeholder images are created with the device, before the first present reads hotreload/render_state.txt, and later draws already hold those views. Rebuilding them when the file changes would leave those views behind, so the key is ignored. The unit test writes only force_opaque_alpha and fallback_magenta and checks that no override is set.
  • force_wireframe sets VK_POLYGON_MODE_LINE only when fillModeNonSolid is available. The device enables that feature when the hardware has it. Otherwise the pipeline stays filled and one line is logged: force_wireframe ignored: fillModeNonSolid is unavailable.
  • force_opaque_alpha is no longer an alias of disable_blend. Turning blend off does not write alpha 1.
  • A draw keeps the override in std::optional<State> and constructs it only when a cull, depth, or blend override is set.
  • render_override_tests no longer calls configure_windows_unwind. On MinGW it compiles with -fasynchronous-unwind-tables, the same as the other host-only tests that do not link libc.

render_override passed here (MinGW g++ 16.2). Not run against a title.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6249790091 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#issuecomment-6249790091). Originally posted by [ivica00](https://github.com/ivica00) on 2026-10-18T12:14:44Z. --- Addressed on `2934c1bf9`. - `fallback_magenta` is removed. Placeholder images are created with the device, before the first present reads `hotreload/render_state.txt`, and later draws already hold those views. Rebuilding them when the file changes would leave those views behind, so the key is ignored. The unit test writes only `force_opaque_alpha` and `fallback_magenta` and checks that no override is set. - `force_wireframe` sets `VK_POLYGON_MODE_LINE` only when `fillModeNonSolid` is available. The device enables that feature when the hardware has it. Otherwise the pipeline stays filled and one line is logged: `force_wireframe ignored: fillModeNonSolid is unavailable`. - `force_opaque_alpha` is no longer an alias of `disable_blend`. Turning blend off does not write alpha 1. - A draw keeps the override in `std::optional<State>` and constructs it only when a cull, depth, or blend override is set. - `render_override_tests` no longer calls `configure_windows_unwind`. On MinGW it compiles with `-fasynchronous-unwind-tables`, the same as the other host-only tests that do not link `libc`. `render_override` passed here (MinGW g++ 16.2). Not run against a title.
MarcZX10 commented 2026-11-16 20:23:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-16T20:23:22Z.

Review: COMMENTED


Reviewed — comments

The added render overrides and reload trigger were inspected at head 4aff7f5047fc79c99ebf6cc7620f6ec0914338d9; no blocking defect was verified, and no checks were run.

What I ran

No commands or tests were run. I inspected the prepared diff and targeted source context through repo_read.py.

Results

Check Result Note
Diff and changed lines passed All 11 changed files’ added lines were read
Automated checks not run No tests or build commands were run

Negative Control

Not run; the new test was not executed.

Findings

Blocking

None.

Non-blocking

  • PollRenderOverride records the file timestamp before opening and parsing it. If opening fails transiently, that timestamp prevents another attempt until the file’s timestamp changes (core/libs/prx/libSceAgcDriver/Graphics/src/RenderOverride.cpp:56). Consider updating lastOverrideWrite only after a successful read so a transient access error can recover on its own.

Sources

The findings and behavior above are based on the prepared diff and the changed source at the pinned head.

Not verified

The Windows/MinGW unit-test run described by the author was not independently verified. No build, automated checks, or title/game behavior were run. The changed files’ full head text was not available in review/files/; added lines were inspected in diff.patch, and targeted repository source ranges were read for render-state polling, draw-state application, pipeline construction, cache clearing, presentation, and the added test. files.json was not available through the reader; the changed-file inventory was taken from manifest.json.

To get this to a good state

Nothing is required. Optional: retry parsing after a transient file-open failure by recording the timestamp only after a successful read.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5926975068 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7275#pullrequestreview-5926975068). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-16T20:23:22Z. **Review:** COMMENTED --- # Reviewed — comments The added render overrides and reload trigger were inspected at head `4aff7f5047fc79c99ebf6cc7620f6ec0914338d9`; no blocking defect was verified, and no checks were run. ## What I ran No commands or tests were run. I inspected the prepared diff and targeted source context through `repo_read.py`. ## Results | Check | Result | Note | |---|---|---| | Diff and changed lines | passed | All 11 changed files’ added lines were read | | Automated checks | not run | No tests or build commands were run | ## Negative Control Not run; the new test was not executed. ## Findings ### Blocking None. ### Non-blocking - `PollRenderOverride` records the file timestamp before opening and parsing it. If opening fails transiently, that timestamp prevents another attempt until the file’s timestamp changes (`core/libs/prx/libSceAgcDriver/Graphics/src/RenderOverride.cpp:56`). Consider updating `lastOverrideWrite` only after a successful read so a transient access error can recover on its own. ## Sources The findings and behavior above are based on the prepared diff and the changed source at the pinned head. ## Not verified The Windows/MinGW unit-test run described by the author was not independently verified. No build, automated checks, or title/game behavior were run. The changed files’ full head text was not available in `review/files/`; added lines were inspected in `diff.patch`, and targeted repository source ranges were read for render-state polling, draw-state application, pipeline construction, cache clearing, presentation, and the added test. `files.json` was not available through the reader; the changed-file inventory was taken from `manifest.json`. ## To get this to a good state Nothing is required. Optional: retry parsing after a transient file-open failure by recording the timestamp only after a successful read.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/7275:upstream-pr/7275'
git switch 'upstream-pr/7275'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/7275'
git switch 'upstream-pr/7275'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/7275'
git switch 'upstream-pr/7275'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/7275'
git switch 'main'
git merge --squash 'upstream-pr/7275'
git switch 'main'
git merge --ff-only 'upstream-pr/7275'
git switch 'main'
git merge 'upstream-pr/7275'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!7275
No description provided.