From 73599fad8f5892a6e450844b39f8110c061d8d53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Mon, 5 Oct 2026 14:31:11 +0200 Subject: [PATCH 01/42] fix(shader): apply clamp on v_div_scale_f64 and accept omod on the f32 division steps and v_div_scale Co-Authored-By: Claude --- .../execution/DivisionOutputModifiers.cpp | 188 ++++++++++++++++++ .../execution/DivisionResultModifiers.cpp | 14 -- .../RdnaDecoder/src/RdnaVectorOpDecoder.cpp | 7 +- .../Translation/src/Float64Instructions.cpp | 2 +- 4 files changed, 195 insertions(+), 16 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/DivisionOutputModifiers.cpp diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DivisionOutputModifiers.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DivisionOutputModifiers.cpp new file mode 100644 index 000000000..69d530e1b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DivisionOutputModifiers.cpp @@ -0,0 +1,188 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 32; +constexpr std::uint32_t Inputs = 4; +constexpr std::uint32_t Results = 16; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; + +alignas(256) constexpr std::array Code{ + 0x34020084, 0x34060086, 0xe0381000, 0x80000401, 0xbf8c3f70, 0x36100e81, 0x7d8a1080, 0xd56f000a, + 0x0c1a0b04, 0xd56f000b, 0x5c1a0905, 0xd55f000c, 0x141a0b04, 0xd55f020d, 0x3c1a0b04, 0xd56d8c0e, + 0x041a0b04, 0xd56d0c0f, 0x0c1a0b04, 0xd56d0c10, 0x1c1a0b06, 0xd56d8c11, 0x141a0b06, 0xd56e8c12, + 0x04120d04, 0xd56e0c14, 0x0c120d06, 0xd56e0c16, 0x1c120d04, 0xd56e8c18, 0x14120d06, 0xe0781000, + 0x80010a03, 0xe0781010, 0x80010e03, 0xe0781020, 0x80011203, 0xe0781030, 0x80011603, 0xbf810000, +}; + +constexpr std::uint32_t Rows[32][4] = { + {0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x00000000u, 0x00800000u, 0x3ec00000u, 0x9ffbf25eu}, + {0x00800000u, 0x40000000u, 0xb2400000u, 0x6eb48efcu}, + {0x20000000u, 0xe4380000u, 0xabbe954cu, 0xd080849du}, + {0x3f800000u, 0x80800000u, 0x64280000u, 0x013367a7u}, + {0x7f800000u, 0x3f400000u, 0xff800000u, 0xefc44097u}, + {0xbf400000u, 0xc0780000u, 0x3f800000u, 0xe44de90bu}, + {0xbf800000u, 0x20000000u, 0x7f800000u, 0x13eab756u}, + {0xc0200000u, 0x40400000u, 0xbf800000u, 0xe2d60270u}, + {0x80000000u, 0xff7fffffu, 0x00a80000u, 0xab35a9b1u}, + {0x00000000u, 0x7ff00000u, 0x00000000u, 0x7ff00000u}, + {0xe57ddac0u, 0x40900000u, 0x00800000u, 0xf93e81a9u}, + {0x3f000000u, 0x3f400000u, 0x40000000u, 0xf16dbe02u}, + {0x00000000u, 0x3ff00000u, 0x00000000u, 0x3ff00000u}, + {0x00000000u, 0xbff00000u, 0x00000000u, 0xbff00000u}, + {0x00000000u, 0xfff00000u, 0x00000000u, 0xfff00000u}, + {0x3f400000u, 0x5f800000u, 0xc0000000u, 0x9c6e0e69u}, + {0x7f300000u, 0x20000000u, 0x3f300000u, 0xb96bd6afu}, + {0x80800000u, 0x3f800000u, 0x3f800000u, 0xa545f3c8u}, + {0xbf800000u, 0x80800000u, 0xbf800000u, 0x215c2862u}, + {0xff200000u, 0x7f800000u, 0x80800000u, 0xd46cde99u}, + {0x40000000u, 0x32200000u, 0xff7fffffu, 0x198be250u}, + {0x40000000u, 0x5f000000u, 0x3f7fffffu, 0x6616ec89u}, + {0x1f800000u, 0x40680000u, 0xff800000u, 0xfde11576u}, + {0x3f7fffffu, 0xffc00000u, 0x3ff00000u, 0x03998b2fu}, + {0x7f7fffffu, 0x62f2a21bu, 0xbfe80000u, 0x7e544d56u}, + {0x80000000u, 0x36f675ccu, 0x80800000u, 0x6b0d549bu}, + {0xbff00000u, 0x40000000u, 0x7f7fffffu, 0x1ef68f28u}, + {0x00000000u, 0x1e200000u, 0x3f000000u, 0xea5b840eu}, + {0x00000000u, 0x1f800000u, 0x00800000u, 0x729eabeeu}, + {0x00000000u, 0x3f400000u, 0x80000000u, 0xa8333fe6u}, + {0x00000000u, 0x46180000u, 0x80800000u, 0x146bbdacu} +}; +constexpr std::uint32_t Expected[32][16] = { + {0x00000000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xfff80000u, 0x00000000u, 0xfff80000u, 0x00000000u, 0x00000000u}, + {0x3f400000u, 0x3e400000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x3e400000u, 0x3f800000u, 0x00000000u, 0x08800000u, 0x3ec00000u, 0xa7fbf25eu, 0x00000000u, 0x08800000u, 0x00000000u, 0x00000000u}, + {0xb2c00000u, 0xb1c00000u, 0x81800000u, 0x80000000u, 0x00800000u, 0x01000000u, 0xb1c00000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0xb2400000u, 0x6eb48efcu, 0x00800000u, 0x40000000u, 0x00000000u, 0x3ff00000u}, + {0xa5380000u, 0x24380000u, 0x21000000u, 0x9f800000u, 0x3f800000u, 0x40800000u, 0xcb3e954cu, 0x00000000u, 0x00000000u, 0x00000000u, 0xabbe954cu, 0xd080849du, 0x20000000u, 0xe4380000u, 0x00000000u, 0x00000000u}, + {0x7f800000u, 0x7f800000u, 0xc0800000u, 0x3f000000u, 0x3f800000u, 0x40000000u, 0x63a80000u, 0x3f800000u, 0x00000000u, 0x00000000u, 0x64280000u, 0x093367a7u, 0x3f800000u, 0x88800000u, 0x64280000u, 0x093367a7u}, + {0xffc00000u, 0xff800000u, 0xff800000u, 0xff800000u, 0x3f800000u, 0x7f800000u, 0xff800000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0xff800000u, 0xefc44097u, 0x7f800000u, 0x47400000u, 0x00000000u, 0x00000000u}, + {0x20fa0000u, 0x9f740000u, 0xc0400000u, 0x3ec00000u, 0x00000000u, 0xbfc00000u, 0x3f000000u, 0x3f800000u, 0x00000000u, 0x00000000u, 0x3f800000u, 0xe44de90bu, 0xbf400000u, 0xc0780000u, 0x00000000u, 0x00000000u}, + {0x7f800000u, 0x7f800000u, 0x7f800000u, 0x7f800000u, 0x00000000u, 0xc0000000u, 0x7f800000u, 0x3f800000u, 0xbf800000u, 0x20000000u, 0x7f800000u, 0x13eab756u, 0xbf800000u, 0x20000000u, 0x7f800000u, 0x13eab756u}, + {0xc1880000u, 0x40500000u, 0xc1200000u, 0xbfa00000u, 0x00000000u, 0xc0a00000u, 0xbf000000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0xbf800000u, 0xe2d60270u, 0xc0200000u, 0x40400000u, 0x00000000u, 0x00000000u}, + {0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x01a80000u, 0x00000000u, 0x00000000u, 0x00a80000u, 0xb335a9b1u, 0x80000000u, 0xff7fffffu, 0x00000000u, 0x00000000u}, + {0x7ff00000u, 0x7ff00000u, 0x7ff00000u, 0x7ff00000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0x00000000u, 0x7ff00000u, 0x00000000u, 0x7ff00000u, 0x00000000u, 0x3ff00000u}, + {0xc70ecb0cu, 0x460ecb0cu, 0x667ddac0u, 0x64fddac0u, 0x00000000u, 0xff800000u, 0x20000000u, 0x21800000u, 0x00000000u, 0x3ff00000u, 0x00800000u, 0xf93e81a9u, 0xe57ddac0u, 0x48900000u, 0x00000000u, 0x00000000u}, + {0x40980000u, 0x3f500000u, 0x40000000u, 0x3e800000u, 0x3f000000u, 0x3f800000u, 0x3f800000u, 0x3f800000u, 0x00000000u, 0x3ff00000u, 0x40000000u, 0xf16dbe02u, 0x3f000000u, 0x47400000u, 0x00000000u, 0x00000000u}, + {0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0x00000000u, 0x3ff00000u, 0x00000000u, 0x3ff00000u, 0x00000000u, 0x3ff00000u}, + {0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xbff00000u, 0x00000000u, 0xbff00000u, 0x00000000u, 0x00000000u}, + {0xfff00000u, 0xfff00000u, 0xfff00000u, 0x7ff00000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xfff00000u, 0x00000000u, 0xfff00000u, 0x00000000u, 0x00000000u}, + {0x7f800000u, 0xfec00000u, 0xc0400000u, 0xbec00000u, 0x3f400000u, 0x3fc00000u, 0xbf800000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0xc0000000u, 0xa46e0e69u, 0x3f400000u, 0x5f800000u, 0x00000000u, 0x00000000u}, + {0x40300000u, 0xbf300000u, 0x7f800000u, 0x7eb00000u, 0x3f800000u, 0x7f800000u, 0x3eb00000u, 0x3f800000u, 0x7f300000u, 0x20000000u, 0x3f300000u, 0xb96bd6afu, 0x7f300000u, 0x20000000u, 0x00000000u, 0x00000000u}, + {0x40000000u, 0x3f000000u, 0x01800000u, 0x00000000u, 0x00000000u, 0x81000000u, 0x3f000000u, 0x3f800000u, 0x80800000u, 0x3f800000u, 0x3f800000u, 0xa545f3c8u, 0x80800000u, 0x3f800000u, 0x00000000u, 0x00000000u}, + {0xc0000000u, 0xbf000000u, 0x40800000u, 0xbf000000u, 0x00000000u, 0xc0000000u, 0xbf000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xbf800000u, 0x295c2862u, 0xbf800000u, 0x88800000u, 0xbf800000u, 0x295c2862u}, + {0xff800000u, 0x7f800000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xff800000u, 0x80000000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0x80800000u, 0xd46cde99u, 0xff200000u, 0x7f800000u, 0x00000000u, 0x00000000u}, + {0xff800000u, 0xfeffffffu, 0xc1000000u, 0xbf800000u, 0x3f800000u, 0x40800000u, 0xfeffffffu, 0x00000000u, 0x40000000u, 0x32200000u, 0xff7fffffu, 0x198be250u, 0x40000000u, 0x32200000u, 0xff7fffffu, 0x198be250u}, + {0x40000000u, 0xbf000000u, 0x41000000u, 0x3f800000u, 0x3f800000u, 0x40800000u, 0x3effffffu, 0x3f800000u, 0x00000000u, 0x3ff00000u, 0x3f7fffffu, 0x6616ec89u, 0x40000000u, 0x5f000000u, 0x00000000u, 0x3ff00000u}, + {0xff800000u, 0xff800000u, 0xff800000u, 0xff800000u, 0x1f800000u, 0x20000000u, 0xff800000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0xff800000u, 0xfde11576u, 0x1f800000u, 0x48680000u, 0x00000000u, 0x00000000u}, + {0xffc00000u, 0xffc00000u, 0xffc00000u, 0x7fc00000u, 0x3f7fffffu, 0x3fffffffu, 0x3f700000u, 0x3f800000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0x0b998b2fu, 0x3f7fffffu, 0xffc00000u, 0x3ff00000u, 0x0b998b2fu}, + {0x7f800000u, 0xff800000u, 0xff800000u, 0xfeffffffu, 0x3f800000u, 0x7f800000u, 0xbf680000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0xbfe80000u, 0x7e544d56u, 0x7f7fffffu, 0x62f2a21bu, 0x00000000u, 0x3ff00000u}, + {0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xa0000000u, 0x00000000u, 0x80000000u, 0x3ef675ccu, 0x80800000u, 0x6b0d549bu, 0x80000000u, 0x3ef675ccu, 0x00000000u, 0x3ff00000u}, + {0x7f800000u, 0x7effffffu, 0x40f00000u, 0x3f700000u, 0x00000000u, 0xc0700000u, 0x7effffffu, 0x3f800000u, 0x00000000u, 0x3ff00000u, 0x7f7fffffu, 0x1ef68f28u, 0xbff00000u, 0x40000000u, 0x7f7fffffu, 0x1ef68f28u}, + {0x3f800000u, 0x3e800000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x3e800000u, 0x3f800000u, 0x00000000u, 0x26200000u, 0x3f000000u, 0xea5b840eu, 0x00000000u, 0x26200000u, 0x00000000u, 0x00000000u}, + {0x01000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x20000000u, 0x21800000u, 0x00000000u, 0x27800000u, 0x00800000u, 0x729eabeeu, 0x00000000u, 0x27800000u, 0x00000000u, 0x3ff00000u}, + {0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xffc00000u, 0xffc00000u, 0x00000000u, 0x00000000u, 0x3f400000u, 0x80000000u, 0xa8333fe6u, 0x00000000u, 0x3f400000u, 0x00000000u, 0x00000000u}, + {0x81000000u, 0x80000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0xa0000000u, 0x00000000u, 0x00000000u, 0x3ff00000u, 0x80800000u, 0x1c6bbdacu, 0x00000000u, 0x46180000u, 0x80800000u, 0x1c6bbdacu} +}; +constexpr std::uint32_t Checked[32] = {0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xfffcu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu, 0xffffu}; +constexpr const char* Names[16] = { + "v_div_fmas_f32 v10, v4, v5, v6 mul:2", + "v_div_fmas_f32 v11, v5, -v4, v6 div:2", + "v_div_fixup_f32 v12, v4, v5, v6 mul:4", + "v_div_fixup_f32 v13, -v4, |v5|, v6 div:2", + "v_div_scale_f32 v14, s12, v4, v5, v6 clamp", + "v_div_scale_f32 v15, s12, v4, v5, v6 mul:2", + "v_div_scale_f32 v16, s12, v6, v5, v6 div:2", + "v_div_scale_f32 v17, s12, v6, v5, v6 clamp mul:4", + "v_div_scale_f64 v[18:19], s12, v[4:5], v[6:7], v[4:5] clamp lo", + "v_div_scale_f64 v[18:19], s12, v[4:5], v[6:7], v[4:5] clamp hi", + "v_div_scale_f64 v[20:21], s12, v[6:7], v[6:7], v[4:5] mul:2 lo", + "v_div_scale_f64 v[20:21], s12, v[6:7], v[6:7], v[4:5] mul:2 hi", + "v_div_scale_f64 v[22:23], s12, v[4:5], v[6:7], v[4:5] div:2 lo", + "v_div_scale_f64 v[22:23], s12, v[4:5], v[6:7], v[4:5] div:2 hi", + "v_div_scale_f64 v[24:25], s12, v[6:7], v[6:7], v[4:5] clamp mul:4 lo", + "v_div_scale_f64 v[24:25], s12, v[6:7], v[6:7], v[4:5] clamp mul:4 hi", +}; + +void Fill(std::uint32_t tid, std::uint32_t* words) { + std::copy(std::begin(Rows[tid]), std::end(Rows[tid]), words); +} + +std::array BufferDescriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; +} + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +void Expect(std::uint32_t tid, std::uint32_t actual, std::uint32_t expected, const char* name) { + Require(actual == expected, std::string("division output modifiers: lane ") + std::to_string(tid) + " " + name + " is " + Hex(actual) + ", expected " + Hex(expected)); +} + +void Run(AgcDriver::VulkanDevice& device) { + for (std::uint32_t tid = 0; tid < Threads; ++tid) Fill(tid, &Input[tid * Inputs]); + Output.fill(0xdeadbeefu); + std::vector userData(8, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size() * 4u)); + std::copy(input.begin(), input.end(), userData.begin()); + std::copy(output.begin(), output.end(), userData.begin() + 4); + const std::span code(Code); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + const auto result = ShaderRecompiler::Recompile(request); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void Check() { + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const std::uint32_t* in = &Input[tid * Inputs]; + const std::uint32_t* out = &Output[tid * Results]; + for (std::uint32_t i = 0; i < 16; ++i) { + if ((Checked[tid] >> i) & 1u) Expect(tid, out[i], Expected[tid][i], Names[i]); + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + Run(*device); + Check(); + std::puts("division output modifiers tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DivisionResultModifiers.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DivisionResultModifiers.cpp index d6ac16fc2..8ea6352d8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DivisionResultModifiers.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DivisionResultModifiers.cpp @@ -165,19 +165,6 @@ void Run(AgcDriver::VulkanDevice& device) { device.WaitIdle(); } -void CheckF32OmodRefused(AgcDriver::VulkanDevice& device) { - for (const std::uint32_t opcode : {0x15fu, 0x16fu}) { - alignas(256) const std::array code{0xd400000au | (opcode << 16u), 0x0c1a0b04u, 0xbf810000u}; - std::string refusal; - try { - static_cast(Compile(device, code)); - } catch (const std::exception& error) { - refusal = error.what(); - } - Require(refusal.find("VOP3 source modifiers are not implemented") != std::string::npos, "VOP3 opcode " + Hex(opcode) + " with omod was not refused"); - } -} - void Check() { for (std::uint32_t tid = 0; tid < Threads; ++tid) { const std::uint32_t* in = &Input[tid * Inputs]; @@ -196,7 +183,6 @@ int main() { if (!device) return VulkanTestSkipped; Run(*device); Check(); - CheckF32OmodRefused(*device); std::puts("division result modifiers tests passed"); return 0; } catch (const std::exception& error) { diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp index f91cfbcd5..19e0c468b 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp @@ -1910,7 +1910,11 @@ bool supportsNativeVop3ResultModifiers(RdnaOpcode opcode) { case RdnaOpcode::VFmaF16: case RdnaOpcode::VCvtPkrtzF16F32: case RdnaOpcode::VLdexpF32: + case RdnaOpcode::VDivScaleF32: + case RdnaOpcode::VDivFmasF32: + case RdnaOpcode::VDivFixupF32: case RdnaOpcode::VFmaF64: + case RdnaOpcode::VDivScaleF64: case RdnaOpcode::VDivFmasF64: case RdnaOpcode::VDivFixupF64: case RdnaOpcode::VAddF64: @@ -1968,7 +1972,8 @@ void checkNativeVop3Modifiers(RdnaOpcode opcode, bool permlane, bool carryInOut, } if (carryInOut || scalarDst) { const bool floatCompare = scalarDst && isVopcFloatCompareOpcode(opcode); - if ((clamp != 0u && !isVop3BMadU64Opcode(opcode)) || omod != 0u || (neg != 0u && !floatCompare && opcode != RdnaOpcode::VDivScaleF32 && opcode != RdnaOpcode::VDivScaleF64)) { + const bool divScale = opcode == RdnaOpcode::VDivScaleF32 || opcode == RdnaOpcode::VDivScaleF64; + if ((clamp != 0u && !isVop3BMadU64Opcode(opcode)) || (omod != 0u && !divScale) || (neg != 0u && !floatCompare && !divScale)) { throw std::invalid_argument("VOP3 source modifiers are not implemented"); } return; diff --git a/core/shader/recompiler/Translation/src/Float64Instructions.cpp b/core/shader/recompiler/Translation/src/Float64Instructions.cpp index 622c6b41b..0e031dc92 100644 --- a/core/shader/recompiler/Translation/src/Float64Instructions.cpp +++ b/core/shader/recompiler/Translation/src/Float64Instructions.cpp @@ -84,7 +84,7 @@ bool TranslationContext::vDivScaleF64(const RdnaInstruction& inst) { result[1] = IrU32(ir.Select(rescale.Value(), result[1].Value(), value[1].Value())); result[0] = IrU32(ir.Select(zero.Value(), ir.Constant(0u), result[0].Value())); result[1] = IrU32(ir.Select(zero.Value(), ir.Constant(0xfff80000u), result[1].Value())); - writeOperand(inst.destination, &ir.ConstructU64(result[0].Value(), result[1].Value())); + writeF64Result(inst.destination, ir.ConstructU64(result[0].Value(), result[1].Value())); writeMask(inst.destination2, IrU1(ir.LogicalOr(nearMax.Value(), ir.LogicalAnd(notDenormal.Value(), nearMin.Value())))); return true; } From 3e65449c40171db7140578ce706cdd7b4370bd48 Mon Sep 17 00:00:00 2001 From: Lexroid Date: Mon, 5 Oct 2026 19:07:20 +0300 Subject: [PATCH 02/42] feat(libSceAgcDriver): implement sceAgcDriverSubmitMultiDcbs and sceAgcDriverAgrSubmitMultiDcbs Both submit each DCB of the address and size arrays to the graphics queue in array order, as sceAgcDriverSubmitDcb does for one. A count of 0 is accepted without reading the arrays; null arrays with a non-zero count and arrays outside guest memory throw. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/Submit/include/Dcb.hpp | 2 ++ .../prx/libSceAgcDriver/Submit/src/Dcb.cpp | 26 +++++++++-------- .../libs/prx/libSceAgcDriver/tests/Submit.cpp | 28 +++++++++++++++++++ 3 files changed, 45 insertions(+), 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Submit/include/Dcb.hpp b/core/libs/prx/libSceAgcDriver/Submit/include/Dcb.hpp index 4639d647f..56db31822 100644 --- a/core/libs/prx/libSceAgcDriver/Submit/include/Dcb.hpp +++ b/core/libs/prx/libSceAgcDriver/Submit/include/Dcb.hpp @@ -5,5 +5,7 @@ extern "C" int APS5_VABI sceAgcDriverSubmitDcb(const Packet* packet); extern "C" int APS5_VABI sceAgcDriverAgrSubmitDcb(const Packet* packet); +extern "C" int APS5_VABI sceAgcDriverSubmitMultiDcbs(std::uint32_t* const* dcbGpuAddrs, const std::uint32_t* dcbSizesInDwords, std::uint32_t count); +extern "C" int APS5_VABI sceAgcDriverAgrSubmitMultiDcbs(std::uint32_t* const* dcbGpuAddrs, const std::uint32_t* dcbSizesInDwords, std::uint32_t count); #endif diff --git a/core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp b/core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp index 48da441e6..6ced7913b 100644 --- a/core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp +++ b/core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp @@ -10,6 +10,18 @@ #include "SceTypes.hpp" #include "prx/libc/include/General.hpp" +static int SubmitMany(std::uint32_t* const* addresses, const std::uint32_t* sizes, std::uint32_t count) { + if (count == 0) return 0; + if (!addresses || !sizes) throw std::runtime_error("AGC driver: null multi-DCB arrays"); + AgcDriver::GuestMemory::CheckRange(addresses, count * sizeof(*addresses), alignof(std::uint32_t*)); + AgcDriver::GuestMemory::CheckRange(sizes, count * sizeof(*sizes), alignof(std::uint32_t)); + for (std::uint32_t i = 0; i < count; ++i) { + const Packet packet{addresses[i], sizes[i], 0, {}}; + AgcDriver::Submit(&packet, 0); + } + return 0; +} + extern "C" { std::uint32_t APS5_VABI sceAgcDriverGetWaitRenderingPacketSizeInDwords() { @@ -33,12 +45,8 @@ int APS5_VABI sceAgcDriverSubmitDcb(const Packet* packet) { return 0; } -int APS5_VABI sceAgcDriverSubmitMultiDcbs(uint32_t* const* dcb_gpu_addrs, const uint32_t* dcb_sizes_in_dwords, uint32_t count) { - (void)dcb_gpu_addrs; - (void)dcb_sizes_in_dwords; - (void)count; - NotImplemented_nid_no_patch(__func__); - return 0; +int APS5_VABI sceAgcDriverSubmitMultiDcbs(std::uint32_t* const* dcbGpuAddrs, const std::uint32_t* dcbSizesInDwords, std::uint32_t count) { + return SubmitMany(dcbGpuAddrs, dcbSizesInDwords, count); } int APS5_VABI sceAgcDriverAgrSubmitDcb(const Packet* packet) { @@ -47,11 +55,7 @@ int APS5_VABI sceAgcDriverAgrSubmitDcb(const Packet* packet) { } int APS5_VABI sceAgcDriverAgrSubmitMultiDcbs(std::uint32_t* const* dcbGpuAddrs, const std::uint32_t* dcbSizesInDwords, std::uint32_t count) { - (void)dcbGpuAddrs; - (void)dcbSizesInDwords; - (void)count; - NotImplemented_nid_no_patch(__func__); - return 0; + return SubmitMany(dcbGpuAddrs, dcbSizesInDwords, count); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/Submit.cpp b/core/libs/prx/libSceAgcDriver/tests/Submit.cpp index e2b8d991f..50071e742 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Submit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Submit.cpp @@ -342,6 +342,33 @@ void testWaitFreeSubmissionTheCpuWaitsFor() { AgcDriverWaitIdle_nid_postfix(); } +void testMultiSubmissions() { + alignas(64) static volatile std::uint32_t value = 0, done = 0; + check(sceAgcDriverSubmitMultiDcbs(nullptr, nullptr, 0) == 0, "empty multi-DCB submit failed"); + check(sceAgcDriverAgrSubmitMultiDcbs(nullptr, nullptr, 0) == 0, "empty AGR multi-DCB submit failed"); + std::array invalid{0xc0017600, 0x20c, 0}; + std::array invalidAddresses{invalid.data()}; + std::array invalidSizes{2}; + expectFailure([&] { sceAgcDriverSubmitMultiDcbs(nullptr, invalidSizes.data(), 1); }); + expectFailure([&] { sceAgcDriverAgrSubmitMultiDcbs(invalidAddresses.data(), nullptr, 1); }); + expectFailure([&] { sceAgcDriverSubmitMultiDcbs(invalidAddresses.data(), invalidSizes.data(), 1); }); + expectFailure([&] { sceAgcDriverAgrSubmitMultiDcbs(invalidAddresses.data(), invalidSizes.data(), 1); }); + for (bool agr : {false, true}) { + value = 0; + done = 0; + auto first = writeData(&value, 1); + auto second = writeData(&value, 2); + auto third = writeData(&done, 1); + std::array addresses{first.data(), second.data(), third.data()}; + std::array sizes{static_cast(first.size()), static_cast(second.size()), static_cast(third.size())}; + const int result = agr ? sceAgcDriverAgrSubmitMultiDcbs(addresses.data(), sizes.data(), 3) : sceAgcDriverSubmitMultiDcbs(addresses.data(), sizes.data(), 3); + check(result == 0, "multi-DCB submit failed"); + waitFor(&done, 1, "the last DCB of a multi-DCB submit never ran"); + check(value == 2, "multi-DCB submit did not run its DCBs in order"); + AgcDriverWaitIdle_nid_postfix(); + } +} + void testWorkerFailure() { std::array words{0xc0031500, 1, 1, 1, 0x41}; Packet packet{words.data(), static_cast(words.size()), 0, {}}; @@ -375,6 +402,7 @@ int main() { testWaitFreeSubmissionQueue0WaitsOn(); testWaitFreeSubmissionBehindHeldOne(); testWaitFreeSubmissionTheCpuWaitsFor(); + testMultiSubmissions(); testWorkerFailure(); check(expectFailure([] { LibcRunShutdown_nid_postfix(); }).find("required shader register") != std::string::npos, "shutdown lost worker failure"); std::puts("AGC driver submit tests passed"); From 8e96e48fbd225a163ee90a81cce70504c5da6174 Mon Sep 17 00:00:00 2001 From: Merijn Date: Mon, 5 Oct 2026 18:50:25 +0200 Subject: [PATCH 03/42] fix(libkernel): report reserved virtual ranges in sceKernelVirtualQuery A range reserved with sceKernelReserveVirtualRange is registered as not readable, and sceKernelVirtualQuery only searched readable registrations, so a query inside a reservation fell back to the host and returned EACCES. Reserved ranges are now tracked until a direct or flexible mapping or an unmap covers them, and a query inside one succeeds with the reserved piece as its extent, protection 0 and is_committed clear. PPSA12544's allocator queries a reservation before committing it and treated the error as a failed commit, then wrote to the inaccessible range. Co-Authored-By: Claude Opus 5.5 --- .../libkernel/DirectMemory/DirectMemory.cpp | 48 ++++++++++++++++++- .../libkernel/DirectMemory/DirectMemory.hpp | 1 + .../prx/libkernel/DirectMemory/Export.cpp | 7 +++ core/libs/tests/GuestMemory.cpp | 29 ++++++++++- 4 files changed, 83 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp index 25147d08a..fc2285a5b 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp @@ -490,6 +490,31 @@ void EraseProtections(std::uintptr_t start, std::uintptr_t end) { } } +std::mutex g_reservationLock; +std::map g_reservations; + +void EraseReservations(const void* addr, size_t len) { + const auto start = reinterpret_cast(addr); + const auto end = start + len; + std::lock_guard lock(g_reservationLock); + auto it = g_reservations.lower_bound(start); + if (it != g_reservations.begin() && std::prev(it)->second > start) --it; + while (it != g_reservations.end() && it->first < end) { + const auto rangeStart = it->first; + const auto rangeEnd = it->second; + it = g_reservations.erase(it); + if (rangeStart < start) g_reservations.emplace(rangeStart, start); + if (rangeEnd > end) it = g_reservations.emplace(end, rangeEnd).first; + } +} + +void RecordReservation(const void* addr, size_t len) { + EraseReservations(addr, len); + const auto start = reinterpret_cast(addr); + std::lock_guard lock(g_reservationLock); + g_reservations.emplace(start, start + len); +} + void RecordProtection(const void* addr, size_t len, int prot) { const auto start = reinterpret_cast(addr); std::lock_guard lock(g_protectionLock); @@ -522,6 +547,7 @@ int DoMapDirect(void** addr, size_t len, int prot, int flags, int64_t physStart, } GuestAllocations::Mutation mutation; if (RemapFixedIntoRegistered(mutation, *addr, len, prot, flags, physStart)) { + EraseReservations(*addr, len); RecordProtection(*addr, len, prot); return 0; } @@ -538,6 +564,7 @@ int DoMapDirect(void** addr, size_t len, int prot, int flags, int64_t physStart, throw; } *addr = mapped; + EraseReservations(mapped, len); RecordProtection(mapped, len, prot); Trace("map direct %p+0x%zx phys=0x%llx prot=0x%x flags=0x%x align=0x%zx", mapped, len, static_cast(physStart), prot, flags, alignment); return 0; @@ -548,6 +575,7 @@ int DoMapAnon(void** addr, size_t len, int prot, int flags) { if (len == 0 || (len & (PS5_PAGE_SIZE - 1)) != 0) return SCE_KERNEL_ERROR_EINVAL; GuestAllocations::Mutation mutation; if (RemapFixedIntoRegistered(mutation, *addr, len, prot, flags)) { + EraseReservations(*addr, len); RecordProtection(*addr, len, prot); return 0; } @@ -560,6 +588,7 @@ int DoMapAnon(void** addr, size_t len, int prot, int flags) { throw; } *addr = mapped; + EraseReservations(mapped, len); RecordProtection(mapped, len, prot); Trace("map anon %p+0x%zx prot=0x%x flags=0x%x", mapped, len, prot, flags); return 0; @@ -610,6 +639,7 @@ int DoMunmap(void* addr, size_t len) { else munmap(pieceAddress, pieceBytes); #endif }); + EraseReservations(addr, len); RecordProtection(addr, len, -1); return 0; } @@ -621,7 +651,11 @@ int DoReserveVirtual(void** addr, size_t len, int flags, size_t alignment) { const bool fixed = *addr != nullptr && (flags & GuestMapFixedFlag) != 0; if (fixed && mutation.Covers(*addr, len)) { constexpr int GuestMapNoOverwrite = 0x80; - if ((flags & GuestMapNoOverwrite) == 0 && RemapFixedIntoRegistered(mutation, *addr, len, 0, GuestMapFixedFlag)) return 0; + if ((flags & GuestMapNoOverwrite) == 0 && RemapFixedIntoRegistered(mutation, *addr, len, 0, GuestMapFixedFlag)) { + RecordProtection(*addr, len, -1); + RecordReservation(*addr, len); + return 0; + } mutation.RequireAvailable(*addr, len); } if (fixed) mutation.RequireAvailable(*addr, len); @@ -634,6 +668,7 @@ int DoReserveVirtual(void** addr, size_t len, int flags, size_t alignment) { throw; } *addr = mapped; + RecordReservation(mapped, len); Trace("reserve %p+0x%zx flags=0x%x align=0x%zx", mapped, len, flags, alignment); return 0; } @@ -659,6 +694,17 @@ void ForgetDirectMemory(int64_t start, size_t len) { Trace("release physical 0x%llx+0x%zx", static_cast(first), len); } +bool GuestReservation(std::uintptr_t addr, std::uintptr_t* start, std::uintptr_t* end) { + std::lock_guard lock(g_reservationLock); + const auto next = g_reservations.upper_bound(addr); + if (next == g_reservations.begin()) return false; + const auto containing = std::prev(next); + if (addr >= containing->second) return false; + *start = containing->first; + *end = containing->second; + return true; +} + bool GuestProtection(uintptr_t addr, int* prot) { std::lock_guard lock(g_protectionLock); auto next = g_protections.upper_bound(addr); diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp index badcadce6..3ea3a950b 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp @@ -22,5 +22,6 @@ int DoMprotect(const void* addr, size_t len, int prot); int DoMunmap(void* addr, size_t len); int DoReserveVirtual(void** addr, size_t len, int flags, size_t alignment); bool GuestProtection(uintptr_t addr, int* prot); +bool GuestReservation(std::uintptr_t addr, std::uintptr_t* start, std::uintptr_t* end); #endif \ No newline at end of file diff --git a/core/libs/prx/libkernel/DirectMemory/Export.cpp b/core/libs/prx/libkernel/DirectMemory/Export.cpp index 373de6c2a..622f21cc3 100644 --- a/core/libs/prx/libkernel/DirectMemory/Export.cpp +++ b/core/libs/prx/libkernel/DirectMemory/Export.cpp @@ -212,6 +212,13 @@ int APS5_VABI sceKernelVirtualQuery(const void* addr, int flags, VirtualQueryInf // mapping at or above it: titles walk their mappings and check that a mapping covers a whole // allocation, so the answer must be the registered allocation, not a page. constexpr int findNext = 1; + std::uintptr_t reservedStart = 0; + std::uintptr_t reservedEnd = 0; + if (GuestReservation(address, &reservedStart, &reservedEnd)) { + info->start = reservedStart; + info->end = reservedEnd; + return 0; + } const auto lease = GuestAllocations::GuestAllocationsAcquire_nid_postfix(); const GuestAllocations::Range* best = nullptr; for (const auto& range : lease) { diff --git a/core/libs/tests/GuestMemory.cpp b/core/libs/tests/GuestMemory.cpp index 4b6c3cbcd..908edab23 100644 --- a/core/libs/tests/GuestMemory.cpp +++ b/core/libs/tests/GuestMemory.cpp @@ -193,7 +193,8 @@ static void CheckFixedVirtualReservation() { Require(sceKernelReserveVirtualRange(&reserved, page * 2, 0x10, 0) == 0); Require(reserved == requested); VirtualQueryInfo after{}; - Require(sceKernelVirtualQuery(reserved, 0, &after, sizeof(after)) != 0); + Require(sceKernelVirtualQuery(reserved, 0, &after, sizeof(after)) == 0); + Require(!after.is_committed && !after.is_direct && after.protection == 0); void* remapped = requested; Require(sceKernelMapDirectMemory(&remapped, page * 2, 3, 0x10, phys, 0) == 0); Require(remapped == requested); @@ -215,6 +216,31 @@ static void CheckFixedVirtualReservation() { Require(sceKernelMunmap(pooled, page * 2) == 0); } +static void CheckReservedRangeIsNotCommitted() { + constexpr std::size_t page = 0x4000; + void* reserved = nullptr; + Require(sceKernelReserveVirtualRange(&reserved, page * 2, 0, 0) == 0); + const auto start = reinterpret_cast(reserved); + VirtualQueryInfo info{}; + Require(sceKernelVirtualQuery(reserved, 0, &info, sizeof(info)) == 0); + Require(!info.is_committed && !info.is_direct && !info.is_flexible && info.protection == 0); + Require(info.start == start && info.end == start + page * 2); + std::int64_t phys = 0; + Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, page, 0, 0, &phys) == 0); + void* fixed = reserved; + Require(sceKernelMapDirectMemory(&fixed, page, 3, 0x10, phys, 0) == 0); + Require(fixed == reserved); + static_cast(fixed)[0] = 7; + Require(sceKernelVirtualQuery(reserved, 0, &info, sizeof(info)) == 0); + Require(info.is_committed && info.is_direct && info.protection == 3); + Require(info.start == start && info.end == start + page); + Require(sceKernelVirtualQuery(static_cast(reserved) + page, 0, &info, sizeof(info)) == 0); + Require(!info.is_committed && info.protection == 0); + Require(info.start == start + page && info.end == start + page * 2); + Require(sceKernelMunmap(reserved, page * 2) == 0); + Require(sceKernelReleaseDirectMemory(phys, page) == 0); +} + #ifdef _WIN32 static void CheckNoOverwriteRejectsHostOccupiedMapping() { constexpr std::size_t page = 0x4000; @@ -669,6 +695,7 @@ int main() { CheckInternalNamedFlexibleMapping(); CheckDirectMemoryFollowsPhysicalPages(); CheckFixedVirtualReservation(); + CheckReservedRangeIsNotCommitted(); CheckMlock(); CheckSharedDirectMemoryLifecycle(); CheckHeapAfterMappingReuse(); From 65e5c9932c155ba56e31cc437f86f77629c5ae0c Mon Sep 17 00:00:00 2001 From: Merijn Date: Mon, 5 Oct 2026 19:20:43 +0200 Subject: [PATCH 04/42] feat(libkernel): implement sceKernelCheckedReleaseDirectMemory Release direct memory only when the whole range is allocated: a misaligned start or length returns EINVAL, a zero length succeeds, and a range that leaves direct memory or covers an unallocated page returns ENOENT without releasing anything, as in shadPS4. The check and the release run under the pool lock. Co-Authored-By: Claude Opus 5.5 --- .../libkernel/DirectMemory/DirectMemory.hpp | 1 + .../prx/libkernel/DirectMemory/Export.cpp | 7 ++-- .../prx/libkernel/DirectMemory/MemoryPool.cpp | 42 +++++++++++++------ core/libs/tests/GuestMemory.cpp | 19 +++++++++ 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp index badcadce6..2fd79f093 100644 --- a/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp +++ b/core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp @@ -11,6 +11,7 @@ static constexpr size_t PS5_PAGE_SIZE = 0x4000; int DirectMemoryAlloc(int64_t searchStart, int64_t searchEnd, size_t len, size_t alignment, int memoryType, int64_t* physOut); void DirectMemoryFree(int64_t start, size_t len); +bool DirectMemoryCheckedFree(int64_t start, size_t len); void CreateDirectMemoryBacking(int64_t start, size_t len, int memoryType); bool QueryDirectMapping(std::uintptr_t address, std::uintptr_t* start, std::uintptr_t* end, std::uint64_t* offset, int* memoryType); void ForgetDirectMemory(int64_t start, size_t len); diff --git a/core/libs/prx/libkernel/DirectMemory/Export.cpp b/core/libs/prx/libkernel/DirectMemory/Export.cpp index 373de6c2a..949b039b5 100644 --- a/core/libs/prx/libkernel/DirectMemory/Export.cpp +++ b/core/libs/prx/libkernel/DirectMemory/Export.cpp @@ -284,10 +284,9 @@ int APS5_VABI sceKernelVirtualQuery(const void* addr, int flags, VirtualQueryInf // --------------------------------------------------------------------------- int APS5_VABI sceKernelCheckedReleaseDirectMemory(int64_t start, size_t len) { - (void)start; - (void)len; - NotImplemented_nid_no_patch(__func__); - return 0; + if (start < 0 || (static_cast(start) & (PS5_PAGE_SIZE - 1)) != 0 || (len & (PS5_PAGE_SIZE - 1)) != 0) return SCE_KERNEL_ERROR_EINVAL; + if (len == 0) return 0; + return DirectMemoryCheckedFree(start, len) ? 0 : SCE_KERNEL_ERROR_ENOENT; } int APS5_VABI sceKernelMtypeprotect(const void* addr, size_t len, int type, int prot) { diff --git a/core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp b/core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp index 1175ada11..b1e04c262 100644 --- a/core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp +++ b/core/libs/prx/libkernel/DirectMemory/MemoryPool.cpp @@ -32,18 +32,17 @@ struct PhysicalMemoryPool { void Free(uint64_t start, size_t len) { std::lock_guard lock(_mutex); - ForgetDirectMemory(static_cast(start), len); - _mark(start, len, false); - const uint64_t end = start + len; - auto it = _blocks.upper_bound(start); - if (it != _blocks.begin() && std::prev(it)->second.end > start) --it; - while (it != _blocks.end() && it->first < end) { - const uint64_t blockStart = it->first; - const Block block = it->second; - it = _blocks.erase(it); - if (blockStart < start) _blocks[blockStart] = {start, block.type}; - if (block.end > end) it = _blocks.emplace(end, Block{block.end, block.type}).first; - } + _free(start, len); + } + + bool CheckedFree(uint64_t start, size_t len) { + std::lock_guard lock(_mutex); + if (start > DIRECT_MEMORY_SIZE || len > DIRECT_MEMORY_SIZE - start) return false; + const size_t first = start / PS5_PAGE_SIZE; + for (size_t i = 0; i < len / PS5_PAGE_SIZE; ++i) + if (!_used[first + i]) return false; + _free(start, len); + return true; } bool Find(uint64_t offset, bool findNext, int64_t* start, int64_t* end, int* memoryType) { @@ -70,6 +69,21 @@ struct PhysicalMemoryPool { } private: + void _free(uint64_t start, size_t len) { + ForgetDirectMemory(static_cast(start), len); + _mark(start, len, false); + const uint64_t end = start + len; + auto it = _blocks.upper_bound(start); + if (it != _blocks.begin() && std::prev(it)->second.end > start) --it; + while (it != _blocks.end() && it->first < end) { + const uint64_t blockStart = it->first; + const Block block = it->second; + it = _blocks.erase(it); + if (blockStart < start) _blocks[blockStart] = {start, block.type}; + if (block.end > end) it = _blocks.emplace(end, Block{block.end, block.type}).first; + } + } + bool _isFree(uint64_t offset, size_t len) const { size_t first = offset / PS5_PAGE_SIZE; size_t count = len / PS5_PAGE_SIZE; @@ -103,6 +117,10 @@ void DirectMemoryFree(int64_t start, size_t len) { PhysicalMemoryPool::Instance().Free(static_cast(start), len); } +bool DirectMemoryCheckedFree(int64_t start, size_t len) { + return PhysicalMemoryPool::Instance().CheckedFree(static_cast(start), len); +} + bool DirectMemoryFind(int64_t offset, bool findNext, int64_t* start, int64_t* end, int* memoryType) { return PhysicalMemoryPool::Instance().Find(static_cast(offset), findNext, start, end, memoryType); } diff --git a/core/libs/tests/GuestMemory.cpp b/core/libs/tests/GuestMemory.cpp index 4b6c3cbcd..4057e22ca 100644 --- a/core/libs/tests/GuestMemory.cpp +++ b/core/libs/tests/GuestMemory.cpp @@ -48,6 +48,7 @@ int APS5_VABI sceKernelClearVirtualRangeName(const void*, std::uint64_t); int APS5_VABI sceKernelAllocateDirectMemory(std::int64_t, std::int64_t, std::size_t, std::size_t, int, std::int64_t*); int APS5_VABI sceKernelMapDirectMemory(void**, std::size_t, int, int, std::int64_t, std::size_t); int APS5_VABI sceKernelReleaseDirectMemory(std::int64_t, std::size_t); +int APS5_VABI sceKernelCheckedReleaseDirectMemory(std::int64_t, std::size_t); int APS5_VABI sceKernelReserveVirtualRange(void**, std::size_t, int, std::size_t); int APS5_VABI sceKernelMemoryPoolReserve(void*, std::size_t, std::size_t, int, void**); int APS5_VABI sceKernelOpen(const char*, int, std::uint16_t); @@ -121,6 +122,23 @@ static void CheckInternalNamedFlexibleMapping() { Require(sceKernelAvailableFlexibleMemorySize(&available) == 0 && available == before); } +static void CheckCheckedReleaseDirectMemory() { + constexpr std::size_t page = 0x4000; + std::int64_t phys = 0; + Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, page * 2, 0, 0, &phys) == 0); + Require(sceKernelCheckedReleaseDirectMemory(phys + 1, page) == SCE_KERNEL_ERROR_EINVAL); + Require(sceKernelCheckedReleaseDirectMemory(phys, page + 1) == SCE_KERNEL_ERROR_EINVAL); + Require(sceKernelCheckedReleaseDirectMemory(phys, 0) == 0); + Require(sceKernelCheckedReleaseDirectMemory(phys, page * 3) == SCE_KERNEL_ERROR_ENOENT); + void* mapped = nullptr; + Require(sceKernelMapDirectMemory(&mapped, page * 2, 3, 0, phys, 0) == 0); + Require(sceKernelMunmap(mapped, page * 2) == 0); + Require(sceKernelCheckedReleaseDirectMemory(phys + page, page) == 0); + Require(sceKernelCheckedReleaseDirectMemory(phys, page * 2) == SCE_KERNEL_ERROR_ENOENT); + Require(sceKernelCheckedReleaseDirectMemory(phys, page) == 0); + Require(sceKernelCheckedReleaseDirectMemory(phys, page) == SCE_KERNEL_ERROR_ENOENT); +} + static void CheckDirectMemoryFollowsPhysicalPages() { constexpr std::size_t page = 0x4000; std::int64_t phys = 0; @@ -667,6 +685,7 @@ static void CheckDirectMemoryWriteWatch() { int main() { CheckNamedAndHintedMappings(); CheckInternalNamedFlexibleMapping(); + CheckCheckedReleaseDirectMemory(); CheckDirectMemoryFollowsPhysicalPages(); CheckFixedVirtualReservation(); CheckMlock(); From ba8c8c4b05d262951a2c1eb4141258ce8196bdb1 Mon Sep 17 00:00:00 2001 From: alfalfa-star Date: Mon, 5 Oct 2026 19:55:15 +0200 Subject: [PATCH 05/42] feat(libkernel): implement sceKernelGetModuleInfoFromAddr A title's libc.prx calls it from __cxa_thread_atexit with flags 2 and stores the returned module id in the destructor record. The 0x1A8-byte info reports the name, id, TLS block, init and fini procedures, eh_frame_hdr and eh_frame, and up to four load segments of the image containing the address. The id is the loader handle when the image was opened through sceKernelLoadStartModule and otherwise a stable id from the same range. Unknown flags and st_size values throw. Co-Authored-By: Claude Opus 5.5 --- core/libs/SceTypes.hpp | 36 +++- core/libs/prx/libkernel/CMakeLists.txt | 10 + .../libkernel/Module/src/DynamicLoader.cpp | 10 + core/libs/prx/libkernel/Module/src/Module.cpp | 8 - .../prx/libkernel/Module/src/ModuleInfo.cpp | 186 ++++++++++++++++++ core/libs/tests/GuestModuleInfo.cpp | 64 ++++++ docs/dev/TechnicalDebt.md | 1 + 7 files changed, 302 insertions(+), 13 deletions(-) create mode 100644 core/libs/prx/libkernel/Module/src/ModuleInfo.cpp create mode 100644 core/libs/tests/GuestModuleInfo.cpp diff --git a/core/libs/SceTypes.hpp b/core/libs/SceTypes.hpp index f58476bec..84a48a94f 100644 --- a/core/libs/SceTypes.hpp +++ b/core/libs/SceTypes.hpp @@ -199,13 +199,39 @@ struct FileStat { KernelTimespec st_birthtim; }; -struct ModuleInfo { - std::uint64_t size; - std::uint64_t info[32]; - KernelModule handle; - std::uint8_t pad[156]; +struct ModuleSegmentInfo { + std::uint64_t address; + std::uint32_t size; + std::int32_t prot; }; +struct ModuleInfoEx { + std::uint64_t st_size; + char name[256]; + KernelModule id; + std::uint32_t tls_index; + std::uint64_t tls_init_addr; + std::uint32_t tls_init_size; + std::uint32_t tls_size; + std::uint32_t tls_offset; + std::uint32_t tls_align; + std::uint64_t init_proc_addr; + std::uint64_t fini_proc_addr; + std::uint64_t reserved1; + std::uint64_t reserved2; + std::uint64_t eh_frame_hdr_addr; + std::uint64_t eh_frame_addr; + std::uint32_t eh_frame_hdr_size; + std::uint32_t eh_frame_size; + ModuleSegmentInfo segments[4]; + std::uint32_t segment_count; + std::uint32_t ref_count; +}; +static_assert(offsetof(ModuleInfoEx, id) == 0x108); +static_assert(offsetof(ModuleInfoEx, eh_frame_hdr_addr) == 0x148); +static_assert(offsetof(ModuleInfoEx, segments) == 0x160); +static_assert(sizeof(ModuleInfoEx) == 0x1A8); + struct ModuleInfoForUnwind { std::uint64_t st_size; char name[256]; diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 2e5364b1b..fdc0e284a 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -36,6 +36,7 @@ add_library(libkernel SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/EventFlag/src/EventFlag.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Module/src/Module.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Module/src/DynamicLoader.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Module/src/ModuleInfo.cpp ${LIBS_INCLUDE_DIR}/nid/src/NidCompute.cpp ${LIBS_INCLUDE_DIR}/nid/src/Sha1.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Aio/src/Aio.cpp @@ -98,6 +99,15 @@ if(BUILD_TESTING) set_tests_properties(guest_dynamic_loader PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + if(NOT WIN32) + add_test_executable(guest_module_info_tests ${LIBS_INCLUDE_DIR}/tests/GuestModuleInfo.cpp) + target_include_directories(guest_module_info_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_module_info_tests PRIVATE libkernel libc) + add_dependencies(guest_module_info_tests guest_module_fixture) + add_test(NAME guest_module_info COMMAND guest_module_info_tests $) + set_tests_properties(guest_module_info PROPERTIES + WORKING_DIRECTORY "$") + endif() add_test_executable(guest_filesystem_tests ${LIBS_INCLUDE_DIR}/tests/GuestFilesystem.cpp) target_include_directories(guest_filesystem_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_filesystem_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp b/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp index e1091def8..b85934bb8 100644 --- a/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp +++ b/core/libs/prx/libkernel/Module/src/DynamicLoader.cpp @@ -37,6 +37,7 @@ struct Module { std::mutex modulesMutex; std::map> modules; std::uintptr_t nextHandle = 0x20000000; +std::map imageIds; void* Symbol(Module& module, const char* name) { #ifdef _WIN32 return reinterpret_cast(GetProcAddress(static_cast(module.native), name)); @@ -123,4 +124,13 @@ int APS5_VABI dlclose_nid_postfix(void* handle) { module.reset(); return 0; } +std::int32_t ModuleIdForImage_nid_no_patch(const void* native) { + std::lock_guard lock(modulesMutex); + for (const auto& [handle, module] : modules) { + if (module->native == native) return static_cast(handle); + } + const auto [found, inserted] = imageIds.emplace(native, nextHandle); + if (inserted) ++nextHandle; + return static_cast(found->second); +} } diff --git a/core/libs/prx/libkernel/Module/src/Module.cpp b/core/libs/prx/libkernel/Module/src/Module.cpp index 3e5ba3656..1d52dc2ea 100644 --- a/core/libs/prx/libkernel/Module/src/Module.cpp +++ b/core/libs/prx/libkernel/Module/src/Module.cpp @@ -84,14 +84,6 @@ int APS5_VABI sceKernelGetModuleInfoForUnwind(uint64_t addr, int flags, ModuleIn #endif } -int APS5_VABI sceKernelGetModuleInfoFromAddr(uint64_t addr, int n, ModuleInfo* r) { - (void)addr; - (void)n; - (void)r; - NotImplemented_nid_no_patch(__func__); - return 0; -} - KernelModule APS5_VABI sceKernelLoadStartModule(const char* module_file_name, size_t args, const void* argp, uint32_t flags, const KernelLoadModuleOpt* opt, int* res) { (void)args; (void)argp; diff --git a/core/libs/prx/libkernel/Module/src/ModuleInfo.cpp b/core/libs/prx/libkernel/Module/src/ModuleInfo.cpp new file mode 100644 index 000000000..926f25ae5 --- /dev/null +++ b/core/libs/prx/libkernel/Module/src/ModuleInfo.cpp @@ -0,0 +1,186 @@ +#include +#include +#include +#include +#include +#include +#include +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libkernel/KernelErrors.hpp" +#ifndef _WIN32 +#include +#include +#include +#endif + +extern "C" std::int32_t ModuleIdForImage_nid_no_patch(const void* native); + +namespace { + +#ifndef _WIN32 +constexpr char GuestModuleSuffix[] = ".guest.prx"; +constexpr std::int32_t ProtRead = 1; +constexpr std::int32_t ProtWrite = 2; +constexpr std::int32_t ProtExecute = 4; + +struct ImageSearch { + std::uintptr_t address; + ModuleInfoEx* info; + bool found; +}; + +bool Contains(const dl_phdr_info& image, std::uintptr_t begin, std::uint64_t size) { + for (std::uint16_t i = 0; i < image.dlpi_phnum; ++i) { + const auto& header = image.dlpi_phdr[i]; + if (header.p_type != PT_LOAD) continue; + const std::uintptr_t start = image.dlpi_addr + header.p_vaddr; + if (begin >= start && begin - start <= header.p_memsz && size <= header.p_memsz - (begin - start)) return true; + } + return false; +} + +std::uint32_t ToU32(std::uint64_t value, const char* field) { + if (value > std::numeric_limits::max()) + throw std::runtime_error(std::string("sceKernelGetModuleInfoFromAddr: ") + field + " exceeds 32 bits"); + return static_cast(value); +} + +std::uintptr_t EhFrameAddress(const dl_phdr_info& image, std::uintptr_t header) { + if (!Contains(image, header, 8)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame_hdr outside the image"); + const auto* bytes = reinterpret_cast(header); + if (bytes[0] != 1) throw std::runtime_error("sceKernelGetModuleInfoFromAddr: unsupported eh_frame_hdr version"); + const std::uintptr_t field = header + 4; + switch (bytes[1]) { + case 0x1b: { + std::int32_t offset; + std::memcpy(&offset, bytes + 4, sizeof(offset)); + return field + static_cast(offset); + } + case 0x03: { + std::uint32_t value; + std::memcpy(&value, bytes + 4, sizeof(value)); + return value; + } + case 0x00: { + std::uint64_t value; + if (!Contains(image, header, 12)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame_hdr outside the image"); + std::memcpy(&value, bytes + 4, sizeof(value)); + return static_cast(value); + } + default: + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: unsupported eh_frame_ptr encoding"); + } +} + +std::uint64_t EhFrameSize(const dl_phdr_info& image, std::uintptr_t frame) { + std::uintptr_t position = frame; + for (;;) { + if (!Contains(image, position, 4)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame outside the image"); + std::uint32_t length; + std::memcpy(&length, reinterpret_cast(position), sizeof(length)); + position += 4; + if (length == 0) return position - frame; + std::uint64_t recordLength = length; + if (length == 0xffffffffu) { + if (!Contains(image, position, 8)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame outside the image"); + std::memcpy(&recordLength, reinterpret_cast(position), sizeof(recordLength)); + position += 8; + } + if (!Contains(image, position, recordLength)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: eh_frame record outside the image"); + position += recordLength; + } +} + +std::string ImageName(const dl_phdr_info& image) { + std::string path = image.dlpi_name ? image.dlpi_name : ""; + if (path.empty()) { + char executable[4096]; + const auto length = ::readlink("/proc/self/exe", executable, sizeof(executable) - 1); + if (length < 0) throw std::runtime_error("sceKernelGetModuleInfoFromAddr: cannot resolve the executable path"); + path.assign(executable, static_cast(length)); + } + std::string name = path.substr(path.find_last_of('/') + 1); + if (name.size() > sizeof(GuestModuleSuffix) - 1 && name.ends_with(GuestModuleSuffix)) + name.resize(name.size() - (sizeof(GuestModuleSuffix) - 1)); + return name; +} + +void Fill(const dl_phdr_info& image, ModuleInfoEx& info) { + const auto name = ImageName(image); + if (name.size() >= sizeof(info.name)) + throw std::runtime_error("sceKernelGetModuleInfoFromAddr: module name too long: " + name); + std::memcpy(info.name, name.c_str(), name.size() + 1); + info.tls_index = ToU32(image.dlpi_tls_modid, "TLS module index"); + for (std::uint16_t i = 0; i < image.dlpi_phnum; ++i) { + const auto& header = image.dlpi_phdr[i]; + const std::uintptr_t address = image.dlpi_addr + header.p_vaddr; + if (header.p_type == PT_LOAD && info.segment_count < std::size(info.segments)) { + auto& segment = info.segments[info.segment_count++]; + segment.address = address; + segment.size = ToU32(header.p_memsz, "segment size"); + segment.prot = ((header.p_flags & PF_R) ? ProtRead : 0) | ((header.p_flags & PF_W) ? ProtWrite : 0) | ((header.p_flags & PF_X) ? ProtExecute : 0); + } else if (header.p_type == PT_TLS) { + info.tls_init_addr = address; + info.tls_init_size = ToU32(header.p_filesz, "TLS image size"); + info.tls_size = ToU32(header.p_memsz, "TLS size"); + info.tls_align = ToU32(header.p_align, "TLS alignment"); + } else if (header.p_type == PT_GNU_EH_FRAME) { + info.eh_frame_hdr_addr = address; + info.eh_frame_hdr_size = ToU32(header.p_memsz, "eh_frame_hdr size"); + info.eh_frame_addr = EhFrameAddress(image, address); + info.eh_frame_size = ToU32(EhFrameSize(image, info.eh_frame_addr), "eh_frame size"); + } else if (header.p_type == PT_DYNAMIC) { + for (const auto* entry = reinterpret_cast(address); entry->d_tag != DT_NULL; ++entry) { + if (entry->d_tag == DT_INIT) info.init_proc_addr = image.dlpi_addr + entry->d_un.d_ptr; + else if (entry->d_tag == DT_FINI) info.fini_proc_addr = image.dlpi_addr + entry->d_un.d_ptr; + } + } + } + info.ref_count = 1; +} + +int FindImage(dl_phdr_info* image, std::size_t, void* data) { + auto& search = *static_cast(data); + if (!Contains(*image, search.address, 1)) return 0; + Fill(*image, *search.info); + search.found = true; + return 1; +} +#endif + +} + +extern "C" { + +int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t address, int flags, ModuleInfoEx* info) { + if (!info) return SCE_KERNEL_ERROR_EFAULT; + if (flags != 2) throw std::invalid_argument("sceKernelGetModuleInfoFromAddr: unsupported flags " + std::to_string(flags)); + if (info->st_size != sizeof(ModuleInfoEx)) + throw std::invalid_argument("sceKernelGetModuleInfoFromAddr: unsupported st_size " + std::to_string(info->st_size)); +#ifdef _WIN32 + (void)address; + NotImplemented_nid_no_patch(__func__); + return 0; +#else + Dl_info symbol{}; + link_map* native = nullptr; + if (!dladdr1(reinterpret_cast(address), &symbol, reinterpret_cast(&native), RTLD_DL_LINKMAP) || !native) + return SCE_KERNEL_ERROR_ESRCH; + ModuleInfoEx result{}; + result.st_size = sizeof(ModuleInfoEx); + ImageSearch search{static_cast(address), &result, false}; + dl_iterate_phdr(FindImage, &search); + if (!search.found) return SCE_KERNEL_ERROR_ESRCH; + result.id = ModuleIdForImage_nid_no_patch(native); + *info = result; + return 0; +#endif +} + +} diff --git a/core/libs/tests/GuestModuleInfo.cpp b/core/libs/tests/GuestModuleInfo.cpp new file mode 100644 index 000000000..5921931c9 --- /dev/null +++ b/core/libs/tests/GuestModuleInfo.cpp @@ -0,0 +1,64 @@ +#include "SceTypes.hpp" +#include "prx/libkernel/KernelErrors.hpp" +#include +#include +#include +#include +#include +extern "C" { +void* APS5_VABI dlopen_nid_postfix(const char*, int); +void* APS5_VABI dlsym_nid_postfix(void*, const char*); +int APS5_VABI dlclose_nid_postfix(void*); +int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t, int, ModuleInfoEx*); +} +static void Require(bool value) { if (!value) std::abort(); } +template +static bool ThrowsInvalidArgument(TFunction function) { + try { + function(); + } catch (const std::invalid_argument&) { + return true; + } + return false; +} +static ModuleInfoEx Query(const void* address, int expected) { + ModuleInfoEx info{}; + info.st_size = sizeof(ModuleInfoEx); + Require(sceKernelGetModuleInfoFromAddr(reinterpret_cast(address), 2, &info) == expected); + return info; +} +int main(int argc, char** argv) { + Require(argc == 2); + void* module = dlopen_nid_postfix(argv[1], 2); + Require(module != nullptr); + const void* add = dlsym_nid_postfix(module, "GuestModuleAdd"); + Require(add != nullptr); + const auto info = Query(add, 0); + Require(info.st_size == sizeof(ModuleInfoEx)); + Require(info.id == static_cast(reinterpret_cast(module))); + Require(std::string(info.name) == std::string(argv[1]).substr(std::string(argv[1]).find_last_of("/\\") + 1)); + Require(info.segment_count > 0 && info.segment_count <= 4 && info.ref_count == 1); + bool executable = false; + for (std::uint32_t i = 0; i < info.segment_count; ++i) { + const auto& segment = info.segments[i]; + if (reinterpret_cast(add) >= segment.address && reinterpret_cast(add) - segment.address < segment.size) + executable = (segment.prot & 5) == 5; + } + Require(executable); + Require(info.eh_frame_hdr_addr != 0 && info.eh_frame_hdr_size != 0 && info.eh_frame_addr != 0 && info.eh_frame_size != 0); + Require(info.init_proc_addr == 0 || info.init_proc_addr >= info.segments[0].address); + const auto self = Query(reinterpret_cast(&Require), 0); + Require(self.id != info.id && Query(reinterpret_cast(&Query), 0).id == self.id); + void* second = dlopen_nid_postfix(argv[1], 2); + Require(second && Query(add, 0).id == info.id); + Require(dlclose_nid_postfix(second) == 0); + int local = 0; + Query(&local, SCE_KERNEL_ERROR_ESRCH); + Require(sceKernelGetModuleInfoFromAddr(reinterpret_cast(add), 2, nullptr) == SCE_KERNEL_ERROR_EFAULT); + ModuleInfoEx invalid{}; + invalid.st_size = sizeof(ModuleInfoEx); + Require(ThrowsInvalidArgument([&] { sceKernelGetModuleInfoFromAddr(reinterpret_cast(add), 1, &invalid); })); + invalid.st_size = sizeof(ModuleInfoEx) - 8; + Require(ThrowsInvalidArgument([&] { sceKernelGetModuleInfoFromAddr(reinterpret_cast(add), 2, &invalid); })); + Require(dlclose_nid_postfix(module) == 0); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 02ea84a84..6b7eee902 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -40,6 +40,7 @@ Throughout the project, every function at every stage either **does exactly what - [gQkqkLttcpw](../../core/libs/prx/libSceAgc/Acb/src/Control.cpp) (libSceAgc) - unknown name, signature - [sceAgcDcbPrimeUtcl2](../../core/libs/prx/libSceAgc/DcbState/src/Display.cpp) (libSceAgc) - assumed to write the packet `sceAgcAcbPrimeUtcl2` writes: PRIME_UTCL2 has the same 5 dwords on the graphics and compute rings. Not confirmed on a title. Both write a NOP of that size, as there is no TLB to prime - [sceKernelInternalMemoryGetModuleSegmentInfo](../../core/libs/prx/libkernel/Module/src/Module.cpp) (libkernel) - unknown signature +- [sceKernelGetModuleInfoFromAddr](../../core/libs/prx/libkernel/Module/src/ModuleInfo.cpp) (libkernel) - the 0x1A8-byte info layout follows the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation; a title's `libc.prx` reads only `id` (PPSA14632). The meaning of `flags` is unknown; only 2 is accepted, as is only the full `st_size`. The id is the `sceKernelLoadStartModule` handle of an image opened through the loader and otherwise a stable id from the same range. The name is the host file name without `.guest.prx`. An image with more than 4 load segments (the converted executable has 7) reports its first 4. `tls_offset` is 0 and `ref_count` is 1, as the host loader exposes neither. Not implemented on Windows - [sceKernelSyncOnAddressWait](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - the only known caller passes a null timeout and a name string as the fourth argument; the timeout is assumed to point to microseconds like the other kernel waits, and the name is ignored - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 unknown; only the sceKernelMapNamedFlexibleMemory flags are accepted - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature From b8e19367839ab79a384b1ce7525223a767d9095b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Mon, 5 Oct 2026 14:38:42 +0200 Subject: [PATCH 06/42] fix(shader): accept clamp and omod on every f16 VOP3 result op clamp (and omod, ignored while f16 denormals are enabled) were refused or dropped per op: v_{add,sub,subrev,mul,min,max}_f16, v_ldexp_f16, v_frexp_mant_f16, v_cvt_norm_{i,u}16_f16, v_{max3,min3,med3,div_fixup}_f16. They now share one clamp on the f16 bits (clampF16Bits). Co-Authored-By: Claude --- .../tests/execution/Float16Modifiers.cpp | 198 ++++++++++++++++++ .../tests/execution/Float16TernaryClamp.cpp | 181 ++++++++++++++++ .../RdnaDecoder/src/RdnaVectorOpDecoder.cpp | 24 ++- .../Translation/TranslationContext.hpp | 1 + .../Translation/src/FloatInstructions.cpp | 6 +- .../src/TranslationContext/OperandAccess.cpp | 10 + 6 files changed, 413 insertions(+), 7 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/Float16Modifiers.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/Float16TernaryClamp.cpp diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/Float16Modifiers.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/Float16Modifiers.cpp new file mode 100644 index 000000000..c53d40431 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/Float16Modifiers.cpp @@ -0,0 +1,198 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 32; +constexpr std::uint32_t Inputs = 4; +constexpr std::uint32_t Results = 16; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; + +alignas(256) constexpr std::array Code{ + 0x34020084, 0x34060086, 0xe0381000, 0x80000401, 0xbf8c3f70, 0x7e140280, 0x7e160280, 0x7e180280, + 0x7e1a0280, 0x7e1c0280, 0x7e1e0280, 0x7e200280, 0x7e220280, 0x7e240280, 0x7e260280, 0x7e280280, + 0x7e2a0280, 0x7e2c0280, 0x7e2e0280, 0x7e300280, 0x7e320280, 0xd532800a, 0x02020b04, 0xd532000b, + 0x0a020b04, 0xd533800c, 0x02020b04, 0xd534800d, 0x1a020b04, 0xd535800e, 0x02020b04, 0xd53a800f, + 0x02020b04, 0xd5390010, 0x12020b04, 0xd53b8011, 0x02020b04, 0xd53b0012, 0x0a020b04, 0xd5d98013, + 0x02010104, 0xd5e38014, 0x02010104, 0xd5e40015, 0x0a010104, 0xd7540016, 0x0c1a0b04, 0xd7578017, + 0x141a0b04, 0xd7510018, 0x1c1a0b04, 0xd74b0019, 0x0c1a0b04, 0xe0781000, 0x80010a03, 0xe0781010, + 0x80010e03, 0xe0781020, 0x80011203, 0xe0781030, 0x80011603, 0xbf810000, +}; + +constexpr std::uint32_t Rows[32][4] = { + {0x00000000u, 0x0000ec99u, 0x000073abu, 0x0000965eu}, + {0x0000c000u, 0x000079cbu, 0x0000cb00u, 0x00004400u}, + {0x000003ffu, 0x0000b555u, 0x0000e3efu, 0x00000ab8u}, + {0x0000656au, 0x0000a767u, 0x0000a66bu, 0x0000b800u}, + {0x00003e00u, 0x00000f3eu, 0x0000c000u, 0x00009980u}, + {0x00003800u, 0x0000fc00u, 0x000003ffu, 0x000084e5u}, + {0x0000fe00u, 0x00007bffu, 0x00003c01u, 0x00001400u}, + {0x00006822u, 0x0000fee5u, 0x0000154cu, 0x000050b6u}, + {0x0000834cu, 0x00004900u, 0x00003800u, 0x00006680u}, + {0x00008000u, 0x00004000u, 0x0000fe00u, 0x00007bffu}, + {0x000036a8u, 0x00008001u, 0x00007851u, 0x00000200u}, + {0x00006b77u, 0x00003bffu, 0x0000c74cu, 0x0000563eu}, + {0x00004400u, 0x00000002u, 0x0000c20eu, 0x00002274u}, + {0x0000c200u, 0x0000bc00u, 0x00007c00u, 0x00002d7cu}, + {0x0000303au, 0x00007e00u, 0x00000400u, 0x00002187u}, + {0x00000001u, 0x0000fbffu, 0x00004400u, 0x0000001eu}, + {0x0000b555u, 0x0000cdacu, 0x0000ff76u, 0x000035f1u}, + {0x00001400u, 0x00009a1du, 0x000019afu, 0x00007e00u}, + {0x00003c00u, 0x0000c000u, 0x00000001u, 0x0000d48du}, + {0x0000fc00u, 0x000003ffu, 0x0000b555u, 0x00003e36u}, + {0x00007bffu, 0x00003c01u, 0x00002091u, 0x00007bd5u}, + {0x000022bfu, 0x00002ecdu, 0x00004f91u, 0x0000d15bu}, + {0x0000b9b3u, 0x00003800u, 0x0000f0beu, 0x0000afddu}, + {0x0000e1d7u, 0x0000fe00u, 0x00007bffu, 0x00003c01u}, + {0x00008001u, 0x00004153u, 0x00000200u, 0x000041c9u}, + {0x00003bffu, 0x00007fb2u, 0x00004900u, 0x00003800u}, + {0x0000119bu, 0x00008000u, 0x00004000u, 0x00009da9u}, + {0x000047bcu, 0x00007c00u, 0x0000bfbdu, 0x00003555u}, + {0x00007e00u, 0x00000400u, 0x00003bffu, 0x0000d000u}, + {0x0000fbffu, 0x000021afu, 0x00000002u, 0x00008000u}, + {0x00005000u, 0x0000c200u, 0x0000859du, 0x000023edu}, + {0x0000ec70u, 0x0000b800u, 0x0000b372u, 0x00000400u} +}; +constexpr std::uint32_t Expected[32][16] = { + {0x00000000u, 0x0000ec99u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x000073abu, 0x00000000u, 0x0000ec99u, 0x000073abu}, + {0x00003c00u, 0x000079cbu, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x000079cbu, 0x00000000u, 0x0000fc00u, 0x00000000u, 0x00008001u, 0x00000000u, 0x000079cbu, 0x00000000u, 0x0000cb00u, 0x0000fc00u}, + {0x00000000u, 0x0000b555u, 0x00003555u, 0x00000000u, 0x00000000u, 0x00000000u, 0x000003ffu, 0x00000000u, 0x00000000u, 0x00003bfeu, 0x00000002u, 0x00000004u, 0x000003ffu, 0x00000000u, 0x0000e3efu, 0x0000e3efu}, + {0x00003c00u, 0x0000656au, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x0000656au, 0x00000000u, 0x00000000u, 0x0000396au, 0x00007fffu, 0x0000ffffu, 0x0000656au, 0x00000000u, 0x0000a767u, 0x0000d103u}, + {0x00003c00u, 0x00003e00u, 0x00003c00u, 0x00000000u, 0x0000116eu, 0x00000f3eu, 0x00003e00u, 0x00003c00u, 0x00007c00u, 0x00003a00u, 0x00007fffu, 0x0000ffffu, 0x00003e00u, 0x00000f3eu, 0x0000c000u, 0x0000bfffu}, + {0x00000000u, 0x0000fc00u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00004000u, 0x00008000u, 0x00003800u, 0x000003ffu, 0x0000fc00u, 0x0000fc00u}, + {0x00000000u, 0x0000fe00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00003c00u, 0x00007bffu, 0x00000000u, 0x0000fe00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00007bffu, 0x00003c00u, 0x00003c01u, 0x0000fe00u}, + {0x00000000u, 0x0000fee5u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00003c00u, 0x00006822u, 0x00000000u, 0x00000000u, 0x00003822u, 0x00007fffu, 0x0000ffffu, 0x00006822u, 0x0000154cu, 0x0000154cu, 0x0000fee5u}, + {0x00003c00u, 0x00004900u, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00004900u, 0x00000000u, 0x0000fc00u, 0x00000000u, 0x0000fffeu, 0x00000000u, 0x00004900u, 0x00003800u, 0x0000834cu, 0x000037feu}, + {0x00003c00u, 0x00004000u, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00004000u, 0x00000000u, 0x00008000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00004000u, 0x00000000u, 0x00008000u, 0x0000fe00u}, + {0x000036a8u, 0x000036a8u, 0x000036a8u, 0x00000000u, 0x00000000u, 0x00000000u, 0x000036a8u, 0x00000000u, 0x00000000u, 0x00003aa8u, 0x00003540u, 0x00006a80u, 0x00007851u, 0x000036a8u, 0x00008001u, 0x00007851u}, + {0x00003c00u, 0x00006b77u, 0x00003c00u, 0x00000000u, 0x00003c00u, 0x00003bffu, 0x00006b77u, 0x00003c00u, 0x00007c00u, 0x00003b77u, 0x00007fffu, 0x0000ffffu, 0x00006b77u, 0x00003bffu, 0x0000c74cu, 0x00006b72u}, + {0x00003c00u, 0x00004400u, 0x00003c00u, 0x00000000u, 0x00000008u, 0x00000002u, 0x00004400u, 0x00003c00u, 0x00004c00u, 0x00003800u, 0x00007fffu, 0x0000ffffu, 0x00004400u, 0x00000002u, 0x0000c20eu, 0x0000c20eu}, + {0x00000000u, 0x0000c400u, 0x00000000u, 0x00003c00u, 0x00003c00u, 0x00000000u, 0x0000bc00u, 0x00000000u, 0x00008000u, 0x00000000u, 0x00008001u, 0x00000000u, 0x00007c00u, 0x00000000u, 0x0000c200u, 0x00007c00u}, + {0x00000000u, 0x00007e00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x0000303au, 0x0000303au, 0x00003c00u, 0x00007c00u, 0x0000383au, 0x000010e8u, 0x000021d0u, 0x0000303au, 0x00000400u, 0x00000400u, 0x00007e00u}, + {0x00000000u, 0x0000fbffu, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000001u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00000000u, 0x00000000u, 0x00004400u, 0x00000001u, 0x0000fbffu, 0x000043feu}, + {0x00000000u, 0x0000cdc1u, 0x00003c00u, 0x00000000u, 0x00003c00u, 0x00000000u, 0x0000b555u, 0x00000000u, 0x00008000u, 0x00000000u, 0x0000d558u, 0x00000000u, 0x0000b555u, 0x00000000u, 0x0000cdacu, 0x0000ff76u}, + {0x00000000u, 0x0000981du, 0x00001c0eu, 0x00000000u, 0x00000000u, 0x00000000u, 0x00001400u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00000020u, 0x00000040u, 0x000019afu, 0x00001400u, 0x00009a1du, 0x000019adu}, + {0x00000000u, 0x0000bc00u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00007fffu, 0x0000ffffu, 0x00003c00u, 0x00000001u, 0x0000c000u, 0x0000c000u}, + {0x00000000u, 0x0000fc00u, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x000003ffu, 0x00000000u, 0x0000fc00u, 0x00000000u, 0x00008001u, 0x00000000u, 0x000003ffu, 0x00000000u, 0x0000fc00u, 0x0000fc00u}, + {0x00003c00u, 0x00007bffu, 0x00003c00u, 0x00000000u, 0x00003c00u, 0x00003c00u, 0x00007bffu, 0x00003c00u, 0x00007c00u, 0x00003bffu, 0x00007fffu, 0x0000ffffu, 0x00007bffu, 0x00003c00u, 0x00002091u, 0x00007c00u}, + {0x00002fa5u, 0x00002fa5u, 0x00000000u, 0x00002df5u, 0x000015bcu, 0x000022bfu, 0x00002ecdu, 0x00003c00u, 0x00007c00u, 0x00003abfu, 0x000001b0u, 0x0000035fu, 0x00004f91u, 0x00002ecdu, 0x000022bfu, 0x00004f91u}, + {0x00000000u, 0x0000b2ccu, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00000000u, 0x0000fc00u, 0x00000000u, 0x0000a4d1u, 0x00000000u, 0x00003800u, 0x00000000u, 0x0000f0beu, 0x0000f0beu}, + {0x00000000u, 0x0000fe00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x0000e1d7u, 0x00000000u, 0x00008000u, 0x00000000u, 0x00008001u, 0x00000000u, 0x00007bffu, 0x00000000u, 0x0000e1d7u, 0x0000fe00u}, + {0x00003c00u, 0x00004153u, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00004153u, 0x00000000u, 0x0000fc00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00004153u, 0x00000200u, 0x00008001u, 0x000001fdu}, + {0x00000000u, 0x00007fb2u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00003bffu, 0x00003bffu, 0x00003c00u, 0x00007c00u, 0x00003bffu, 0x00007fefu, 0x0000ffdfu, 0x00004900u, 0x00003bffu, 0x00003bffu, 0x00007fb2u}, + {0x0000119bu, 0x0000119bu, 0x0000119bu, 0x00000000u, 0x00000000u, 0x00000000u, 0x0000119bu, 0x00000000u, 0x00000000u, 0x0000399bu, 0x00000016u, 0x0000002du, 0x00004000u, 0x0000119bu, 0x00008000u, 0x00004000u}, + {0x00003c00u, 0x00007c00u, 0x00000000u, 0x00003c00u, 0x00003c00u, 0x00003c00u, 0x00007c00u, 0x00003c00u, 0x00007c00u, 0x00003bbcu, 0x00007fffu, 0x0000ffffu, 0x00007c00u, 0x00003c00u, 0x0000bfbdu, 0x00007c00u}, + {0x00000000u, 0x00007e00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000400u, 0x00000400u, 0x00000000u, 0x00007e00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00003bffu, 0x00000400u, 0x00000400u, 0x00007e00u}, + {0x00000000u, 0x0000fbffu, 0x00000000u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x000021afu, 0x00000000u, 0x0000fc00u, 0x00000000u, 0x00008001u, 0x00000000u, 0x000021afu, 0x00000002u, 0x0000fbffu, 0x0000e1aeu}, + {0x00003c00u, 0x00004f40u, 0x00003c00u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00005000u, 0x00000000u, 0x00000000u, 0x00003800u, 0x00007fffu, 0x0000ffffu, 0x00005000u, 0x00000000u, 0x0000c200u, 0x0000d600u}, + {0x00000000u, 0x0000ec70u, 0x00000000u, 0x00003c00u, 0x00003c00u, 0x00000000u, 0x0000b800u, 0x00000000u, 0x00008000u, 0x00000000u, 0x00008001u, 0x00000000u, 0x0000b372u, 0x00000000u, 0x0000ec70u, 0x00006870u} +}; +constexpr const char* Names[16] = { + "v_add_f16 clamp", + "v_add_f16 mul:2", + "v_sub_f16 clamp", + "v_subrev_f16 clamp div:2", + "v_mul_f16 clamp", + "v_min_f16 clamp", + "v_max_f16 mul:4", + "v_ldexp_f16 clamp", + "v_ldexp_f16 mul:2", + "v_frexp_mant_f16 clamp", + "v_cvt_norm_i16_f16 clamp", + "v_cvt_norm_u16_f16 mul:2", + "v_max3_f16 mul:2", + "v_med3_f16 clamp mul:4", + "v_min3_f16 div:2", + "v_fma_f16 mul:2" +}; + +void Fill(std::uint32_t tid, std::uint32_t* words) { + std::copy(std::begin(Rows[tid]), std::end(Rows[tid]), words); +} + +std::array BufferDescriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; +} + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +void Expect(std::uint32_t tid, std::uint32_t actual, std::uint32_t expected, const char* name) { + Require(actual == expected, std::string("float16 modifiers: lane ") + std::to_string(tid) + " " + name + " is " + Hex(actual) + ", expected " + Hex(expected)); +} + +bool IsNan(std::uint32_t half) { + return (half & 0x7fffu) > 0x7c00u; +} + +void ExpectHalf(std::uint32_t tid, std::uint32_t actual, std::uint32_t expected, const char* name) { + actual &= 0xffffu; + if (IsNan(expected) && IsNan(actual)) return; + Expect(tid, actual, expected, name); +} + +void Run(AgcDriver::VulkanDevice& device) { + for (std::uint32_t tid = 0; tid < Threads; ++tid) Fill(tid, &Input[tid * Inputs]); + Output.fill(0xdeadbeefu); + std::vector userData(8, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size() * 4u)); + std::copy(input.begin(), input.end(), userData.begin()); + std::copy(output.begin(), output.end(), userData.begin() + 4); + const std::span code(Code); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + const auto result = ShaderRecompiler::Recompile(request); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void Check() { + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const std::uint32_t* in = &Input[tid * Inputs]; + const std::uint32_t* out = &Output[tid * Results]; + for (std::uint32_t i = 0; i < 16; ++i) ExpectHalf(tid, out[i], Expected[tid][i], Names[i]); + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + Run(*device); + Check(); + std::puts("float16 modifiers tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/Float16TernaryClamp.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/Float16TernaryClamp.cpp new file mode 100644 index 000000000..655d71fad --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/Float16TernaryClamp.cpp @@ -0,0 +1,181 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 32; +constexpr std::uint32_t Inputs = 4; +constexpr std::uint32_t Results = 16; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; + +alignas(256) constexpr std::array Code{ + 0x34020084, 0x34060086, 0xe0381000, 0x80000401, 0xbf8c3f70, 0x7e1c0307, 0x7e200307, 0x7e220307, + 0x7e140307, 0x7e160307, 0x7e180307, 0x7e1a0307, 0x7e1e0307, 0x7e240307, 0xd754800a, 0x041a0b04, + 0xd751800b, 0x041a0b04, 0xd757800c, 0x041a0b04, 0xd75f800d, 0x041a0b04, 0xd754fa0e, 0x24120d05, + 0xd751a80f, 0x44160906, 0xd757f410, 0x84120d05, 0xd75fd811, 0x04160906, 0xd75fa212, 0xa4120d05, + 0xe0781000, 0x80010a03, 0xe0781010, 0x80010e03, 0xe0781020, 0x80011203, 0xbf810000, +}; + +constexpr std::uint32_t Rows[32][4] = { + {0x00000400u, 0x3bffb4a2u, 0x7bff7bffu, 0xfd976299u}, + {0x0001755du, 0x00007c00u, 0x07b7be05u, 0x32b8562au}, + {0x00017d23u, 0x42007c01u, 0x3c00fc01u, 0xfb47feb7u}, + {0xbfa8fd5au, 0x00008000u, 0x7d232fe0u, 0x6a55b5f1u}, + {0x1000d324u, 0xfc00f936u, 0xa88cfc00u, 0x455742adu}, + {0x87bb3c00u, 0x7c012000u, 0x00000000u, 0x517cded7u}, + {0xc2d6b555u, 0x2a2fbc00u, 0x3c00fae5u, 0x3726d2dfu}, + {0x000103ffu, 0x3555b555u, 0x3c14bc00u, 0xf06fead4u}, + {0x2000fc01u, 0x79817bffu, 0x7bff8001u, 0xe6607650u}, + {0x84003c00u, 0x5daf6841u, 0x3c00064eu, 0x3d4d4112u}, + {0x7e00fc00u, 0x7c007e00u, 0x7e00fc00u, 0x90b35b97u}, + {0x081d4286u, 0xbd763c00u, 0x84004200u, 0x510fb8c3u}, + {0x8a2b0000u, 0x05170400u, 0x03ffc7e5u, 0x6e83a7f0u}, + {0xc0007e00u, 0x7d237e00u, 0x7c017c00u, 0x45c0f96bu}, + {0xb95a7bffu, 0x007d8001u, 0x7c010ccbu, 0xb9c23f62u}, + {0x00017e00u, 0x1f9d8001u, 0x417698d1u, 0xe7b478feu}, + {0x048f7edbu, 0x5e8a4fd9u, 0x81b2fe00u, 0x9f542371u}, + {0x7c00c000u, 0xbc00fc00u, 0x3c000000u, 0x9004ee95u}, + {0x7e00f5ddu, 0x7e008000u, 0xfc01bc00u, 0x8fd0b012u}, + {0xb5558284u, 0x1000d1adu, 0xfe003460u, 0x76315f60u}, + {0x00003c00u, 0xc0008400u, 0x040039f3u, 0x9266fdd2u}, + {0x0000bc00u, 0x064de034u, 0x74c2fc01u, 0xcbe5dec7u}, + {0x3c01b555u, 0x42007c00u, 0x7c003555u, 0x36190caau}, + {0xc000fbffu, 0x3c004200u, 0x7d23c000u, 0xb63ec222u}, + {0x000000a1u, 0xf41e891eu, 0xbfb23436u, 0x35b2cc39u}, + {0x0000018fu, 0xb555844du, 0xcaf50000u, 0x1f46ce67u}, + {0x0000027cu, 0x7e00932bu, 0x35557c01u, 0xeedc6a0cu}, + {0x000003ffu, 0x0bc83555u, 0x076a4000u, 0x6dde7f88u}, + {0x000003ffu, 0x7bff2000u, 0xde652493u, 0xc36c95c2u}, + {0x000003ffu, 0xfbfffc01u, 0x40007d23u, 0x85da3cafu}, + {0x00000400u, 0x7789e844u, 0x80000001u, 0xa570949du}, + {0x0000053du, 0x12482000u, 0x8d328bb0u, 0x80525003u} +}; +constexpr std::uint32_t Expected[32][12] = { + {0xfd973c00u, 0xfd970000u, 0xfd970400u, 0xfd970000u, 0x3c006299u, 0xfd970000u, 0x00006299u, 0x00006299u, 0xfd970000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x32b83c00u, 0x32b80000u, 0x32b83c00u, 0x32b80000u, 0x07b7562au, 0x32b80000u, 0x07b7562au, 0x3c00562au, 0x32b80000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xfb470000u, 0xfb470000u, 0xfb470000u, 0xfb470000u, 0x3c00feb7u, 0xfb473c00u, 0x0000feb7u, 0x0000feb7u, 0xfb470000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x6a552fe0u, 0x6a550000u, 0x6a550000u, 0x6a550000u, 0x0000b5f1u, 0x6a550000u, 0x0000b5f1u, 0x0000b5f1u, 0x6a550000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x45570000u, 0x45570000u, 0x45570000u, 0x45573c00u, 0x3c0042adu, 0x45570000u, 0x000042adu, 0x000042adu, 0x45570000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x517c3c00u, 0x517c0000u, 0x517c2000u, 0x517c0000u, 0x0000ded7u, 0x517c0000u, 0x0000ded7u, 0x0000ded7u, 0x517c3c00u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x37260000u, 0x37260000u, 0x37260000u, 0x37263555u, 0x3c00d2dfu, 0x37262a2fu, 0x0000d2dfu, 0x3c00d2dfu, 0x37263c00u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xf06f03ffu, 0xf06f0000u, 0xf06f0000u, 0xf06f03ffu, 0x3c00ead4u, 0xf06f0000u, 0x0000ead4u, 0x0000ead4u, 0xf06f0000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xe6603c00u, 0xe6600000u, 0xe6600000u, 0xe6600000u, 0x3c007650u, 0xe6603c00u, 0x3c007650u, 0x3c007650u, 0xe6600000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x3d4d3c00u, 0x3d4d064eu, 0x3d4d3c00u, 0x3d4d3c00u, 0x3c004112u, 0x3d4d0000u, 0x3c004112u, 0x00004112u, 0x3d4d3c00u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x90b30000u, 0x90b30000u, 0x90b30000u, 0x90b30000u, 0x00005b97u, 0x90b33c00u, 0x00005b97u, 0x00005b97u, 0x90b30000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x510f3c00u, 0x510f3c00u, 0x510f3c00u, 0x510f3c00u, 0x3c00b8c3u, 0x510f0000u, 0x0000b8c3u, 0x0400b8c3u, 0x510f0000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x6e830400u, 0x6e830000u, 0x6e830000u, 0x6e830000u, 0x03ffa7f0u, 0x6e830000u, 0x03ffa7f0u, 0x0000a7f0u, 0x6e830400u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x45c03c00u, 0x45c03c00u, 0x45c03c00u, 0x45c00000u, 0x0000f96bu, 0x45c00000u, 0x0000f96bu, 0x0000f96bu, 0x45c00000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xb9c23c00u, 0xb9c20000u, 0xb9c20ccbu, 0xb9c20000u, 0x00003f62u, 0xb9c20000u, 0x00003f62u, 0x3c003f62u, 0xb9c20001u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xe7b40000u, 0xe7b40000u, 0xe7b40000u, 0xe7b43c00u, 0x3c0078feu, 0xe7b41f9du, 0x000078feu, 0x000078feu, 0xe7b40000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x9f543c00u, 0x9f543c00u, 0x9f543c00u, 0x9f540000u, 0x048f2371u, 0x9f540000u, 0x00002371u, 0x01b22371u, 0x9f540000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x90040000u, 0x90040000u, 0x90040000u, 0x90040000u, 0x3c00ee95u, 0x90040000u, 0x0000ee95u, 0x0000ee95u, 0x90040000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x8fd00000u, 0x8fd00000u, 0x8fd00000u, 0x8fd03c00u, 0x0000b012u, 0x8fd03c00u, 0x0000b012u, 0x0000b012u, 0x8fd00000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x76313460u, 0x76310000u, 0x76310000u, 0x76310000u, 0x00005f60u, 0x76310284u, 0x00005f60u, 0x3c005f60u, 0x76313c00u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x92663c00u, 0x92660000u, 0x926639f3u, 0x92660000u, 0x3c00fdd2u, 0x92660000u, 0x0000fdd2u, 0x0000fdd2u, 0x92660000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xcbe50000u, 0xcbe50000u, 0xcbe50000u, 0xcbe50000u, 0x3c00dec7u, 0xcbe5064du, 0x0000dec7u, 0x0000dec7u, 0xcbe50000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x36193c00u, 0x36190000u, 0x36193555u, 0x36190000u, 0x3c000caau, 0x36193555u, 0x3c000caau, 0x3c000caau, 0x36190000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xb63e3c00u, 0xb63e0000u, 0xb63e0000u, 0xb63e0000u, 0x0000c222u, 0xb63e3c00u, 0x0000c222u, 0x0000c222u, 0xb63e3c00u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x35b23436u, 0x35b20000u, 0x35b200a1u, 0x35b20000u, 0x3c00cc39u, 0x35b20000u, 0x0000cc39u, 0x0000cc39u, 0x35b20000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x1f46018fu, 0x1f460000u, 0x1f460000u, 0x1f460000u, 0x3c00ce67u, 0x1f460000u, 0x0000ce67u, 0x0000ce67u, 0x1f460000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xeedc027cu, 0xeedc0000u, 0xeedc0000u, 0xeedc0000u, 0x35556a0cu, 0xeedc0000u, 0x00006a0cu, 0x00006a0cu, 0xeedc0000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x6dde3c00u, 0x6dde03ffu, 0x6dde3555u, 0x6dde03ffu, 0x076a7f88u, 0x6dde0000u, 0x076a7f88u, 0x3c007f88u, 0x6dde0000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xc36c2493u, 0xc36c03ffu, 0xc36c2000u, 0xc36c03ffu, 0x3c0095c2u, 0xc36c0000u, 0x000095c2u, 0x3c0095c2u, 0xc36c0000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x85da03ffu, 0x85da03ffu, 0x85da03ffu, 0x85da0000u, 0x3c003cafu, 0x85da0000u, 0x00003cafu, 0x00003cafu, 0x85da0000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0xa5700400u, 0xa5700000u, 0xa5700001u, 0xa5700000u, 0x0000949du, 0xa5700000u, 0x0000949du, 0x0000949du, 0xa5700000u, 0x00000000u, 0x00000000u, 0x00000000u}, + {0x80522000u, 0x80520000u, 0x8052053du, 0x80520000u, 0x0d325003u, 0x80520000u, 0x00005003u, 0x3c005003u, 0x80520000u, 0x00000000u, 0x00000000u, 0x00000000u} +}; +constexpr std::uint32_t Checked[32] = {0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1feu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1afu, 0x1ffu, 0x17fu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1dfu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1ffu, 0x1fbu, 0x1feu, 0x1feu, 0x1fdu, 0x1fdu, 0x1f8u, 0x1fbu, 0x1ffu}; +constexpr const char* Names[9] = { + "v_max3_f16 v10, v4, v5, v6 clamp", + "v_min3_f16 v11, v4, v5, v6 clamp", + "v_med3_f16 v12, v4, v5, v6 clamp", + "v_div_fixup_f16 v13, v4, v5, v6 clamp", + "v_max3_f16 v14, -v5, |v6|, v4 op_sel:[1,1,1,1] clamp", + "v_min3_f16 v15, v6, -v4, v5 op_sel:[1,0,1,0] clamp", + "v_med3_f16 v16, v5, v6, -|v4| op_sel:[0,1,1,1] clamp", + "v_div_fixup_f16 v17, v6, v4, v5 op_sel:[1,1,0,1] clamp", + "v_div_fixup_f16 v18, -v5, |v6|, -v4 op_sel:[0,0,1,0] clamp", +}; + +void Fill(std::uint32_t tid, std::uint32_t* words) { + std::copy(std::begin(Rows[tid]), std::end(Rows[tid]), words); +} + +std::array BufferDescriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; +} + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +void Expect(std::uint32_t tid, std::uint32_t actual, std::uint32_t expected, const char* name) { + Require(actual == expected, std::string("float16 ternary clamp: lane ") + std::to_string(tid) + " " + name + " is " + Hex(actual) + ", expected " + Hex(expected)); +} + +void Run(AgcDriver::VulkanDevice& device) { + for (std::uint32_t tid = 0; tid < Threads; ++tid) Fill(tid, &Input[tid * Inputs]); + Output.fill(0xdeadbeefu); + std::vector userData(8, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size() * 4u)); + std::copy(input.begin(), input.end(), userData.begin()); + std::copy(output.begin(), output.end(), userData.begin() + 4); + const std::span code(Code); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + const auto result = ShaderRecompiler::Recompile(request); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void Check() { + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const std::uint32_t* in = &Input[tid * Inputs]; + const std::uint32_t* out = &Output[tid * Results]; + for (std::uint32_t i = 0; i < 9; ++i) { + if ((Checked[tid] >> i) & 1u) Expect(tid, out[i], Expected[tid][i], Names[i]); + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + Run(*device); + Check(); + std::puts("float16 ternary clamp tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp index 025e2844a..c2df3f72f 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp @@ -1936,6 +1936,16 @@ bool supportsNativeVop3ResultModifiers(RdnaOpcode opcode) { case RdnaOpcode::VMadF32: case RdnaOpcode::VFmaF32: case RdnaOpcode::VFmaF16: + case RdnaOpcode::VAddF16: + case RdnaOpcode::VSubF16: + case RdnaOpcode::VSubrevF16: + case RdnaOpcode::VMulF16: + case RdnaOpcode::VMinF16: + case RdnaOpcode::VMaxF16: + case RdnaOpcode::VLdexpF16: + case RdnaOpcode::VFrexpMantF16: + case RdnaOpcode::VCvtNormI16F16: + case RdnaOpcode::VCvtNormU16F16: case RdnaOpcode::VCvtPkrtzF16F32: case RdnaOpcode::VLdexpF32: case RdnaOpcode::VFmaF64: @@ -1959,6 +1969,9 @@ bool isF32DivisionStepOpcode(RdnaOpcode opcode) { } bool supportsNativeVop3Clamp(RdnaOpcode opcode) { + if (isNativeVop3F16TernaryOpcode(opcode)) { + return true; + } return supportsNativeVop3ResultModifiers(opcode) || usesInexactClampControl(opcode) || usesIntegerSaturateClamp(opcode) || isF32DivisionStepOpcode(opcode) || isCubeOpcode(opcode); } @@ -1971,9 +1984,6 @@ void checkNativeVop3Modifiers(RdnaOpcode opcode, bool permlane, bool carryInOut, return; } if (isNativeVop3F16TernaryOpcode(opcode)) { - if (opcode != RdnaOpcode::VFmaF16 && (clamp != 0u || omod != 0u)) { - throw std::invalid_argument("VOP3 source modifiers are not implemented"); - } return; } if (isNativeVop3I16TernaryOpcode(opcode)) { @@ -2013,12 +2023,18 @@ void checkNativeVop3Modifiers(RdnaOpcode opcode, bool permlane, bool carryInOut, } return; } - if (opcode == RdnaOpcode::VLdexpF16 || opcode == RdnaOpcode::VCvtPkU8F32) { + if (opcode == RdnaOpcode::VCvtPkU8F32) { if ((abs & ~1u) != 0u || opSel != 0u || clamp != 0u || omod != 0u || (neg & ~1u) != 0u) { throw std::invalid_argument("VOP3 source modifiers are not implemented"); } return; } + if (opcode == RdnaOpcode::VLdexpF16) { + if ((abs & ~1u) != 0u || opSel != 0u || (neg & ~1u) != 0u) { + throw std::invalid_argument("VOP3 source modifiers are not implemented"); + } + return; + } if (opcode == RdnaOpcode::VCndmaskB32) { if ((abs & ~0x3u) != 0u || opSel != 0u || clamp != 0u || omod != 0u || (neg & ~0x3u) != 0u) { throw std::invalid_argument("VOP3 source modifiers are not implemented"); diff --git a/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp b/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp index 3bf343733..8b73a8241 100644 --- a/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp +++ b/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp @@ -46,6 +46,7 @@ private: void writeRawU32(const RdnaOperand& operand, IrU32 value); IrF32 applyF32ResultModifiers(const RdnaOperand& operand, IrF32 value); IrF32 applyF16ResultModifiers(const RdnaOperand& operand, IrF32 value); + IrU32 clampF16Bits(const RdnaOperand& operand, IrU32 bits); void writeOperand(const RdnaOperand& operand, IrValue* value); IrU32 packHalf2x16(IrF32 low, IrF32 high); void write16Bits(const RdnaOperand& operand, IrU32 value); diff --git a/core/shader/recompiler/Translation/src/FloatInstructions.cpp b/core/shader/recompiler/Translation/src/FloatInstructions.cpp index 958edd283..4d8d0a6e7 100644 --- a/core/shader/recompiler/Translation/src/FloatInstructions.cpp +++ b/core/shader/recompiler/Translation/src/FloatInstructions.cpp @@ -161,7 +161,7 @@ bool TranslationContext::vDivFixupF16(const RdnaInstruction& inst) { result = IrU32(ir.Select(ir.LogicalOr(bothZero.Value(), bothInf.Value()), ir.Constant(0xfe00u), result.Value())); result = IrU32(ir.Select(isNan(1u).Value(), ir.BitwiseOr(bits[1].Value(), ir.Constant(0x0200u)), result.Value())); result = IrU32(ir.Select(isNan(2u).Value(), ir.BitwiseOr(bits[2].Value(), ir.Constant(0x0200u)), result.Value())); - write16Bits(inst.destination, result); + write16Bits(inst.destination, clampF16Bits(inst.destination, result)); return true; } @@ -250,7 +250,7 @@ bool TranslationContext::vLdexpF16(const RdnaInstruction& inst) { const IrF16 scaled(ir.Emit(IrOpcode::ConvertF16F32, IrType::F16, {&ir.Emit(IrOpcode::FPMul32, IrType::F32, {&value.Value(), &power})})); const IrU32 result(ir.Emit(IrOpcode::ConvertU32U16, IrType::U32, {&ir.Emit(IrOpcode::BitCastU16F16, IrType::U16, {&scaled.Value()})})); const IrU1 nan(ir.UGreaterThan(ir.BitwiseAnd(bits.Value(), ir.Constant(0x7fffu)), ir.Constant(0x7c00u))); - write16Bits(inst.destination, IrU32(ir.Select(nan.Value(), ir.BitwiseOr(bits.Value(), ir.Constant(0x200u)), result.Value()))); + write16Bits(inst.destination, clampF16Bits(inst.destination, IrU32(ir.Select(nan.Value(), ir.BitwiseOr(bits.Value(), ir.Constant(0x200u)), result.Value())))); return true; } @@ -270,7 +270,7 @@ bool TranslationContext::vFrexpF16(const RdnaInstruction& inst, bool exponent) { const IrU32 converted(ir.Emit(IrOpcode::ConvertU32U16, IrType::U32, {&ir.Emit(IrOpcode::BitCastU16F16, IrType::U16, {&half.Value()})})); const IrU1 nan(ir.UGreaterThan(ir.BitwiseAnd(bits.Value(), ir.Constant(0x7fffu)), ir.Constant(0x7c00u))); const IrU32 kept(ir.Select(nan.Value(), ir.BitwiseOr(bits.Value(), ir.Constant(0x200u)), bits.Value())); - write16Bits(inst.destination, IrU32(ir.Select(special.Value(), kept.Value(), converted.Value()))); + write16Bits(inst.destination, clampF16Bits(inst.destination, IrU32(ir.Select(special.Value(), kept.Value(), converted.Value())))); return true; } diff --git a/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp b/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp index d0b6568c0..917075c25 100644 --- a/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp +++ b/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp @@ -290,6 +290,16 @@ IrF32 TranslationContext::applyF16ResultModifiers(const RdnaOperand& operand, Ir return selectF32(positive, limited, zero); } +IrU32 TranslationContext::clampF16Bits(const RdnaOperand& operand, IrU32 bits) { + if (!operand.clamp) { + return bits; + } + const IrU32 magnitude(ir.BitwiseAnd(bits.Value(), ir.Constant(0x7fffu))); + const IrU1 zero(ir.LogicalOr(ir.UGreaterThan(bits.Value(), ir.Constant(0x7fffu)), ir.UGreaterThan(magnitude.Value(), ir.Constant(0x7c00u)))); + const IrU32 limited(ir.Select(ir.UGreaterThan(magnitude.Value(), ir.Constant(0x3c00u)), ir.Constant(0x3c00u), bits.Value())); + return IrU32(ir.Select(zero.Value(), ir.Constant(0u), limited.Value())); +} + IrU32 TranslationContext::readScalarCode(std::uint32_t code) { if (code < NumScalarRegs) { return IrU32(ir.GetScalarReg(static_cast(code))); From 5864b20dcbabe6d2dc457718e423d2c99fbdf06e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Mon, 5 Oct 2026 14:59:52 +0200 Subject: [PATCH 07/42] feat(shader): accept every SDWA selector, clamp and omod on v_ldexp_f16 Co-Authored-By: Claude --- .../tests/execution/SdwaLdexpF16.cpp | 221 ++++++++++++++++++ .../RdnaDecoder/src/RdnaVectorOpDecoder.cpp | 13 +- 2 files changed, 228 insertions(+), 6 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/SdwaLdexpF16.cpp diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SdwaLdexpF16.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SdwaLdexpF16.cpp new file mode 100644 index 000000000..fa99d9da1 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SdwaLdexpF16.cpp @@ -0,0 +1,221 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 32; +constexpr std::uint32_t Inputs = 4; +constexpr std::uint32_t Results = 16; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; + +alignas(256) constexpr std::array Code{ + 0x34020084, 0x34060086, 0xe0381000, 0x80000401, 0xbf8c3f70, 0x76140af9, 0x06000604, 0x7e160307, + 0x76160af9, 0x00091504, 0x76180af9, 0x09120c04, 0x761a0af9, 0x02230004, 0x7e1c0307, 0x761c0af9, + 0x0b041104, 0x761e0af9, 0x04050a04, 0x76200af9, 0x05360304, 0x76220af9, 0x0d0d0604, 0x76240af9, + 0x0c060d04, 0x76260af9, 0x06042504, 0x7e280307, 0x76280af9, 0x05153404, 0x762a0af9, 0x0c262604, + 0x762c0af9, 0x06062c04, 0x762e0af9, 0x06044604, 0x7e300307, 0x76300af9, 0x0c15f504, 0x76320af9, + 0x050b0404, 0xe0781000, 0x80010a03, 0xe0781010, 0x80010e03, 0xe0781020, 0x80011203, 0xe0781030, + 0x80011603, 0xbf810000, +}; + +constexpr std::uint32_t Rows[32][4] = { + {0x00000000u, 0x684e9968u, 0xff007c00u, 0x6f931b8au}, + {0x808003ffu, 0x0004fffcu, 0x00ff8080u, 0x7bff0004u}, + {0xfff0fff0u, 0x00108000u, 0x7bffbc00u, 0xa45c7559u}, + {0x7d22fe4du, 0x056329d8u, 0xd7096658u, 0x38008080u}, + {0x8bb3fddeu, 0x00ff0004u, 0x80800040u, 0xbc0003ffu}, + {0xfc7a7ca0u, 0x7c007f7fu, 0xef4b2407u, 0xcc04a29cu}, + {0x7d007d00u, 0x7b6150bfu, 0x6dcc8926u, 0x8000fffcu}, + {0x7e007e00u, 0x00103c00u, 0x3c00bc00u, 0xb9cb4fcfu}, + {0x7e097c3cu, 0x7c007d00u, 0x0080fc00u, 0x80808080u}, + {0x7eedf7dbu, 0x00000080u, 0x7bff3c00u, 0x8000fffcu}, + {0x7efc7d70u, 0xc2404efau, 0x03ff0000u, 0xf8e9b3fau}, + {0x7f7f7f7fu, 0x03ff3c00u, 0x0a0a0ef4u, 0x00043800u}, + {0x925cfc30u, 0xc2c739c1u, 0x7c00ffc0u, 0x3c00fff0u}, + {0xfcb6fe11u, 0x7bfffffcu, 0xfc000004u, 0x00ff0000u}, + {0xffc0ffc0u, 0x00400004u, 0x935ed482u, 0xfff07e00u}, + {0xfffcfffcu, 0x80807bffu, 0x7d000080u, 0x42e04aebu}, + {0x9308fc92u, 0x800003ffu, 0x8080fffcu, 0x00107d00u}, + {0x9759fcb4u, 0xea4692e5u, 0xffc04400u, 0xd16a9b24u}, + {0x9b437c27u, 0x00040001u, 0x00803800u, 0xf26a25eau}, + {0x9d757cb2u, 0x7d00fc00u, 0xfffc0080u, 0x03ff8000u}, + {0xa2207fd4u, 0x77acf39bu, 0x00000040u, 0x4321d11au}, + {0xa9957e8au, 0x784edcbcu, 0xc1986687u, 0x1673526du}, + {0xab057dadu, 0x03ff0000u, 0xfc00fff0u, 0xa912eb3au}, + {0xacdffc34u, 0x01c450c4u, 0x00007c00u, 0xff00fff0u}, + {0xb5317eabu, 0x6d3223e0u, 0xb2c8089au, 0x001000ffu}, + {0xb8987d0au, 0x3800fff0u, 0x28bc3cd4u, 0x7bfffff0u}, + {0xbca4fe29u, 0x6af4ea82u, 0x800000ffu, 0x409ee072u}, + {0xc242ffedu, 0x00107d00u, 0x45a37ba4u, 0x7f7f4400u}, + {0xc31cfca9u, 0x25115884u, 0xa6568fceu, 0x7d0003ffu}, + {0xc492fd96u, 0x330fbd35u, 0x00ff7d00u, 0x8248e011u}, + {0xcabaff3cu, 0x0000fc00u, 0x000400ffu, 0xbc007bffu}, + {0xcd717c3bu, 0x808000ffu, 0xffc003ffu, 0x6af2aa83u} +}; +constexpr std::uint32_t Expected[32][16] = { + {0x00000000u, 0x00001b8au, 0xffff8000u, 0x00000000u, 0x6f93008au, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x6f930000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00001b8au, 0x00000000u}, + {0x00000010u, 0x7c000004u, 0xffff8040u, 0x00000000u, 0x7bffff04u, 0x00080000u, 0xfe000000u, 0x00008800u, 0x00400000u, 0x00400000u, 0x7bff0800u, 0x00000040u, 0x00000040u, 0x00000040u, 0x00080004u, 0x0000ff80u}, + {0x00000000u, 0xffff7559u, 0xffff8000u, 0x000000f8u, 0xa45cf059u, 0xfff00000u, 0xf0000000u, 0x0000fff0u, 0xfff00000u, 0x00000000u, 0xa45c0000u, 0x00000000u, 0x00000000u, 0x0000fff0u, 0x00007559u, 0x0000ffffu}, + {0x00007c00u, 0xfffe8080u, 0xfffffc00u, 0x00000000u, 0x38004d80u, 0x00220000u, 0x4d000000u, 0x00007f22u, 0xfe4d0000u, 0x00000000u, 0x38000000u, 0x00000000u, 0x00000000u, 0x0000fe4du, 0x00008080u, 0x00007c00u}, + {0x00000af0u, 0xfffd03ffu, 0xffff80b3u, 0x00000000u, 0xbc00deffu, 0xffb30000u, 0xde000000u, 0x0000fc00u, 0xffde0000u, 0x00000000u, 0xbc003c00u, 0x00000000u, 0x00000000u, 0x0000ffdeu, 0x1bb303ffu, 0x0000ff8bu}, + {0x00007c00u, 0x7c00a29cu, 0xfffffc00u, 0x000000fcu, 0xcc04a09cu, 0x007a0000u, 0xa0000000u, 0x0000fe7au, 0x7ea00000u, 0x00000000u, 0xcc040000u, 0x00000000u, 0x00000000u, 0x00007ea0u, 0x0000a29cu, 0x0000fffcu}, + {0x00000000u, 0x7c00fffcu, 0xffff8000u, 0x00000000u, 0x800000fcu, 0x00000000u, 0x00000000u, 0x00007f00u, 0x7f000000u, 0x00000000u, 0x80000000u, 0x00000000u, 0x00000000u, 0x00007f00u, 0x0000fffcu, 0x00007c00u}, + {0x00000000u, 0x007e4fcfu, 0xffff8000u, 0x000000e0u, 0xb9cb00cfu, 0x00000000u, 0x00000000u, 0x00007e00u, 0x7e000000u, 0x00000000u, 0xb9cb0000u, 0x00000000u, 0x00000000u, 0x00007e00u, 0x00004fcfu, 0x000037e0u}, + {0x00007c00u, 0x007c8080u, 0xfffffc00u, 0x0000007eu, 0x80803c80u, 0x00090000u, 0x3c000000u, 0x00007e09u, 0x7e3c0000u, 0x00000000u, 0x80800000u, 0x00000000u, 0x00000000u, 0x00007e3cu, 0x00008080u, 0x00007c00u}, + {0x00007c00u, 0xfff7fffcu, 0xffff80edu, 0x0000007eu, 0x8000dbfcu, 0xffed0000u, 0xdb000000u, 0x00007eedu, 0xfc000000u, 0x00000000u, 0x80000000u, 0x00003c00u, 0x00000000u, 0x0000fc00u, 0x0000fffcu, 0x0000007eu}, + {0x00007c00u, 0x7c00b3fau, 0xfffffc00u, 0x00000000u, 0xf8e970fau, 0xfffc0000u, 0x70000000u, 0x00007efcu, 0x7f700000u, 0x00000000u, 0xf8e90000u, 0x00000000u, 0x00000000u, 0x00007f70u, 0x0000b3fau, 0x00000000u}, + {0x00007c00u, 0x007f3800u, 0xfffffc00u, 0x00000000u, 0x00047f00u, 0x007f0000u, 0x7f000000u, 0x00007f7fu, 0x7f7f0000u, 0x00000000u, 0x00040000u, 0x00000000u, 0x00000000u, 0x00007f7fu, 0x00003800u, 0x00007c00u}, + {0x00007c00u, 0xfffcfff0u, 0xfffffc00u, 0x00000000u, 0x3c0030f0u, 0x00000000u, 0x30000000u, 0x00008000u, 0xfe300000u, 0x00000000u, 0x3c000000u, 0x00000000u, 0x00000000u, 0x0000fe30u, 0x3c00fff0u, 0x0000ff92u}, + {0x00000001u, 0xfffe0000u, 0xffff805bu, 0x00000000u, 0x00ff1100u, 0xffb60000u, 0x11000000u, 0x0000feb6u, 0xfe110000u, 0x00000000u, 0x00ff0000u, 0x00000000u, 0x00000000u, 0x0000fe11u, 0x00000000u, 0x0000fffcu}, + {0x00000a00u, 0xffff7e00u, 0xffff80c0u, 0x00000000u, 0xfff0c000u, 0xffc00000u, 0xc0000000u, 0x0000ffc0u, 0xffc00000u, 0x00000000u, 0xfff00000u, 0x00000000u, 0x00000000u, 0x0000ffc0u, 0x00007e00u, 0x0000ffffu}, + {0x00007c00u, 0xffff4aebu, 0xfffffc00u, 0x00000000u, 0x42e0fcebu, 0xfffc0000u, 0xfc000000u, 0x0000fffcu, 0xfffc0000u, 0x00000000u, 0x42e00000u, 0x00000000u, 0x00000000u, 0x0000fffcu, 0x00004aebu, 0x0000ffffu}, + {0x00007c00u, 0xfffc7d00u, 0xffff8040u, 0x00000093u, 0x00109200u, 0x00000000u, 0x92000000u, 0x00008000u, 0xfe920000u, 0x00000000u, 0x00100000u, 0x00000000u, 0x00000000u, 0x0000fe92u, 0x3c007d00u, 0x0000ff93u}, + {0x00000000u, 0xfffc9b24u, 0xffff8000u, 0x00000000u, 0xd16ab424u, 0x00000000u, 0xb4000000u, 0x00008000u, 0xfeb40000u, 0x00000000u, 0xd16a0000u, 0x00000000u, 0x00000000u, 0x0000feb4u, 0x00009b24u, 0x0000ff97u}, + {0x0000004eu, 0x00f825eau, 0xffff8043u, 0x000000d8u, 0xf26a27eau, 0x00430000u, 0x27000000u, 0x0000ab43u, 0x7e270000u, 0x00000000u, 0xf26a2b43u, 0x00000000u, 0x00000000u, 0x00007e27u, 0x1f4325eau, 0x0000ff9bu}, + {0x00000000u, 0x007c8000u, 0xffff8007u, 0x0000009du, 0x03ffb200u, 0x00000000u, 0xb2000000u, 0x0000fc00u, 0x7eb20000u, 0x00000000u, 0x03ff3c00u, 0x00000000u, 0x00000000u, 0x00007eb2u, 0x00008000u, 0x0000ff9du}, + {0x00000000u, 0x7c00d11au, 0xffff8000u, 0x00000000u, 0x4321d41au, 0x00000000u, 0xd4000000u, 0x0000fc00u, 0x7fd40000u, 0x00000000u, 0x43213c00u, 0x00000000u, 0x00000000u, 0x00007fd4u, 0x0000d11au, 0x0000ffa2u}, + {0x00000000u, 0x7c00526du, 0xffff8000u, 0x00000000u, 0x16738a6du, 0x00000000u, 0x8a000000u, 0x0000fc00u, 0x7e8a0000u, 0x00000000u, 0x16733c00u, 0x00000000u, 0x00000000u, 0x00007e8au, 0x0000526du, 0x0000ffa9u}, + {0x000000adu, 0x007deb3au, 0xffff8005u, 0x00000000u, 0xa912ad3au, 0x00050000u, 0xad000000u, 0x0000fc00u, 0x7fad0000u, 0x00000000u, 0xa9123c00u, 0x00000000u, 0x00000000u, 0x00007fadu, 0x2b05eb3au, 0x0000ffabu}, + {0x00007c00u, 0xfffcfff0u, 0xfffffc00u, 0x00000000u, 0xff0034f0u, 0x00000000u, 0x34000000u, 0x0000fc00u, 0xfe340000u, 0x00000000u, 0xff003c00u, 0x00000000u, 0x00000000u, 0x0000fe34u, 0x3c00fff0u, 0x0000ffacu}, + {0x00007c00u, 0x7c0000ffu, 0xfffffc00u, 0x00000000u, 0x0010abffu, 0x00000000u, 0xab000000u, 0x0000fc00u, 0x7eab0000u, 0x00000000u, 0x00103c00u, 0x00000000u, 0x00000000u, 0x00007eabu, 0x3c0000ffu, 0x0000ffb5u}, + {0x00000000u, 0x7c00fff0u, 0xffff804cu, 0x000000b8u, 0x7bff0af0u, 0xff930000u, 0x0a000000u, 0x0000fc00u, 0x7f0a0000u, 0x00000000u, 0x7bff3c00u, 0x00000000u, 0x00000000u, 0x00007f0au, 0x0093fff0u, 0x0000ffb8u}, + {0x00000000u, 0xfffee072u, 0xffff8000u, 0x00000000u, 0x409e2972u, 0x00000000u, 0x29000000u, 0x0000fc00u, 0xfe290000u, 0x00000000u, 0x409e3c00u, 0x00000000u, 0x00000000u, 0x0000fe29u, 0x0000e072u, 0x0000ffbcu}, + {0x00007c00u, 0xffff4400u, 0xfffffc00u, 0x00000010u, 0x7f7fed00u, 0x00000000u, 0xed000000u, 0x0000fc00u, 0xffed0000u, 0x00000000u, 0x7f7f3c00u, 0x00000000u, 0x00000000u, 0x0000ffedu, 0x3c004400u, 0x0000ffc2u}, + {0x00007c00u, 0xfffc03ffu, 0xfffffc00u, 0x00000018u, 0x7d00a9ffu, 0x00000000u, 0xa9000000u, 0x0000fc00u, 0xfea90000u, 0x00000000u, 0x7d003c00u, 0x00000000u, 0x00000000u, 0x0000fea9u, 0x3c0003ffu, 0x0000ffc3u}, + {0x00000000u, 0xfffde011u, 0xffff8000u, 0x00000020u, 0x82489611u, 0x00000000u, 0x96000000u, 0x0000fc00u, 0xff960000u, 0x00000000u, 0x82483c00u, 0x00000000u, 0x00000000u, 0x0000ff96u, 0x0000e011u, 0x0000ffc4u}, + {0x00000000u, 0xffff7bffu, 0xffff800cu, 0x000000cau, 0xbc003cffu, 0x00000000u, 0x3c000000u, 0x0000cabau, 0xff3c0000u, 0x00000000u, 0xbc003c00u, 0x00000000u, 0x00000000u, 0x0000ff3cu, 0x00007bffu, 0x0000ffcau}, + {0x00007c00u, 0x7c00aa83u, 0xffff8071u, 0x00000000u, 0x6af23b83u, 0x00000000u, 0x3b000000u, 0x00008000u, 0x7e3b0000u, 0x00000000u, 0x6af20000u, 0x00000000u, 0x00000000u, 0x00007e3bu, 0x3c00aa83u, 0x0000ffcdu} +}; +constexpr std::uint32_t Checked[32] = {0xffffu, 0x8008u, 0xfff7u, 0x7ffau, 0xfffau, 0xfff0u, 0x7ffdu, 0x7ff5u, 0x7ff0u, 0x7ff2u, 0xfff8u, 0x7ff8u, 0xfffau, 0xfffau, 0xfffau, 0xfffau, 0xfff2u, 0xffffu, 0xfff0u, 0xfff1u, 0xfffdu, 0xfffdu, 0xfff8u, 0xfffau, 0xfff8u, 0xbfd1u, 0xffffu, 0xfff2u, 0xfff2u, 0xfff7u, 0xfff3u, 0xfff8u}; +constexpr const char* Names[16] = { + "BYTE_0/DWORD -> DWORD", + "BYTE_1/BYTE_0 -> WORD_1", + "BYTE_2/BYTE_1 -> WORD_0", + "BYTE_3/BYTE_2 -> BYTE_0", + "WORD_0/BYTE_3 -> BYTE_1", + "WORD_1/WORD_0 -> BYTE_2", + "DWORD/WORD_1 -> BYTE_3", + "WORD_1/WORD_1 -> DWORD", + "DWORD/WORD_0 -> WORD_1", + "WORD_0/DWORD -> WORD_1 clamp", + "WORD_1/WORD_1 -> WORD_0 clamp", + "DWORD/WORD_0 -> DWORD clamp", + "DWORD/DWORD -> WORD_0 clamp", + "WORD_0/DWORD -> DWORD mul:2", + "WORD_1/WORD_0 -> WORD_1 clamp div:2", + "BYTE_3/WORD_1 -> WORD_0", +}; + +void Fill(std::uint32_t tid, std::uint32_t* words) { + std::copy(std::begin(Rows[tid]), std::end(Rows[tid]), words); +} + +std::array BufferDescriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; +} + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +void Expect(std::uint32_t tid, std::uint32_t actual, std::uint32_t expected, const char* name) { + Require(actual == expected, std::string("sdwa ldexp f16: lane ") + std::to_string(tid) + " " + name + " is " + Hex(actual) + ", expected " + Hex(expected)); +} + +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, std::span code) { + std::vector userData(8, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(Input.size() * 4u)); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size() * 4u)); + std::copy(input.begin(), input.end(), userData.begin()); + std::copy(output.begin(), output.end(), userData.begin() + 4); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +void Run(AgcDriver::VulkanDevice& device) { + for (std::uint32_t tid = 0; tid < Threads; ++tid) Fill(tid, &Input[tid * Inputs]); + Output.fill(0xdeadbeefu); + const std::span code(Code); + const auto result = Compile(device, code); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void CheckRefused(AgcDriver::VulkanDevice& device) { + struct Refused { + std::uint32_t modifier; + const char* error; + }; + constexpr std::array forms{{ + {0x04042004u, "VOP2 SDWA clamp with byte selectors is not implemented"}, + {0x06022504u, "VOP2 SDWA clamp with byte selectors is not implemented"}, + {0x01062604u, "VOP2 SDWA clamp with byte selectors is not implemented"}, + {0x10050404u, "VOP2 SDWA source modifiers are not supported"}, + {0x26060604u, "VOP2 SDWA source modifiers are not supported"}, + }}; + for (const auto& form : forms) { + alignas(256) const std::array code{0x76140af9u, form.modifier, 0xbf810000u}; + std::string refusal; + try { + static_cast(Compile(device, code)); + } catch (const std::exception& error) { + refusal = error.what(); + } + Require(refusal.find(form.error) != std::string::npos, "v_ldexp_f16 SDWA form " + Hex(form.modifier) + " was not refused"); + } +} + +void Check() { + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const std::uint32_t* in = &Input[tid * Inputs]; + const std::uint32_t* out = &Output[tid * Results]; + for (std::uint32_t i = 0; i < 16; ++i) { + if ((Checked[tid] >> i) & 1u) { + Expect(tid, out[i], Expected[tid][i], Names[i]); + } + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + Run(*device); + Check(); + CheckRefused(*device); + std::puts("sdwa ldexp f16 tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp index c2df3f72f..86adfa16f 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp @@ -96,7 +96,7 @@ constexpr Vop2OpcodeInfo vop2Opcodes[] = { {0x3cu, RdnaOpcode::VPkFmacF16}, {0x06u, RdnaOpcode::VMacLegacyF32}, {0x07u, RdnaOpcode::VMulLegacyF32, Vop2SdwaProfile::Float}, - {0x3bu, RdnaOpcode::VLdexpF16}, + {0x3bu, RdnaOpcode::VLdexpF16, Vop2SdwaProfile::Float16}, }; constexpr VectorOpcodeInfo vop1Opcodes[] = { @@ -1361,14 +1361,15 @@ void validateVop2Sdwa(const RdnaInstruction& instruction, std::uint32_t opcode, if (fields.src0Sel > 6u || fields.src1Sel > 6u || fields.dstSel > 6u) { throw std::invalid_argument("VOP2 SDWA selector is invalid"); } - const bool clampSupported = isVop2FloatOpcode(instruction.op) || supportsVop2SdwaIntegerClamp(instruction.op, opcode); - if ((fields.clamp != 0u && !clampSupported) || (fields.omod != 0u && !isVop2FloatOpcode(instruction.op))) { + const bool floatResult = isVop2FloatOpcode(instruction.op) || instruction.op == RdnaOpcode::VLdexpF16; + const bool clampSupported = floatResult || supportsVop2SdwaIntegerClamp(instruction.op, opcode); + if ((fields.clamp != 0u && !clampSupported) || (fields.omod != 0u && !floatResult)) { throw std::invalid_argument("VOP2 SDWA output modifiers are not supported"); } + if (hasUnsupportedVop2SourceModifiers(instruction.op, fields.src0Neg != 0u || fields.src0Abs != 0u, fields.src1Neg != 0u || fields.src1Abs != 0u)) { + throw std::invalid_argument("VOP2 SDWA source modifiers are not supported"); + } if (isFullWidthVop2Sdwa(fields)) { - if (hasUnsupportedVop2SourceModifiers(instruction.op, fields.src0Neg != 0u || fields.src0Abs != 0u, fields.src1Neg != 0u || fields.src1Abs != 0u)) { - throw std::invalid_argument("VOP2 SDWA source modifiers are not supported"); - } return; } From 12c229d19ac7f1e4faa345b6d82771e9ceb9cd82 Mon Sep 17 00:00:00 2001 From: RomainROCH Date: Sun, 4 Oct 2026 05:29:53 +0200 Subject: [PATCH 08/42] fix(jpegenc): honor chroma sampling and encode true grayscale JPEGs --- .gitmodules | 3 ++ 3rdparty/libjpeg-turbo | 1 + core/Decoder/Jpeg/CMakeLists.txt | 48 +++++++++++++++++- core/Decoder/Jpeg/include/Decoder/Jpeg.hpp | 8 ++- core/Decoder/Jpeg/src/Jpeg.cpp | 57 ++++++++++++++++------ core/Decoder/Jpeg/tests/Jpeg.cpp | 32 ++++++++++++ core/libs/prx/libSceJpegEnc/Export.cpp | 16 ++++-- core/libs/tests/GuestJpegEnc.cpp | 36 ++++++++++++-- docs/dev/TechnicalDebt.md | 1 - 9 files changed, 173 insertions(+), 29 deletions(-) create mode 160000 3rdparty/libjpeg-turbo diff --git a/.gitmodules b/.gitmodules index 0a5f83fb7..fc2e48631 100644 --- a/.gitmodules +++ b/.gitmodules @@ -28,3 +28,6 @@ [submodule "3rdparty/stb"] path = 3rdparty/stb url = https://github.com/nothings/stb.git +[submodule "3rdparty/libjpeg-turbo"] + path = 3rdparty/libjpeg-turbo + url = https://github.com/libjpeg-turbo/libjpeg-turbo.git diff --git a/3rdparty/libjpeg-turbo b/3rdparty/libjpeg-turbo new file mode 160000 index 000000000..c85e6b905 --- /dev/null +++ b/3rdparty/libjpeg-turbo @@ -0,0 +1 @@ +Subproject commit c85e6b905bf237038faa936dab160ebfc5da0344 diff --git a/core/Decoder/Jpeg/CMakeLists.txt b/core/Decoder/Jpeg/CMakeLists.txt index 2280f398b..fcb338b8c 100644 --- a/core/Decoder/Jpeg/CMakeLists.txt +++ b/core/Decoder/Jpeg/CMakeLists.txt @@ -3,10 +3,56 @@ function(add_jpeg_decoder target runtimeTarget) message(FATAL_ERROR "JPEG decoder requires an existing runtime target: ${runtimeTarget}") endif() + include(ExternalProject) + if(NOT TARGET jpeg_turbo_external) + set(jpeg_turbo_prefix "${CMAKE_BINARY_DIR}/libjpeg-turbo") + if(WIN32) + if(MSVC) + set(jpeg_turbo_library "${jpeg_turbo_prefix}/lib/turbojpeg-static.lib") + else() + set(jpeg_turbo_library "${jpeg_turbo_prefix}/lib/libturbojpeg.a") + endif() + else() + set(jpeg_turbo_library "${jpeg_turbo_prefix}/lib/libturbojpeg.a") + endif() + file(MAKE_DIRECTORY "${jpeg_turbo_prefix}/include") + ExternalProject_Add(jpeg_turbo_external + SOURCE_DIR "${PROJECT_SOURCE_DIR}/3rdparty/libjpeg-turbo" + BINARY_DIR "${CMAKE_BINARY_DIR}/libjpeg-turbo-build" + INSTALL_DIR "${jpeg_turbo_prefix}" + CMAKE_ARGS + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DCMAKE_INSTALL_PREFIX=${jpeg_turbo_prefix} + -DBUILD_SHARED_LIBS=OFF + -DENABLE_STATIC=ON + -DENABLE_SHARED=OFF + -DWITH_SIMD=OFF + -DWITH_TURBOJPEG=ON + -DWITH_TOOLS=OFF + -DWITH_TESTS=OFF + -DCMAKE_INSTALL_LIBDIR=lib + -DCMAKE_C_VISIBILITY_PRESET=hidden + -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON + -DCMAKE_POSITION_INDEPENDENT_CODE=ON + -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} + -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM} + -DCMAKE_C_COMPILER_LAUNCHER=${CMAKE_C_COMPILER_LAUNCHER} + -DCMAKE_CXX_COMPILER_LAUNCHER=${CMAKE_CXX_COMPILER_LAUNCHER} + BUILD_BYPRODUCTS + "${jpeg_turbo_library}" + ) + add_library(jpeg_turbo STATIC IMPORTED GLOBAL) + set_target_properties(jpeg_turbo PROPERTIES + IMPORTED_LOCATION "${jpeg_turbo_library}" + INTERFACE_INCLUDE_DIRECTORIES "${PROJECT_SOURCE_DIR}/3rdparty/libjpeg-turbo/src;${jpeg_turbo_prefix}/include" + ) + add_dependencies(jpeg_turbo jpeg_turbo_external) + endif() + add_library(${target} STATIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/src/Jpeg.cpp) target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/include) target_include_directories(${target} SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb) - target_link_libraries(${target} PRIVATE ${runtimeTarget}) + target_link_libraries(${target} PRIVATE ${runtimeTarget} jpeg_turbo) set_target_properties(${target} PROPERTIES CXX_EXTENSIONS OFF CXX_VISIBILITY_PRESET hidden diff --git a/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp b/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp index 275217fb2..60142fc36 100644 --- a/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp +++ b/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp @@ -21,8 +21,14 @@ struct Header { std::uint32_t channels; }; +enum class Sampling { + Yuv444, + Yuv422, + Yuv420, +}; + std::vector Encode(std::span pixels, std::uint32_t width, std::uint32_t height, - std::uint32_t channels, int quality); + std::uint32_t channels, int quality, Sampling sampling = Sampling::Yuv444); std::optional
ParseHeader(std::span jpeg); diff --git a/core/Decoder/Jpeg/src/Jpeg.cpp b/core/Decoder/Jpeg/src/Jpeg.cpp index 74a50c4f8..c8f1e1eca 100644 --- a/core/Decoder/Jpeg/src/Jpeg.cpp +++ b/core/Decoder/Jpeg/src/Jpeg.cpp @@ -4,16 +4,12 @@ #include #include -#define STB_IMAGE_WRITE_STATIC -#define STB_IMAGE_WRITE_IMPLEMENTATION -#define STBI_WRITE_NO_STDIO -#include "stb_image_write.h" - #define STB_IMAGE_STATIC #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_JPEG #define STBI_NO_STDIO #include "stb_image.h" +#include "turbojpeg.h" namespace Decoder::Jpeg { @@ -21,16 +17,39 @@ namespace { constexpr std::uint32_t MAX_DIMENSION = 0xFFFF; -void appendBytes(void* context, void* data, int size) { - auto* output = static_cast*>(context); - const auto* bytes = static_cast(data); - output->insert(output->end(), bytes, bytes + size); +class Handle { +public: + Handle() : handle(tj3Init(TJINIT_COMPRESS)) { + if (!handle) throw std::runtime_error("Jpeg::Encode: encoder initialization failed"); + } + ~Handle() { tj3Destroy(handle); } + Handle(const Handle&) = delete; + Handle& operator=(const Handle&) = delete; + operator tjhandle() const { return handle; } + +private: + tjhandle handle; +}; + +class Buffer { +public: + ~Buffer() { tj3Free(data); } + unsigned char* data = nullptr; +}; + +int toSubsampling(Sampling sampling) { + switch (sampling) { + case Sampling::Yuv444: return TJSAMP_444; + case Sampling::Yuv422: return TJSAMP_422; + case Sampling::Yuv420: return TJSAMP_420; + } + throw std::invalid_argument("Jpeg::Encode: invalid sampling"); } } // namespace std::vector Encode(std::span pixels, std::uint32_t width, std::uint32_t height, - std::uint32_t channels, int quality) { + std::uint32_t channels, int quality, Sampling sampling) { if (width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION) { throw std::invalid_argument("Jpeg::Encode: unsupported image size"); } @@ -39,12 +58,18 @@ std::vector Encode(std::span pixels, std::uint if (pixels.size() < static_cast(width) * height * channels) { throw std::invalid_argument("Jpeg::Encode: pixel buffer is too small"); } - - std::vector output; - const int written = stbi_write_jpg_to_func(appendBytes, &output, static_cast(width), static_cast(height), - static_cast(channels), pixels.data(), quality); - if (written == 0) throw std::runtime_error("Jpeg::Encode: encoding failed"); - return output; + const int subsampling = toSubsampling(sampling); + Handle handle; + if (tj3Set(handle, TJPARAM_QUALITY, quality) < 0 || tj3Set(handle, TJPARAM_SUBSAMP, channels == 1 ? TJSAMP_GRAY : subsampling) < 0) { + throw std::runtime_error("Jpeg::Encode: encoder configuration failed"); + } + Buffer buffer; + std::size_t size = 0; + const int pixelFormat = channels == 1 ? TJPF_GRAY : TJPF_RGB; + if (tj3Compress8(handle, pixels.data(), static_cast(width), 0, static_cast(height), pixelFormat, &buffer.data, &size) < 0) { + throw std::runtime_error("Jpeg::Encode: encoding failed"); + } + return {buffer.data, buffer.data + size}; } std::optional
ParseHeader(std::span jpeg) { diff --git a/core/Decoder/Jpeg/tests/Jpeg.cpp b/core/Decoder/Jpeg/tests/Jpeg.cpp index 38e2aa42d..d396a00f2 100644 --- a/core/Decoder/Jpeg/tests/Jpeg.cpp +++ b/core/Decoder/Jpeg/tests/Jpeg.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include static void Require(bool value) { if (!value) std::abort(); } @@ -25,6 +26,25 @@ static int Difference(std::uint8_t left, std::uint8_t right) { return left > right ? left - right : right - left; } +struct FrameInfo { int components; std::uint8_t sampling; }; + +static FrameInfo ReadFrame(const std::vector& jpeg) { + std::size_t offset = 2; + while (offset + 3 < jpeg.size()) { + Require(jpeg[offset++] == 0xFF); + while (offset < jpeg.size() && jpeg[offset] == 0xFF) ++offset; + Require(offset < jpeg.size()); + const std::uint8_t marker = jpeg[offset++]; + if (marker == 0xDA || marker == 0xD9) break; + Require(offset + 1 < jpeg.size()); + const std::size_t length = (static_cast(jpeg[offset]) << 8) | jpeg[offset + 1]; + Require(length >= 2 && offset + length <= jpeg.size()); + if (marker >= 0xC0 && marker <= 0xC3) return {jpeg[offset + 7], jpeg[offset + 9]}; + offset += length; + } + std::abort(); +} + int main() { constexpr std::uint32_t width = 32; constexpr std::uint32_t height = 24; @@ -41,6 +61,7 @@ int main() { const std::vector rgbJpeg = Decoder::Jpeg::Encode(rgb, width, height, 3, 90); Require(IsJpeg(rgbJpeg)); + Require(ReadFrame(rgbJpeg).components == 3 && ReadFrame(rgbJpeg).sampling == 0x11); const auto rgbImage = Decoder::Jpeg::Decode(rgbJpeg); Require(rgbImage.has_value()); Require(rgbImage->width == width && rgbImage->height == height && rgbImage->channels == 3); @@ -55,6 +76,7 @@ int main() { } const std::vector grayJpeg = Decoder::Jpeg::Encode(gray, width, height, 1, 90); Require(IsJpeg(grayJpeg)); + Require(ReadFrame(grayJpeg).components == 1); const auto grayImage = Decoder::Jpeg::Decode(grayJpeg); Require(grayImage.has_value()); Require(grayImage->width == width && grayImage->height == height); @@ -69,6 +91,16 @@ int main() { Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0x10000, 1, 3, 90); })); Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height + 1, 3, 90); })); + for (const auto [sampling, factor] : {std::pair{Decoder::Jpeg::Sampling::Yuv444, std::uint8_t{0x11}}, + std::pair{Decoder::Jpeg::Sampling::Yuv422, std::uint8_t{0x21}}, + std::pair{Decoder::Jpeg::Sampling::Yuv420, std::uint8_t{0x22}}}) { + const auto encoded = Decoder::Jpeg::Encode(rgb, 31, 23, 3, 1, sampling); + Require(ReadFrame(encoded).components == 3 && ReadFrame(encoded).sampling == factor); + const auto highQuality = Decoder::Jpeg::Encode(rgb, 31, 23, 3, 100, sampling); + Require(ReadFrame(highQuality).components == 3 && ReadFrame(highQuality).sampling == factor); + } + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, static_cast(3)); })); + Require(!Decoder::Jpeg::Decode({}).has_value()); const std::vector garbage{1, 2, 3, 4, 5, 6, 7, 8}; Require(!Decoder::Jpeg::Decode(garbage).has_value()); diff --git a/core/libs/prx/libSceJpegEnc/Export.cpp b/core/libs/prx/libSceJpegEnc/Export.cpp index d52ad86ac..2d4c66657 100644 --- a/core/libs/prx/libSceJpegEnc/Export.cpp +++ b/core/libs/prx/libSceJpegEnc/Export.cpp @@ -41,7 +41,6 @@ constexpr std::uint8_t SAMPLING_TYPE_420 = 2; constexpr std::uint32_t MAX_IMAGE_DIMENSION = 0xFFFF; constexpr std::uint32_t MAX_IMAGE_PITCH = 0xFFFFFFF; constexpr std::uint64_t MAX_IMAGE_SIZE = 0x7FFFFFFF; -constexpr int SUBSAMPLED_MAX_QUALITY = 90; struct Encoder { Encoder* self; @@ -148,9 +147,16 @@ std::vector toPackedPixels(const JpegEncEncodeParam& param, std::u } int toQuality(const JpegEncEncodeParam& param) { - int quality = 100 - param.compression_ratio * 99 / 255; - if (param.sampling_type != SAMPLING_TYPE_FULL) quality = std::min(quality, SUBSAMPLED_MAX_QUALITY); - return quality; + return 100 - param.compression_ratio * 99 / 255; +} + +Decoder::Jpeg::Sampling toSampling(const JpegEncEncodeParam& param) { + switch (param.sampling_type) { + case SAMPLING_TYPE_FULL: return Decoder::Jpeg::Sampling::Yuv444; + case SAMPLING_TYPE_422: return Decoder::Jpeg::Sampling::Yuv422; + case SAMPLING_TYPE_420: return Decoder::Jpeg::Sampling::Yuv420; + } + throw std::invalid_argument("sceJpegEncEncode: invalid sampling type"); } } // namespace @@ -187,7 +193,7 @@ int32_t APS5_VABI sceJpegEncEncode(void* handle, const JpegEncEncodeParam* param const std::uint32_t channels = param->pixel_format == PIXEL_FORMAT_Y8 ? 1 : 3; const std::vector pixels = toPackedPixels(*param, channels); - const std::vector jpeg = Decoder::Jpeg::Encode(pixels, param->image_width, param->image_height, channels, toQuality(*param)); + const std::vector jpeg = Decoder::Jpeg::Encode(pixels, param->image_width, param->image_height, channels, toQuality(*param), toSampling(*param)); if (jpeg.size() > param->jpeg_size) return SCE_JPEG_ENC_ERROR_INVALID_SIZE; std::memcpy(param->jpeg, jpeg.data(), jpeg.size()); diff --git a/core/libs/tests/GuestJpegEnc.cpp b/core/libs/tests/GuestJpegEnc.cpp index 7f5983747..5a49caa48 100644 --- a/core/libs/tests/GuestJpegEnc.cpp +++ b/core/libs/tests/GuestJpegEnc.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include extern "C" { @@ -23,17 +24,34 @@ static bool IsJpeg(const unsigned char* data, std::uint32_t size) { return size > 4 && data[0] == 0xFF && data[1] == 0xD8 && data[size - 2] == 0xFF && data[size - 1] == 0xD9; } +static std::pair ReadFrame(const unsigned char* jpeg, std::uint32_t size) { + std::size_t offset = 2; + while (offset + 3 < size) { + Require(jpeg[offset++] == 0xFF); + while (offset < size && jpeg[offset] == 0xFF) ++offset; + Require(offset < size); + const std::uint8_t marker = jpeg[offset++]; + if (marker == 0xDA || marker == 0xD9) break; + Require(offset + 1 < size); + const std::size_t length = (static_cast(jpeg[offset]) << 8) | jpeg[offset + 1]; + Require(length >= 2 && offset + length <= size); + if (marker >= 0xC0 && marker <= 0xC3) return {jpeg[offset + 7], jpeg[offset + 9]}; + offset += length; + } + std::abort(); +} + static int AverageError(const std::vector& expected, const std::vector& actual) { long total = 0; for (std::size_t i = 0; i < expected.size(); ++i) total += expected[i] > actual[i] ? expected[i] - actual[i] : actual[i] - expected[i]; return static_cast(total / static_cast(expected.size())); } -static std::vector DecodeOutput(const JpegEncOutputInfo& info) { +static std::vector DecodeOutput(const JpegEncOutputInfo& info, std::uint32_t channels = 3) { Require(IsJpeg(jpeg, info.size)); const auto decoded = Decoder::Jpeg::Decode({jpeg, info.size}); Require(decoded.has_value()); - Require(decoded->width == 16 && decoded->height == 16 && decoded->channels == 3); + Require(decoded->width == 16 && decoded->height == 16 && decoded->channels == channels); return decoded->pixels; } @@ -169,6 +187,7 @@ int main() { info = {}; Require(sceJpegEncEncode(handle, &rgba, &info) == 0); Require(info.height == 16); + Require(ReadFrame(jpeg, info.size) == std::pair{3, std::uint8_t{0x22}}); Require(AverageError(expected, DecodeOutput(info)) < 6); for (std::uint32_t y = 0; y < 16; ++y) { @@ -183,6 +202,7 @@ int main() { bgra.pixel_format = 1; info = {}; Require(sceJpegEncEncode(handle, &bgra, &info) == 0); + Require(ReadFrame(jpeg, info.size) == std::pair{3, std::uint8_t{0x22}}); Require(AverageError(expected, DecodeOutput(info)) < 6); alignas(4) static unsigned char yuyv[16 * 16 * 2]; @@ -202,10 +222,8 @@ int main() { Require(AverageError(std::vector(16 * 16 * 3, 100), DecodeOutput(info)) < 3); static unsigned char gray[16 * 16]; - std::vector expectedGray(16 * 16 * 3); for (std::size_t i = 0; i < sizeof(gray); ++i) { gray[i] = static_cast(((i % 16) + (i / 16)) * 8); - for (int c = 0; c < 3; ++c) expectedGray[i * 3 + c] = gray[i]; } JpegEncEncodeParam y8 = ValidEncodeParam(); y8.image = gray; @@ -216,7 +234,15 @@ int main() { y8.sampling_type = 0; info = {}; Require(sceJpegEncEncode(handle, &y8, &info) == 0); - Require(AverageError(expectedGray, DecodeOutput(info)) < 6); + Require(ReadFrame(jpeg, info.size) == std::pair{1, std::uint8_t{0x11}}); + const auto decodedGray = DecodeOutput(info, 1); + Require(AverageError(std::vector(gray, gray + sizeof(gray)), decodedGray) < 6); + + rgba.sampling_type = 1; + rgba.compression_ratio = 0; + info = {}; + Require(sceJpegEncEncode(handle, &rgba, &info) == 0); + Require(ReadFrame(jpeg, info.size) == std::pair{3, std::uint8_t{0x21}}); std::memset(jpeg, 0, sizeof(jpeg)); Require(sceJpegEncEncode(handle, &rgba, nullptr) == 0); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 2ddee4350..14b8e47df 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -109,7 +109,6 @@ Throughout the project, every function at every stage either **does exactly what - [v_mullit_f32](../../core/shader/recompiler/Translation/src/FloatInstructions.cpp) follows the hardware measured with the MODE register at IEEE=1 and denormals kept (a signaling NaN src0 is quieted, a positive denormal src2 counts as positive): the recompiler does not read MODE, so other IEEE/denormal settings are not modelled. - [v_fma_legacy_f32](../../core/shader/recompiler/Translation/src/FloatInstructions.cpp) (VOP3 0x140) is assumed to be fused, which has not been measured on hardware. LLVM decodes this encoding as `v_mad_legacy_f32` for gfx1013, and `v_mac_legacy_f32` (VOP2 0x06) was measured to round its product before the add, so 0x140 may do the same. - The executable file that [relinker](../../core/relinker/elfpatcher/src/windows/WindowsPeWriter.cpp) generates opens the console when launched, which is inconvenient for playability. -- [libSceJpegEnc](../../core/libs/prx/libSceJpegEnc/Export.cpp) encodes 4:2:2 sampling requests with 4:2:0 chroma subsampling, and grayscale requests as a 3-component JPEG with neutral chroma instead of a single-component one: the [JPEG encoder](../../core/Decoder/Jpeg/src/Jpeg.cpp) (stb) only produces 3-component 4:2:0 and 4:4:4 images. - [PA_CL_CLIP_CNTL](../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - `DX_LINEAR_ATTR_CLIP_ENA` (bit 24) clear is drawn like bit 24 set, with Vulkan's clipping of `NoPerspective` outputs; what a clear bit changes on the console is undocumented. - [v_rcp, v_rsq, v_sqrt, v_log, v_exp, v_sin and v_cos](../../core/shader/recompiler/Translation/src/FloatInstructions.cpp) (f32 and f16) use the driver's approximation for finite results, not the console's: the low bits can differ. Only NaN, invalid, zero and infinite results and the exact sin/cos zeros are chosen on the bits. v_sin_f32/v_cos_f32 with inputs beyond ±256 cycles were not compared with the console. - `--to-intel` does not lower RDPRU/MCOMMIT; the [matcher](../../core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp) fails the relink instead. SHA-1 and SHA-256 instructions with a RIP-relative operand fail the relink. From 09e41584ca92641e927736f1a90cece2dcb505a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Hasi=C5=84ski?= Date: Tue, 6 Oct 2026 00:04:14 +0200 Subject: [PATCH 09/42] fix(shader): apply f32 abs and neg source modifiers on the sign bit F32 operands applied |x| and -x as FAbs and OpFNegate. The NVIDIA driver returns its canonical NaN 0x7fffffff from FAbs of a NaN with a payload, so an instruction that passes a NaN operand through on the bits, such as v_div_fixup_f32 with |v5| = 0x7ff00000, loses the payload. RADV and lavapipe keep it. Clear or flip the sign bit instead, as readOperand already does for U32 operands. IEEE 754 defines abs and negate as sign-bit operations, so this is exact for every input. --- .../src/TranslationContext/OperandAccess.cpp | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp b/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp index d0b6568c0..4215fbd40 100644 --- a/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp +++ b/core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp @@ -151,22 +151,15 @@ IrValue* TranslationContext::readOperand(const RdnaOperand& operand, IrType type return &ir.ConstructU64(pair[0].Value(), pair[1].Value()); } IrU32 bits = applyBitSourceModifiers(operand, readRawU32(operand)); - if (TypesOverlap(type, IrType::F32) && !TypesOverlap(type, IrType::U32)) { - IrF32 value(ir.BitCastF32(bits.Value())); - if (operand.absolute) { - value = IrF32(ir.Emit(IrOpcode::FPAbs32, IrType::F32, {&value.Value()})); - } - if (operand.negate) { - value = IrF32(ir.Emit(IrOpcode::FPNeg32, IrType::F32, {&value.Value()})); - } - return &value.Value(); - } if (operand.absolute) { bits = IrU32(ir.BitwiseAnd(bits.Value(), ir.Constant(0x7fffffffu))); } if (operand.negate) { bits = IrU32(ir.BitwiseXor(bits.Value(), ir.Constant(0x80000000u))); } + if (TypesOverlap(type, IrType::F32) && !TypesOverlap(type, IrType::U32)) { + return &ir.BitCastF32(bits.Value()); + } if (!TypesOverlap(type, IrType::U32)) { throw std::runtime_error("TranslationContext::readOperand requested unsupported operand type"); } From abdf673b1ee5f1feaaaf2f23203514a7b36f448b Mon Sep 17 00:00:00 2001 From: "husari.orozco" Date: Mon, 5 Oct 2026 16:16:46 -0600 Subject: [PATCH 10/42] feat(relinker): support Windows guest TLS reads by ALU instructions Recognize the read-direction ALU forms (add, or, adc, sbb, and, sub, xor, cmp) that read a qword from fs:[disp32], such as the stack canary check `xor rbx, fs:[0x28]` emitted by stack-protected functions. They were rejected as unsupported, which blocked titles relinked on Windows. The stub loads the TLS value and applies the operation in place, keeping the final operation as the last flag-setting instruction and preserving the accumulator and counter. A destination of rax uses rdx as the value scratch so the original accumulator survives. Refs #217 --- .../src/windows/WindowsTlsBuilder.cpp | 55 +++++++++++++------ .../tests/test_tls_function_coverage.py | 34 ++++++++++-- 2 files changed, 68 insertions(+), 21 deletions(-) diff --git a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp index 7a7b94fd4..a38b93257 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp @@ -24,8 +24,13 @@ struct TlsAccess { std::uint32_t Immediate; std::uint8_t Register; std::uint32_t Displacement; + std::uint8_t AluOpcode; }; +bool isAluReadOpcode(std::uint8_t opcode) { + return opcode == 0x03 || opcode == 0x0b || opcode == 0x13 || opcode == 0x1b || opcode == 0x23 || opcode == 0x2b || opcode == 0x33 || opcode == 0x3b; +} + void patchAccess(std::vector& sections, const TlsAccess& access, const std::uint32_t target) { for (auto& section : sections) { if (access.Rva < section.Rva || access.Rva - section.Rva >= section.Data.size()) @@ -85,7 +90,8 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co const auto loadRegister = info.Length - position == 7 ? static_cast(((bytes[position + 1] >> 3) & 7) | ((info.RexPrefix & 4) << 1)) : std::uint8_t{4}; const bool loadValue = supportedPrefixes && (info.RexPrefix == 0x48 || info.RexPrefix == 0x4c) && loadRegister != 4 && bytes[position] == 0x8b && (bytes[position + 1] & 0xc7) == 0x04 && bytes[position + 2] == 0x25; const bool storeImmediate = supportedPrefixes && !hasOperandSizePrefix && (info.RexPrefix == 0 || info.RexPrefix == 0x40) && info.Length - position == 11 && bytes[position] == 0xc7 && bytes[position + 1] == 0x04 && bytes[position + 2] == 0x25 && Io::ReadU32(source, header.Offset + offset + position + 3) == 0x28; - if (!loadValue && !storeImmediate) { + const bool aluRead = supportedPrefixes && (info.RexPrefix == 0x48 || info.RexPrefix == 0x4c) && loadRegister != 4 && info.Length - position == 7 && isAluReadOpcode(bytes[position]) && (bytes[position + 1] & 0xc7) == 0x04 && bytes[position + 2] == 0x25; + if (!loadValue && !storeImmediate && !aluRead) { std::ostringstream message; message << "Unsupported Windows guest TLS instruction (bytes:" << std::hex << std::setfill('0'); for (std::size_t index = 0; index < info.Length; ++index) @@ -93,7 +99,7 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co message << ')'; throw Domain::RelinkerException(message.str(), header.Offset + offset); } - accesses.push_back({rva, header.Offset + offset, info.Length, storeImmediate, storeImmediate ? Io::ReadU32(source, header.Offset + offset + position + 7) : 0, storeImmediate ? std::uint8_t{0} : loadRegister, storeImmediate ? 0 : Io::ReadU32(source, header.Offset + offset + position + 3)}); + accesses.push_back({rva, header.Offset + offset, info.Length, storeImmediate, storeImmediate ? Io::ReadU32(source, header.Offset + offset + position + 7) : 0, storeImmediate ? std::uint8_t{0} : loadRegister, storeImmediate ? 0 : Io::ReadU32(source, header.Offset + offset + position + 3), aluRead ? bytes[position] : std::uint8_t{0}}); } } } @@ -155,24 +161,39 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co if (target != branchTargets.end() && *target < access.Rva + access.Length) throw Domain::RelinkerException("Branch enters a guest TLS instruction", *target); patchAccess(sections, access, code.GetRva()); - const bool preserveAccumulator = access.StoreImmediate || access.Register != 0; - const bool preserveCounter = access.Register != 1; code.Emit({0x48, 0x8d, 0x64, 0x24, 0x80}); - if (preserveCounter) code.Emit({0x51}); - if (preserveAccumulator) code.Emit({0x50}); - loadPointer(); - if (!access.StoreImmediate && access.Displacement != 0) { - code.Emit({0x48, 0x8b, 0x80}); + if (access.AluOpcode != 0 && access.Register == 0) { + code.Emit({0x52}); + code.Emit({0x51}); + loadPointer(); + code.Emit({0x48, 0x8b, 0x90}); code.U32(access.Displacement); + code.Emit({0x48, access.AluOpcode, 0xc2}); + code.Emit({0x59}); + code.Emit({0x5a}); + } else { + const bool preserveAccumulator = access.StoreImmediate || access.Register != 0; + const bool preserveCounter = access.Register != 1; + if (preserveCounter) code.Emit({0x51}); + if (preserveAccumulator) code.Emit({0x50}); + loadPointer(); + if (access.AluOpcode != 0) { + code.Emit({0x48, 0x8b, 0x80}); + code.U32(access.Displacement); + code.Emit({static_cast(0x48 | ((access.Register >> 3) << 2)), access.AluOpcode, static_cast(0xc0 | ((access.Register & 7) << 3))}); + } else if (!access.StoreImmediate && access.Displacement != 0) { + code.Emit({0x48, 0x8b, 0x80}); + code.U32(access.Displacement); + } + if (access.StoreImmediate) { + code.Emit({0xc7, 0x40, 0x28}); + code.U32(access.Immediate); + } else if (access.AluOpcode == 0 && access.Register != 0) { + code.Emit({static_cast(0x48 | (access.Register >> 3)), 0x89, static_cast(0xc0 | (access.Register & 7))}); + } + if (preserveAccumulator) code.Emit({0x58}); + if (preserveCounter) code.Emit({0x59}); } - if (access.StoreImmediate) { - code.Emit({0xc7, 0x40, 0x28}); - code.U32(access.Immediate); - } else if (access.Register != 0) { - code.Emit({static_cast(0x48 | (access.Register >> 3)), 0x89, static_cast(0xc0 | (access.Register & 7))}); - } - if (preserveAccumulator) code.Emit({0x58}); - if (preserveCounter) code.Emit({0x59}); code.Emit({0x48, 0x8d, 0xa4, 0x24, 0x80, 0, 0, 0}); code.Rip({0xe9}, CheckedRva(access.Rva + access.Length)); } diff --git a/core/relinker/relinker/tests/test_tls_function_coverage.py b/core/relinker/relinker/tests/test_tls_function_coverage.py index f39c91929..4d68200c2 100644 --- a/core/relinker/relinker/tests/test_tls_function_coverage.py +++ b/core/relinker/relinker/tests/test_tls_function_coverage.py @@ -30,6 +30,13 @@ def fs_load(register, displacement): return bytes([0x64, 0x48 | (register >> 3) << 2, 0x8b, 0x04 | (register & 7) << 3, 0x25]) + struct.pack("> 3) << 2, opcode, 0x04 | (register & 7) << 3, 0x25]) + struct.pack("> 3) << 2, opcode, 0xc0 | (register & 7) << 3]) if register else bytes([0x48, opcode, 0xc2]) + assert value_load in stub, (case, stub.hex()) + assert operation in stub, (case, stub.hex()) rejected = { "rsp-displacement": fs_load(4, 40), + "rsp-alu": fs_alu(0x33, 4, 40), "dword-load": bytes.fromhex("64 8b 04 25 28 00 00 00"), "register-address": bytes.fromhex("64 48 8b 00"), "gs-load": bytes.fromhex("65 48 8b 04 25 28 00 00 00"), "rex-b-load": bytes.fromhex("64 49 8b 04 25 28 00 00 00"), "rex-x-load": bytes.fromhex("64 4a 8b 04 25 28 00 00 00"), - "compare": bytes.fromhex("64 48 3b 04 25 28 00 00 00"), - "subtract": bytes.fromhex("64 48 2b 04 25 28 00 00 00"), - "add": bytes.fromhex("64 48 03 04 25 28 00 00 00"), - "xor": bytes.fromhex("64 48 33 04 25 28 00 00 00"), } for name, instruction in rejected.items(): convert(name, make_image("register", "unwind", body=instruction + b"\xc3"), From 79feafca58613b77a71c46d2c14d096acb5c346c Mon Sep 17 00:00:00 2001 From: Nahuel Genchi <65604505+NahuelGenchi@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:16:58 -0300 Subject: [PATCH 11/42] fix(shader): keep helper invocations out of the pixel valid mask kill --- .../tests/execution/PixelValidMask.cpp | 137 ++++++++++++++++++ .../SpirvBackend/src/SpirvFlowEmitter.cpp | 8 +- 2 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/PixelValidMask.cpp diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PixelValidMask.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PixelValidMask.cpp new file mode 100644 index 000000000..914ba8e97 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PixelValidMask.cpp @@ -0,0 +1,137 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 32; +constexpr std::byte Kept{0x40}; +alignas(256) std::array Pixels{}; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000, +}; + +alignas(256) constexpr std::array MaskedPixelCode{ + 0x7e040f00, 0x36060481, 0x7da40680, 0x7e0e02f2, 0xf800180f, 0x07070707, 0xbf810000, +}; + +alignas(256) constexpr std::array FullPixelCode{ + 0x7e0e02f2, 0xf800180f, 0x07070707, 0xbf810000, +}; + +std::array BufferDescriptor(const void* data, std::uint32_t stride, std::uint32_t count) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), count, 0x01016facu}; +} + +constexpr std::array, 3> Triangle{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} +}}; + +void Draw(AgcDriver::VulkanDevice& device, std::uint32_t waveSize, std::span pixelCode) { + Pixels.fill(Kept); + const auto target = device.Target(); + + std::vector vertexUserData(4, 0u); + const auto vertexBuffer = BufferDescriptor(Triangle.data(), 16u, static_cast(Triangle.size())); + std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin()); + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {waveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + target, + {0, 0, 0, 64} + }; + vertex.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertex); + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.wave32 = waveSize == 32u; + pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); + pixel.posX = true; + pixel.posY = true; + pixel.targetOutputMode[0] = 9; + pixel.targetExportMapping.fill(0xe4u); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(pixelCode.data()), std::as_bytes(pixelCode)}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(pixelCode.data()), pixelCode, 0, {}}, + {waveSize, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory}, + target, + {0, 0, vertexPush, 128 - vertexPush} + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, vertexPush} + }}; + + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt}; + state.color = {reinterpret_cast(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u}; + state.colors = {state.color}; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.colorWriteMask = 15; + state.blends = {state.blend}; + state.blendConstants = {}; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + device.Draw(state, draw, shaders); + device.WaitIdle(); +} + +void Check(std::uint32_t waveSize, bool masked) { + const auto what = "pixel valid mask wave" + std::to_string(waveSize) + (masked ? " odd columns cleared" : " full EXEC"); + for (std::uint32_t pixel = 0; pixel < Width * Height; ++pixel) { + const bool exported = !masked || (pixel % Width) % 2u == 0u; + const auto expected = exported ? std::byte{255} : Kept; + for (std::uint32_t channel = 0; channel < 4; ++channel) { + const auto actual = Pixels[pixel * 4u + channel]; + Require(actual == expected, what + ": pixel " + std::to_string(pixel) + " channel " + std::to_string(channel) + " is " + std::to_string(static_cast(actual)) + ", expected " + std::to_string(static_cast(expected)) + (exported ? " (exported)" : " (cleared from EXEC before the vm export)")); + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (device->Target().subgroupSize < 32u) { + std::printf("skipped, subgroup size %u cannot hold a wave32\n", device->Target().subgroupSize); + return VulkanTestSkipped; + } + for (const auto waveSize : {64u, 32u}) { + Draw(*device, waveSize, FullPixelCode); + Check(waveSize, false); + Draw(*device, waveSize, MaskedPixelCode); + Check(waveSize, true); + } + std::puts("pixel valid mask tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index c05dcf3df..9a401dca6 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -34,7 +34,13 @@ void EmitKillIfPixelValidMaskInactive(SpirvEmitterState& state) { const auto active = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), maskValue, state.pixelValidMaskVariable); state.module.AddFunction(spv::OpINotEqual, TypeBool(state), active, maskValue, ConstantU32(state, 0u)); - EmitKillIfBoolFalse(state, active); + auto keep = active; + if (const auto helperVariable = InputVariableForKind(state, StageInputKind::HelperInvocation); helperVariable != 0u) { + const auto helper = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeBool(state), helper, helperVariable); + keep = Binary(state, spv::OpLogicalOr, TypeBool(state), active, helper); + } + EmitKillIfBoolFalse(state, keep); } // Block metadata is paired with BlockOrder by position (as IrProgram validation does); terminator From 31e9e67f5407a13006d76d975a229edc030094fc Mon Sep 17 00:00:00 2001 From: "husari.orozco" Date: Mon, 5 Oct 2026 17:50:50 -0600 Subject: [PATCH 12/42] fix(relinker): keep the original rax and rcx in ALU TLS reads loadPointer overwrites rax and rcx, so a destination of rax or rcx computed the operation against the thread pointer or the TLS index instead of the original register. Restore the destination before the operation for both, and include rcx in the byte-level cases, which previously covered only rax, rbx, r8 and r13. Add self-checking execution cases for rax, rcx and rbx destinations: each verifies the result, the preservation of the other two registers and the ZF and CF bits. --- .../src/windows/WindowsTlsBuilder.cpp | 16 +++- .../tests/test_tls_function_coverage.py | 80 +++++++++++++++++-- 2 files changed, 89 insertions(+), 7 deletions(-) diff --git a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp index a38b93257..cec6aec7e 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsTlsBuilder.cpp @@ -163,14 +163,26 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector& source, co patchAccess(sections, access, code.GetRva()); code.Emit({0x48, 0x8d, 0x64, 0x24, 0x80}); if (access.AluOpcode != 0 && access.Register == 0) { - code.Emit({0x52}); code.Emit({0x51}); + code.Emit({0x52}); + code.Emit({0x50}); loadPointer(); code.Emit({0x48, 0x8b, 0x90}); code.U32(access.Displacement); + code.Emit({0x58}); code.Emit({0x48, access.AluOpcode, 0xc2}); - code.Emit({0x59}); code.Emit({0x5a}); + code.Emit({0x59}); + } else if (access.AluOpcode != 0 && access.Register == 1) { + code.Emit({0x51}); + code.Emit({0x50}); + loadPointer(); + code.Emit({0x48, 0x8b, 0x80}); + code.U32(access.Displacement); + code.Emit({0x48, 0x8b, 0x4c, 0x24, 0x08}); + code.Emit({0x48, access.AluOpcode, 0xc8}); + code.Emit({0x58}); + code.Emit({0x48, 0x8d, 0x64, 0x24, 0x08}); } else { const bool preserveAccumulator = access.StoreImmediate || access.Register != 0; const bool preserveCounter = access.Register != 1; diff --git a/core/relinker/relinker/tests/test_tls_function_coverage.py b/core/relinker/relinker/tests/test_tls_function_coverage.py index 4d68200c2..9e0037181 100644 --- a/core/relinker/relinker/tests/test_tls_function_coverage.py +++ b/core/relinker/relinker/tests/test_tls_function_coverage.py @@ -37,6 +37,71 @@ def fs_alu(opcode, register, displacement): return bytes([0x64, 0x48 | (register >> 3) << 2, opcode, 0x04 | (register & 7) << 3, 0x25]) + struct.pack("> 3), 0xb8 | (target & 7)]) + struct.pack("= 8 else 0), 0x39, 0xc0 | (target & 7)])) + + def fail_unless_equal(): + emit(bytes.fromhex("0f 85 00 00 00 00")) + jumps.append(len(code) - 4) + + emit(bytes.fromhex("64 c7 04 25 28 00 00 00") + struct.pack(" mask else 0 + else: + carry = 0 + flags_masked = ((1 if result == 0 else 0) << 6) | carry + for register in (0, 1, 3): + body = alu_check_body(opcode, register, base, value, result, flags_masked) + yield f"alu-exec-{name}-{register}", make_image("register", "unwind", body=body) + + def displacement_load(register, displacement, flags, round_trip=False): saved = (3, 5, 6, 7, 12, 13, 14, 15) code = bytearray() @@ -284,7 +349,7 @@ def main(): for name, image, error in displacement_bounds_cases(): convert(name, image, error, error_offset=0x1240) for name, opcode in ALU_READ.items(): - for register in (0, 3, 8, 13): + for register in (0, 1, 2, 3, 8, 13): for displacement in (0, 40, -8): body = fs_alu(opcode, register, displacement) + b"\xc3" case = f"alu-{name}-{register}-{displacement}" @@ -301,10 +366,15 @@ def main(): assert patched[0] == 0xe9, case stub_address = patched_address + 5 + struct.unpack_from("> 3) << 2, opcode, 0xc0 | (register & 7) << 3]) if register else bytes([0x48, opcode, 0xc2]) - assert value_load in stub, (case, stub.hex()) - assert operation in stub, (case, stub.hex()) + if register == 0: + expected = bytes.fromhex("48 8b 90") + struct.pack("> 3) << 2), opcode, 0xc0 | ((register & 7) << 3)]) + assert expected in stub, (case, expected.hex(), stub.hex()) + for name, image in alu_execution_cases(): + convert(name, image) rejected = { "rsp-displacement": fs_load(4, 40), "rsp-alu": fs_alu(0x33, 4, 40), From 786178bd4edf2fd8fa541f7b39a8998f8a9d08b7 Mon Sep 17 00:00:00 2001 From: Nahuel Genchi <65604505+NahuelGenchi@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:01:18 -0300 Subject: [PATCH 13/42] fix(agc): include the host stage in barriers that name host accesses --- .../prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp | 10 +++++----- core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp | 2 +- .../libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 6 +++--- .../prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 8eca21737..420322e94 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1375,7 +1375,7 @@ bool VulkanDevice::FillBuffer(std::uint64_t address, std::size_t bytes, std::spa if ((covered & VK_ACCESS_TRANSFER_WRITE_BIT) != 0 && Graphics::Recorder::MergeBarriers()) { Graphics::Recorder::CountMerged(CommandClass::Fill); } else { - Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); Graphics::Recorder::CountBarriers(CommandClass::Fill); } const auto offset = address - import->base; @@ -1632,7 +1632,7 @@ VulkanDevice::CopyOutcome VulkanDevice::CopyBuffer(std::uint64_t destination, st if ((covered & transferAccess) == transferAccess && Graphics::Recorder::MergeBarriers()) { Graphics::Recorder::CountMerged(CommandClass::Copy); } else { - Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, transferAccess); + Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, transferAccess); Graphics::Recorder::CountBarriers(CommandClass::Copy); } const auto gpuTiming = recorder.BeginGpuTiming(programAddress); @@ -3134,7 +3134,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { // The group counts were stored by earlier recorded work (a dispatch in place, a fill) or the // host; the indirect read follows all of it. const auto timing = recorder.BeginGpuTiming(CommandClass::IndirectArguments); - Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT); + Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT); Graphics::Recorder::CountBarriers(CommandClass::IndirectArguments); recorder.EndGpuTiming(timing, 12); recorder.NotePendingRead(arguments, 12, Graphics::Recorder::ReadKind::Indirect); @@ -3146,7 +3146,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { Graphics::Recorder::CountMerged(CommandClass::DispatchLeading); } else { const auto timing = recorder.BeginGpuTiming(CommandClass::DispatchLeading); - Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); Graphics::Recorder::CountBarriers(CommandClass::DispatchLeading); recorder.EndGpuTiming(timing); ++d.preBarriersRecorded; @@ -3162,7 +3162,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recorder.EndGpuTiming(gpuTiming); const auto trailingTiming = recorder.BeginGpuTiming(CommandClass::DispatchTrailing); constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; - Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); + Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); Graphics::Recorder::CountBarriers(CommandClass::DispatchTrailing); recorder.EndGpuTiming(trailingTiming); recorder.MarkCovered(dispatchedAccess); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 75d874fec..aafdb1e31 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1045,7 +1045,7 @@ void recordDrawCommands(const Context& context, VkCommandBuffer commands, const bool recordIndirectArguments(const Context& context, VkCommandBuffer commands, Recorder* recorder, bool recorded, const IndirectRecord& indirect, std::unique_ptr& scratch, VkBuffer& argumentBuffer, VkDeviceSize& argumentOffset, const std::function& countBarrier) { using Rule = Pm4::DrawParameters::IndirectDraw::Rule; const auto* args = indirect.args; - RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT); countBarrier(1); if (recorded) { // Read in place from the import when the batch runs (a synchronous draw waits for its own). diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 9c08d1a48..a8d9ed9ca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -2131,7 +2131,7 @@ void GuestBufferMemory::recordGpuCopies(std::span copies, bool ad for (const auto* region : copies) reads.emplace_back(region->begin, region->end); recorder->NoteAccess(Recorder::CommandClass::StagingIn, Recorder::Access{reads, {}, {}, VK_PIPELINE_STAGE_TRANSFER_BIT}); } - RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); Recorder::CountBarriers(Recorder::CommandClass::StagingIn); bool stagedAny = false; std::uint64_t copiedBytes = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 624821852..bb8f5fb2b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1433,7 +1433,7 @@ void Recorder::recordKeyStores(bool forWriter) { const auto timing = beginTiming(ClassKey(CommandClass::DccKeyStore)); // Ordered behind every earlier recorded read or write of the ranges (the title's DCC clear or // decompress kernel storing keys through a V#), and visible to the work after and to the host. - recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT); + recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT); const auto fill = context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer"); const auto copy = context.Resolved(&DeviceFunctions::cmdCopyBuffer, "vkCmdCopyBuffer"); std::uint64_t bytes = 0; @@ -1970,7 +1970,7 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) { } done += count; const bool last = done == pendingSamples.size(); - recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, samplePipeline); struct { VkDeviceAddress counter; @@ -2031,7 +2031,7 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec } } if (meshArgumentState < 0) return false; - recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); + recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, meshArgumentPipeline); struct { VkDeviceAddress record; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp index f15aaf502..10b10065e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp @@ -234,7 +234,7 @@ void recordCopies(const UnitShadow& shadow, const std::vector& copie if (recorder != nullptr && (covered & transferAccess) == transferAccess && Recorder::MergeBarriers()) { Recorder::CountMerged(CommandClass::ShadowPublish); } else { - RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, transferAccess); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, transferAccess); Recorder::CountBarriers(CommandClass::ShadowPublish); } const auto copyBuffer = context.Resolved(&DeviceFunctions::cmdCopyBuffer, "vkCmdCopyBuffer"); From e5b7427c75a4bfd644850f33d934126973168ec8 Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:35:40 +0200 Subject: [PATCH 14/42] feat(shader): accept every SDWA selector on v_mov_b32 v_mov_b32_sdwa threw 'VOP1 SDWA destination selector ... is not supported' when a byte source (src0_sel BYTE_0..3) met a partial destination (dst_sel BYTE_0..3 or WORD_0/1): the VMovB32 rule allowed only WORD and DWORD sources there. Every src0_sel, src0_sext, dst_sel and dst_unused combination is now accepted. Translation already follows RDNA2 for all of them (applyBitSourceModifiers, writeRawU32): the selected field is zero- or sign-extended, and the result's low bits go to the dst_sel field with the other bits zeroed, sign-extended above and zeroed below, or preserved. Reserved selectors, dst_unused 3, and neg/abs on sub-dword sources still throw. agc_driver_sdwa_move_selectors runs all 294 combinations as wave32 and wave64 on the GPU, plus the in-place byte broadcast under a partial exec mask, which is not checked on subgroups narrower than 32 lanes, as in the other EXEC-masked execution tests. agc_vop1_sdwa_move_decode checks the decoded operands and the reserved encodings. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 13 + .../tests/Vop1SdwaMoveDecode.cpp | 77 +++++ .../tests/execution/SdwaMoveSelectors.cpp | 282 ++++++++++++++++++ .../RdnaDecoder/src/RdnaVectorOpDecoder.cpp | 2 +- 4 files changed, 373 insertions(+), 1 deletion(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/Vop1SdwaMoveDecode.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/SdwaMoveSelectors.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 90d971f7a..3d0ca99b3 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -804,6 +804,19 @@ if(BUILD_TESTING) endif() endif() +add_test_executable(agc_vop1_sdwa_move_decode_tests EXCLUDE_FROM_ALL tests/Vop1SdwaMoveDecode.cpp) +target_link_libraries(agc_vop1_sdwa_move_decode_tests PRIVATE shader_recompiler_agc_driver libc) +set_target_properties(agc_vop1_sdwa_move_decode_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_vop1_sdwa_move_decode_tests) +if(BUILD_TESTING) + set_target_properties(agc_vop1_sdwa_move_decode_tests PROPERTIES EXCLUDE_FROM_ALL OFF) + add_test(NAME agc_vop1_sdwa_move_decode COMMAND agc_vop1_sdwa_move_decode_tests) + if(WIN32) + set_tests_properties(agc_vop1_sdwa_move_decode PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() + add_test_executable(agc_pixel_position_export_tests EXCLUDE_FROM_ALL tests/PixelPositionExport.cpp) target_link_libraries(agc_pixel_position_export_tests PRIVATE shader_recompiler_agc_driver libc) set_target_properties(agc_pixel_position_export_tests PROPERTIES CXX_EXTENSIONS OFF) diff --git a/core/libs/prx/libSceAgcDriver/tests/Vop1SdwaMoveDecode.cpp b/core/libs/prx/libSceAgcDriver/tests/Vop1SdwaMoveDecode.cpp new file mode 100644 index 000000000..786d06005 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/Vop1SdwaMoveDecode.cpp @@ -0,0 +1,77 @@ +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include +#include +#include +#include +#include + +using namespace ShaderRecompiler; + +namespace { + +constexpr std::uint32_t MoveSdwa = 0x7e0602f9u; +constexpr std::uint32_t SourceVector = 4; +constexpr std::uint32_t DestinationVector = 3; + +constexpr std::uint32_t Modifier(std::uint32_t destinationSelector, std::uint32_t unused, std::uint32_t sourceSelector, std::uint32_t signExtend) { + return SourceVector | (destinationSelector << 8u) | (unused << 11u) | (sourceSelector << 16u) | (signExtend << 19u); +} + +bool Matches(const RdnaInstruction& instruction, std::uint32_t destinationSelector, std::uint32_t unused, std::uint32_t sourceSelector, std::uint32_t signExtend) { + return instruction.op == RdnaOpcode::VMovB32 && instruction.wordCount == 2u && instruction.sourceCount == 1u && + instruction.destination.kind == RdnaOperandKind::VectorRegister && instruction.destination.reg == DestinationVector && + instruction.destination.explicitSdwaDst && instruction.destination.sdwaSel == destinationSelector && + instruction.destination.sdwaDstUnused == unused && + instruction.source0.kind == RdnaOperandKind::VectorRegister && instruction.source0.reg == SourceVector && + instruction.source0.sdwaSel == sourceSelector && instruction.source0.sdwaSext == (signExtend != 0u) && + !instruction.source0.negate && !instruction.source0.absolute; +} + +} + +int main() { + int failures = 0; + for (std::uint32_t sourceSelector = 0; sourceSelector < 7u; ++sourceSelector) { + for (std::uint32_t signExtend = 0; signExtend < 2u; ++signExtend) { + for (std::uint32_t destinationSelector = 0; destinationSelector < 7u; ++destinationSelector) { + for (std::uint32_t unused = 0; unused < 3u; ++unused) { + const std::array words{MoveSdwa, Modifier(destinationSelector, unused, sourceSelector, signExtend)}; + try { + if (!Matches(DecodeRdnaInstruction(0u, words, 0u), destinationSelector, unused, sourceSelector, signExtend)) { + std::fprintf(stderr, "dst_sel %u dst_unused %u src0_sel %u sext %u decodes with the wrong operands\n", destinationSelector, unused, sourceSelector, signExtend); + ++failures; + } + } catch (const std::exception& error) { + std::fprintf(stderr, "dst_sel %u dst_unused %u src0_sel %u sext %u: %s\n", destinationSelector, unused, sourceSelector, signExtend, error.what()); + ++failures; + } + } + } + } + } + struct Rejected { + const char* name; + std::uint32_t modifier; + }; + constexpr std::array rejected{{ + {"reserved dst_unused on a byte destination", Modifier(1u, 3u, 0u, 0u)}, + {"reserved dst_unused on a dword destination", Modifier(6u, 3u, 6u, 0u)}, + {"reserved dst_sel", Modifier(7u, 0u, 0u, 0u)}, + {"reserved src0_sel", Modifier(0u, 2u, 7u, 0u)}, + {"neg on a byte source", Modifier(1u, 2u, 0u, 0u) | (1u << 20u)}, + {"abs on a word source", Modifier(5u, 2u, 4u, 0u) | (1u << 21u)}, + }}; + for (const auto& entry : rejected) { + const std::array words{MoveSdwa, entry.modifier}; + try { + static_cast(DecodeRdnaInstruction(0u, words, 0u)); + std::fprintf(stderr, "%s decodes\n", entry.name); + ++failures; + } catch (const std::invalid_argument&) { + } catch (const std::exception& error) { + std::fprintf(stderr, "%s: %s\n", entry.name, error.what()); + ++failures; + } + } + return failures == 0 ? 0 : 1; +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SdwaMoveSelectors.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SdwaMoveSelectors.cpp new file mode 100644 index 000000000..67a89cf6d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SdwaMoveSelectors.cpp @@ -0,0 +1,282 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Selectors = 7; +constexpr std::uint32_t UnusedModes = 3; +constexpr std::uint32_t Combinations = Selectors * 2u * Selectors * UnusedModes; +constexpr std::uint32_t BroadcastResult = Combinations; +constexpr std::uint32_t MaxLanes = 64; +constexpr std::uint32_t Inputs = 2; +constexpr std::uint32_t Results = Combinations + 1u; +constexpr std::uint32_t InputIndexVector = 1; +constexpr std::uint32_t OutputIndexVector = 2; +constexpr std::uint32_t BroadcastVector = 3; +constexpr std::uint32_t SourceVector = 4; +constexpr std::uint32_t PreviousVector = 5; +constexpr std::uint32_t DataVector = 6; +constexpr std::uint32_t ThreadVector = 0; +constexpr std::uint32_t ExecLoRegister = 0x7eu; +constexpr std::uint32_t ExecHiRegister = 0x7fu; +constexpr std::uint32_t InputRegister = 0; +constexpr std::uint32_t OutputRegister = 4; +constexpr std::uint32_t ConstantZero = 0x80u; +constexpr std::uint32_t ConstantOne = 0x81u; +constexpr std::uint32_t ConstantAllOnes = 0xc1u; +constexpr std::uint32_t Literal = 0xffu; +constexpr std::uint32_t Sdwa = 0xf9u; +constexpr std::uint32_t VectorSource = 0x100u; +constexpr std::uint32_t Endpgm = 0xbf810000u; +constexpr std::array BroadcastExec{0xa5a5a5a5u, 0x3c3c3c3cu}; + +template +constexpr std::size_t CodeWords = 15u + (WaveSize == 64u ? 5u : 3u) + Combinations * 5u + 3u; + +constexpr std::array Sources{ + 0x00000000u, 0xffffffffu, 0x80808080u, 0x7f7f7f7fu, 0x000000ffu, 0x0000ff00u, 0x00ff0000u, 0xff000000u, + 0x00000080u, 0x00008000u, 0x00800000u, 0x80000000u, 0x0000007fu, 0x00007fffu, 0x007fffffu, 0x7fffffffu, + 0x01020384u, 0x8504f306u, 0x12345678u, 0x9abcdef0u, 0xfedcba98u, 0x76543210u, 0x00ff00ffu, 0xff00ff00u, + 0x80007fffu, 0x7fff8000u, 0xc3a5815au, 0x5a81a5c3u, 0x0f1e2d3cu, 0xf0e1d2c3u, 0x40c08001u, 0xdeadbeefu, +}; + +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; + +constexpr std::uint32_t Sop1(std::uint32_t opcode, std::uint32_t destination, std::uint32_t source) { + return 0xbe800000u | (destination << 16u) | (opcode << 8u) | source; +} + +constexpr std::uint32_t Vop1(std::uint32_t opcode, std::uint32_t destination, std::uint32_t source) { + return 0x7e000000u | (destination << 17u) | (opcode << 9u) | source; +} + +constexpr std::uint32_t Vop2(std::uint32_t opcode, std::uint32_t destination, std::uint32_t source0, std::uint32_t source1) { + return (opcode << 25u) | (destination << 17u) | (source1 << 9u) | source0; +} + +constexpr std::uint32_t SdwaModifier(std::uint32_t source, std::uint32_t destinationSelector, std::uint32_t unused, std::uint32_t sourceSelector, std::uint32_t signExtend) { + return source | (destinationSelector << 8u) | (unused << 11u) | (sourceSelector << 16u) | (signExtend << 19u); +} + +constexpr std::uint32_t BufferAccess(std::uint32_t data, std::uint32_t index, std::uint32_t descriptor) { + return (ConstantZero << 24u) | ((descriptor / 4u) << 16u) | (data << 8u) | index; +} + +constexpr std::uint32_t CombinationIndex(std::uint32_t sourceSelector, std::uint32_t signExtend, std::uint32_t destinationSelector, std::uint32_t unused) { + return ((sourceSelector * 2u + signExtend) * Selectors + destinationSelector) * UnusedModes + unused; +} + +template +constexpr std::array> BuildCode() { + constexpr std::uint32_t sMovB32 = 0x03u; + constexpr std::uint32_t sMovB64 = 0x04u; + constexpr std::uint32_t vMovB32 = 0x01u; + constexpr std::uint32_t vMulU32U24 = 0x0bu; + constexpr std::uint32_t vLshlrevB32 = 0x1au; + constexpr std::uint32_t bufferLoadDwordIndexed = 0xe0302000u; + constexpr std::uint32_t bufferStoreDwordIndexed = 0xe0702000u; + constexpr std::uint32_t waitVmcnt = 0xbf8c3f70u; + std::array> code{}; + std::size_t count = 0; + code[count++] = Vop2(vLshlrevB32, InputIndexVector, ConstantOne, ThreadVector); + code[count++] = Vop2(vMulU32U24, OutputIndexVector, Literal, ThreadVector); + code[count++] = Results; + code[count++] = bufferLoadDwordIndexed; + code[count++] = BufferAccess(SourceVector, InputIndexVector, InputRegister); + code[count++] = bufferLoadDwordIndexed | 4u; + code[count++] = BufferAccess(PreviousVector, InputIndexVector, InputRegister); + code[count++] = waitVmcnt; + code[count++] = Vop1(vMovB32, BroadcastVector, VectorSource | SourceVector); + code[count++] = Sop1(sMovB32, ExecLoRegister, Literal); + code[count++] = BroadcastExec[0]; + if constexpr (WaveSize == 64u) { + code[count++] = Sop1(sMovB32, ExecHiRegister, Literal); + code[count++] = BroadcastExec[1]; + } + for (std::uint32_t byte = 1; byte < 4u; ++byte) { + code[count++] = Vop1(vMovB32, BroadcastVector, Sdwa); + code[count++] = SdwaModifier(BroadcastVector, byte, 2u, 0u, 0u); + } + code[count++] = WaveSize == 64u ? Sop1(sMovB64, ExecLoRegister, ConstantAllOnes) : Sop1(sMovB32, ExecLoRegister, ConstantAllOnes); + for (std::uint32_t sourceSelector = 0; sourceSelector < Selectors; ++sourceSelector) { + for (std::uint32_t signExtend = 0; signExtend < 2u; ++signExtend) { + for (std::uint32_t destinationSelector = 0; destinationSelector < Selectors; ++destinationSelector) { + for (std::uint32_t unused = 0; unused < UnusedModes; ++unused) { + code[count++] = Vop1(vMovB32, DataVector, VectorSource | PreviousVector); + code[count++] = Vop1(vMovB32, DataVector, Sdwa); + code[count++] = SdwaModifier(SourceVector, destinationSelector, unused, sourceSelector, signExtend); + code[count++] = bufferStoreDwordIndexed | (CombinationIndex(sourceSelector, signExtend, destinationSelector, unused) * 4u); + code[count++] = BufferAccess(DataVector, OutputIndexVector, OutputRegister); + } + } + } + } + code[count++] = bufferStoreDwordIndexed | (BroadcastResult * 4u); + code[count++] = BufferAccess(BroadcastVector, OutputIndexVector, OutputRegister); + code[count++] = Endpgm; + return code; +} + +alignas(256) constexpr std::array> Wave32Code = BuildCode<32>(); +alignas(256) constexpr std::array> Wave64Code = BuildCode<64>(); + +std::uint32_t Source(std::uint32_t tid) { + return std::rotl(Sources[tid % 32u], static_cast(tid / 32u) * 8); +} + +std::uint32_t Previous(std::uint32_t tid) { + return 0xabcd1234u ^ (tid * 0x01030507u); +} + +bool BroadcastActive(std::uint32_t tid) { + return ((BroadcastExec[tid / 32u] >> (tid % 32u)) & 1u) != 0u; +} + +void FillInput() { + for (std::uint32_t tid = 0; tid < MaxLanes; ++tid) { + Input[tid * Inputs] = Source(tid); + Input[tid * Inputs + 1u] = Previous(tid); + } +} + +std::uint32_t FieldOffset(std::uint32_t selector) { + return selector < 4u ? selector * 8u : (selector - 4u) * 16u; +} + +std::uint32_t FieldMask(std::uint32_t selector) { + return selector < 4u ? 0xffu : 0xffffu; +} + +std::uint32_t SignExtendField(std::uint32_t field, std::uint32_t mask) { + return (field & ((mask >> 1u) + 1u)) != 0u ? field | ~mask : field; +} + +std::uint32_t SelectSource(std::uint32_t value, std::uint32_t selector, bool signExtend) { + if (selector == 6u) { + return value; + } + const std::uint32_t field = (value >> FieldOffset(selector)) & FieldMask(selector); + return signExtend ? SignExtendField(field, FieldMask(selector)) : field; +} + +std::uint32_t PlaceDestination(std::uint32_t result, std::uint32_t selector, std::uint32_t unused, std::uint32_t previous) { + if (selector == 6u) { + return result; + } + const std::uint32_t offset = FieldOffset(selector); + const std::uint32_t mask = FieldMask(selector); + const std::uint32_t field = result & mask; + switch (unused) { + case 0u: return field << offset; + case 1u: return SignExtendField(field, mask) << offset; + default: return (previous & ~(mask << offset)) | (field << offset); + } +} + +std::string Hex(std::uint32_t value) { + char text[16]; + std::snprintf(text, sizeof(text), "0x%08x", value); + return text; +} + +std::string Describe(std::uint32_t sourceSelector, bool signExtend, std::uint32_t destinationSelector, std::uint32_t unused) { + constexpr const char* selectorNames[Selectors] = {"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD"}; + constexpr const char* unusedNames[UnusedModes] = {"UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"}; + return std::string("v_mov_b32_sdwa dst_sel:") + selectorNames[destinationSelector] + " dst_unused:" + unusedNames[unused] + + " src0_sel:" + selectorNames[sourceSelector] + (signExtend ? " sext" : ""); +} + +std::array BufferDescriptor(const void* data, std::uint32_t count) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (4u << 16u), count, 0x01016facu}; +} + +void Run(AgcDriver::VulkanDevice& device, std::span code, std::uint32_t waveSize, const ShaderRecompiler::SpirvTarget& target) { + Output.fill(0xdeadbeefu); + std::vector userData(8, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(Input.size())); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size())); + std::copy(input.begin(), input.end(), userData.begin() + InputRegister); + std::copy(output.begin(), output.end(), userData.begin() + OutputRegister); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{waveSize, 1, 1}, 0, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory}, + target, + {0, 0, 0, 128} + }; + request.useCache = false; + const auto result = ShaderRecompiler::Recompile(request); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void Check(std::uint32_t waveSize, const char* run, bool masked) { + for (std::uint32_t tid = 0; tid < waveSize; ++tid) { + const std::uint32_t source = Source(tid); + const std::uint32_t previous = Previous(tid); + const auto* out = &Output[tid * Results]; + const auto where = [&](std::uint32_t result) { + return std::string("sdwa move selectors ") + run + ": lane " + std::to_string(tid) + " source " + Hex(source) + " previous " + Hex(previous) + " result " + Hex(out[result]); + }; + for (std::uint32_t sourceSelector = 0; sourceSelector < Selectors; ++sourceSelector) { + for (std::uint32_t signExtend = 0; signExtend < 2u; ++signExtend) { + const std::uint32_t selected = SelectSource(source, sourceSelector, signExtend != 0u); + for (std::uint32_t destinationSelector = 0; destinationSelector < Selectors; ++destinationSelector) { + for (std::uint32_t unused = 0; unused < UnusedModes; ++unused) { + const std::uint32_t index = CombinationIndex(sourceSelector, signExtend, destinationSelector, unused); + const std::uint32_t expected = PlaceDestination(selected, destinationSelector, unused, previous); + Require(out[index] == expected, where(index) + ", expected " + Hex(expected) + ": " + Describe(sourceSelector, signExtend != 0u, destinationSelector, unused)); + } + } + } + } + if (!masked) continue; + if (BroadcastActive(tid)) { + const std::uint32_t broadcast = (source & 0xffu) * 0x01010101u; + Require(out[BroadcastResult] == broadcast, where(BroadcastResult) + ", expected " + Hex(broadcast) + ": in-place v_mov_b32_sdwa v3, v3 dst_sel:BYTE_1/2/3 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0 must copy byte 0 into the other bytes"); + } else { + Require(out[BroadcastResult] == source, where(BroadcastResult) + ", expected " + Hex(source) + ": the in-place v_mov_b32_sdwa must not write an inactive lane"); + } + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const bool masked = device->Target().subgroupSize >= 32u; + if (!masked) std::printf("EXEC-masked broadcast skipped, subgroup size %u cannot hold a wave32\n", device->Target().subgroupSize); + FillInput(); + Run(*device, Wave32Code, 32, device->Target()); + Check(32, "wave32", masked); + Run(*device, Wave64Code, 64, device->Target()); + Check(64, "wave64", masked); + Run(*device, Wave64Code, 64, device->ComputeTarget(32)); + Check(64, "wave64 split", masked); + std::puts("sdwa move selector tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp index 025e2844a..460a4c94d 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaVectorOpDecoder.cpp @@ -1112,7 +1112,7 @@ struct Vop1SdwaRule { }; constexpr Vop1SdwaRule vop1SdwaRules[] = { - {RdnaOpcode::VMovB32, sdwaSelAll(), sdwaSelBytes() | sdwaSelWords(), sdwaSelWords() | sdwaSelFull(), false}, + {RdnaOpcode::VMovB32, sdwaSelAll(), sdwaSelBytes() | sdwaSelWords(), sdwaSelAll(), false}, {RdnaOpcode::VCvtF32U32, sdwaSelAll(), 0, 0, false}, {RdnaOpcode::VCvtF32I32, sdwaSelAll(), 0, 0, false}, {RdnaOpcode::VCvtF32Ubyte0, sdwaSelAll(), 0, 0, false}, From 4b0119426b48851ecdd8740d9ec2be5531d37e29 Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:08:39 +0200 Subject: [PATCH 15/42] feat(voiceqos): accept app type 0x10000000 in sceVoiceQoSInit sceVoiceQoSInit accepted only app type 0x20000000 and threw for every other value. PPSA26344 v1.008 passes 0x10000000 at both of its call sites, so its initialization threw. Accept 0x10000000 as a second known app type. Its meaning is unknown, so the constant is named after the value, and it is handled like 0x20000000; the block stays unused. A null or empty block, a second initialization and every other app type still throw. guest_voice_qos_tests now takes the app type as its argument and runs in ctest once per accepted value, because sceVoiceQoSEnd still throws and one process can initialize only once. --- core/libs/prx/libSceVoiceQoS/CMakeLists.txt | 5 +++-- core/libs/prx/libSceVoiceQoS/Export.cpp | 3 ++- core/libs/tests/GuestVoiceQoS.cpp | 13 ++++++++----- docs/dev/TechnicalDebt.md | 2 +- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceVoiceQoS/CMakeLists.txt b/core/libs/prx/libSceVoiceQoS/CMakeLists.txt index 29d56e9ad..31d6ed141 100644 --- a/core/libs/prx/libSceVoiceQoS/CMakeLists.txt +++ b/core/libs/prx/libSceVoiceQoS/CMakeLists.txt @@ -13,9 +13,10 @@ if(BUILD_TESTING) target_include_directories(guest_voice_qos_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_voice_qos_tests PRIVATE libSceVoiceQoS libc) configure_windows_unwind(guest_voice_qos_tests) - add_test(NAME guest_voice_qos COMMAND guest_voice_qos_tests) + add_test(NAME guest_voice_qos COMMAND guest_voice_qos_tests 0x20000000) + add_test(NAME guest_voice_qos_app_type_0x10000000 COMMAND guest_voice_qos_tests 0x10000000) if(WIN32) - set_tests_properties(guest_voice_qos PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(guest_voice_qos guest_voice_qos_app_type_0x10000000 PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceVoiceQoS/Export.cpp b/core/libs/prx/libSceVoiceQoS/Export.cpp index 20ff9b24d..9cc97fe93 100644 --- a/core/libs/prx/libSceVoiceQoS/Export.cpp +++ b/core/libs/prx/libSceVoiceQoS/Export.cpp @@ -9,6 +9,7 @@ namespace { constexpr std::int32_t VOICE_QOS_APP_TYPE_GAME = 0x20000000; +constexpr std::int32_t VOICE_QOS_APP_TYPE_10000000 = 0x10000000; std::mutex g_mutex; bool g_initialized = false; @@ -19,7 +20,7 @@ extern "C" { int APS5_VABI sceVoiceQoSInit(void* mem_block, uint32_t mem_size, int32_t app_type) { if (!mem_block || mem_size == 0) throw std::invalid_argument("sceVoiceQoSInit: null or empty memory block"); - if (app_type != VOICE_QOS_APP_TYPE_GAME) throw std::invalid_argument("sceVoiceQoSInit: unsupported app type " + std::to_string(app_type)); + if (app_type != VOICE_QOS_APP_TYPE_GAME && app_type != VOICE_QOS_APP_TYPE_10000000) throw std::invalid_argument("sceVoiceQoSInit: unsupported app type " + std::to_string(app_type)); std::lock_guard lock(g_mutex); if (g_initialized) throw std::runtime_error("sceVoiceQoSInit: already initialized"); g_initialized = true; diff --git a/core/libs/tests/GuestVoiceQoS.cpp b/core/libs/tests/GuestVoiceQoS.cpp index 9f9e668a6..552a0bf73 100644 --- a/core/libs/tests/GuestVoiceQoS.cpp +++ b/core/libs/tests/GuestVoiceQoS.cpp @@ -20,11 +20,14 @@ static bool Throws(TFunction function) { return false; } -int main() { +int main(int argc, char** argv) { + Require(argc == 2); + const auto appType = static_cast(std::strtoul(argv[1], nullptr, 16)); std::vector memory(0x40000); - Require(Throws([&] { sceVoiceQoSInit(nullptr, 0x40000, 0x20000000); })); - Require(Throws([&] { sceVoiceQoSInit(memory.data(), 0, 0x20000000); })); + Require(Throws([&] { sceVoiceQoSInit(nullptr, 0x40000, appType); })); + Require(Throws([&] { sceVoiceQoSInit(memory.data(), 0, appType); })); Require(Throws([&] { sceVoiceQoSInit(memory.data(), 0x40000, 0); })); - Require(sceVoiceQoSInit(memory.data(), 0x40000, 0x20000000) == 0); - Require(Throws([&] { sceVoiceQoSInit(memory.data(), 0x40000, 0x20000000); })); + Require(Throws([&] { sceVoiceQoSInit(memory.data(), 0x40000, 0x30000000); })); + Require(sceVoiceQoSInit(memory.data(), 0x40000, appType) == 0); + Require(Throws([&] { sceVoiceQoSInit(memory.data(), 0x40000, appType); })); } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index b57c3f774..cf46e3ec9 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -83,7 +83,7 @@ Throughout the project, every function at every stage either **does exactly what - [scePsmlMfsrGetContextBufferRequirement1100, scePsmlMfsrCreateContext1100, scePsmlMfsrGetDispatchMfsrPacket1100](../../core/libs/prx/libScePsml_debug/Export.cpp) (libScePsml_debug) - argument layouts unknown; only 0x8A810001 (not initialized) is returned - [BnMAMrsfVWo](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libc) - unknown name, signature - [scePngEncEncode](../../core/libs/prx/libScePngEnc/Export.cpp) (libScePngEnc) - whether rows may stay unfiltered when `filter_type` names a subset of the filters is unknown; as in shadPS4, they may only for 0 and for the all-filters mask -- [sceVoiceQoSInit](../../core/libs/prx/libSceVoiceQoS/Export.cpp) (libSceVoiceQoS) - the error codes are unknown: a null or empty memory block, an app type other than 0x20000000 (the value PPSA14632 passes) and a second initialization throw. The minimum memory size is unknown and the block is not used, as no endpoint is implemented +- [sceVoiceQoSInit](../../core/libs/prx/libSceVoiceQoS/Export.cpp) (libSceVoiceQoS) - the error codes are unknown: a null or empty memory block, an app type other than 0x20000000 (PPSA14632) or 0x10000000 (PPSA26344) and a second initialization throw. The minimum memory size is unknown; the app type and the block are not used, as no endpoint is implemented - AudioIn, NpSessionSignaling and PlayerInvitationDialog exports added without an implementation have assumed signatures - [vieBRwlh1Lw](../../core/libs/prx/libSceAgc/Unimplemented.cpp) (libSceAgc) - unknown name, signature - [fCWdlnmB1Ks](../../core/libs/prx/libScePad/Export.cpp) (libScePad) - unknown name, signature From e2634022962479da8a539c6afdf98e84a698203e Mon Sep 17 00:00:00 2001 From: Chad Date: Mon, 5 Oct 2026 19:56:34 -0500 Subject: [PATCH 16/42] feat(shader): implement image_msaa_load Decode MIMG opcode 0x80 on 2D MSAA and 2D MSAA array images with a single-bit dmask and return four dwords: the selected component of the fragment named in the address and the three that follow it. Each fragment is read with its own image fetch, adding the fragment step to the packed address dword so a16 layouts keep working. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 8 +++ core/libs/tests/ImageMsaaLoad.cpp | 69 +++++++++++++++++++ .../include/RdnaDecoder/RdnaOpcode.hpp | 1 + .../RdnaDecoder/src/RdnaImageOpDecoder.cpp | 9 ++- .../recompiler/RdnaDecoder/src/RdnaOpcode.cpp | 1 + .../Translation/TranslationContext.hpp | 3 +- .../MemoryInstructions/ImageInstructions.cpp | 14 ++++ .../MemoryInstructionDispatch.cpp | 2 + .../MemoryResourceHelpers.cpp | 7 +- 9 files changed, 110 insertions(+), 4 deletions(-) create mode 100644 core/libs/tests/ImageMsaaLoad.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 90d971f7a..d35258026 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -780,6 +780,14 @@ if(BUILD_TESTING) set_tests_properties(image_sample_gather PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(image_msaa_load_tests ${LIBS_INCLUDE_DIR}/tests/ImageMsaaLoad.cpp) + target_link_libraries(image_msaa_load_tests PRIVATE shader_recompiler_agc_driver libc) + configure_windows_unwind(image_msaa_load_tests) + add_test(NAME image_msaa_load COMMAND image_msaa_load_tests) + if(WIN32) + set_tests_properties(image_msaa_load PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_indexed_draw_tests ${LIBS_INCLUDE_DIR}/tests/GuestIndexedDraw.cpp) target_include_directories(guest_indexed_draw_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_indexed_draw_tests PRIVATE libSceAgc libSceAgcDriver libc) diff --git a/core/libs/tests/ImageMsaaLoad.cpp b/core/libs/tests/ImageMsaaLoad.cpp new file mode 100644 index 000000000..4e3a57353 --- /dev/null +++ b/core/libs/tests/ImageMsaaLoad.cpp @@ -0,0 +1,69 @@ +#include "Translation/TranslationContext.hpp" +#include "RdnaDecoder/RdnaImageOpDecoder.hpp" +#include +#include +#include + +using namespace ShaderRecompiler; +static void Require(bool value) { if (!value) throw std::runtime_error("image msaa load regression"); } +static std::uint32_t Word0(std::uint32_t dmask, std::uint32_t dimension) { + return (0x3cu << 26u) | (dmask << 8u) | (dimension << 3u) | 1u; +} +static RdnaInstruction Decode(std::uint32_t word0, std::uint32_t word1) { + const std::array code{word0, word1}; + return DecodeRdnaMimg(0u, code, 0u); +} +static bool Rejects(std::uint32_t word0, std::uint32_t word1) { + try { + (void)Decode(word0, word1); + } catch (const std::runtime_error&) { + return true; + } + return false; +} +static void Check(std::uint32_t dimension, bool a16, std::uint32_t components, std::uint32_t fragmentDword, std::uint32_t fragmentShift) { + const RdnaInstruction instruction = Decode(Word0(0x4u, dimension), (a16 ? 0x40000000u : 0u) | (8u << 8u)); + Require(instruction.op == RdnaOpcode::ImageMsaaLoad); + Require(instruction.family == RdnaInstructionFamily::MIMG); + Require(IsImageOpcode(instruction.op)); + Require(instruction.imageOpcodeId == 0x80u); + Require(instruction.imageAddressComponents == components); + Require(instruction.dataComponents == 4u); + Require(instruction.dataDwordCount == 4u); + IrProgram program; + auto& block = program.CreateBlock(); + program.SetEntryBlock(block); + TranslationContext context(program, block, 256); + context.TranslateInstruction(instruction); + std::vector reads; + for (auto* value : block.Instructions()) { + if (value->Opcode() == IrOpcode::ImageRead) { + reads.push_back(value); + } + } + Require(reads.size() == 4u); + for (std::uint32_t fragment = 0u; fragment < 4u; ++fragment) { + IrValue* address = reads[fragment]->Argument(1)->Resolve(); + Require(address->Opcode() == IrOpcode::MakeImageAddress); + IrValue* word = address->Argument(fragmentDword)->Resolve(); + if (fragment == 0u) { + Require(word->Opcode() != IrOpcode::IAdd32); + continue; + } + Require(word->Opcode() == IrOpcode::IAdd32); + IrValue* offset = word->Argument(1)->Resolve(); + Require(offset->HasImmediate() && offset->ImmediateU32() == fragment << fragmentShift); + const auto& memory = program.Resources().memoryInfo[reads[fragment]->Flags().index]; + Require(memory.dmask == 0x4u && memory.dataDwords == 1u); + } +} +int main() { + Check(6u, false, 3u, 2u, 0u); + Check(7u, false, 4u, 3u, 0u); + Check(6u, true, 3u, 1u, 0u); + Check(7u, true, 4u, 1u, 16u); + Require(Rejects(Word0(0x1u, 1u), 0u)); + Require(Rejects(Word0(0x3u, 6u), 0u)); + Require(Rejects(Word0(0x1u, 6u), 0x80000000u)); + Require(Rejects(Word0(0x1u, 6u) | 0x00010000u, 0u)); +} diff --git a/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp b/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp index 5986b1d72..ef4daa6c7 100644 --- a/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp +++ b/core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp @@ -955,6 +955,7 @@ enum class RdnaOpcode : std::uint16_t { ImageStoreMip, ImageStorePck, ImageStoreMipPck, + ImageMsaaLoad, ImageAtomicSwap, ImageAtomicAdd, ImageAtomicUmin, diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp index 53e957a5e..b4d31ad94 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp @@ -132,6 +132,7 @@ constexpr ImageOpcodeInfo imageOpcodes[] = { {0x0au, RdnaOpcode::ImageStorePck, nullptr, 0, false, false, false}, {0x0bu, RdnaOpcode::ImageStoreMipPck, nullptr, 0, false, false, false}, {0x0eu, RdnaOpcode::ImageGetResinfo, nullptr, 0, false, false, false}, + {0x80u, RdnaOpcode::ImageMsaaLoad, nullptr, 0, false, false, false}, {0x60u, RdnaOpcode::ImageGetLod, nullptr, 0, false, false, false}, {0xe6u, RdnaOpcode::ImageBvhIntersectRay, "image_bvh_intersect_ray", 0, false, false, false}, {0xe7u, RdnaOpcode::ImageBvh64IntersectRay, "image_bvh64_intersect_ray", 0, false, false, false}, @@ -336,6 +337,10 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span= 1u && opcode <= 5u) || opcode == 9u || opcode == 0x0bu)) { throw std::runtime_error("unsupported multisampled MIMG operation"); } + const bool msaaLoad = info.opcode == RdnaOpcode::ImageMsaaLoad; + if (msaaLoad && !multisampled) { + throw std::runtime_error("image_msaa_load requires a multisampled dimension"); + } auto flags = info.flags | (a16 ? RdnaImageSampleFlagA16 : 0u); if ((info.flags & RdnaImageSampleFlagDerivative) != 0u) { flags |= gradientCount(dimension) << RdnaImageSampleGradientCountShift; @@ -343,7 +348,7 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span> 8u) & 15u; const bool compareSwap = info.opcode == RdnaOpcode::ImageAtomicCmpswap || info.opcode == RdnaOpcode::ImageAtomicFcmpswap; - if (dmask == 0u || (compareSwap ? dmask != 3u : (info.gather || info.atomic) && !std::has_single_bit(dmask))) { + if (dmask == 0u || (compareSwap ? dmask != 3u : (info.gather || info.atomic || msaaLoad) && !std::has_single_bit(dmask))) { throw std::runtime_error("invalid MIMG data mask"); } if (d16 && !(info.sample || info.gather || opcode == 0u || opcode == 1u || opcode == 8u || opcode == 9u)) { @@ -371,7 +376,7 @@ RdnaInstruction DecodeRdnaMimg(std::uint32_t programCounter, std::span 256u - vaddr) { throw std::runtime_error("MIMG address register range overflow"); } - const auto dataComponents = info.gather ? 4u : static_cast(std::popcount(dmask)); + const auto dataComponents = info.gather || msaaLoad ? 4u : static_cast(std::popcount(dmask)); const auto dataDwords = d16 ? (dataComponents + 1u) / 2u : dataComponents; const auto statusDwords = (word0 & 0x00010000u) != 0u ? 1u : 0u; if (dataDwords + statusDwords > 256u - vdata) { diff --git a/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp b/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp index e68c49ad1..0171c61c9 100644 --- a/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp +++ b/core/shader/recompiler/RdnaDecoder/src/RdnaOpcode.cpp @@ -822,6 +822,7 @@ bool IsImageOpcode(RdnaOpcode opcode) { case RdnaOpcode::ImageStoreMip: case RdnaOpcode::ImageStorePck: case RdnaOpcode::ImageStoreMipPck: + case RdnaOpcode::ImageMsaaLoad: case RdnaOpcode::ImageAtomicSwap: case RdnaOpcode::ImageAtomicAdd: case RdnaOpcode::ImageAtomicUmin: diff --git a/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp b/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp index 50e26ccf8..4f4db7b11 100644 --- a/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp +++ b/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp @@ -79,7 +79,7 @@ private: IrValue* getScalarAddressResource(std::uint32_t base); IrValue* getImageResource(const MemoryInfo& memory); IrValue* getSamplerResource(const MemoryInfo& memory); - IrValue* makeImageAddress(const RdnaInstruction& inst, const RdnaOperand& base); + IrValue* makeImageAddress(const RdnaInstruction& inst, const RdnaOperand& base, std::uint32_t fragmentOffset = 0u); IrValue* constructU32x4(const RdnaOperand& base, std::uint32_t count); void writeImageComponents(const RdnaOperand& dst, IrValue* value, const MemoryInfo& memory, std::uint32_t componentLimit); BufferAddress readBufferAddress(const RdnaInstruction& inst); @@ -100,6 +100,7 @@ private: bool imageGetResinfo(const RdnaInstruction& inst); bool imageGetLod(const RdnaInstruction& inst); bool imageLoad(const RdnaInstruction& inst); + bool imageMsaaLoad(const RdnaInstruction& inst); bool imageStore(const RdnaInstruction& inst); bool imageSample(const RdnaInstruction& inst); bool imageGather(const RdnaInstruction& inst); diff --git a/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp b/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp index 2f0bf639b..0207f3e53 100644 --- a/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp +++ b/core/shader/recompiler/Translation/src/MemoryInstructions/ImageInstructions.cpp @@ -120,6 +120,20 @@ bool TranslationContext::imageLoad(const RdnaInstruction& inst) { return true; } +bool TranslationContext::imageMsaaLoad(const RdnaInstruction& inst) { + MemoryInfo memory = imageMemoryInfoFromInstruction(inst); + memory.dataDwords = 1u; + memory.componentCount = 1u; + IrValue* resource = getImageResource(memory); + IrValue& exec = ir.GetExec(); + for (std::uint32_t fragment = 0u; fragment < 4u; ++fragment) { + IrValue* address = makeImageAddress(inst, inst.source0, fragment); + IrValue& result = ir.Emit(IrOpcode::ImageRead, IrOpcodeType(IrOpcode::ImageRead), {resource, address, &exec}, addMemoryInfo(memory, inst.programCounter)); + writeImageComponents(offsetOperand(inst.destination, fragment), &result, memory, 4u); + } + return true; +} + bool TranslationContext::imageStore(const RdnaInstruction& inst) { const MemoryInfo memory = imageMemoryInfoFromInstruction(inst); IrValue* resource = getImageResource(memory); diff --git a/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp b/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp index 24993bd96..5e0a602da 100644 --- a/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp +++ b/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryInstructionDispatch.cpp @@ -600,6 +600,8 @@ bool TranslationContext::emitMemory(const RdnaInstruction& inst) { case RdnaOpcode::ImageLoadMipPck: case RdnaOpcode::ImageLoadMipPckSgn: return imageLoad(inst); + case RdnaOpcode::ImageMsaaLoad: + return imageMsaaLoad(inst); case RdnaOpcode::ImageStore: case RdnaOpcode::ImageStoreMip: case RdnaOpcode::ImageStorePck: diff --git a/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryResourceHelpers.cpp b/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryResourceHelpers.cpp index 369b78f6c..bff55b085 100644 --- a/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryResourceHelpers.cpp +++ b/core/shader/recompiler/Translation/src/MemoryInstructions/MemoryResourceHelpers.cpp @@ -93,7 +93,7 @@ IrValue* TranslationContext::getSamplerResource(const MemoryInfo& memory) { return &ir.Emit(IrOpcode::GetSamplerResource, IrOpcodeType(IrOpcode::GetSamplerResource), {&dword0.Value(), &dword1.Value(), &dword2.Value(), &dword3.Value()}); } -IrValue* TranslationContext::makeImageAddress(const RdnaInstruction& inst, const RdnaOperand& base) { +IrValue* TranslationContext::makeImageAddress(const RdnaInstruction& inst, const RdnaOperand& base, std::uint32_t fragmentOffset) { std::array components{}; IrValue& zero = ir.Constant(0u); components.fill(&zero); @@ -110,6 +110,11 @@ IrValue* TranslationContext::makeImageAddress(const RdnaInstruction& inst, const components[index] = &readRawU32(offsetOperand(plainBase, index)).Value(); } } + if (fragmentOffset != 0u) { + const RdnaImageAddressComponent fragment = GetRdnaImageAddressComponentLayout(inst.imageSampleFlags, inst.imageAddressComponents - 1u); + IrValue*& word = components[fragment.bitOffset / 32u]; + word = &ir.IAdd(*word, ir.Constant(fragmentOffset << (fragment.bitOffset % 32u))); + } if ((inst.imageSampleFlags & RdnaImageSampleFlagCd) != 0u) { const auto mask = ballotMask(IrU1(ir.GetExec())); IrValue& lane = ir.Emit(IrOpcode::LaneId, IrType::U32, {}); From 5d99f135d78212343ba57ba9ab967e2b790cbd9f Mon Sep 17 00:00:00 2001 From: Chad Date: Mon, 5 Oct 2026 20:07:28 -0500 Subject: [PATCH 17/42] feat(libSceAgcDriver): answer the resource registration queries Registration of owners and resources fails with RESOURCE_REGISTRATION_UNAVAILABLE, so no handle is ever valid: the owner and resource getters, sceAgcDriverSetResourceUserData, sceAgcDriverRegisterGdsResource, sceAgcDriverFindResourcesPublic, sceAgcDriverUnregisterAllResourcesForOwner and sceAgcDriverGetDefaultOwner return the same error. sceAgcDriverUnregisterWorkloadStream mirrors the accepting RegisterWorkloadStream. No capture, trace or submit validation ever runs, so their status queries report false. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 9 +++ .../Resource/src/Registration.cpp | 75 +++++++++++++++++++ .../prx/libSceAgcDriver/State/src/Status.cpp | 9 +-- .../prx/libSceAgcDriver/Unimplemented.cpp | 60 --------------- core/libs/tests/GuestAgcDriverResources.cpp | 61 +++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 6 files changed, 149 insertions(+), 66 deletions(-) create mode 100644 core/libs/tests/GuestAgcDriverResources.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 90d971f7a..af284a422 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -675,6 +675,15 @@ if(BUILD_TESTING) set_tests_properties(linear_display_buffer PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(guest_agc_driver_resources_tests ${LIBS_INCLUDE_DIR}/tests/GuestAgcDriverResources.cpp) + target_include_directories(guest_agc_driver_resources_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_agc_driver_resources_tests PRIVATE libSceAgcDriver libc) + configure_windows_unwind(guest_agc_driver_resources_tests) + add_test(NAME guest_agc_driver_resources COMMAND guest_agc_driver_resources_tests) + if(WIN32) + set_tests_properties(guest_agc_driver_resources PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_rendering_wait_tests ${LIBS_INCLUDE_DIR}/tests/GuestRenderingWait.cpp) target_include_directories(guest_rendering_wait_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_rendering_wait_tests PRIVATE libSceAgcDriver libc) diff --git a/core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp b/core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp index 7aec5262e..4e5eaa6ab 100644 --- a/core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp +++ b/core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp @@ -43,4 +43,79 @@ int APS5_VABI sceAgcDriverUnregisterResource(uint32_t resource_handle) { return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; } +int APS5_VABI sceAgcDriverRegisterGdsResource(uint32_t* resource_handle, uint32_t owner_handle, uint32_t gds_offset, uint32_t gds_size, const char* name, uint32_t type, uint64_t user_data) { + (void)resource_handle; + (void)owner_handle; + (void)gds_offset; + (void)gds_size; + (void)name; + (void)type; + (void)user_data; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverUnregisterAllResourcesForOwner(uint32_t owner_handle) { + (void)owner_handle; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverUnregisterWorkloadStream(uint32_t stream_id) { + (void)stream_id; + return 0; +} + +int APS5_VABI sceAgcDriverGetDefaultOwner(uint32_t* owner_handle) { + (void)owner_handle; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverGetOwnerName(uint32_t owner_handle, const char** name) { + (void)owner_handle; + (void)name; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverGetResourceName(uint32_t resource_handle, const char** name) { + (void)resource_handle; + (void)name; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverGetResourceType(uint32_t resource_handle, uint32_t* type) { + (void)resource_handle; + (void)type; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverGetResourceUserData(uint32_t resource_handle, uint64_t* user_data) { + (void)resource_handle; + (void)user_data; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverSetResourceUserData(uint32_t resource_handle, uint64_t user_data) { + (void)resource_handle; + (void)user_data; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverGetResourceBaseAddressAndSizeInBytes(uint32_t resource_handle, void** memory, size_t* size) { + (void)resource_handle; + (void)memory; + (void)size; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverGetResourceShaderGuid(uint32_t resource_handle, void* guid) { + (void)resource_handle; + (void)guid; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + +int APS5_VABI sceAgcDriverFindResourcesPublic(const void* callback, void* user_data) { + (void)callback; + (void)user_data; + return SCE_AGC_ERROR_RESOURCE_REGISTRATION_UNAVAILABLE; +} + } diff --git a/core/libs/prx/libSceAgcDriver/State/src/Status.cpp b/core/libs/prx/libSceAgcDriver/State/src/Status.cpp index e38b28277..ae1a8543f 100644 --- a/core/libs/prx/libSceAgcDriver/State/src/Status.cpp +++ b/core/libs/prx/libSceAgcDriver/State/src/Status.cpp @@ -8,18 +8,15 @@ extern "C" { bool APS5_VABI sceAgcDriverIsCaptureInProgress(void) { - NotImplemented_nid_no_patch(__func__); - return false; + return false; } bool APS5_VABI sceAgcDriverIsTraceInProgress(void) { - NotImplemented_nid_no_patch(__func__); - return false; + return false; } bool APS5_VABI sceAgcDriverIsSubmitValidationEnabled(void) { - NotImplemented_nid_no_patch(__func__); - return false; + return false; } int APS5_VABI sceAgcDriverRequestCaptureStart(const char* path) { diff --git a/core/libs/prx/libSceAgcDriver/Unimplemented.cpp b/core/libs/prx/libSceAgcDriver/Unimplemented.cpp index 775fcced3..8add7f045 100644 --- a/core/libs/prx/libSceAgcDriver/Unimplemented.cpp +++ b/core/libs/prx/libSceAgcDriver/Unimplemented.cpp @@ -5,51 +5,11 @@ extern "C" { -int APS5_VABI sceAgcDriverFindResourcesPublic() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverGetDefaultOwner() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverGetOwnerName() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverGetResourceBaseAddressAndSizeInBytes() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverGetResourceName() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI sceAgcDriverGetResourceRegistrationMaxNameLength() { NotImplemented_nid_no_patch(__func__); return 0; } -int APS5_VABI sceAgcDriverGetResourceShaderGuid() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverGetResourceType() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverGetResourceUserData() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI sceAgcDriverGetShaderDebuggingStatus() { NotImplemented_nid_no_patch(__func__); return 0; @@ -60,31 +20,11 @@ int APS5_VABI sceAgcDriverRegisterDefaultOwner(uint32_t* owner_handle) { return static_cast(0x8A6C9018); } -int APS5_VABI sceAgcDriverRegisterGdsResource() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverSetResourceUserData() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI sceAgcDriverSetValidationErrorOutputFrequency() { NotImplemented_nid_no_patch(__func__); return 0; } -int APS5_VABI sceAgcDriverUnregisterAllResourcesForOwner() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sceAgcDriverUnregisterWorkloadStream() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI sceAgcDriverSetSubmitValidationMode() { NotImplemented_nid_no_patch(__func__); return 0; diff --git a/core/libs/tests/GuestAgcDriverResources.cpp b/core/libs/tests/GuestAgcDriverResources.cpp new file mode 100644 index 000000000..d476831c1 --- /dev/null +++ b/core/libs/tests/GuestAgcDriverResources.cpp @@ -0,0 +1,61 @@ +#include "SceTypes.hpp" +#include +#include +#include +#include + +extern "C" { +int APS5_VABI sceAgcDriverRegisterOwner(std::uint32_t*, const char*); +int APS5_VABI sceAgcDriverRegisterResource(std::uint32_t*, std::uint32_t, const void*, std::size_t, const char*, std::uint32_t, std::uint64_t); +int APS5_VABI sceAgcDriverRegisterGdsResource(std::uint32_t*, std::uint32_t, std::uint32_t, std::uint32_t, const char*, std::uint32_t, std::uint64_t); +int APS5_VABI sceAgcDriverUnregisterAllResourcesForOwner(std::uint32_t); +int APS5_VABI sceAgcDriverRegisterWorkloadStream(std::uint32_t, const void*); +int APS5_VABI sceAgcDriverUnregisterWorkloadStream(std::uint32_t); +int APS5_VABI sceAgcDriverGetDefaultOwner(std::uint32_t*); +int APS5_VABI sceAgcDriverGetOwnerName(std::uint32_t, const char**); +int APS5_VABI sceAgcDriverGetResourceName(std::uint32_t, const char**); +int APS5_VABI sceAgcDriverGetResourceType(std::uint32_t, std::uint32_t*); +int APS5_VABI sceAgcDriverGetResourceUserData(std::uint32_t, std::uint64_t*); +int APS5_VABI sceAgcDriverSetResourceUserData(std::uint32_t, std::uint64_t); +int APS5_VABI sceAgcDriverGetResourceBaseAddressAndSizeInBytes(std::uint32_t, void**, std::size_t*); +int APS5_VABI sceAgcDriverGetResourceShaderGuid(std::uint32_t, void*); +int APS5_VABI sceAgcDriverFindResourcesPublic(const void*, void*); +bool APS5_VABI sceAgcDriverIsCaptureInProgress(void); +bool APS5_VABI sceAgcDriverIsTraceInProgress(void); +bool APS5_VABI sceAgcDriverIsSubmitValidationEnabled(void); +} + +static constexpr int Unavailable = static_cast(0x8A6C9018); +static void Require(bool value) { if (!value) std::abort(); } + +int main() { + std::uint32_t owner = 7u; + std::uint32_t resource = 9u; + const std::uint32_t memory[4]{}; + Require(sceAgcDriverRegisterOwner(&owner, "owner") == Unavailable); + Require(sceAgcDriverRegisterResource(&resource, owner, memory, sizeof(memory), "resource", 1u, 2u) == Unavailable); + Require(sceAgcDriverRegisterGdsResource(&resource, owner, 0u, 64u, "gds", 1u, 2u) == Unavailable); + Require(owner == 7u && resource == 9u); + Require(sceAgcDriverGetDefaultOwner(&owner) == Unavailable && owner == 7u); + const char* name = "unchanged"; + Require(sceAgcDriverGetOwnerName(owner, &name) == Unavailable); + Require(sceAgcDriverGetResourceName(resource, &name) == Unavailable); + std::uint32_t type = 3u; + Require(sceAgcDriverGetResourceType(resource, &type) == Unavailable && type == 3u); + std::uint64_t userData = 4u; + Require(sceAgcDriverGetResourceUserData(resource, &userData) == Unavailable && userData == 4u); + Require(sceAgcDriverSetResourceUserData(resource, 5u) == Unavailable); + void* base = nullptr; + std::size_t size = 6u; + Require(sceAgcDriverGetResourceBaseAddressAndSizeInBytes(resource, &base, &size) == Unavailable && base == nullptr && size == 6u); + std::uint8_t guid[16]{}; + Require(sceAgcDriverGetResourceShaderGuid(resource, guid) == Unavailable); + Require(sceAgcDriverFindResourcesPublic(nullptr, nullptr) == Unavailable); + Require(sceAgcDriverUnregisterAllResourcesForOwner(owner) == Unavailable); + Require(std::string_view(name) == "unchanged"); + Require(sceAgcDriverRegisterWorkloadStream(1u, memory) == 0); + Require(sceAgcDriverUnregisterWorkloadStream(1u) == 0); + Require(!sceAgcDriverIsCaptureInProgress()); + Require(!sceAgcDriverIsTraceInProgress()); + Require(!sceAgcDriverIsSubmitValidationEnabled()); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index b57c3f774..d6ac07fc1 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -117,6 +117,7 @@ Throughout the project, every function at every stage either **does exactly what - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) - the added `sceUltQueuePop`, `sceUltQueueTryPush`, `sceUltQueueDestroy` and `sceUltQueueDataResourcePoolDestroy` signatures are inferred from the existing push/pop and object APIs. Queue destruction is assumed to reject blocked callers with `ULT_ERROR_BUSY` and otherwise discard queued data; pool exhaustion returns `ULT_ERROR_AGAIN`. These rules, alignment checks and shared slot limits have not been confirmed on PS5 hardware or a title. Non-null queue and data-pool option parameters throw because their layouts are unknown. - [_sceUlobjmgrRegisterObject](../../core/libs/prx/ulobjmgr/Export.cpp) (ulobjmgr) - parameters taken from shadPS4 (PS4): a nonzero 64-bit object, a nonzero 32-bit kind and a 32-bit id output; the meaning of the first two and the PS5 signature are unverified. The id bound of `_sceUlobjmgrUnregisterObject` (below 0x4000) and the raw `EINVAL` (22) return also come from shadPS4 - [sceShareGetCurrentStatus](../../core/libs/prx/libSceShare/Export.cpp) (libSceShare) - validation (feature flag non-zero, status non-null) and the all-zero 16-byte status taken from the [KytyPS5](https://github.com/KytyPS5/KytyPS5) reimplementation, not confirmed on a PS5 title; the meaning of the recording status values is unknown +- [Resource registration](../../core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp) (libSceAgcDriver) - registration always fails with `RESOURCE_REGISTRATION_UNAVAILABLE`, so the owner and resource queries, `sceAgcDriverSetResourceUserData`, `sceAgcDriverFindResourcesPublic` and `sceAgcDriverUnregisterAllResourcesForOwner` return the same error without reading their arguments. Their parameter lists follow the libSceGnmDriver counterparts and are unverified ### Functional From 77550ab731944d70ff803de3a377cef36fcd26e0 Mon Sep 17 00:00:00 2001 From: Chad Date: Mon, 5 Oct 2026 20:10:13 -0500 Subject: [PATCH 18/42] feat(libkernel): implement sendmsg and recvmsg Both take the FreeBSD msghdr (48 bytes, iovecs of a pointer and a 64-bit length) and run on the host sockets: sendmsg gathers the iovecs and sends through sendto, recvmsg receives into one buffer and scatters it. A datagram longer than the iovecs is cut and reported with MSG_TRUNC, also on Windows where recvfrom fails with WSAEMSGSIZE. More than 1024 iovecs fail with EMSGSIZE. No ancillary data is ever received, so recvmsg clears msg_controllen; sending control data throws. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libkernel/Socket/src/Udp.cpp | 93 ++++++++++++++++++++++ core/libs/prx/libkernel/Unimplemented.cpp | 10 --- core/libs/tests/GuestUdp.cpp | 50 ++++++++++++ 3 files changed, 143 insertions(+), 10 deletions(-) diff --git a/core/libs/prx/libkernel/Socket/src/Udp.cpp b/core/libs/prx/libkernel/Socket/src/Udp.cpp index bffca9598..ea3b56fa0 100644 --- a/core/libs/prx/libkernel/Socket/src/Udp.cpp +++ b/core/libs/prx/libkernel/Socket/src/Udp.cpp @@ -20,6 +20,9 @@ #include #include #include +#include +#include +#include extern "C" int* APS5_VABI __error_nid_postfix(); namespace { @@ -383,4 +386,94 @@ std::int64_t APS5_VABI recvfrom_nid_postfix(int descriptor, void* buffer, std::u if (address) GuestAddress(native, address, addressLength); return result; } +struct GuestIovec { + void* base; + std::uint64_t length; +}; +struct GuestMsghdr { + void* name; + std::uint32_t nameLength; + GuestIovec* iov; + int iovLength; + void* control; + std::uint32_t controlLength; + int flags; +}; +static_assert(sizeof(GuestMsghdr) == 48 && offsetof(GuestMsghdr, iov) == 16 && offsetof(GuestMsghdr, control) == 32 && offsetof(GuestMsghdr, flags) == 44); +static std::int64_t MessageLength(const GuestMsghdr* message) { + if (!message) return Fail(14); + if (message->iovLength < 0 || message->iovLength > 1024) return Fail(40); + if (message->iovLength && !message->iov) return Fail(14); + std::uint64_t total = 0; + for (int i = 0; i < message->iovLength; ++i) { + const auto& entry = message->iov[i]; + if (!entry.base && entry.length) return Fail(14); + if (entry.length > INT_MAX - total) return Fail(22); + total += entry.length; + } + return static_cast(total); +} +std::int64_t APS5_VABI sendmsg_nid_postfix(int descriptor, const GuestMsghdr* message, int flags) { + const auto total = MessageLength(message); + if (total < 0) return -1; + if (message->control && message->controlLength) throw std::runtime_error("sendmsg: control data is not supported"); + std::vector buffer; + try { + buffer.resize(static_cast(total)); + } catch (const std::bad_alloc&) { + return Fail(55); + } + std::size_t offset = 0; + for (int i = 0; i < message->iovLength; ++i) { + if (message->iov[i].length) std::memcpy(buffer.data() + offset, message->iov[i].base, message->iov[i].length); + offset += message->iov[i].length; + } + return sendto_nid_postfix(descriptor, buffer.data(), buffer.size(), flags, message->name, message->name ? message->nameLength : 0u); +} +std::int64_t APS5_VABI recvmsg_nid_postfix(int descriptor, GuestMsghdr* message, int flags) { + const auto total = MessageLength(message); + if (total < 0) return -1; + const auto socket = Lookup(descriptor); + if (!socket) return -1; + if ((flags & ~2) != 0) return Fail(45); + const bool datagram = socket->type == 2; + std::vector buffer; + try { + buffer.resize(static_cast(total) + (datagram ? 1u : 0u)); + } catch (const std::bad_alloc&) { + return Fail(55); + } + sockaddr_storage native{}; + socklen_t size = sizeof(native); + std::int64_t received = ::recvfrom(socket->value, buffer.data(), static_cast(buffer.size()), + flags & 2 ? MSG_PEEK : 0, reinterpret_cast(&native), &size); + if (received < 0) { +#ifdef _WIN32 + if (!datagram || WSAGetLastError() != WSAEMSGSIZE) return Fail(NativeError()); + received = static_cast(buffer.size()); +#else + return Fail(NativeError()); +#endif + } + message->flags = 0; + if (received > total) { + received = total; + message->flags = 0x10; + } + std::size_t offset = 0; + for (int i = 0; i < message->iovLength && offset < static_cast(received); ++i) { + const auto count = std::min(message->iov[i].length, static_cast(received) - offset); + std::memcpy(message->iov[i].base, buffer.data() + offset, count); + offset += count; + } + if (message->name) { + if (size > 0 && (native.ss_family == AF_INET || native.ss_family == AF_INET6)) { + GuestAddress(native, message->name, &message->nameLength); + } else { + message->nameLength = 0; + } + } + message->controlLength = 0; + return received; +} } diff --git a/core/libs/prx/libkernel/Unimplemented.cpp b/core/libs/prx/libkernel/Unimplemented.cpp index 6c5ee71eb..227845831 100644 --- a/core/libs/prx/libkernel/Unimplemented.cpp +++ b/core/libs/prx/libkernel/Unimplemented.cpp @@ -41,14 +41,4 @@ int APS5_VABI futimes_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; } - -int APS5_VABI recvmsg_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI sendmsg_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} } diff --git a/core/libs/tests/GuestUdp.cpp b/core/libs/tests/GuestUdp.cpp index 86f1ec678..488ea5221 100644 --- a/core/libs/tests/GuestUdp.cpp +++ b/core/libs/tests/GuestUdp.cpp @@ -20,6 +20,23 @@ const char* APS5_VABI inet_ntop_nid_postfix(int, const void*, char*, std::uint32 int APS5_VABI inet_pton_nid_postfix(int, const char*, void*); int* APS5_VABI __error_nid_postfix(); } +struct Iovec { + void* base; + std::uint64_t length; +}; +struct Msghdr { + void* name; + std::uint32_t nameLength; + Iovec* iov; + int iovLength; + void* control; + std::uint32_t controlLength; + int flags; +}; +extern "C" { +std::int64_t APS5_VABI sendmsg_nid_postfix(int, const Msghdr*, int); +std::int64_t APS5_VABI recvmsg_nid_postfix(int, Msghdr*, int); +} static void Require(bool value) { if (!value) std::abort(); } int main() { const int receiver = socket_nid_postfix(2, 2, 0); @@ -63,6 +80,39 @@ int main() { Require(std::strcmp(buffer, message) == 0 && source[1] == 2 && source[4] == 127); Require(ioctl_nid_postfix(receiver, 0x4004667f, &queued) == 0 && queued == 0); Require(ioctl_nid_postfix(receiver, 123, &queued) == -1 && *__error_nid_postfix() == 25); + char head[] = "scatter "; + char tail[] = "gather"; + Iovec parts[2]{{head, 8}, {tail, 6}}; + Msghdr outgoing{destination.data(), static_cast(destination.size()), parts, 2, nullptr, 0, 0}; + Require(sendmsg_nid_postfix(sender, &outgoing, 0) == 14); + const auto wait = [&] { + queued = 0; + for (int i = 0; i < 100 && queued == 0; ++i) { + Require(ioctl_nid_postfix(receiver, 0x4004667f, &queued) == 0); + if (!queued) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + Require(queued != 0); + }; + wait(); + char first[4]{}, second[16]{}; + Iovec pieces[2]{{first, sizeof(first)}, {second, sizeof(second)}}; + source.fill(0); + unsigned char control[8]{}; + Msghdr incoming{source.data(), static_cast(source.size()), pieces, 2, control, sizeof(control), -1}; + Require(recvmsg_nid_postfix(receiver, &incoming, 0) == 14); + Require(std::memcmp(first, "scat", 4) == 0 && std::memcmp(second, "ter gather", 10) == 0); + Require(incoming.flags == 0 && incoming.controlLength == 0 && incoming.nameLength == 16 && source[1] == 2 && source[4] == 127); + Require(sendmsg_nid_postfix(sender, &outgoing, 0) == 14); + wait(); + char shortBuffer[5]{}; + Iovec single{shortBuffer, sizeof(shortBuffer)}; + Msghdr truncated{nullptr, 0, &single, 1, nullptr, 0, 0}; + Require(recvmsg_nid_postfix(receiver, &truncated, 0) == 5); + Require(std::memcmp(shortBuffer, "scatt", 5) == 0 && truncated.flags == 0x10); + Require(recvmsg_nid_postfix(receiver, &truncated, 0) == -1 && *__error_nid_postfix() == 35); + Msghdr oversized{nullptr, 0, parts, 1025, nullptr, 0, 0}; + Require(sendmsg_nid_postfix(sender, &oversized, 0) == -1 && *__error_nid_postfix() == 40); + Require(recvmsg_nid_postfix(receiver, nullptr, 0) == -1 && *__error_nid_postfix() == 14); Require(close_nid_postfix(receiver) == 0); Require(close_nid_postfix(receiver) == -1 && *__error_nid_postfix() == 9); Require(ioctl_nid_postfix(receiver, 0x4004667f, &queued) == -1); From a74f28235962ed77ad5da4152c8bc85bfb7c5f87 Mon Sep 17 00:00:00 2001 From: Chad Date: Mon, 5 Oct 2026 20:14:09 -0500 Subject: [PATCH 19/42] feat(libSceIme): report the closed IME panel sceImeOpen is not implemented, so the IME panel is never open. sceImeClose, sceImeSetCaret, sceImeSetText and sceImeSetTextGeometry return SCE_IME_ERROR_NOT_OPENED, checking the panel before their arguments, as sceImeKeyboardGetInfo does for the keyboard. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceIme/Export.cpp | 12 ++++-------- core/libs/tests/GuestImeParameters.cpp | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/core/libs/prx/libSceIme/Export.cpp b/core/libs/prx/libSceIme/Export.cpp index db1dd7a85..480dbbd24 100644 --- a/core/libs/prx/libSceIme/Export.cpp +++ b/core/libs/prx/libSceIme/Export.cpp @@ -31,8 +31,7 @@ std::set g_openKeyboards; extern "C" { int APS5_VABI sceImeClose_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; + return ErrorNotOpened; } int APS5_VABI sceImeGetPanelSize(const Param* param, uint32_t* width, uint32_t* height) { @@ -94,22 +93,19 @@ void APS5_VABI sceImeParamInit(Param* param) { int APS5_VABI sceImeSetCaret(const Caret* caret) { (void)caret; - NotImplemented_nid_no_patch(__func__); - return 0; + return ErrorNotOpened; } int APS5_VABI sceImeSetText(const char16_t* text, uint32_t length) { (void)text; (void)length; - NotImplemented_nid_no_patch(__func__); - return 0; + return ErrorNotOpened; } int APS5_VABI sceImeSetTextGeometry(TextAreaMode mode, const TextGeometry* geometry) { (void)mode; (void)geometry; - NotImplemented_nid_no_patch(__func__); - return 0; + return ErrorNotOpened; } int APS5_VABI sceImeUpdate(EventHandler handler) { diff --git a/core/libs/tests/GuestImeParameters.cpp b/core/libs/tests/GuestImeParameters.cpp index 880ebb9e0..3612fb077 100644 --- a/core/libs/tests/GuestImeParameters.cpp +++ b/core/libs/tests/GuestImeParameters.cpp @@ -7,6 +7,10 @@ extern "C" { void APS5_VABI sceImeParamInit(Param* param); int APS5_VABI sceImeGetPanelSize(const Param* param, uint32_t* width, uint32_t* height); +int APS5_VABI sceImeClose_nid_postfix(void); +int APS5_VABI sceImeSetCaret(const Caret* caret); +int APS5_VABI sceImeSetText(const char16_t* text, uint32_t length); +int APS5_VABI sceImeSetTextGeometry(TextAreaMode mode, const TextGeometry* geometry); } static_assert(sizeof(Param) == 96); @@ -102,8 +106,21 @@ static void CheckErrors() { Require(width == 0x12345678 && height == 0x87654321, "outputs changed on error"); } +static void CheckClosedPanel() { + constexpr int notOpened = static_cast(0x80bc0002u); + Caret caret{}; + TextGeometry geometry{}; + const char16_t text[] = u"text"; + Require(sceImeSetCaret(&caret) == notOpened, "caret needs an open panel"); + Require(sceImeSetCaret(nullptr) == notOpened, "caret checks the panel first"); + Require(sceImeSetText(text, 4) == notOpened, "text needs an open panel"); + Require(sceImeSetTextGeometry(TextAreaMode::Edit, &geometry) == notOpened, "geometry needs an open panel"); + Require(sceImeClose_nid_postfix() == notOpened, "closing needs an open panel"); +} + int main() { CheckInitialization(); CheckPanelSizes(); CheckErrors(); + CheckClosedPanel(); } From ebe0515180ad6a24e4d6beeb92f032020640a1cc Mon Sep 17 00:00:00 2001 From: Chad Date: Mon, 5 Oct 2026 20:19:09 -0500 Subject: [PATCH 20/42] feat(libSceAppContent): answer add-content mounts without installed content No additional content is installed, so sceAppContentAddcontMount returns SCE_APP_CONTENT_ERROR_NOT_FOUND with the mount point untouched, and sceAppContentAddcontUnmount finds no mount to release. A missing label or mount point is a parameter error. The library gets its own CMakeLists for the new guest_appcontent test. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAppContent/CMakeLists.txt | 21 +++++++++++++++ core/libs/prx/libSceAppContent/Export.cpp | 12 ++++----- core/libs/tests/GuestAppContent.cpp | 27 +++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 4 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 core/libs/prx/libSceAppContent/CMakeLists.txt create mode 100644 core/libs/tests/GuestAppContent.cpp diff --git a/core/libs/prx/libSceAppContent/CMakeLists.txt b/core/libs/prx/libSceAppContent/CMakeLists.txt new file mode 100644 index 000000000..ee3ad98c7 --- /dev/null +++ b/core/libs/prx/libSceAppContent/CMakeLists.txt @@ -0,0 +1,21 @@ +add_library(libSceAppContent SHARED EXCLUDE_FROM_ALL Export.cpp) +target_include_directories(libSceAppContent PRIVATE ${LIBS_INCLUDE_DIR}) +configure_windows_unwind(libSceAppContent) + +if(MINGW) + foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static) + string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}") + endforeach() +endif() + +if(BUILD_TESTING) + add_test_executable(guest_appcontent_tests ${LIBS_INCLUDE_DIR}/tests/GuestAppContent.cpp) + target_include_directories(guest_appcontent_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_appcontent_tests PRIVATE libSceAppContent libc) + configure_windows_unwind(guest_appcontent_tests) + add_test(NAME guest_appcontent COMMAND guest_appcontent_tests) + if(WIN32) + set_tests_properties(guest_appcontent PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAppContent/Export.cpp b/core/libs/prx/libSceAppContent/Export.cpp index 1d72d4913..dfc8300ad 100644 --- a/core/libs/prx/libSceAppContent/Export.cpp +++ b/core/libs/prx/libSceAppContent/Export.cpp @@ -10,6 +10,7 @@ #include static constexpr int SCE_APP_CONTENT_ERROR_PARAMETER = static_cast(0x80D90002); +static constexpr int SCE_APP_CONTENT_ERROR_NOT_FOUND = static_cast(0x80D90005); static constexpr uint32_t APPPARAM_ID_SKU_FLAG = 1; static constexpr int32_t SKU_FLAG_FULL = 3; @@ -30,16 +31,13 @@ extern "C" { int APS5_VABI sceAppContentAddcontMount(uint32_t service_label, const NpUnifiedEntitlementLabel* entitlement_label, AppContentMountPoint* mount_point) { (void)service_label; - (void)entitlement_label; - (void)mount_point; - NotImplemented_nid_no_patch(__func__); - return 0; + if (!entitlement_label || !mount_point) return SCE_APP_CONTENT_ERROR_PARAMETER; + return SCE_APP_CONTENT_ERROR_NOT_FOUND; } int APS5_VABI sceAppContentAddcontUnmount(const AppContentMountPoint* mount_point) { - (void)mount_point; - NotImplemented_nid_no_patch(__func__); - return 0; + if (!mount_point) return SCE_APP_CONTENT_ERROR_PARAMETER; + return SCE_APP_CONTENT_ERROR_NOT_FOUND; } int APS5_VABI sceAppContentAppParamGetInt(uint32_t param_id, int32_t* value) { diff --git a/core/libs/tests/GuestAppContent.cpp b/core/libs/tests/GuestAppContent.cpp new file mode 100644 index 000000000..d78335075 --- /dev/null +++ b/core/libs/tests/GuestAppContent.cpp @@ -0,0 +1,27 @@ +#include "SceTypes.hpp" +#include +#include + +extern "C" { +int APS5_VABI sceAppContentAddcontMount(uint32_t, const NpUnifiedEntitlementLabel*, AppContentMountPoint*); +int APS5_VABI sceAppContentAddcontUnmount(const AppContentMountPoint*); +} + +static constexpr int ErrorParameter = static_cast(0x80D90002); +static constexpr int ErrorNotFound = static_cast(0x80D90005); +static void Require(bool value) { if (!value) std::abort(); } + +int main() { + NpUnifiedEntitlementLabel label{}; + std::memcpy(&label, "ADDCONT000000001", 16); + AppContentMountPoint mountPoint{}; + std::memset(&mountPoint, 0x5a, sizeof(mountPoint)); + const AppContentMountPoint untouched = mountPoint; + Require(sceAppContentAddcontMount(0, &label, &mountPoint) == ErrorNotFound); + Require(std::memcmp(&mountPoint, &untouched, sizeof(mountPoint)) == 0); + Require(sceAppContentAddcontMount(0, nullptr, &mountPoint) == ErrorParameter); + Require(sceAppContentAddcontMount(0, &label, nullptr) == ErrorParameter); + std::memcpy(mountPoint.data, "/addcont0", 10); + Require(sceAppContentAddcontUnmount(&mountPoint) == ErrorNotFound); + Require(sceAppContentAddcontUnmount(nullptr) == ErrorParameter); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index b57c3f774..7083e9275 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -120,6 +120,7 @@ Throughout the project, every function at every stage either **does exactly what ### Functional +- [Additional content](../../core/libs/prx/libSceAppContent/Export.cpp) (libSceAppContent) is not installed or mounted: `sceAppContentAddcontMount` answers `NOT_FOUND` for every entitlement label and `sceAppContentAddcontUnmount` for every mount point, as no add-content mount is ever handed out - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) use preallocated host storage instead of the supplied guest work area; its existing size formula and the 512-byte object layouts remain unverified. Waiting-queue pool thread limits and waiter priority ordering are not implemented. Finalization wakes blocked queue callers with `ULT_ERROR_STATE`. - [MIMG `tfe` and `lwe`](../../core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp) never write the status VGPR after the data. On hardware it is written only when a texel fetch hits an unmapped page of a partially resident texture, or, for `lwe` on sample/gather, when the LOD is below the T# `MIN_LOD_WARN`; texture memory is always resident here, and `lwe` on sample, gather and `image_get_lod` throws. - [Image atomics](../../core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp) on 32_SINT and 32_FLOAT surfaces act on the raw dword through an R32_UINT storage view; their float results are assumed to match those measured on 32_UINT surfaces. Other formats throw. From 8cfe87bd164719cb4eaf1036690644ead44ff385 Mon Sep 17 00:00:00 2001 From: Chad Date: Mon, 5 Oct 2026 20:21:50 -0500 Subject: [PATCH 21/42] build(libSceAgcDriver): register the image_msaa_load test apart from other pending tests Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index d35258026..89d4f60b8 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -780,14 +780,6 @@ if(BUILD_TESTING) set_tests_properties(image_sample_gather PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - add_test_executable(image_msaa_load_tests ${LIBS_INCLUDE_DIR}/tests/ImageMsaaLoad.cpp) - target_link_libraries(image_msaa_load_tests PRIVATE shader_recompiler_agc_driver libc) - configure_windows_unwind(image_msaa_load_tests) - add_test(NAME image_msaa_load COMMAND image_msaa_load_tests) - if(WIN32) - set_tests_properties(image_msaa_load PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() add_test_executable(guest_indexed_draw_tests ${LIBS_INCLUDE_DIR}/tests/GuestIndexedDraw.cpp) target_include_directories(guest_indexed_draw_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_indexed_draw_tests PRIVATE libSceAgc libSceAgcDriver libc) @@ -825,3 +817,14 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endif() + +if(BUILD_TESTING) + add_test_executable(image_msaa_load_tests ${LIBS_INCLUDE_DIR}/tests/ImageMsaaLoad.cpp) + target_link_libraries(image_msaa_load_tests PRIVATE shader_recompiler_agc_driver libc) + configure_windows_unwind(image_msaa_load_tests) + add_test(NAME image_msaa_load COMMAND image_msaa_load_tests) + if(WIN32) + set_tests_properties(image_msaa_load PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() From 7edf5d2ec2dc41ac3738a4e7d2c35e4c87c4431f Mon Sep 17 00:00:00 2001 From: 011010 Date: Mon, 5 Oct 2026 19:39:50 -0600 Subject: [PATCH 22/42] fix(relinker): derive ZF from the subtraction in ALU execution tests The cmp-equal execution case computed ZF from the untouched destination operand instead of the comparison result, so the self-check took the failure path and the Windows CI job failed with exit code 8. Derive ZF from the real subtraction for sub/cmp and from the real sum for add. --- core/relinker/relinker/tests/test_tls_function_coverage.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/relinker/relinker/tests/test_tls_function_coverage.py b/core/relinker/relinker/tests/test_tls_function_coverage.py index 9e0037181..3a8cae4dd 100644 --- a/core/relinker/relinker/tests/test_tls_function_coverage.py +++ b/core/relinker/relinker/tests/test_tls_function_coverage.py @@ -91,12 +91,15 @@ def alu_execution_cases(): for name, opcode, operation, base, value in cases: result = operation(base, value) & mask if opcode in (0x2b, 0x3b): + zero = 1 if (base - value) & mask == 0 else 0 carry = 1 if base < value else 0 elif opcode == 0x03: + zero = 1 if (base + value) & mask == 0 else 0 carry = 1 if base + value > mask else 0 else: + zero = 1 if result == 0 else 0 carry = 0 - flags_masked = ((1 if result == 0 else 0) << 6) | carry + flags_masked = (zero << 6) | carry for register in (0, 1, 3): body = alu_check_body(opcode, register, base, value, result, flags_masked) yield f"alu-exec-{name}-{register}", make_image("register", "unwind", body=body) From 7789c0a57be6a70f5f42be511d34fe8f8153d74d Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:10:48 -0300 Subject: [PATCH 23/42] feat(libs): implement homebrew libc and kernel runtime exports --- core/libs/prx/libc/CMakeLists.txt | 14 ++++ core/libs/prx/libc/src/FileAndHeap.cpp | 23 ++++++ core/libs/prx/libc/src/Filesystem.cpp | 62 +++++++++++++++ core/libs/prx/libc/src/Math.cpp | 5 ++ core/libs/prx/libc/src/Multibyte.cpp | 2 + core/libs/prx/libc/src/StandardStreams.cpp | 3 + core/libs/prx/libkernel/File/src/Stdio.cpp | 16 ++++ .../prx/libkernel/System/src/Notification.cpp | 10 +++ core/libs/tests/GuestAccess.cpp | 77 +++++++++++++++++++ core/libs/tests/GuestFilesystem.cpp | 44 +++++++++++ core/libs/tests/GuestMath.cpp | 9 +++ core/libs/tests/GuestStandardStreams.cpp | 35 +++++++++ 12 files changed, 300 insertions(+) create mode 100644 core/libs/tests/GuestAccess.cpp diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index 847b8ffc3..5025b5920 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -40,7 +40,21 @@ target_include_directories(libc PRIVATE ${LIBS_INCLUDE_DIR} ) +if(WIN32) + target_link_libraries(libc PRIVATE advapi32) +endif() + if(BUILD_TESTING) + add_test_executable(guest_access_tests ${LIBS_INCLUDE_DIR}/tests/GuestAccess.cpp) + target_include_directories(guest_access_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_access_tests PRIVATE libc) + configure_windows_unwind(guest_access_tests) + add_test(NAME guest_access COMMAND guest_access_tests) + if(WIN32) + target_link_libraries(guest_access_tests PRIVATE advapi32) + set_tests_properties(guest_access PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(file_position_tests ${LIBS_INCLUDE_DIR}/tests/FilePosition.cpp) target_include_directories(file_position_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(file_position_tests PRIVATE libc) diff --git a/core/libs/prx/libc/src/FileAndHeap.cpp b/core/libs/prx/libc/src/FileAndHeap.cpp index a98e27855..80f1716a1 100644 --- a/core/libs/prx/libc/src/FileAndHeap.cpp +++ b/core/libs/prx/libc/src/FileAndHeap.cpp @@ -16,6 +16,29 @@ extern "C" { [[noreturn]] void APS5_VABI _ZSt11_Xbad_allocv_nid_postfix(); +FileStream* APS5_VABI fdopen_nid_postfix(int descriptor, const char* mode) { + if (descriptor < 0) { errno = 9; return nullptr; } + if (!mode) { errno = 22; return nullptr; } + const char* supported[] = {"r", "w", "a", "rb", "wb", "ab", "r+", "w+", "a+", + "rb+", "wb+", "ab+", "r+b", "w+b", "a+b"}; + bool valid = false; + for (const auto* candidate : supported) if (std::strcmp(mode, candidate) == 0) valid = true; + if (!valid) { errno = 22; return nullptr; } + try { + const auto release = [](void* pointer) { ::operator delete(pointer); }; + std::unique_ptr storage(::operator new(sizeof(FileStream)), release); +#ifdef _WIN32 + auto* native = ::_fdopen(descriptor, mode); +#else + auto* native = ::fdopen(descriptor, mode); +#endif + if (!native) return nullptr; + auto* stream = new (storage.get()) FileStream(native, true); + storage.release(); + return stream; + } catch (const std::bad_alloc&) { errno = 12; return nullptr; } +} + FileStream* APS5_VABI freopen_nid_postfix(const char* filename, const char* mode, FileStream* stream) { if (!stream || !mode) { errno = 22; return nullptr; } if (!filename) { errno = 45; return nullptr; } // Mode-only reopening is not supported. diff --git a/core/libs/prx/libc/src/Filesystem.cpp b/core/libs/prx/libc/src/Filesystem.cpp index 60a4c02c6..258f10c3f 100644 --- a/core/libs/prx/libc/src/Filesystem.cpp +++ b/core/libs/prx/libc/src/Filesystem.cpp @@ -1,8 +1,11 @@ #include "prx/libc/include/General.hpp" #include +#include #ifdef _WIN32 #define NOMINMAX #include +#else +#include #endif namespace { @@ -26,6 +29,65 @@ int FilesystemError(const std::error_code& error) { } } +extern "C" int APS5_VABI access_nid_postfix(const char* path, int mode) { + if (!path) { errno = 14; return -1; } + if (mode < 0 || (mode & ~7)) { errno = 22; return -1; } + if (!*path) { errno = 2; return -1; } + try { + const auto resolved = ResolvePath_nid_no_patch(path); +#ifdef _WIN32 + const DWORD attributes = GetFileAttributesW(resolved.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES) { + errno = FilesystemError(std::error_code(static_cast(GetLastError()), std::system_category())); + return -1; + } + if (mode == 0) return 0; + if ((mode & 2) && !(attributes & FILE_ATTRIBUTE_DIRECTORY) && (attributes & FILE_ATTRIBUTE_READONLY)) { + errno = 13; return -1; + } + DWORD size = 0; + constexpr auto information = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; + GetFileSecurityW(resolved.c_str(), information, nullptr, 0, &size); + if (!size) { errno = 13; return -1; } + std::vector descriptor(size); + if (!GetFileSecurityW(resolved.c_str(), information, descriptor.data(), size, &size)) { + errno = 13; return -1; + } + struct Token { + HANDLE value = nullptr; + ~Token() { if (value) CloseHandle(value); } + } source, impersonation; + if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &source.value)) { + if (GetLastError() != ERROR_NO_TOKEN || + !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &source.value)) { + errno = 13; return -1; + } + } + if (!DuplicateToken(source.value, SecurityImpersonation, &impersonation.value)) { errno = 13; return -1; } + DWORD desired = 0; + if (mode & 4) desired |= FILE_READ_DATA; + if (mode & 2) desired |= FILE_WRITE_DATA; + if (mode & 1) desired |= FILE_EXECUTE; + GENERIC_MAPPING mapping{FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_GENERIC_EXECUTE, FILE_ALL_ACCESS}; + PRIVILEGE_SET privileges{}; + DWORD privilegeSize = sizeof(privileges), granted = 0; + BOOL allowed = FALSE; + if (!AccessCheck(descriptor.data(), impersonation.value, desired, &mapping, + &privileges, &privilegeSize, &granted, &allowed) || !allowed) { + errno = 13; return -1; + } + return 0; +#else + if (::access(resolved.c_str(), mode) == 0) return 0; + errno = FilesystemError(std::error_code(errno, std::generic_category())); + return -1; +#endif + } catch (const std::bad_alloc&) { errno = 12; return -1; } + catch (const std::filesystem::filesystem_error& error) { + errno = FilesystemError(error.code()); return -1; + } +} + extern "C" int APS5_VABI rename_nid_postfix(const char* from, const char* to) { if (!from || !to) { errno = 14; return -1; } if (!*from || !*to) { errno = 2; return -1; } diff --git a/core/libs/prx/libc/src/Math.cpp b/core/libs/prx/libc/src/Math.cpp index f2fb249c4..37e89f563 100644 --- a/core/libs/prx/libc/src/Math.cpp +++ b/core/libs/prx/libc/src/Math.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -9,6 +10,10 @@ extern "C" { +std::lldiv_t APS5_VABI lldiv_nid_postfix(long long numerator, long long denominator) { + return std::lldiv(numerator, denominator); +} + float APS5_VABI fmodf_nid_postfix(float x, float y) { return std::fmod(x, y); } float APS5_VABI asinf_nid_postfix(float x) { return std::asin(x); } float APS5_VABI acosf_nid_postfix(float x) { return std::acos(x); } diff --git a/core/libs/prx/libc/src/Multibyte.cpp b/core/libs/prx/libc/src/Multibyte.cpp index c521ced22..2a76fc7dc 100644 --- a/core/libs/prx/libc/src/Multibyte.cpp +++ b/core/libs/prx/libc/src/Multibyte.cpp @@ -13,6 +13,8 @@ int APS5_VABI ___mb_cur_max_nid_postfix() { return 1; } +int APS5_VABI _Getmbcurmax_nid_postfix() { return ___mb_cur_max_nid_postfix(); } + int APS5_VABI mbsinit_nid_postfix(const void*) { return 1; } diff --git a/core/libs/prx/libc/src/StandardStreams.cpp b/core/libs/prx/libc/src/StandardStreams.cpp index 530bccdf3..32837f9cf 100644 --- a/core/libs/prx/libc/src/StandardStreams.cpp +++ b/core/libs/prx/libc/src/StandardStreams.cpp @@ -80,4 +80,7 @@ int APS5_VABI setvbuf_nid_postfix(FileStream* stream, char* buffer, int mode, st const int native = mode == 0 ? _IOFBF : mode == 1 ? _IOLBF : _IONBF; return std::setvbuf(GetNativeStream(stream), buffer, native, size); } +void APS5_VABI setbuf_nid_postfix(FileStream* stream, char* buffer) { + setvbuf_nid_postfix(stream, buffer, buffer ? 0 : 2, buffer ? 1024 : 0); +} } diff --git a/core/libs/prx/libkernel/File/src/Stdio.cpp b/core/libs/prx/libkernel/File/src/Stdio.cpp index cb05e7ce6..5785a3c9b 100644 --- a/core/libs/prx/libkernel/File/src/Stdio.cpp +++ b/core/libs/prx/libkernel/File/src/Stdio.cpp @@ -20,6 +20,7 @@ #ifdef _WIN32 #include #include +#include #include #include #include @@ -182,6 +183,21 @@ static int PosixResult(int result) { return result < 0 ? PosixFailure(result & 0xffff) : result; } +extern "C" int APS5_VABI pipe_nid_postfix(int* descriptors) { + if (!descriptors) return PosixFailure(GUEST_EFAULT); + const GuestArena::HostWrite destination(descriptors, 2 * sizeof(int)); + if (!destination.Open()) return PosixFailure(GUEST_EFAULT); + int native[2]; +#ifdef _WIN32 + const int result = ::_pipe(native, 4096, _O_BINARY); +#else + const int result = ::pipe(native); +#endif + if (result != 0) return PosixFailure(SceErrorFromErrno(errno) & 0xffff); + std::memcpy(descriptors, native, sizeof(native)); + return 0; +} + static int PathError(const char* path) { if (path == nullptr) return GUEST_EFAULT; return *path == '\0' ? GUEST_ENOENT : 0; diff --git a/core/libs/prx/libkernel/System/src/Notification.cpp b/core/libs/prx/libkernel/System/src/Notification.cpp index dc06ae9d4..8303ed619 100644 --- a/core/libs/prx/libkernel/System/src/Notification.cpp +++ b/core/libs/prx/libkernel/System/src/Notification.cpp @@ -12,6 +12,16 @@ #include #endif +extern "C" int APS5_VABI sceKernelDebugOutText(int channel, const char* text) { + if (channel < 0) return static_cast(0x80020016u); + if (!text) return static_cast(0x8002000eu); + static std::mutex outputMutex; + const std::lock_guard lock(outputMutex); + if (std::fprintf(stderr, "[debug:%d] %s", channel, text) < 0 || std::fflush(stderr) != 0) + return static_cast(0x80020005u); + return 0; +} + extern "C" int APS5_VABI sceKernelSendNotificationRequest(int device, const void* request, std::size_t size, int flags) { constexpr auto invalidArgument = static_cast(0x80020016u); constexpr auto badAddress = static_cast(0x8002000eu); diff --git a/core/libs/tests/GuestAccess.cpp b/core/libs/tests/GuestAccess.cpp new file mode 100644 index 000000000..723b9c090 --- /dev/null +++ b/core/libs/tests/GuestAccess.cpp @@ -0,0 +1,77 @@ +#include "prx/libc/include/General.hpp" +#include +#include +#include +#ifdef _WIN32 +#define NOMINMAX +#include +#include +#endif + +extern "C" { +int APS5_VABI access_nid_postfix(const char*, int); +int APS5_VABI chdir_nid_postfix(const char*); +int* APS5_VABI __error_nid_postfix(); +} + +static void Require(bool value) { if (!value) std::abort(); } + +int main() { + const auto name = "anyps5-access-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); + const auto directory = std::filesystem::current_path() / name; + Require(std::filesystem::create_directory(directory)); + const auto file = directory / "sample.txt"; + { std::ofstream output(file); output << "sample"; } + Require(chdir_nid_postfix(name.c_str()) == 0); + *__error_nid_postfix() = 34; + Require(access_nid_postfix("sample.txt", 0) == 0 && *__error_nid_postfix() == 34); + Require(access_nid_postfix("sample.txt", 6) == 0); + Require(access_nid_postfix(".", 7) == 0); + Require(access_nid_postfix(("/" + name + "/sample.txt").c_str(), 4) == 0); + AddPathAlias_nid_no_patch("access-alias", directory.string().c_str()); + Require(access_nid_postfix("/access-alias/sample.txt", 0) == 0); + RemovePathAlias_nid_no_patch("access-alias"); + Require(access_nid_postfix("missing", 0) == -1 && *__error_nid_postfix() == 2); + Require(access_nid_postfix("", 0) == -1 && *__error_nid_postfix() == 2); + Require(access_nid_postfix(nullptr, 0) == -1 && *__error_nid_postfix() == 14); + Require(access_nid_postfix("sample.txt", 8) == -1 && *__error_nid_postfix() == 22); + Require(access_nid_postfix("sample.txt", -1) == -1 && *__error_nid_postfix() == 22); +#ifdef _WIN32 + Require(SetFileAttributesW(file.c_str(), FILE_ATTRIBUTE_READONLY)); + Require(access_nid_postfix("sample.txt", 4) == 0); + Require(access_nid_postfix("sample.txt", 2) == -1 && *__error_nid_postfix() == 13); + Require(SetFileAttributesW(file.c_str(), FILE_ATTRIBUTE_NORMAL)); + PSECURITY_DESCRIPTOR original = nullptr; + PACL originalAcl = nullptr; + Require(GetNamedSecurityInfoW(const_cast(file.c_str()), SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, nullptr, nullptr, &originalAcl, nullptr, &original) == ERROR_SUCCESS); + char sid[SECURITY_MAX_SID_SIZE]; + DWORD sidBytes = sizeof(sid); + Require(CreateWellKnownSid(WinWorldSid, nullptr, sid, &sidBytes)); + EXPLICIT_ACCESSW denial{}; + denial.grfAccessPermissions = FILE_EXECUTE; + denial.grfAccessMode = DENY_ACCESS; + denial.Trustee.TrusteeForm = TRUSTEE_IS_SID; + denial.Trustee.ptstrName = reinterpret_cast(sid); + PACL deniedAcl = nullptr; + Require(SetEntriesInAclW(1, &denial, originalAcl, &deniedAcl) == ERROR_SUCCESS); + Require(SetNamedSecurityInfoW(const_cast(file.c_str()), SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, nullptr, nullptr, deniedAcl, nullptr) == ERROR_SUCCESS); + const int denied = access_nid_postfix("sample.txt", 1); + const int deniedError = *__error_nid_postfix(); + const int readable = access_nid_postfix("sample.txt", 4); + Require(SetNamedSecurityInfoW(const_cast(file.c_str()), SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, nullptr, nullptr, originalAcl, nullptr) == ERROR_SUCCESS); + LocalFree(deniedAcl); + LocalFree(original); + Require(denied == -1 && deniedError == 13 && readable == 0); +#else + std::filesystem::permissions(file, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); + Require(access_nid_postfix("sample.txt", 1) == -1 && *__error_nid_postfix() == 13); + std::filesystem::permissions(file, std::filesystem::perms::owner_exec, std::filesystem::perm_options::add); + Require(access_nid_postfix("sample.txt", 1) == 0); +#endif + Require(chdir_nid_postfix("/") == 0); + std::filesystem::remove(file); + std::filesystem::remove(directory); +} diff --git a/core/libs/tests/GuestFilesystem.cpp b/core/libs/tests/GuestFilesystem.cpp index b58ee6061..1a7f71ad9 100644 --- a/core/libs/tests/GuestFilesystem.cpp +++ b/core/libs/tests/GuestFilesystem.cpp @@ -5,6 +5,12 @@ #include #include #include +#include +#ifdef _WIN32 +#include +#else +#include +#endif extern "C" { int APS5_VABI remove_nid_postfix(const char*); int APS5_VABI rename_nid_postfix(const char*, const char*); @@ -28,6 +34,10 @@ int APS5_VABI sceKernelStat(const char*, FileStat*); int APS5_VABI sceKernelUnlink(const char*); int APS5_VABI sceKernelRmdir(const char*); int* APS5_VABI __error_nid_postfix(); +int APS5_VABI pipe_nid_postfix(int*); +std::int64_t APS5_VABI read_nid_postfix(int, void*, std::size_t); +std::int64_t APS5_VABI write_nid_postfix(int, const void*, std::size_t); +int APS5_VABI sceKernelDebugOutText(int, const char*); } static void Check(bool value, int line) { if (!value) { @@ -37,6 +47,40 @@ static void Check(bool value, int line) { } #define Require(value) Check((value), __LINE__) int main() { + Require(sceKernelDebugOutText(-1, "text") == static_cast(0x80020016u)); + Require(sceKernelDebugOutText(0, nullptr) == static_cast(0x8002000eu)); + auto* captured = std::tmpfile(); + Require(captured != nullptr); +#ifdef _WIN32 + const int saved = ::_dup(::_fileno(stderr)); + Require(saved >= 0 && ::_dup2(::_fileno(captured), ::_fileno(stderr)) == 0); +#else + const int saved = ::dup(::fileno(stderr)); + Require(saved >= 0 && ::dup2(::fileno(captured), ::fileno(stderr)) == ::fileno(stderr)); +#endif + const int debugResult = sceKernelDebugOutText(3, "%s%d literal\n"); +#ifdef _WIN32 + Require(::_dup2(saved, ::_fileno(stderr)) == 0 && ::_close(saved) == 0); +#else + Require(::dup2(saved, ::fileno(stderr)) == ::fileno(stderr) && ::close(saved) == 0); +#endif + Require(debugResult == 0); + std::rewind(captured); + char debugText[64]{}; + Require(std::fread(debugText, 1, sizeof(debugText), captured) == 23); + Require(std::strcmp(debugText, "[debug:3] %s%d literal\n") == 0); + Require(std::fclose(captured) == 0); + Require(pipe_nid_postfix(nullptr) == -1 && *__error_nid_postfix() == 14); + int descriptors[2] = {-1, -1}; + Require(pipe_nid_postfix(descriptors) == 0 && descriptors[0] >= 0 && descriptors[1] >= 0); + const char payload[] = {'A', '\0', '\r', '\n', '\x1a', 'Z'}; + Require(write_nid_postfix(descriptors[1], payload, sizeof(payload)) == sizeof(payload)); + Require(close_nid_postfix(descriptors[1]) == 0); + char received[sizeof(payload)]{}; + Require(read_nid_postfix(descriptors[0], received, sizeof(received)) == sizeof(received)); + Require(std::memcmp(received, payload, sizeof(payload)) == 0); + Require(read_nid_postfix(descriptors[0], received, sizeof(received)) == 0); + Require(close_nid_postfix(descriptors[0]) == 0); const auto root = std::filesystem::path("anyps5-filesystem-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); Require(std::filesystem::create_directory(root)); diff --git a/core/libs/tests/GuestMath.cpp b/core/libs/tests/GuestMath.cpp index eaf3cc121..259aeb3d6 100644 --- a/core/libs/tests/GuestMath.cpp +++ b/core/libs/tests/GuestMath.cpp @@ -5,6 +5,7 @@ #include #include #include +#include extern "C" { double APS5_VABI atof_nid_postfix(const char*); float APS5_VABI strtof_nid_postfix(const char*, char**); @@ -38,10 +39,18 @@ int APS5_VABI __isfinitef_nid_postfix(float); int APS5_VABI __isnormal_nid_postfix(double); int APS5_VABI __isnormalf_nid_postfix(float); int APS5_VABI __isinff_nid_postfix(float); +std::lldiv_t APS5_VABI lldiv_nid_postfix(long long, long long); } static void Require(bool value) { if (!value) std::abort(); } static void CheckIntegerConversions() { + for (const long long numerator : {4294967301LL, -4294967301LL}) { + for (const long long denominator : {3LL, -3LL}) { + const auto result = lldiv_nid_postfix(numerator, denominator); + Require(result.quot == numerator / denominator && result.rem == numerator % denominator); + Require(result.quot * denominator + result.rem == numerator); + } + } struct SignedCase { const char* text; int base; diff --git a/core/libs/tests/GuestStandardStreams.cpp b/core/libs/tests/GuestStandardStreams.cpp index 83ad92e28..ee322b0d4 100644 --- a/core/libs/tests/GuestStandardStreams.cpp +++ b/core/libs/tests/GuestStandardStreams.cpp @@ -7,6 +7,9 @@ #include #include #include +#ifndef _WIN32 +#include +#endif extern "C" { FileStream* APS5_VABI freopen_nid_postfix(const char*, const char*, FileStream*); int APS5_VABI fseeko_nid_postfix(FileStream*, std::int64_t, int); @@ -34,6 +37,11 @@ int APS5_VABI feof_nid_postfix(FileStream*); int APS5_VABI fileno_nid_postfix(FileStream*); void APS5_VABI clearerr_nid_postfix(FileStream*); int APS5_VABI setvbuf_nid_postfix(FileStream*, char*, int, std::size_t); +void APS5_VABI setbuf_nid_postfix(FileStream*, char*); +FileStream* APS5_VABI fdopen_nid_postfix(int, const char*); +int APS5_VABI fclose_nid_postfix(FileStream*); +int APS5_VABI _Getmbcurmax_nid_postfix(); +int APS5_VABI ___mb_cur_max_nid_postfix(); } static void Require(bool value) { if (!value) std::abort(); } static int APS5_VABI WriteFormatted(FileStream* stream, const char* format, ...) { @@ -69,6 +77,33 @@ static int APS5_VABI FormatString(char* buffer, const char* format, ...) { return result; } int main() { + Require(_Getmbcurmax_nid_postfix() == 1 && _Getmbcurmax_nid_postfix() == ___mb_cur_max_nid_postfix()); + Require(fdopen_nid_postfix(-1, "rb") == nullptr && *__error_nid_postfix() == 9); + Require(fdopen_nid_postfix(0, nullptr) == nullptr && *__error_nid_postfix() == 22); + Require(fdopen_nid_postfix(0, "invalid") == nullptr && *__error_nid_postfix() == 22); + std::FILE* original = std::tmpfile(); + Require(original != nullptr); + std::fputs("retained", original); + std::fflush(original); +#ifdef _WIN32 + const int descriptor = _dup(_fileno(original)); +#else + const int descriptor = ::dup(::fileno(original)); +#endif + Require(descriptor >= 0); + auto* wrapped = fdopen_nid_postfix(descriptor, "r+b"); + Require(wrapped != nullptr && fileno_nid_postfix(wrapped) == descriptor); + setbuf_nid_postfix(wrapped, nullptr); + Require(fseek_nid_postfix(wrapped, 0, SEEK_SET) == 0); + char contents[32]{}; + Require(fgets_nid_postfix(contents, sizeof(contents), wrapped) == contents && std::strcmp(contents, "retained") == 0); + Require(fclose_nid_postfix(wrapped) == 0); +#ifdef _WIN32 + Require(_close(descriptor) == -1); +#else + Require(::close(descriptor) == -1); +#endif + Require(std::fclose(original) == 0); char stringOutput[256]; std::memset(stringOutput, '!', sizeof(stringOutput)); std::int64_t count = -1; From 41cd420cc691292ec30a7f20dc80ba574e71aa27 Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:11:04 -0300 Subject: [PATCH 24/42] feat(agc): support version initialization and raw compute programs --- core/libs/prx/libSceAgc/CMakeLists.txt | 8 +++++ core/libs/prx/libSceAgc/DcbState/src/Init.cpp | 11 ++++-- core/libs/prx/libSceAgc/tests/Commands.cpp | 20 ++++++++--- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 1 + .../include/Driver/Shaders/ShaderRegistry.hpp | 1 + .../src/Driver/Dispatch/Dispatch.cpp | 18 ++++++---- .../src/Driver/Shaders/ShaderRegistry.cpp | 29 +++++++++++++++ .../libs/prx/libSceAgcDriver/tests/Submit.cpp | 35 +++++++++++++++++++ 8 files changed, 109 insertions(+), 14 deletions(-) diff --git a/core/libs/prx/libSceAgc/CMakeLists.txt b/core/libs/prx/libSceAgc/CMakeLists.txt index 544eb0e9f..d3bb48f0b 100644 --- a/core/libs/prx/libSceAgc/CMakeLists.txt +++ b/core/libs/prx/libSceAgc/CMakeLists.txt @@ -69,6 +69,14 @@ add_test_executable(agc_command_tests EXCLUDE_FROM_ALL tests/Commands.cpp) target_include_directories(agc_command_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(agc_command_tests PRIVATE libSceAgc libc) configure_windows_unwind(agc_command_tests) +if(BUILD_TESTING) + set_target_properties(agc_command_tests PROPERTIES EXCLUDE_FROM_ALL OFF) + add_test(NAME agc_initialization COMMAND agc_command_tests defaults) + if(WIN32) + set_tests_properties(agc_initialization PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() configure_windows_unwind(libSceAgc) add_test_executable(agc_platform_tests EXCLUDE_FROM_ALL tests/Platform.cpp) diff --git a/core/libs/prx/libSceAgc/DcbState/src/Init.cpp b/core/libs/prx/libSceAgc/DcbState/src/Init.cpp index 737e0b62a..7c8283eaa 100644 --- a/core/libs/prx/libSceAgc/DcbState/src/Init.cpp +++ b/core/libs/prx/libSceAgc/DcbState/src/Init.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgc/DcbState/include/Init.hpp" #include "prx/libSceAgc/Command/include/Packet.hpp" +#include "prx/libSceAgc/Command/include/RegisterDefaults.hpp" #include #include #include "SceTypes.hpp" @@ -8,11 +9,17 @@ extern "C" { -APS5_EXPORT("23LRUSvYu1M", sceAgcInit); -int APS5_VABI sceAgcInit(std::uint32_t* state, std::uint32_t version) { +APS5_EXPORT("23LRUSvYu1M", sceAgcInitState_nid_no_patch); +int APS5_VABI sceAgcInitState_nid_no_patch(std::uint32_t* state, std::uint32_t version) { Agc::Command::CheckAddress(reinterpret_cast(state), alignof(std::uint32_t), __func__); Agc::Command::Require(version < 14, __func__, "unsupported AGC initialization version"); return 0; } +int APS5_VABI sceAgcInit(std::uint32_t version) { + Agc::Command::GetRegisterDefaults(version, false, __func__); + Agc::Command::GetRegisterDefaults(version, true, __func__); + return 0; +} + } diff --git a/core/libs/prx/libSceAgc/tests/Commands.cpp b/core/libs/prx/libSceAgc/tests/Commands.cpp index 5b394c586..feefffe0b 100644 --- a/core/libs/prx/libSceAgc/tests/Commands.cpp +++ b/core/libs/prx/libSceAgc/tests/Commands.cpp @@ -13,7 +13,8 @@ extern "C" std::uint32_t* APS5_VABI sceAgcDcbResetQueue(CommandBuffer* buf, std::uint32_t op, std::uint32_t state); extern "C" std::uint32_t* APS5_VABI sceAgcDcbSetFlip(CommandBuffer* buf, std::uint32_t handle, std::int32_t index, std::uint32_t mode, std::int64_t argument); extern "C" int APS5_VABI sceAgcSuspendPoint(); -extern "C" int APS5_VABI sceAgcInit(std::uint32_t* state, std::uint32_t version); +extern "C" int APS5_VABI sceAgcInit(std::uint32_t version); +extern "C" int APS5_VABI sceAgcInitState_nid_no_patch(std::uint32_t* state, std::uint32_t version); extern "C" std::uint32_t* APS5_VABI sceAgcDcbDrawIndexAuto(CommandBuffer* buf, std::uint32_t indexCount, std::uint64_t modifier); extern "C" std::uint32_t* APS5_VABI sceAgcDcbDrawIndexIndirect(CommandBuffer* buf, std::uint32_t dataOffsetInBytes, std::uint64_t modifier); extern "C" std::uint32_t* APS5_VABI sceAgcDcbDrawIndexIndirectMulti(CommandBuffer* buf, std::uint32_t dataOffsetInBytes, std::uint32_t countIndirect, std::uint32_t maxCountOrCount, const volatile void* countAddress, std::uint32_t strideInBytes, std::uint64_t modifier); @@ -336,9 +337,12 @@ void testMemory() { void testDefaults() { std::uint32_t state = 0x12345678; - check(sceAgcInit(&state, 8) == 0 && state == 0x12345678, "AGC initialization failed or modified caller state"); - expectFailure([] { sceAgcInit(nullptr, 8); }); - expectFailure([&] { sceAgcInit(&state, 14); }); + check(sceAgcInitState_nid_no_patch(&state, 8) == 0 && state == 0x12345678, "AGC initialization failed or modified caller state"); + expectFailure([] { sceAgcInitState_nid_no_patch(nullptr, 8); }); + expectFailure([&] { sceAgcInitState_nid_no_patch(&state, 14); }); + check(sceAgcInit(8) == 0, "AGC version initialization failed"); + expectFailure([] { sceAgcInit(14); }); + expectFailure([] { sceAgcInit(0xffffffffu); }); for (std::uint32_t version = 0; version < 14; ++version) { for (const bool internal : {false, true}) { auto* first = Agc::Command::GetRegisterDefaults(version, internal, __func__); @@ -351,8 +355,14 @@ void testDefaults() { } -int main() { +int main(int argc, char** argv) { try { + if (argc == 2 && std::strcmp(argv[1], "defaults") == 0) { + testDefaults(); + LibcRunShutdown_nid_postfix(); + std::puts("AGC initialization tests passed"); + return 0; + } testPackets(); testIndexedIndirectDraws(); testMarkers(); diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 90d971f7a..c3bb3b625 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -214,6 +214,7 @@ add_test_executable(agc_driver_tests EXCLUDE_FROM_ALL target_include_directories(agc_driver_tests PRIVATE ${LIBS_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/core/shader/recompiler ) target_link_libraries(agc_driver_tests PRIVATE diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp index 6189cbfec..1f6012ccb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp @@ -38,6 +38,7 @@ struct ShaderSnapshot { using ShaderRegistry = std::map>; bool FailureMemo(); +std::shared_ptr ReadRawComputeShader(std::uint64_t address); std::uint64_t NullPixelProgramAddress(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 25c05fb21..25ff62716 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -12,10 +12,13 @@ namespace AgcDriver::DriverDetail { void Driver::dispatch(QueueState& queue, std::span packet, const Submission& submission, std::uint64_t indirectArguments) { const auto address = (static_cast(readRegister(queue.shader, 0x20c)) << 8u) | (static_cast(readRegister(queue.shader, 0x20d) & 0xffu) << 40u); auto it = submission.shaders->upper_bound(address); - require(it != submission.shaders->begin(), "compute program does not belong to a registered shader"); - --it; - const auto& snapshot = *it->second; - require(address - snapshot.codeAddress < snapshot.code.size() * sizeof(std::uint32_t), "compute program is outside registered shader code"); + std::shared_ptr registeredShader; + if (it != submission.shaders->begin()) { + --it; + if (address - it->second->codeAddress < it->second->code.size() * sizeof(std::uint32_t)) registeredShader = it->second; + } + if (!registeredShader) registeredShader = ReadRawComputeShader(address); + const auto& snapshot = *registeredShader; require(snapshot.type == 0, "compute program refers to a non-compute shader"); const auto userCount = (readRegister(queue.shader, 0x213) >> 1u) & 0x1fu; std::vector userData; @@ -23,7 +26,8 @@ void Driver::dispatch(QueueState& queue, std::span packet, userData.push_back(readRegister(queue.shader, 0x240 + i)); } auto compute = Graphics::DecodeComputeStageInfo(queue.shader); - const std::array memory{{{snapshot.codeAddress, std::as_bytes(std::span(snapshot.code))}, {snapshot.headerAddress, snapshot.header}}}; + std::vector memory{{snapshot.codeAddress, std::as_bytes(std::span(snapshot.code))}}; + if (!snapshot.header.empty()) memory.push_back({snapshot.headerAddress, snapshot.header}); static const bool unlockedDevice = std::getenv("APS5_NO_UNLOCKED_DEVICE") == nullptr; std::shared_ptr localDevice = unlockedDevice ? device.Load() : nullptr; @@ -174,7 +178,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, previous.key = key; } - if (!stampValidate()) mix(reinterpret_cast(it->second.get())); + if (!stampValidate()) mix(reinterpret_cast(registeredShader.get())); phaseTiming.Phase(PhaseKey); lookupDispatch(address, submission, key, noDispatchCache, traceCache, profile, memory, phaseTiming, phaseMs, compiledResult, keepVariant, captured, liveWords, dataHit, cached, validated, missedEntry, missedDiffering); if (cached) { @@ -226,7 +230,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, } recompileMs += phaseTiming.Elapsed(); phaseTiming.Phase(PhaseRecompile); - insertDispatch(address, key, noDispatchCache, profile, it->second, forgetAtCapture, memory, shaderMemory, captured, capture, compiledResult, missedEntry, missedDiffering, attachVariant, phaseTiming); + insertDispatch(address, key, noDispatchCache, profile, registeredShader, forgetAtCapture, memory, shaderMemory, captured, capture, compiledResult, missedEntry, missedDiffering, attachVariant, phaseTiming); } if (verifyDataHits() && dataHit) verifyDataHit(snapshot, codeOffset, localDevice->Serial(), request, memory, address, *keepVariant, liveWords, *compiledResult); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index abd485168..d40f7e4d4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -7,9 +7,38 @@ #include #include #include +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" namespace AgcDriver::DriverDetail { +std::shared_ptr ReadRawComputeShader(std::uint64_t address) { + GuestMemory::CheckRange(reinterpret_cast(address), sizeof(std::uint32_t), 256); + constexpr std::size_t limit = 1024 * 1024; + const auto ranges = GuestMemory::CommittedRanges(address, limit); + std::uint64_t end = address; + for (const auto& range : ranges) { + if (range.first != end) break; + end = range.second; + } + const auto available = static_cast(end - address) / sizeof(std::uint32_t); + ShaderSnapshot snapshot{address, 0, 0, {}, {}}; + while (snapshot.code.size() < available) { + const auto previous = snapshot.code.size(); + snapshot.code.resize(std::min(available, std::max(64, previous * 2))); + GuestMemory::Read(address + previous * sizeof(std::uint32_t), + std::as_writable_bytes(std::span(snapshot.code).subspan(previous)), alignof(std::uint32_t)); + try { + const auto decoded = ShaderRecompiler::RdnaInstructionDecoder{}.Decode(snapshot.code); + const auto& last = decoded.instructions.back(); + snapshot.code.resize(last.programCounter / sizeof(std::uint32_t) + last.wordCount); + return std::make_shared(std::move(snapshot)); + } catch (const std::out_of_range&) { + if (snapshot.code.size() == available) break; + } + } + throw std::runtime_error("AGC driver: raw compute program has no reachable end within mapped code or the size limit"); +} + bool FailureMemo() { static const bool memo = std::getenv("APS5_NO_FAILURE_MEMO") == nullptr; return memo; diff --git a/core/libs/prx/libSceAgcDriver/tests/Submit.cpp b/core/libs/prx/libSceAgcDriver/tests/Submit.cpp index 28a8f081a..a37a89f14 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Submit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Submit.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/QueueState.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libc/include/Shutdown.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "prx/libSceAgcDriver/Submit/include/Acb.hpp" @@ -7,6 +8,7 @@ #include "prx/libSceAgcDriver/Eq/include/Event.hpp" #include "prx/libkernel/Equeue/Equeue.hpp" #include +#include #include #include #include @@ -15,6 +17,9 @@ #include #include #include +#ifdef _WIN32 +#include +#endif extern "C" int APS5_VABI sceKernelCreateEqueue(KernelEqueue* eq, const char* name); extern "C" int APS5_VABI sceKernelDeleteEqueue(KernelEqueue eq); @@ -362,6 +367,36 @@ void testWorkerFailure() { int main() { try { + alignas(256) std::array rawCode{}; + rawCode.fill(0xbf800000); + rawCode[0] = 0xbe8003ff; + rawCode[1] = 0xbf810000; + rawCode[2] = 0xbf810000; + const auto rawAddress = reinterpret_cast(rawCode.data()); + const auto literal = AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress); + check(literal->code.size() == 3 && literal->header.empty(), "raw compute stopped at an instruction literal"); + rawCode[0] = 0xbf820002; + rawCode[1] = 0xbf810000; + rawCode[2] = 0xbf800000; + rawCode[3] = 0xbf810000; + const auto branched = AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress); + check(branched->code.size() == 4 && literal->code[0] == 0xbe8003ff, "raw compute lost branch targets or modified an earlier snapshot"); + check(!expectFailure([&] { AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress + 4); }).empty(), "raw compute accepted a misaligned entry"); + check(!expectFailure([] { AgcDriver::DriverDetail::ReadRawComputeShader(0); }).empty(), "raw compute accepted an unmapped entry"); +#ifdef _WIN32 + auto* mapping = static_cast(VirtualAlloc(nullptr, 8192, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + check(mapping != nullptr, "cannot allocate raw compute boundary test"); + DWORD protection = 0; + check(VirtualProtect(mapping + 1024, 4096, PAGE_NOACCESS, &protection) != 0, "cannot protect raw compute boundary"); + auto* boundedCode = mapping + 1024 - 64; + std::fill_n(boundedCode, 64, 0xbf800000u); + const auto boundedAddress = reinterpret_cast(boundedCode); + const auto unterminated = expectFailure([&] { AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); }); + boundedCode[63] = 0xbf810000; + const auto bounded = AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); + check(VirtualFree(mapping, 0, MEM_RELEASE) != 0, "cannot release raw compute boundary test"); + check(!unterminated.empty() && bounded->code.size() == 64, "raw compute crossed inaccessible memory or missed its last instruction"); +#endif testEvents(); testValidation(); testClearState(); From e5191ebf130610e4605a3e4ce2c9e441a66ea7f6 Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:52:03 -0300 Subject: [PATCH 25/42] fix(agc): reuse validated raw compute snapshots --- core/libs/prx/libSceAgc/DcbState/src/Init.cpp | 4 +- core/libs/prx/libSceAgc/tests/Commands.cpp | 9 ++-- .../src/Driver/Shaders/ShaderRegistry.cpp | 41 ++++++++++++++++++- .../libs/prx/libSceAgcDriver/tests/Submit.cpp | 32 +++++++++++++++ 4 files changed, 79 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgc/DcbState/src/Init.cpp b/core/libs/prx/libSceAgc/DcbState/src/Init.cpp index 7c8283eaa..1b63094d1 100644 --- a/core/libs/prx/libSceAgc/DcbState/src/Init.cpp +++ b/core/libs/prx/libSceAgc/DcbState/src/Init.cpp @@ -9,8 +9,8 @@ extern "C" { -APS5_EXPORT("23LRUSvYu1M", sceAgcInitState_nid_no_patch); -int APS5_VABI sceAgcInitState_nid_no_patch(std::uint32_t* state, std::uint32_t version) { +APS5_EXPORT("23LRUSvYu1M", sceAgcUnknownInitState); +int APS5_VABI sceAgcUnknownInitState(std::uint32_t* state, std::uint32_t version) { Agc::Command::CheckAddress(reinterpret_cast(state), alignof(std::uint32_t), __func__); Agc::Command::Require(version < 14, __func__, "unsupported AGC initialization version"); return 0; diff --git a/core/libs/prx/libSceAgc/tests/Commands.cpp b/core/libs/prx/libSceAgc/tests/Commands.cpp index feefffe0b..4e11a5bed 100644 --- a/core/libs/prx/libSceAgc/tests/Commands.cpp +++ b/core/libs/prx/libSceAgc/tests/Commands.cpp @@ -14,7 +14,7 @@ extern "C" std::uint32_t* APS5_VABI sceAgcDcbResetQueue(CommandBuffer* buf, std: extern "C" std::uint32_t* APS5_VABI sceAgcDcbSetFlip(CommandBuffer* buf, std::uint32_t handle, std::int32_t index, std::uint32_t mode, std::int64_t argument); extern "C" int APS5_VABI sceAgcSuspendPoint(); extern "C" int APS5_VABI sceAgcInit(std::uint32_t version); -extern "C" int APS5_VABI sceAgcInitState_nid_no_patch(std::uint32_t* state, std::uint32_t version); +extern "C" int APS5_VABI sceAgcUnknownInitState(std::uint32_t* state, std::uint32_t version); extern "C" std::uint32_t* APS5_VABI sceAgcDcbDrawIndexAuto(CommandBuffer* buf, std::uint32_t indexCount, std::uint64_t modifier); extern "C" std::uint32_t* APS5_VABI sceAgcDcbDrawIndexIndirect(CommandBuffer* buf, std::uint32_t dataOffsetInBytes, std::uint64_t modifier); extern "C" std::uint32_t* APS5_VABI sceAgcDcbDrawIndexIndirectMulti(CommandBuffer* buf, std::uint32_t dataOffsetInBytes, std::uint32_t countIndirect, std::uint32_t maxCountOrCount, const volatile void* countAddress, std::uint32_t strideInBytes, std::uint64_t modifier); @@ -337,9 +337,10 @@ void testMemory() { void testDefaults() { std::uint32_t state = 0x12345678; - check(sceAgcInitState_nid_no_patch(&state, 8) == 0 && state == 0x12345678, "AGC initialization failed or modified caller state"); - expectFailure([] { sceAgcInitState_nid_no_patch(nullptr, 8); }); - expectFailure([&] { sceAgcInitState_nid_no_patch(&state, 14); }); + check(sceAgcUnknownInitState(&state, 8) == 0 && state == 0x12345678, "AGC initialization failed or modified caller state"); + check(sceAgcUnknownInitState(&state, 13) == 0 && state == 0x12345678, "AGC version 13 initialization changed caller state"); + expectFailure([] { sceAgcUnknownInitState(nullptr, 8); }); + expectFailure([&] { sceAgcUnknownInitState(&state, 14); }); check(sceAgcInit(8) == 0, "AGC version initialization failed"); expectFailure([] { sceAgcInit(14); }); expectFailure([] { sceAgcInit(0xffffffffu); }); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index d40f7e4d4..8ba86476a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -6,6 +6,7 @@ #include "Optimization/ResourceProgram.hpp" #include #include +#include #include #include "RdnaDecoder/RdnaInstructionDecoder.hpp" @@ -13,6 +14,25 @@ namespace AgcDriver::DriverDetail { std::shared_ptr ReadRawComputeShader(std::uint64_t address) { GuestMemory::CheckRange(reinterpret_cast(address), sizeof(std::uint32_t), 256); + static std::mutex cacheMutex; + static std::list> cache; + static std::size_t cacheBytes = 0; + std::shared_ptr cached; + { + std::lock_guard lock(cacheMutex); + const auto found = std::find_if(cache.begin(), cache.end(), [address](const auto& entry) { return entry->codeAddress == address; }); + if (found != cache.end()) cached = *found; + } + if (cached) { + const auto code = std::as_bytes(std::span(cached->code)); + GuestMemory::FlushGpuWrites(address, code.size()); + if (GuestMemory::CompareMapped(address, code) == GuestMemory::Compare::Equal) { + std::lock_guard lock(cacheMutex); + const auto found = std::find(cache.begin(), cache.end(), cached); + if (found != cache.end()) cache.splice(cache.begin(), cache, found); + return cached; + } + } constexpr std::size_t limit = 1024 * 1024; const auto ranges = GuestMemory::CommittedRanges(address, limit); std::uint64_t end = address; @@ -31,7 +51,26 @@ std::shared_ptr ReadRawComputeShader(std::uint64_t address const auto decoded = ShaderRecompiler::RdnaInstructionDecoder{}.Decode(snapshot.code); const auto& last = decoded.instructions.back(); snapshot.code.resize(last.programCounter / sizeof(std::uint32_t) + last.wordCount); - return std::make_shared(std::move(snapshot)); + auto result = std::make_shared(std::move(snapshot)); + std::lock_guard lock(cacheMutex); + const auto found = std::find_if(cache.begin(), cache.end(), [address](const auto& entry) { return entry->codeAddress == address; }); + if (found != cache.end()) { + if ((*found)->code == result->code) { + result = *found; + cache.splice(cache.begin(), cache, found); + return result; + } + cacheBytes -= (*found)->code.size() * sizeof(std::uint32_t); + cache.erase(found); + } + const auto bytes = result->code.size() * sizeof(std::uint32_t); + while (!cache.empty() && (cache.size() >= 64 || cacheBytes + bytes > 8 * 1024 * 1024)) { + cacheBytes -= cache.back()->code.size() * sizeof(std::uint32_t); + cache.pop_back(); + } + cache.push_front(result); + cacheBytes += bytes; + return result; } catch (const std::out_of_range&) { if (snapshot.code.size() == available) break; } diff --git a/core/libs/prx/libSceAgcDriver/tests/Submit.cpp b/core/libs/prx/libSceAgcDriver/tests/Submit.cpp index a37a89f14..6888c50b6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Submit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Submit.cpp @@ -375,12 +375,35 @@ int main() { const auto rawAddress = reinterpret_cast(rawCode.data()); const auto literal = AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress); check(literal->code.size() == 3 && literal->header.empty(), "raw compute stopped at an instruction literal"); + check(AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress) == literal, "unchanged raw compute code lost its snapshot identity"); rawCode[0] = 0xbf820002; rawCode[1] = 0xbf810000; rawCode[2] = 0xbf800000; rawCode[3] = 0xbf810000; const auto branched = AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress); check(branched->code.size() == 4 && literal->code[0] == 0xbe8003ff, "raw compute lost branch targets or modified an earlier snapshot"); + check(branched != literal, "changed raw compute code reused a stale snapshot"); + std::array, 8> concurrent; + std::vector readers; + for (auto& snapshot : concurrent) readers.emplace_back([&snapshot, rawAddress] { + snapshot = AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress); + }); + for (auto& reader : readers) reader.join(); + for (const auto& snapshot : concurrent) check(snapshot == branched, "concurrent raw compute readers lost snapshot reuse"); + alignas(256) std::array, 65> programs{}; + for (auto& program : programs) program[0] = 0xbf810000; + const auto firstAddress = reinterpret_cast(programs.front().data()); + readers.clear(); + for (auto& snapshot : concurrent) readers.emplace_back([&snapshot, firstAddress] { + snapshot = AgcDriver::DriverDetail::ReadRawComputeShader(firstAddress); + }); + for (auto& reader : readers) reader.join(); + for (const auto& snapshot : concurrent) check(snapshot == concurrent.front(), "concurrent raw compute misses duplicated snapshots"); + const auto evicted = AgcDriver::DriverDetail::ReadRawComputeShader(firstAddress); + for (std::size_t i = 1; i < programs.size(); ++i) + AgcDriver::DriverDetail::ReadRawComputeShader(reinterpret_cast(programs[i].data())); + check(AgcDriver::DriverDetail::ReadRawComputeShader(firstAddress) != evicted && evicted->code[0] == 0xbf810000, + "raw compute cache eviction lost snapshot lifetime or exceeded its entry limit"); check(!expectFailure([&] { AgcDriver::DriverDetail::ReadRawComputeShader(rawAddress + 4); }).empty(), "raw compute accepted a misaligned entry"); check(!expectFailure([] { AgcDriver::DriverDetail::ReadRawComputeShader(0); }).empty(), "raw compute accepted an unmapped entry"); #ifdef _WIN32 @@ -394,6 +417,15 @@ int main() { const auto unterminated = expectFailure([&] { AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); }); boundedCode[63] = 0xbf810000; const auto bounded = AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); + check(VirtualProtect(mapping + 1024, 4096, PAGE_READWRITE, &protection) != 0, "cannot extend raw compute mapping"); + boundedCode[63] = 0xbf800000; + boundedCode[64] = 0xbf810000; + const auto extended = AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); + check(extended != bounded && extended->code.size() == 65, "raw compute reused code before its end changed"); + check(VirtualProtect(mapping + 1024, 4096, PAGE_NOACCESS, &protection) != 0, "cannot revoke cached raw compute tail"); + check(!expectFailure([&] { AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); }).empty(), "raw compute reused an inaccessible cached tail"); + check(VirtualProtect(mapping, 4096, PAGE_NOACCESS, &protection) != 0, "cannot revoke cached raw compute code"); + check(!expectFailure([&] { AgcDriver::DriverDetail::ReadRawComputeShader(boundedAddress); }).empty(), "raw compute reused inaccessible cached code"); check(VirtualFree(mapping, 0, MEM_RELEASE) != 0, "cannot release raw compute boundary test"); check(!unterminated.empty() && bounded->code.size() == 64, "raw compute crossed inaccessible memory or missed its last instruction"); #endif From be6705e97758be2fb84be4c0d52753a26a8dbc99 Mon Sep 17 00:00:00 2001 From: Akhil Moola <24420588+ThisIsAkill@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:06:18 -0600 Subject: [PATCH 26/42] feat(libc): export std::_Fiopen as unimplemented PPSA21564 and PPSA21567 import std::_Fiopen (NID vYWK2Pz8vGE), the only libc NID the host libc lacks. Without it the executable fails to load against the host libc when the title's own libc.prx is left out of the guest conversion, which is how the Linux runs of PPSA21564 avoid the libc.prx binding crash. The values of the open mode and the meaning of the protection argument are unknown, so the export throws when called; it was never called in a 300 s run of PPSA21567. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_014A3UgWDUxE1EeHyVZm6tiN --- core/libs/prx/libc/CMakeLists.txt | 10 ++++++++++ core/libs/prx/libc/src/CxxAbiSupport.cpp | 9 +++++++++ core/libs/tests/GuestFiopen.cpp | 15 +++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 4 files changed, 35 insertions(+) create mode 100644 core/libs/tests/GuestFiopen.cpp diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index 847b8ffc3..56b01feda 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -87,6 +87,16 @@ if(BUILD_TESTING) set_tests_properties(guest_execute_once PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(guest_fiopen_tests ${LIBS_INCLUDE_DIR}/tests/GuestFiopen.cpp) + target_include_directories(guest_fiopen_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_fiopen_tests PRIVATE libc) + configure_windows_unwind(guest_fiopen_tests) + add_test(NAME guest_fiopen COMMAND guest_fiopen_tests) + set_tests_properties(guest_fiopen PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_fiopen PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_working_directory_tests ${LIBS_INCLUDE_DIR}/tests/GuestWorkingDirectory.cpp) target_include_directories(guest_working_directory_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_working_directory_tests PRIVATE libc) diff --git a/core/libs/prx/libc/src/CxxAbiSupport.cpp b/core/libs/prx/libc/src/CxxAbiSupport.cpp index 8f32a8572..fd29fb581 100644 --- a/core/libs/prx/libc/src/CxxAbiSupport.cpp +++ b/core/libs/prx/libc/src/CxxAbiSupport.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -41,6 +42,14 @@ int APS5_VABI LibcInternalExtCxaThreadAtexit_nid_postfix(void (*destructor)(void const std::error_category* _ZSt17iostream_categoryv_nid_postfix() { return &std::iostream_category(); } +std::FILE* APS5_VABI _ZSt7_FiopenPKcNSt5_IosbIiE9_OpenmodeEi_nid_postfix(const char* filename, int mode, int protection) { + static_cast(filename); + static_cast(mode); + static_cast(protection); + NotImplemented_nid_no_patch("std::_Fiopen"); + return nullptr; +} + int APS5_VABI _ZSt13_Execute_onceRSt9once_flagPFiPvS1_PS1_ES1__nid_postfix( int* flag, int (APS5_VABI *callback)(void*, void*, void**), void* arg ) { diff --git a/core/libs/tests/GuestFiopen.cpp b/core/libs/tests/GuestFiopen.cpp new file mode 100644 index 000000000..379cda811 --- /dev/null +++ b/core/libs/tests/GuestFiopen.cpp @@ -0,0 +1,15 @@ +#include "prx/libc/include/general/VabiMacros.hpp" +#include +#include +#include + +extern "C" std::FILE* APS5_VABI _ZSt7_FiopenPKcNSt5_IosbIiE9_OpenmodeEi_nid_postfix(const char*, int, int); + +int main() { + try { + _ZSt7_FiopenPKcNSt5_IosbIiE9_OpenmodeEi_nid_postfix("unused", 1, 0); + } catch (const std::runtime_error& error) { + return std::string_view(error.what()) == "std::_Fiopen not implemented" ? 0 : 1; + } + return 1; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index dade5a9e4..b9b006705 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -69,6 +69,7 @@ Throughout the project, every function at every stage either **does exactly what - [Guest arena](../../core/libs/prx/libc/src/GuestArena.cpp) (libc) - the application map area is assumed to end at 0xFC_0000_0000, as `SCE_KERNEL_APP_MAP_AREA_END_ADDR` does on the PS4. On Windows, host allocations made in the arena before libc loads stay, and a fixed guest mapping over one throws - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature - [sceLibcInternalHeapErrorReportForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature +- [std::_Fiopen](../../core/libs/prx/libc/src/CxxAbiSupport.cpp) (libc) - `_ZSt7_FiopenPKcNSt5_IosbIiE9_OpenmodeEi` (NID `vYWK2Pz8vGE`; the name comes from the public NID list): the values of the `_Openmode` argument and the meaning of the protection argument are unknown, so it throws when called. It is exported so that a title that imports it (PPSA21564 and PPSA21567 do) loads against the host libc when its own `libc.prx` is left out of the guest conversion. - [_sceLibcInternalThreadAtexit, _sceLibcInternalThreadDtors](../../core/libs/prx/libSceLibcInternal/Export.cpp) (libSceLibcInternal) - FreeBSD `__cxa_thread_atexit` semantics assumed; a null or non-image destructor and an allocation failure throw - [_sceLibcInternalForceTlsDestructor](../../core/libs/prx/libSceLibcInternal/Export.cpp) (libSceLibcInternal) - unknown return type and behaviour; a title's `libc.prx` calls it from `__cxa_finalize` with the module handle of a non-null dso - [__progname](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - unknown data export From 9c4b4d701cf41430ee84577b599100c64f0c8c1d Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:36:25 -0300 Subject: [PATCH 27/42] fix(agc): write profiling reports off GPU workers --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 14 ++ .../Execution/include/ProfileOutput.hpp | 145 ++++++++++++++++++ .../Dispatch/DispatchCacheStatistics.cpp | 9 +- .../src/Driver/Dispatch/DispatchTiming.cpp | 3 +- .../src/Driver/Packets/PacketFlush.cpp | 3 +- .../Execution/src/GuestMemory.cpp | 25 +-- .../Execution/src/VulkanDevice.cpp | 27 ++-- .../Graphics/src/BufferPool.cpp | 3 +- .../Graphics/src/GuestBufferMemory.cpp | 19 +-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 27 ++-- .../Graphics/src/ShaderResources.cpp | 15 +- .../libSceAgcDriver/tests/ProfileOutput.cpp | 121 +++++++++++++++ 12 files changed, 350 insertions(+), 61 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 90d971f7a..f0b6ceb8a 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -200,6 +200,20 @@ target_link_libraries(libSceAgcDriver PRIVATE set_target_properties(libSceAgcDriver PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(libSceAgcDriver) + +if(BUILD_TESTING) + add_test_executable(agc_profile_output_tests tests/ProfileOutput.cpp) + target_include_directories(agc_profile_output_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_profile_output_tests PRIVATE libc) + configure_windows_unwind(agc_profile_output_tests) + add_test(NAME agc_profile_output COMMAND agc_profile_output_tests) + set_tests_properties(agc_profile_output PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(agc_profile_output PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() + if(WIN32) set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/GuestMemory.cpp PROPERTIES COMPILE_DEFINITIONS _WIN32_WINNT=0x0602) endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp new file mode 100644 index 000000000..9c714409e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +class ProfileOutput { +public: + explicit ProfileOutput(std::function writer, std::size_t capacity = 4 * 1024 * 1024) : writer(std::move(writer)), capacity(capacity) { + if (!this->writer || capacity == 0) throw std::invalid_argument("invalid profile output writer or capacity"); + worker = std::thread([this] { run(); }); + } + + ~ProfileOutput() { + { + std::lock_guard lock(mutex); + stopping = true; + } + changed.notify_one(); + worker.join(); + } + + bool Write(std::string text) { + { + std::lock_guard lock(mutex); + if (failure) std::rethrow_exception(failure); + if (stopping) throw std::runtime_error("profile output is stopping"); + if (text.empty()) return true; + if (text.size() > capacity - bytes) { + ++dropped; + changed.notify_one(); + return false; + } + const auto size = text.size(); + pending.push_back(std::move(text)); + bytes += size; + } + changed.notify_one(); + return true; + } + + template + void Print(const char* format, TArgs... args) { + std::array local{}; + const auto size = std::snprintf(local.data(), local.size(), format, args...); + if (size < 0) throw std::runtime_error("profile output formatting failed"); + if (static_cast(size) < local.size()) { + Write(std::string(local.data(), size)); + } else if (static_cast(size) > capacity) { + std::lock_guard lock(mutex); + if (failure) std::rethrow_exception(failure); + ++dropped; + changed.notify_one(); + } else { + std::vector text(static_cast(size) + 1); + if (std::snprintf(text.data(), text.size(), format, args...) != size) throw std::runtime_error("profile output formatting changed"); + Write(std::string(text.data(), size)); + } + } + + void Flush() { + std::unique_lock lock(mutex); + idle.wait(lock, [&] { return failure || (pending.empty() && !writing && dropped == 0); }); + if (failure) std::rethrow_exception(failure); + } + +private: + void run() noexcept { + try { + for (;;) { + std::string batch; + std::size_t consumed = 0; + { + std::unique_lock lock(mutex); + changed.wait(lock, [&] { return stopping || !pending.empty() || dropped != 0; }); + if (stopping && pending.empty() && dropped == 0) return; + while (!pending.empty() && (batch.empty() || batch.size() + pending.front().size() <= 65536)) { + consumed += pending.front().size(); + batch += pending.front(); + pending.pop_front(); + } + if (dropped != 0) { + batch += "[profile-output] dropped " + std::to_string(dropped) + " chunks because the diagnostic writer fell behind\n"; + dropped = 0; + } + writing = true; + } + writer(batch); + { + std::lock_guard lock(mutex); + bytes -= consumed; + writing = false; + } + idle.notify_all(); + } + } catch (...) { + { + std::lock_guard lock(mutex); + failure = std::current_exception(); + writing = false; + } + idle.notify_all(); + } + } + + std::function writer; + const std::size_t capacity; + std::mutex mutex; + std::condition_variable changed; + std::condition_variable idle; + std::deque pending; + std::size_t bytes = 0; + std::size_t dropped = 0; + bool writing = false; + bool stopping = false; + std::exception_ptr failure; + std::thread worker; +}; + +inline ProfileOutput& ProfileOutput_nid_no_patch() { + static ProfileOutput output([](std::string_view text) { + if (std::fwrite(text.data(), 1, text.size(), stderr) != text.size() || std::fflush(stderr) != 0) + throw std::runtime_error("profile output write failed"); + }); + return output; +} + +template +void ProfilePrint_nid_no_patch(const char* format, TArgs... args) { + ProfileOutput_nid_no_patch().Print(format, args...); +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp index d2fe53c1e..dae236316 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "Optimization/ResourceProgram.hpp" @@ -42,7 +43,7 @@ void Driver::classifyDiffering(std::uint64_t program, std::uint64_t key, const D void Driver::reportDispatchCache(EntryCounters& counters) { const auto count = [](std::uint64_t value) { return static_cast(value); }; const auto validated = counters.lookups - counters.absent; - std::fprintf(stderr, "[dispatch-cache] %llu lookups (10 s): %llu no entry, %llu validated by value in %.1f us each: %llu equal, %llu differing, %llu page not mapped, %llu queued label, %llu image being stored, %llu publish generation moved, %llu pending serial moved, %llu forget serial moved (%llu pending images stored first, %llu pending runs synced first, %llu equal entries inserted before a forget; gate retried %llu: %llu equal, %llu moved again); runs per entry %.1f validated / %.1f inserted; %llu misses found the entry replaced meanwhile; %llu inserts (%llu captures not kept: unstable), %llu evictions in total, %zu entries, %llu LRU moves\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.equal), count(counters.differing), count(counters.inaccessible), count(counters.queuedLabel), count(counters.flushingImage), count(counters.publishMoved), count(counters.pendingMoved), count(counters.forgetMoved), count(counters.imagesFlushed), count(counters.runsSynced), count(counters.forgetSinceInsert), count(counters.retriesEqual + counters.retriesMoved), count(counters.retriesEqual), count(counters.retriesMoved), validated != 0 ? static_cast(counters.runsValidated) / static_cast(validated) : 0.0, counters.inserts != 0 ? static_cast(counters.runsInserted) / static_cast(counters.inserts) : 0.0, count(counters.replaced), count(counters.inserts), count(counters.unstable), count(dispatchCacheEvictions), dispatchCache.size(), count(counters.touches)); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] %llu lookups (10 s): %llu no entry, %llu validated by value in %.1f us each: %llu equal, %llu differing, %llu page not mapped, %llu queued label, %llu image being stored, %llu publish generation moved, %llu pending serial moved, %llu forget serial moved (%llu pending images stored first, %llu pending runs synced first, %llu equal entries inserted before a forget; gate retried %llu: %llu equal, %llu moved again); runs per entry %.1f validated / %.1f inserted; %llu misses found the entry replaced meanwhile; %llu inserts (%llu captures not kept: unstable), %llu evictions in total, %zu entries, %llu LRU moves\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.equal), count(counters.differing), count(counters.inaccessible), count(counters.queuedLabel), count(counters.flushingImage), count(counters.publishMoved), count(counters.pendingMoved), count(counters.forgetMoved), count(counters.imagesFlushed), count(counters.runsSynced), count(counters.forgetSinceInsert), count(counters.retriesEqual + counters.retriesMoved), count(counters.retriesEqual), count(counters.retriesMoved), validated != 0 ? static_cast(counters.runsValidated) / static_cast(validated) : 0.0, counters.inserts != 0 ? static_cast(counters.runsInserted) / static_cast(counters.inserts) : 0.0, count(counters.replaced), count(counters.inserts), count(counters.unstable), count(dispatchCacheEvictions), dispatchCache.size(), count(counters.touches)); std::vector> programs(counters.differingByProgram.begin(), counters.differingByProgram.end()); std::sort(programs.begin(), programs.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); std::string top; @@ -51,21 +52,21 @@ void Driver::reportDispatchCache(EntryCounters& counters) { std::snprintf(text, sizeof(text), " 0x%llx x%llu", static_cast(programs[i].first), count(programs[i].second)); top += text; } - std::fprintf(stderr, "[dispatch-cache] differing by class (10 s, %llu classified): address-only %llu, data-only %llu, walk %llu, mixed %llu (runs changed %llu); matched one of the last 3 value sets %llu; differing words %llu in total (misses with 1 / 2-4 / 5-16 / >16 words: %llu / %llu / %llu / %llu), %zu distinct positions (first %zu, last %zu); top programs by differing:%s\n", count(counters.differingClassified), count(counters.differingAddress), count(counters.differingData), count(counters.differingWalk), count(counters.differingMixed), count(counters.differingRunsChanged), count(counters.differingMatchedPrior), count(counters.differingWords), count(counters.differingWordBuckets[0]), count(counters.differingWordBuckets[1]), count(counters.differingWordBuckets[2]), count(counters.differingWordBuckets[3]), counters.differingPositions.size(), counters.differingPositions.empty() ? std::size_t{0} : counters.differingFirstPosition, counters.differingLastPosition, top.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] differing by class (10 s, %llu classified): address-only %llu, data-only %llu, walk %llu, mixed %llu (runs changed %llu); matched one of the last 3 value sets %llu; differing words %llu in total (misses with 1 / 2-4 / 5-16 / >16 words: %llu / %llu / %llu / %llu), %zu distinct positions (first %zu, last %zu); top programs by differing:%s\n", count(counters.differingClassified), count(counters.differingAddress), count(counters.differingData), count(counters.differingWalk), count(counters.differingMixed), count(counters.differingRunsChanged), count(counters.differingMatchedPrior), count(counters.differingWords), count(counters.differingWordBuckets[0]), count(counters.differingWordBuckets[1]), count(counters.differingWordBuckets[2]), count(counters.differingWordBuckets[3]), counters.differingPositions.size(), counters.differingPositions.empty() ? std::size_t{0} : counters.differingFirstPosition, counters.differingLastPosition, top.c_str()); std::string ranks; for (std::size_t rank = 0; rank < dispatchVariants(); ++rank) { char text[32]; std::snprintf(text, sizeof(text), "%s%llu", rank == 0 ? "" : " / ", count(counters.variantHitsByRank[rank])); ranks += text; } - std::fprintf(stderr, "[dispatch-cache] variants (10 s, k = %zu): hits by rank 1..k %s; %.2f variants compared per validation; %llu inserted into an entry, %llu evicted beyond k; %.2f variants per entry (%llu over %zu entries, ~%.1f MiB)\n", dispatchVariants(), ranks.c_str(), validated != 0 ? static_cast(counters.variantsCompared) / static_cast(validated) : 0.0, count(counters.variantsInserted), count(counters.variantsEvicted), dispatchCache.empty() ? 0.0 : static_cast(dispatchCacheVariants) / static_cast(dispatchCache.size()), count(dispatchCacheVariants), dispatchCache.size(), static_cast(dispatchCacheVariantBytes) / (1024.0 * 1024.0)); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] variants (10 s, k = %zu): hits by rank 1..k %s; %.2f variants compared per validation; %llu inserted into an entry, %llu evicted beyond k; %.2f variants per entry (%llu over %zu entries, ~%.1f MiB)\n", dispatchVariants(), ranks.c_str(), validated != 0 ? static_cast(counters.variantsCompared) / static_cast(validated) : 0.0, count(counters.variantsInserted), count(counters.variantsEvicted), dispatchCache.empty() ? 0.0 : static_cast(dispatchCacheVariants) / static_cast(dispatchCache.size()), count(dispatchCacheVariants), dispatchCache.size(), static_cast(dispatchCacheVariantBytes) / (1024.0 * 1024.0)); std::string dataRanks; for (std::size_t rank = 0; rank < dispatchVariants(); ++rank) { char text[32]; std::snprintf(text, sizeof(text), "%s%llu", rank == 0 ? "" : " / ", count(counters.dataHitsByRank[rank])); dataRanks += text; } - std::fprintf(stderr, "[dispatch-cache] data hits (10 s): %llu (%llu words refreshed; by rank 1..k %s; %llu data variants missed on pending runs), verified %llu; inserts with data positions %llu of %llu (%.1f positions each), leaves skipped: unmapped %llu, mismatched %llu, aliased %llu\n", count(counters.dataHits), count(counters.dataWordsRefreshed), dataRanks.c_str(), count(dataPendingMisses.exchange(0, std::memory_order_relaxed)), count(counters.dataVerified), count(counters.dataInserts), count(counters.inserts), counters.dataInserts != 0 ? static_cast(counters.dataPositionsInserted) / static_cast(counters.dataInserts) : 0.0, count(counters.dataLeavesUnmapped), count(counters.dataLeavesMismatched), count(counters.dataLeavesAliased)); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] data hits (10 s): %llu (%llu words refreshed; by rank 1..k %s; %llu data variants missed on pending runs), verified %llu; inserts with data positions %llu of %llu (%.1f positions each), leaves skipped: unmapped %llu, mismatched %llu, aliased %llu\n", count(counters.dataHits), count(counters.dataWordsRefreshed), dataRanks.c_str(), count(dataPendingMisses.exchange(0, std::memory_order_relaxed)), count(counters.dataVerified), count(counters.dataInserts), count(counters.inserts), counters.dataInserts != 0 ? static_cast(counters.dataPositionsInserted) / static_cast(counters.dataInserts) : 0.0, count(counters.dataLeavesUnmapped), count(counters.dataLeavesMismatched), count(counters.dataLeavesAliased)); counters = EntryCounters{}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp index ecfdfb711..b887acd81 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchTiming.hpp" @@ -25,7 +26,7 @@ void Driver::addDriverPhases(DispatchClass which, const std::array(line.validations) : 0.0; - std::fprintf(stderr, "[dispatch] driver phases %s (10 s, %llu dispatches, %llu cache hits), us per dispatch:%s, total %.1f (%.1f ms); validate %.1f us per validation (%llu validations; GPU waits inside it %.1f us per validation apart)\n", DispatchClassNames[cls], static_cast(line.dispatches), static_cast(line.hits), report.c_str(), total * 1000 / static_cast(line.dispatches), total, line.ms[PhaseValidate] * perValidation, static_cast(line.validations), line.ms[PhaseValidateWait] * perValidation); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch] driver phases %s (10 s, %llu dispatches, %llu cache hits), us per dispatch:%s, total %.1f (%.1f ms); validate %.1f us per validation (%llu validations; GPU waits inside it %.1f us per validation apart)\n", DispatchClassNames[cls], static_cast(line.dispatches), static_cast(line.hits), report.c_str(), total * 1000 / static_cast(line.dispatches), total, line.ms[PhaseValidate] * perValidation, static_cast(line.validations), line.ms[PhaseValidateWait] * perValidation); line = {}; } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp index 0729d6a79..33863d1b2 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" @@ -98,7 +99,7 @@ void Driver::flushBetweenPackets(std::uint32_t queue, std::uint32_t header, bool lastReport = reportNow; const auto stores = Graphics::Recorder::StoreCounts(); const auto failed = [](TrySite site) { return static_cast(triesFailed[site].load()); }; - std::fprintf(stderr, "[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); + AgcDriver::ProfilePrint_nid_no_patch("[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 291369842..8bea6b6a1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "ThreadOwned.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -292,30 +293,30 @@ public: auto last = state.lastReport.load(); if (nowMs - last < 10000 || !state.lastReport.compare_exchange_strong(last, nowMs)) return; const auto totals = FoldMemoryCounters(); - std::fprintf(stderr, "[guestmem]"); + AgcDriver::ProfilePrint_nid_no_patch("[guestmem]"); for (std::size_t i = 0; i < MemoryCounterCount; ++i) { - std::fprintf(stderr, " %s %llu calls %.0f MiB %.1f s", MemoryCounterNames[i], static_cast(totals[i][0]), totals[i][1] / 1048576.0, totals[i][2] / 1e9); + AgcDriver::ProfilePrint_nid_no_patch(" %s %llu calls %.0f MiB %.1f s", MemoryCounterNames[i], static_cast(totals[i][0]), totals[i][1] / 1048576.0, totals[i][2] / 1e9); } - std::fprintf(stderr, " collect-memo hits %llu, collect epochs %llu", static_cast(collectMemoHits.load()), static_cast(collectEpochBumps.load())); - std::fprintf(stderr, " collect-dirty %llu tracker waits %llu / %llu", static_cast(collectDirty.load()), static_cast(trackerWaits.load()), static_cast(trackerAcquisitions.load())); - std::fprintf(stderr, " | arena 0x%llx+0x%llx image 0x%llx+0x%llx forgets %llu (%.0f MiB)", static_cast(PagesBase()), static_cast(PagesSize()), static_cast(ImagePagesBase()), static_cast(ImagePagesSize()), static_cast(forgetCalls.load()), forgetBytes.load() / 1048576.0); + AgcDriver::ProfilePrint_nid_no_patch(" collect-memo hits %llu, collect epochs %llu", static_cast(collectMemoHits.load()), static_cast(collectEpochBumps.load())); + AgcDriver::ProfilePrint_nid_no_patch(" collect-dirty %llu tracker waits %llu / %llu", static_cast(collectDirty.load()), static_cast(trackerWaits.load()), static_cast(trackerAcquisitions.load())); + AgcDriver::ProfilePrint_nid_no_patch(" | arena 0x%llx+0x%llx image 0x%llx+0x%llx forgets %llu (%.0f MiB)", static_cast(PagesBase()), static_cast(PagesSize()), static_cast(ImagePagesBase()), static_cast(ImagePagesSize()), static_cast(forgetCalls.load()), forgetBytes.load() / 1048576.0); { std::lock_guard lock(state.callersMutex); - std::fprintf(stderr, " | read callers:"); + AgcDriver::ProfilePrint_nid_no_patch(" | read callers:"); for (const auto& [caller, count] : state.callers) { - if (count != 0) std::fprintf(stderr, " +0x%llx=%llu", caller, static_cast(count)); + if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" +0x%llx=%llu", caller, static_cast(count)); } - std::fprintf(stderr, " | write callers:"); + AgcDriver::ProfilePrint_nid_no_patch(" | write callers:"); for (const auto& [caller, count] : state.writeCallers) { - if (count != 0) std::fprintf(stderr, " +0x%llx=%llu", caller, static_cast(count)); + if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" +0x%llx=%llu", caller, static_cast(count)); } } - std::fprintf(stderr, " | read sites:"); + AgcDriver::ProfilePrint_nid_no_patch(" | read sites:"); for (std::size_t site = 0; site < static_cast(ReadSite::Count); ++site) { const auto count = readSiteSamples[site].load(std::memory_order_relaxed); - if (count != 0) std::fprintf(stderr, " %s=%llu", ReadSiteName(static_cast(site)), static_cast(count)); + if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" %s=%llu", ReadSiteName(static_cast(site)), static_cast(count)); } - std::fprintf(stderr, "\n"); + AgcDriver::ProfilePrint_nid_no_patch("\n"); } private: MemoryCounterKind kind; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 5f2479057..5cadb337f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "BdaAbi.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" @@ -1327,7 +1328,7 @@ bool VulkanDevice::FillBuffer(std::uint64_t address, std::size_t bytes, std::spa const auto now = std::chrono::steady_clock::now(); if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; - std::fprintf(stderr, "[fill-sync] fills: %llu synced (%llu with a completion label pending) waited %.0f ms, %llu ordered by barrier, %llu with no pending write; phases ms: decide %.0f record %.0f notes %.0f; %llu uniform, %llu pattern (%llu doubling steps in place; pattern buffers reused %llu, made %llu)\n", static_cast(synced), static_cast(labelSynced), syncedMs, static_cast(ordered), static_cast(fills - synced - ordered), decideMs, recordMs, notesMs, static_cast(uniformFills), static_cast(patternFills), static_cast(doublingSteps), static_cast(patternBuffersReused), static_cast(patternBuffersMade)); + AgcDriver::ProfilePrint_nid_no_patch("[fill-sync] fills: %llu synced (%llu with a completion label pending) waited %.0f ms, %llu ordered by barrier, %llu with no pending write; phases ms: decide %.0f record %.0f notes %.0f; %llu uniform, %llu pattern (%llu doubling steps in place; pattern buffers reused %llu, made %llu)\n", static_cast(synced), static_cast(labelSynced), syncedMs, static_cast(ordered), static_cast(fills - synced - ordered), decideMs, recordMs, notesMs, static_cast(uniformFills), static_cast(patternFills), static_cast(doublingSteps), static_cast(patternBuffersReused), static_cast(patternBuffersMade)); } } auto phaseStart = fillStart; @@ -1958,7 +1959,7 @@ bool VulkanDevice::PresentDisplayBuffer(const DisplayBuffer& buffer) { } if (profile && std::chrono::steady_clock::now() - lastReport > std::chrono::seconds(10)) { lastReport = std::chrono::steady_clock::now(); - std::fprintf(stderr, "[flip] %llu presents from the resident image (%llu refreshed first), through guest memory: %llu not pending, %llu unsuitable; %llu GPU frame dumps\n", static_cast(residentPresents), static_cast(refreshedPresents), static_cast(notPending), static_cast(unsuitable), static_cast(gpuDumps)); + AgcDriver::ProfilePrint_nid_no_patch("[flip] %llu presents from the resident image (%llu refreshed first), through guest memory: %llu not pending, %llu unsuitable; %llu GPU frame dumps\n", static_cast(residentPresents), static_cast(refreshedPresents), static_cast(notPending), static_cast(unsuitable), static_cast(gpuDumps)); } CaptureTrace::Log("present dump=%d address=%llx width=%u height=%u resident=%d generation=%llu", dumpFrame ? state->nextDumpIndex : -1, static_cast(buffer.address), buffer.width, buffer.height, resident != nullptr, static_cast(resident ? resident->Generation() : 0)); VkClearColorValue uniform{}; @@ -2685,7 +2686,7 @@ void reportRecipes() { const auto precheckUs = perHit(counters.precheckNs); const auto proofUs = perHit(counters.proofNs); const auto recordUs = perHit(counters.recordNs); - std::fprintf(stderr, "[recipe] %s (10 s): hits %llu; pre-check misses: %s; proofs: %s; rebuilds: %s; presyncs from the recipe %llu (recomputed %llu, waited %llu); data refreshes recorded %llu / skipped by hash %llu (%llu decided by words: data hits); restarts %llu, attaches %llu; us per hit: pre-check %.1f, proof %.1f, record %.1f; verified %llu (object replaced %llu)\n", kind == 0 ? "dispatch" : kind == 1 ? "indirect" : "draw", hits, misses.c_str(), proofs.c_str(), rebuilds.c_str(), take(counters.presyncsFromRecipe), take(counters.presyncsRecomputed), take(counters.presyncWaits), take(counters.dataRefreshed), take(counters.dataSkipped), take(counters.refreshByWords), take(counters.restarts), take(counters.attaches), precheckUs, proofUs, recordUs, take(counters.verified), take(counters.verifyReplaced)); + AgcDriver::ProfilePrint_nid_no_patch("[recipe] %s (10 s): hits %llu; pre-check misses: %s; proofs: %s; rebuilds: %s; presyncs from the recipe %llu (recomputed %llu, waited %llu); data refreshes recorded %llu / skipped by hash %llu (%llu decided by words: data hits); restarts %llu, attaches %llu; us per hit: pre-check %.1f, proof %.1f, record %.1f; verified %llu (object replaced %llu)\n", kind == 0 ? "dispatch" : kind == 1 ? "indirect" : "draw", hits, misses.c_str(), proofs.c_str(), rebuilds.c_str(), take(counters.presyncsFromRecipe), take(counters.presyncsRecomputed), take(counters.presyncWaits), take(counters.dataRefreshed), take(counters.dataSkipped), take(counters.refreshByWords), take(counters.restarts), take(counters.attaches), precheckUs, proofUs, recordUs, take(counters.verified), take(counters.verifyReplaced)); } } @@ -2715,7 +2716,7 @@ struct DispatchTimer { add(which, ms); phaseStart = now; // Slow phases are reported as they finish, so a dispatch that never completes shows where it is. - if (ms > 1000) std::fprintf(stderr, "[dispatch] %s took %.0f ms (%zu words, program 0x%llx)\n", DispatchRowName(which), ms, spirvWords, static_cast(programAddress)); + if (ms > 1000) AgcDriver::ProfilePrint_nid_no_patch("[dispatch] %s took %.0f ms (%zu words, program 0x%llx)\n", DispatchRowName(which), ms, spirvWords, static_cast(programAddress)); } void restart() { phaseStart = std::chrono::steady_clock::now(); } // The call's phases as text, only when wanted: a slow call, or a new [indirect] maximum. @@ -2738,7 +2739,7 @@ struct DispatchTimer { for (std::size_t row = 0; row < DispatchPhaseCount; ++row) { if (d.phaseTotals[row] != 0) report += " " + std::string(DispatchRowName(row)) + "=" + std::to_string(static_cast(d.phaseTotals[row] / 1000)) + "s"; } - std::fprintf(stderr, "[dispatch] %llu dispatches, phase totals:%s\n", static_cast(d.profiledDispatches), report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch] %llu dispatches, phase totals:%s\n", static_cast(d.profiledDispatches), report.c_str()); } // The call's end: the proc lookups it made, the slow-call report, the [indirect] hold // accounting (`indirectHold`: the call was an indirect dispatch, CPU-resolved or not) and line. @@ -2748,7 +2749,7 @@ struct DispatchTimer { d.procLookups += Graphics::DeviceProcLookups() - lookupsBefore; const auto now = std::chrono::steady_clock::now(); const auto totalMs = std::chrono::duration(now - start).count(); - if (totalMs > 100) std::fprintf(stderr, "[dispatch] %s %zu words:%s\n", groupsText, spirvWords, formatCall().c_str()); + if (totalMs > 100) AgcDriver::ProfilePrint_nid_no_patch("[dispatch] %s %zu words:%s\n", groupsText, spirvWords, formatCall().c_str()); if (!indirectHold) return; auto& hold = d.indirectHold; ++hold.count; @@ -2767,7 +2768,7 @@ struct DispatchTimer { else std::snprintf(text, sizeof(text), " %s %.0f ms", DispatchRowName(i), hold.phaseMs[i]); report += text; } - std::fprintf(stderr, "[indirect] %llu indirect dispatches spent %.0f ms inside the device call (10 s; max %.1f ms:%s), by phase (the 'resources: ...' rows split 'resources'; 'hook waits' overlaps them; 'images: ...' rows are the lookups by outcome, count x ms, inside 'B images'):%s; copied-writer lists scanned per decision: dispatch avg %.1f (max %zu), draw avg %.1f\n", static_cast(hold.count), hold.totalMs, hold.maxMs, hold.maxPhases.c_str(), report.c_str(), hold.count != 0 ? static_cast(hold.writersScanned) / hold.count : 0.0, hold.maxWriters, hold.count != 0 ? static_cast(hold.drawWritersScanned) / hold.count : 0.0); + AgcDriver::ProfilePrint_nid_no_patch("[indirect] %llu indirect dispatches spent %.0f ms inside the device call (10 s; max %.1f ms:%s), by phase (the 'resources: ...' rows split 'resources'; 'hook waits' overlaps them; 'images: ...' rows are the lookups by outcome, count x ms, inside 'B images'):%s; copied-writer lists scanned per decision: dispatch avg %.1f (max %zu), draw avg %.1f\n", static_cast(hold.count), hold.totalMs, hold.maxMs, hold.maxPhases.c_str(), report.c_str(), hold.count != 0 ? static_cast(hold.writersScanned) / hold.count : 0.0, hold.maxWriters, hold.count != 0 ? static_cast(hold.drawWritersScanned) / hold.count : 0.0); hold.phaseMs = {}; hold.phaseCounts = {}; hold.count = 0; @@ -2902,7 +2903,7 @@ std::uint64_t VulkanDevice::presync(std::span(std::chrono::steady_clock::now().time_since_epoch()).count(); auto last = counters.lastReport.load(); - if (nowMs - last >= 10000 && counters.lastReport.compare_exchange_strong(last, nowMs)) std::fprintf(stderr, "[presync] %llu dispatches checked, %llu pre-syncs waited %.0f ms (cumulative)\n", static_cast(counters.checked.load()), static_cast(counters.presyncs.load()), counters.waitedUs.load() / 1000.0); + if (nowMs - last >= 10000 && counters.lastReport.compare_exchange_strong(last, nowMs)) AgcDriver::ProfilePrint_nid_no_patch("[presync] %llu dispatches checked, %llu pre-syncs waited %.0f ms (cumulative)\n", static_cast(counters.checked.load()), static_cast(counters.presyncs.load()), counters.waitedUs.load() / 1000.0); } return serial; } @@ -3361,8 +3362,8 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec } if (profile && std::chrono::steady_clock::now() - d.cacheReport > std::chrono::seconds(10)) { d.cacheReport = std::chrono::steady_clock::now(); - std::fprintf(stderr, "[rescache] %llu hits, %llu misses, %llu invalidated, %zu entries (dispatch + draw); template hits: %llu refreshed the data buffers (revalidate %.1f ms), %llu had the same words; Find calls %llu, Touch calls %llu\n", static_cast(d.cacheHits), static_cast(d.cacheMisses), static_cast(d.cacheInvalidated), state->resourceCache.Size(), static_cast(d.templateRefreshed), d.templateRevalidateMs, static_cast(d.templateSameWords), static_cast(ResourceCache::Finds()), static_cast(ResourceCache::Touches())); - std::fprintf(stderr, "[vk] deviceProc lookups inside the device call: %llu (%.2f per dispatch); pre-dispatch barriers recorded %llu, skipped %llu\n", static_cast(d.procLookups), d.profiledDispatches != 0 ? static_cast(d.procLookups) / static_cast(d.profiledDispatches) : 0.0, static_cast(d.preBarriersRecorded), static_cast(d.preBarriersSkipped)); + AgcDriver::ProfilePrint_nid_no_patch("[rescache] %llu hits, %llu misses, %llu invalidated, %zu entries (dispatch + draw); template hits: %llu refreshed the data buffers (revalidate %.1f ms), %llu had the same words; Find calls %llu, Touch calls %llu\n", static_cast(d.cacheHits), static_cast(d.cacheMisses), static_cast(d.cacheInvalidated), state->resourceCache.Size(), static_cast(d.templateRefreshed), d.templateRevalidateMs, static_cast(d.templateSameWords), static_cast(ResourceCache::Finds()), static_cast(ResourceCache::Touches())); + AgcDriver::ProfilePrint_nid_no_patch("[vk] deviceProc lookups inside the device call: %llu (%.2f per dispatch); pre-dispatch barriers recorded %llu, skipped %llu\n", static_cast(d.procLookups), d.profiledDispatches != 0 ? static_cast(d.procLookups) / static_cast(d.profiledDispatches) : 0.0, static_cast(d.preBarriersRecorded), static_cast(d.preBarriersSkipped)); reportRecipes(); } timing.Mark("shader_resources"); @@ -3449,9 +3450,9 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec lastReport = now; std::vector> hot(byProgram.begin(), byProgram.end()); std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second.ms > b.second.ms; }); - std::fprintf(stderr, "[address-sync] %llu address-based dispatch syncs waited %.1f s in total; by program (10 s):", static_cast(syncs), waitedMs / 1000); - for (std::size_t i = 0; i < hot.size() && i < 8; ++i) std::fprintf(stderr, " 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); - std::fprintf(stderr, "\n"); + AgcDriver::ProfilePrint_nid_no_patch("[address-sync] %llu address-based dispatch syncs waited %.1f s in total; by program (10 s):", static_cast(syncs), waitedMs / 1000); + for (std::size_t i = 0; i < hot.size() && i < 8; ++i) AgcDriver::ProfilePrint_nid_no_patch(" 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); + AgcDriver::ProfilePrint_nid_no_patch("\n"); byProgram.clear(); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp index cdd541e0f..bdee4b50f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include #include @@ -68,7 +69,7 @@ std::optional BufferPool::Take(std::size_t bytes, VkBufferUsag const auto now = std::chrono::steady_clock::now(); if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; - std::fprintf(stderr, "[bufferpool] small: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB); large: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB)%s; device: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB of %llu)\n", static_cast(smallTier.hits), static_cast(smallTier.misses), static_cast(smallTier.evictions), smallTier.slots, smallTier.retainedBytes / 1048576.0, static_cast(largeTier.hits), static_cast(largeTier.misses), static_cast(largeTier.evictions), largeTier.slots, largeTier.retainedBytes / 1048576.0, sharedTiers() ? " (shared)" : "", static_cast(deviceTier.hits), static_cast(deviceTier.misses), static_cast(deviceTier.evictions), deviceTier.slots, deviceTier.retainedBytes / 1048576.0, static_cast(deviceTier.budget >> 20u)); + AgcDriver::ProfilePrint_nid_no_patch("[bufferpool] small: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB); large: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB)%s; device: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB of %llu)\n", static_cast(smallTier.hits), static_cast(smallTier.misses), static_cast(smallTier.evictions), smallTier.slots, smallTier.retainedBytes / 1048576.0, static_cast(largeTier.hits), static_cast(largeTier.misses), static_cast(largeTier.evictions), largeTier.slots, largeTier.retainedBytes / 1048576.0, sharedTiers() ? " (shared)" : "", static_cast(deviceTier.hits), static_cast(deviceTier.misses), static_cast(deviceTier.evictions), deviceTier.slots, deviceTier.retainedBytes / 1048576.0, static_cast(deviceTier.budget >> 20u)); } } auto& tier = tierFor(capacity, properties); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index a8d9ed9ca..bb16630cc 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" @@ -818,7 +819,7 @@ void reportMirrors() { } heapBytes = state.heapBytes; } - std::fprintf(stderr, "[buffers] image mirrors: %zu ranges (%.1f MiB, %zu writable, %zu heap %.1f MiB), %llu address-based builds served, %llu descriptor sub-ranges bound, %llu rebuilds, %llu refreshes: %llu blocks compared, %llu copied, %llu refresh syncs; heap refills %llu, unwatched heaps %llu\n", count, bytes / 1048576.0, writable, heaps, heapBytes / 1048576.0, static_cast(state.builds), static_cast(state.subranges), static_cast(state.rebuilds), static_cast(state.refreshes), static_cast(state.blocksCompared), static_cast(state.blocksCopied), static_cast(state.syncs), static_cast(state.heapRefills), static_cast(state.heapUnwatched)); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] image mirrors: %zu ranges (%.1f MiB, %zu writable, %zu heap %.1f MiB), %llu address-based builds served, %llu descriptor sub-ranges bound, %llu rebuilds, %llu refreshes: %llu blocks compared, %llu copied, %llu refresh syncs; heap refills %llu, unwatched heaps %llu\n", count, bytes / 1048576.0, writable, heaps, heapBytes / 1048576.0, static_cast(state.builds), static_cast(state.subranges), static_cast(state.rebuilds), static_cast(state.refreshes), static_cast(state.blocksCompared), static_cast(state.blocksCopied), static_cast(state.syncs), static_cast(state.heapRefills), static_cast(state.heapUnwatched)); } // Deferred lease release. The lease an address-based build takes (AcquireRegistered) is dropped by its @@ -962,7 +963,7 @@ void CountLeaseOutcome(bool synced, std::uint64_t batchSerial) { const auto& stats = state.stats; const auto table = BdaResources::TableCacheCounters(); const auto& snapshots = Snapshots(); - std::fprintf(stderr, "[address-sync] leases: %llu released at completion, %llu synced at once; %llu pin-contention waits by guest threads (%llu finished the lease batch, %llu drained the recorder, %llu cache-only drops) %.1f s; BDA table cache %llu hits / %llu misses (%zu tables held); snapshot compares: %llu skipped (live-backed region), %llu made\n", static_cast(stats.deferred), static_cast(stats.synced), static_cast(stats.contentionWaits), static_cast(stats.contentionSyncs), static_cast(stats.contentionDrains), static_cast(stats.cacheDrops), stats.contentionMs / 1000, static_cast(table.hits), static_cast(table.misses), table.held, static_cast(snapshots.skipped.load(std::memory_order_relaxed)), static_cast(snapshots.checked.load(std::memory_order_relaxed))); + AgcDriver::ProfilePrint_nid_no_patch("[address-sync] leases: %llu released at completion, %llu synced at once; %llu pin-contention waits by guest threads (%llu finished the lease batch, %llu drained the recorder, %llu cache-only drops) %.1f s; BDA table cache %llu hits / %llu misses (%zu tables held); snapshot compares: %llu skipped (live-backed region), %llu made\n", static_cast(stats.deferred), static_cast(stats.synced), static_cast(stats.contentionWaits), static_cast(stats.contentionSyncs), static_cast(stats.contentionDrains), static_cast(stats.cacheDrops), stats.contentionMs / 1000, static_cast(table.hits), static_cast(table.misses), table.held, static_cast(snapshots.skipped.load(std::memory_order_relaxed)), static_cast(snapshots.checked.load(std::memory_order_relaxed))); } LeaseStats LeaseCounters() { @@ -1166,7 +1167,7 @@ void GuestBufferMemory::CountAddressBuild(double snapshotsUs) { const auto delta = [](std::uint64_t now, std::uint64_t before) { return static_cast(now - before); }; const auto space = AddressSpaceCounters(); const auto& spaceSeen = totals.spaceSeen; - std::fprintf(stderr, "[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu / rebuilds: generation %llu, epoch %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast(totals.sums.blocksCompared)), per(static_cast(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty)); + AgcDriver::ProfilePrint_nid_no_patch("[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu / rebuilds: generation %llu, epoch %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast(totals.sums.blocksCompared)), per(static_cast(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty)); totals.tableSeen = table; totals.spaceSeen = space; totals.builds = 0; @@ -1691,7 +1692,7 @@ void reportStaging() { const auto staged = stats.staged.load(); const auto in = stats.stagedInBytes.load(); const auto out = stats.stagedOutBytes.load(); - std::fprintf(stderr, "[buffers] staging: %llu regions staged device-local (%llu with atomics, %llu of reused builds), %.0f KiB copied in, %.0f KiB copied back, %llu without copy-back, %llu shadows refused; last 10 s: %llu regions, %.0f KiB in, %.0f KiB back\n", static_cast(staged), static_cast(stats.stagedAtomic.load()), static_cast(stats.stagedReused.load()), in / 1024.0, out / 1024.0, static_cast(stats.stagedLost.load()), static_cast(stats.stagingRefused.load()), static_cast(staged - lastStaged), (in - lastIn) / 1024.0, (out - lastOut) / 1024.0); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] staging: %llu regions staged device-local (%llu with atomics, %llu of reused builds), %.0f KiB copied in, %.0f KiB copied back, %llu without copy-back, %llu shadows refused; last 10 s: %llu regions, %.0f KiB in, %.0f KiB back\n", static_cast(staged), static_cast(stats.stagedAtomic.load()), static_cast(stats.stagedReused.load()), in / 1024.0, out / 1024.0, static_cast(stats.stagedLost.load()), static_cast(stats.stagingRefused.load()), static_cast(staged - lastStaged), (in - lastIn) / 1024.0, (out - lastOut) / 1024.0); lastStaged = staged; lastIn = in; lastOut = out; @@ -2028,7 +2029,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) { const auto uploads = uploadsProfiled.fetch_add(1, std::memory_order_relaxed) + 1; if (uploads % 2000 == 0) { const auto& copies = Copies(); - std::fprintf(stderr, "[buffers] %llu uploads: import lookup %.0f ms, buffer allocation %.0f ms, guest read %.0f ms; copies on the GPU: %llu regions (%.0f KiB) copied out of imports, %llu written sub-ranges (%.0f KiB) copied back, %llu staging stores by the CPU at write-back\n", static_cast(uploads), importUs.load(std::memory_order_relaxed) / 1000.0, allocateUs.load(std::memory_order_relaxed) / 1000.0, readUs.load(std::memory_order_relaxed) / 1000.0, static_cast(copies.gpuCopies.load(std::memory_order_relaxed)), copies.gpuCopyBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.gpuCopyBacks.load(std::memory_order_relaxed)), copies.gpuCopyBackBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.stagingStores.load(std::memory_order_relaxed))); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] %llu uploads: import lookup %.0f ms, buffer allocation %.0f ms, guest read %.0f ms; copies on the GPU: %llu regions (%.0f KiB) copied out of imports, %llu written sub-ranges (%.0f KiB) copied back, %llu staging stores by the CPU at write-back\n", static_cast(uploads), importUs.load(std::memory_order_relaxed) / 1000.0, allocateUs.load(std::memory_order_relaxed) / 1000.0, readUs.load(std::memory_order_relaxed) / 1000.0, static_cast(copies.gpuCopies.load(std::memory_order_relaxed)), copies.gpuCopyBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.gpuCopyBacks.load(std::memory_order_relaxed)), copies.gpuCopyBackBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.stagingStores.load(std::memory_order_relaxed))); } const auto ms = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); if (ms > 50) { @@ -2040,7 +2041,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) { largest = std::max(largest, region.end - region.begin); if (region.buffer != nullptr) copied += region.end - region.begin; } - std::fprintf(stderr, "[resources] guest upload of %zu regions, %.1f MiB (largest %.1f MiB, copied %.1f MiB, addressable %d) took %.0f ms to finish\n", regions.size(), total / 1048576.0, largest / 1048576.0, copied / 1048576.0, addressable ? 1 : 0, ms); + AgcDriver::ProfilePrint_nid_no_patch("[resources] guest upload of %zu regions, %.1f MiB (largest %.1f MiB, copied %.1f MiB, addressable %d) took %.0f ms to finish\n", regions.size(), total / 1048576.0, largest / 1048576.0, copied / 1048576.0, addressable ? 1 : 0, ms); } // Debug aid: APS5_TRACE_BIGBUF lists every copied region of at least 1 MiB. static const bool traceBig = std::getenv("APS5_TRACE_BIGBUF") != nullptr; @@ -2080,9 +2081,9 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) { if (++uploads % 1000 == 0) { // 'misaligned in imports' are the ones the GPU did not copy: over APS5_GPU_COPY_MAX_KIB, // sparse, APS5_CPU_COPIES, no recorder, or an import gone by UploadFinish. - std::fprintf(stderr, "[buffers] %llu copied regions on the CPU: %llu snapshots (%.0f MiB), %llu misaligned in imports (%.0f MiB), %llu outside imports (%.0f MiB):", static_cast(uploads), static_cast(snapshotOnly), snapshotBytes / 1048576.0, static_cast(misaligned), misalignedBytes / 1048576.0, static_cast(noImport), noImportBytes / 1048576.0); - for (const auto& [granule, counts] : outside) std::fprintf(stderr, " 0x%llx0000000:%llu/%.0fMiB", static_cast(granule), static_cast(counts.first), counts.second / 1048576.0); - std::fprintf(stderr, "\n"); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] %llu copied regions on the CPU: %llu snapshots (%.0f MiB), %llu misaligned in imports (%.0f MiB), %llu outside imports (%.0f MiB):", static_cast(uploads), static_cast(snapshotOnly), snapshotBytes / 1048576.0, static_cast(misaligned), misalignedBytes / 1048576.0, static_cast(noImport), noImportBytes / 1048576.0); + for (const auto& [granule, counts] : outside) AgcDriver::ProfilePrint_nid_no_patch(" 0x%llx0000000:%llu/%.0fMiB", static_cast(granule), static_cast(counts.first), counts.second / 1048576.0); + AgcDriver::ProfilePrint_nid_no_patch("\n"); } } const auto allocateStart = std::chrono::steady_clock::now(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index bb8f5fb2b..439fd70de 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -779,7 +780,7 @@ void ReportHookSyncs(HookSyncStats& stats) { std::snprintf(text, sizeof(text), " [0x%x %s %s +0x%llx/+0x%llx/+0x%llx/+0x%llx/+0x%llx/+0x%llx: %llu/%.0fms u%llu/%llu/%llu c%llu s%llu %.0fK/%.0fK]", key.queue, PacketName(key.opcode).c_str(), GuestMemory::ReadSiteName(key.site), key.frames[0], key.frames[1], key.frames[2], key.frames[3], key.frames[4], key.frames[5], count(totals.count), totals.waitedMs, count(k.unchangedOpen), count(k.unchangedPending), count(k.unchangedSignaled), count(k.changed), count(k.stores), totals.rangeBytes / 1024.0 / totals.count, totals.accessBytes / 1024.0 / totals.count); report += text; } - std::fprintf(stderr, "%s\n", report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats = HookSyncStats{}; } @@ -900,7 +901,7 @@ void ReportRecordedStoreSyncs(RecordedStoreStats& stats) { std::snprintf(text, sizeof(text), " [0x%x %s %s +0x%llx/+0x%llx/+0x%llx: %llu/%.0fms k%llu y%llu/n%llu c%llu/u%llu d%llu/l%llu]", key.queue, PacketName(key.opcode).c_str(), GuestMemory::ReadSiteName(key.site), key.frames[0], key.frames[1], key.frames[2], count(k.count), k.waitedMs, count(k.skipped), count(k.cpuWrittenYes), count(k.cpuWrittenNo), count(k.changed), count(k.unchanged), count(k.imagesDead), count(k.imagesLive)); report += text; } - std::fprintf(stderr, "%s\n", report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats.byKey.clear(); stats.totals = {}; } @@ -1718,7 +1719,7 @@ void reportBarriers() { std::snprintf(text, sizeof(text), " %s %llu", CommandClassNames[i], static_cast(mergedCount)); mergedLine += text; } - std::fprintf(stderr, "[barriers] %llu recorded (10 s) by class:%s; merged %llu:%s", static_cast(total), line.c_str(), static_cast(merged), mergedLine.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[barriers] %llu recorded (10 s) by class:%s; merged %llu:%s", static_cast(total), line.c_str(), static_cast(merged), mergedLine.c_str()); if (Recorder::BarrierValidate()) { std::uint64_t emitted = 0, skipped = 0; std::string classes, kinds; @@ -1737,9 +1738,9 @@ void reportBarriers() { std::snprintf(text, sizeof(text), " %s %llu", HazardNames[i], static_cast(validateKinds[i].exchange(0, std::memory_order_relaxed))); kinds += text; } - std::fprintf(stderr, "; validate: would emit %llu (%s) + %llu batch ends, would skip %llu; emitted/skipped by class:%s", static_cast(emitted), kinds.c_str() + 1, static_cast(validateBatchEnds.exchange(0, std::memory_order_relaxed)), static_cast(skipped), classes.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("; validate: would emit %llu (%s) + %llu batch ends, would skip %llu; emitted/skipped by class:%s", static_cast(emitted), kinds.c_str() + 1, static_cast(validateBatchEnds.exchange(0, std::memory_order_relaxed)), static_cast(skipped), classes.c_str()); } - std::fputc('\n', stderr); + AgcDriver::ProfilePrint_nid_no_patch("\n"); } } @@ -2147,9 +2148,9 @@ void Recorder::readGpuTiming(Batch& batch) { } std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second.ms > b.second.ms; }); // The first field stays the program sum: the measure scripts match on it. - std::fprintf(stderr, "[gputime] %.0f ms of GPU time in %llu batches over 10 s (batch %.0f ms first to last command; classes %.0f ms, all ranges %.0f ms, untimed %.0f ms outside every range; %llu presents; %llu ranges dropped at the %u cap); by program:", timingProgramMs, static_cast(timingBatches), timingBatchMs, timingClassMs, timingUnionMs, timingBatchMs - timingUnionMs, static_cast(presents), static_cast(timingDropped.exchange(0, std::memory_order_relaxed)), MaxTimedRanges); - for (std::size_t i = 0; i < hot.size() && i < 12; ++i) std::fprintf(stderr, " 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); - std::fprintf(stderr, "; by class:%s\n", classes.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[gputime] %.0f ms of GPU time in %llu batches over 10 s (batch %.0f ms first to last command; classes %.0f ms, all ranges %.0f ms, untimed %.0f ms outside every range; %llu presents; %llu ranges dropped at the %u cap); by program:", timingProgramMs, static_cast(timingBatches), timingBatchMs, timingClassMs, timingUnionMs, timingBatchMs - timingUnionMs, static_cast(presents), static_cast(timingDropped.exchange(0, std::memory_order_relaxed)), MaxTimedRanges); + for (std::size_t i = 0; i < hot.size() && i < 12; ++i) AgcDriver::ProfilePrint_nid_no_patch(" 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); + AgcDriver::ProfilePrint_nid_no_patch("; by class:%s\n", classes.c_str()); timingByKey.clear(); timingProgramMs = timingClassMs = timingUnionMs = timingBatchMs = 0; timingBatches = 0; @@ -2996,7 +2997,7 @@ void ReportSyncWaits(SyncWaitStats& stats) { else std::snprintf(text, sizeof(text), " 0x%x %llu", queue, static_cast(count)); report += text; } - std::fprintf(stderr, "%s\n", report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats = SyncWaitStats{}; } @@ -3202,11 +3203,11 @@ void Recorder::finish(std::unique_ptr batch, bool wait, int source) { if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; const auto& h = holdCounters; - std::fprintf(stderr, "[recorder] %llu syncs waited %.1f s for the GPU in total (sources, count/wait: idle %llu/%.1fs, pending write %llu/%.1fs, recorded store %llu/%.1fs, address-based %llu/%.1fs, other %llu/%.1fs); hook %llu calls, %llu locked; %llu targeted syncs left %llu batches in flight; snapshot %llu rebuilds %.0f ms, %llu notes covered; %llu unlocked timeline waits %.1f s; %llu submissions, %zu label entries, %llu completion labels pending; fence waits by thread (count/wait):%s; top sync sites (source@caller syncs/batches/wait):%s; under holds (cumulative): %llu completions ran %.0f ms (kept objects released %.0f ms), pending-write syncs from completions: %llu skipped, %llu waited %.0f ms; %llu reaps (%llu with work) retired %llu batches in %.0f ms; hook waits unlocked %llu / %.0f ms GPU (pending write %llu / %.0f ms, recorded store %llu / %.0f ms) + %.0f ms relock (%llu found the recorder torn down), locked %llu; deferred releases: on the release thread %llu batches (%llu objects) in %.0f ms, inline %llu batches (%llu objects) in %.0f ms (%llu batches over the queue bound of %zu), queue max %llu batches, %llu pending\n",static_cast(waits), waitedMs / 1000, static_cast(syncCounts[0]), syncWaitedMs[0] / 1000, static_cast(syncCounts[1]), syncWaitedMs[1] / 1000, static_cast(syncCounts[2]), syncWaitedMs[2] / 1000, static_cast(syncCounts[3]), syncWaitedMs[3] / 1000, static_cast(syncCounts[4]), syncWaitedMs[4] / 1000, static_cast(hookCalls.load()), static_cast(hookLocks.load()), static_cast(targetedSyncs.load()), static_cast(batchesLeftInFlight.load()), static_cast(snapshotRebuilds), snapshotRebuildMs, static_cast(snapshotCovered), static_cast(unlockedWaits.load()), unlockedWaitedUs.load() / 1e6, static_cast(recorder.submissions), recorder.PendingLabels(), static_cast(completionLabels.load()), ThreadSyncReport().c_str(), SyncSiteReport().c_str(), static_cast(h.completions), h.completionMs, h.keptReleaseMs, static_cast(h.completionSyncsSkipped), static_cast(h.completionSyncsWaited), h.completionSyncWaitMs, static_cast(h.reaps), static_cast(h.reapsWithWork), static_cast(h.reapBatches), h.reapMs, static_cast(h.hookUnlockedWaits), h.hookUnlockedWaitMs, static_cast(h.hookUnlockedWaitsBySource[1]), h.hookUnlockedWaitMsBySource[1], static_cast(h.hookUnlockedWaitsBySource[2]), h.hookUnlockedWaitMsBySource[2], h.hookRelockMs, static_cast(h.hookUnlockedTornDown), static_cast(h.hookLockedWaits), static_cast(threadReleases.load()), static_cast(threadObjects.load()), threadReleaseUs.load() / 1000.0, static_cast(inlineReleases.load()), static_cast(inlineObjects.load()), inlineReleaseUs.load() / 1000.0, static_cast(inlineOverBound.load()), ReleaseQueueBound(), static_cast(releaseQueueMax.load()), static_cast(deferredPending.load())); - std::fprintf(stderr, "[recorder] completion label stores: %llu run, %llu skipped (no CPU write-back overlapped them); %llu counted pending at a write-back; %llu write-backs over a tracked label; %llu write-back completions pending\n", static_cast(completionStoresRun.load()), static_cast(completionStoresSkipped.load()), static_cast(completionLabelsCountedLate.load()), static_cast(writeBacksOverLabels.load()), static_cast(writeBackCompletions.load())); - std::fprintf(stderr, "[recorder] submits %llu, vkQueueSubmit mean %.1f us, max %.1f us\n", static_cast(submitCount), submitCount != 0 ? submitUs / static_cast(submitCount) : 0.0, submitMaxUs); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] %llu syncs waited %.1f s for the GPU in total (sources, count/wait: idle %llu/%.1fs, pending write %llu/%.1fs, recorded store %llu/%.1fs, address-based %llu/%.1fs, other %llu/%.1fs); hook %llu calls, %llu locked; %llu targeted syncs left %llu batches in flight; snapshot %llu rebuilds %.0f ms, %llu notes covered; %llu unlocked timeline waits %.1f s; %llu submissions, %zu label entries, %llu completion labels pending; fence waits by thread (count/wait):%s; top sync sites (source@caller syncs/batches/wait):%s; under holds (cumulative): %llu completions ran %.0f ms (kept objects released %.0f ms), pending-write syncs from completions: %llu skipped, %llu waited %.0f ms; %llu reaps (%llu with work) retired %llu batches in %.0f ms; hook waits unlocked %llu / %.0f ms GPU (pending write %llu / %.0f ms, recorded store %llu / %.0f ms) + %.0f ms relock (%llu found the recorder torn down), locked %llu; deferred releases: on the release thread %llu batches (%llu objects) in %.0f ms, inline %llu batches (%llu objects) in %.0f ms (%llu batches over the queue bound of %zu), queue max %llu batches, %llu pending\n",static_cast(waits), waitedMs / 1000, static_cast(syncCounts[0]), syncWaitedMs[0] / 1000, static_cast(syncCounts[1]), syncWaitedMs[1] / 1000, static_cast(syncCounts[2]), syncWaitedMs[2] / 1000, static_cast(syncCounts[3]), syncWaitedMs[3] / 1000, static_cast(syncCounts[4]), syncWaitedMs[4] / 1000, static_cast(hookCalls.load()), static_cast(hookLocks.load()), static_cast(targetedSyncs.load()), static_cast(batchesLeftInFlight.load()), static_cast(snapshotRebuilds), snapshotRebuildMs, static_cast(snapshotCovered), static_cast(unlockedWaits.load()), unlockedWaitedUs.load() / 1e6, static_cast(recorder.submissions), recorder.PendingLabels(), static_cast(completionLabels.load()), ThreadSyncReport().c_str(), SyncSiteReport().c_str(), static_cast(h.completions), h.completionMs, h.keptReleaseMs, static_cast(h.completionSyncsSkipped), static_cast(h.completionSyncsWaited), h.completionSyncWaitMs, static_cast(h.reaps), static_cast(h.reapsWithWork), static_cast(h.reapBatches), h.reapMs, static_cast(h.hookUnlockedWaits), h.hookUnlockedWaitMs, static_cast(h.hookUnlockedWaitsBySource[1]), h.hookUnlockedWaitMsBySource[1], static_cast(h.hookUnlockedWaitsBySource[2]), h.hookUnlockedWaitMsBySource[2], h.hookRelockMs, static_cast(h.hookUnlockedTornDown), static_cast(h.hookLockedWaits), static_cast(threadReleases.load()), static_cast(threadObjects.load()), threadReleaseUs.load() / 1000.0, static_cast(inlineReleases.load()), static_cast(inlineObjects.load()), inlineReleaseUs.load() / 1000.0, static_cast(inlineOverBound.load()), ReleaseQueueBound(), static_cast(releaseQueueMax.load()), static_cast(deferredPending.load())); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] completion label stores: %llu run, %llu skipped (no CPU write-back overlapped them); %llu counted pending at a write-back; %llu write-backs over a tracked label; %llu write-back completions pending\n", static_cast(completionStoresRun.load()), static_cast(completionStoresSkipped.load()), static_cast(completionLabelsCountedLate.load()), static_cast(writeBacksOverLabels.load()), static_cast(writeBackCompletions.load())); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] submits %llu, vkQueueSubmit mean %.1f us, max %.1f us\n", static_cast(submitCount), submitCount != 0 ? submitUs / static_cast(submitCount) : 0.0, submitMaxUs); const auto reads = Recorder::ReadCounts(); - std::fprintf(stderr, "[recorder] in-place reads: %llu noted, %llu queries, hits by reader: dispatch element %llu, gpu copy %llu, address-based %llu, indirect %llu, storage upload %llu, copy source %llu; %llu hits on signaled batches ignored\n", static_cast(reads.noted), static_cast(reads.queries), static_cast(reads.hits[0]), static_cast(reads.hits[1]), static_cast(reads.hits[2]), static_cast(reads.hits[3]), static_cast(reads.hits[4]), static_cast(reads.hits[5]), static_cast(reads.staleIgnored)); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] in-place reads: %llu noted, %llu queries, hits by reader: dispatch element %llu, gpu copy %llu, address-based %llu, indirect %llu, storage upload %llu, copy source %llu; %llu hits on signaled batches ignored\n", static_cast(reads.noted), static_cast(reads.queries), static_cast(reads.hits[0]), static_cast(reads.hits[1]), static_cast(reads.hits[2]), static_cast(reads.hits[3]), static_cast(reads.hits[4]), static_cast(reads.hits[5]), static_cast(reads.staleIgnored)); } } } report{profile, source, waitStart, *this, signaledAtStart}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index c1fff993b..d6d69c35f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -170,7 +171,7 @@ void reportTextureCounters() { auto last = counters.lastReport.load(); if (nowMs - last < 10000 || !counters.lastReport.compare_exchange_strong(last, nowMs)) return; const auto count = [](const std::atomic& value) { return static_cast(value.load(std::memory_order_relaxed)); }; - std::fprintf(stderr, "[textures] sampled created: %llu from storage images, %llu snapshots (%llu snapshot reads over recorded writes inside cachedTexture, %llu storage-path fallbacks); stage-A records %llu: %llu fast hits, %llu full lookups; storage images %llu hits, %llu created, %llu own-object refreshes\n", count(counters.fromStorage), count(counters.snapshots), count(counters.pendingReads), count(counters.storageFallbacks), count(counters.records), count(counters.fastHits), count(counters.fastMisses), count(counters.storageHits), count(counters.storageCreated), count(counters.ownRefreshes)); + AgcDriver::ProfilePrint_nid_no_patch("[textures] sampled created: %llu from storage images, %llu snapshots (%llu snapshot reads over recorded writes inside cachedTexture, %llu storage-path fallbacks); stage-A records %llu: %llu fast hits, %llu full lookups; storage images %llu hits, %llu created, %llu own-object refreshes\n", count(counters.fromStorage), count(counters.snapshots), count(counters.pendingReads), count(counters.storageFallbacks), count(counters.records), count(counters.fastHits), count(counters.fastMisses), count(counters.storageHits), count(counters.storageCreated), count(counters.ownRefreshes)); } // What the sampled-texture lookups on this thread proved their returned objects current against, @@ -836,7 +837,7 @@ struct ThreadBuildProfile { builds = 0; std::string report; for (std::size_t i = 0; i < BuildPhaseCount; ++i) report += " " + std::string(BuildPhaseNames[i]) + "=" + std::to_string(static_cast(profile.ms[i])) + "ms"; - std::fprintf(stderr, "[resources] %llu builds, phase totals:%s\n", static_cast(profile.builds), report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[resources] %llu builds, phase totals:%s\n", static_cast(profile.builds), report.c_str()); } }; @@ -872,7 +873,7 @@ double ShaderResources::phase(BuildPhase which) { const auto now = std::chrono::steady_clock::now(); const auto ms = std::chrono::duration(now - phaseStart).count(); addBuildPhase(which, ms); - if (ms > 50) std::fprintf(stderr, "[resources] %s took %.0f ms (%zu textures, %zu storage images, %zu buffers, bda %d)\n", BuildPhaseNames[static_cast(which)], ms, textures.size(), storageTextures.size(), allocations.size(), usesBda ? 1 : 0); + if (ms > 50) AgcDriver::ProfilePrint_nid_no_patch("[resources] %s took %.0f ms (%zu textures, %zu storage images, %zu buffers, bda %d)\n", BuildPhaseNames[static_cast(which)], ms, textures.size(), storageTextures.size(), allocations.size(), usesBda ? 1 : 0); phaseStart = now; return ms; } @@ -1161,7 +1162,7 @@ void ShaderResources::reportDescriptorCaches() const { const auto descriptors = context.descriptorCache != nullptr ? context.descriptorCache->Counters() : DescriptorCache::Stats{}; const auto samplerHits = context.samplerCache != nullptr ? context.samplerCache->Hits() : 0; const auto samplerMisses = context.samplerCache != nullptr ? context.samplerCache->Misses() : 0; - std::fprintf(stderr, "[descriptors] layouts %llu hits / %llu created, sets %llu from %llu pools, samplers %llu hits / %llu created\n", static_cast(descriptors.layoutHits), static_cast(descriptors.layoutMisses), static_cast(descriptors.sets), static_cast(descriptors.pools), static_cast(samplerHits), static_cast(samplerMisses)); + AgcDriver::ProfilePrint_nid_no_patch("[descriptors] layouts %llu hits / %llu created, sets %llu from %llu pools, samplers %llu hits / %llu created\n", static_cast(descriptors.layoutHits), static_cast(descriptors.layoutMisses), static_cast(descriptors.sets), static_cast(descriptors.pools), static_cast(samplerHits), static_cast(samplerMisses)); } std::vector ShaderResources::ContentKey(const CompiledShader& shader, bool dataWords, bool movableBuffers) { @@ -1344,7 +1345,7 @@ void countRevalidate(bool fast, bool ok, std::chrono::steady_clock::time_point s const auto reasons = byReason(profile.fastFails, FastFailNames); const auto fullReasons = byReason(profile.fullByReason, FastFailNames); const auto fallbacks = byReason(profile.ownFallbacks, OwnRefreshFallbackNames); - std::fprintf(stderr, "[rescache] revalidate %llu calls %.1f ms: fast %llu, full %llu, failed %llu; fast-fail by reason:%s; full walks: T1 refreshed %llu (%llu storage images, %llu view sources, %llu views served by their own pending source, %llu overlaps left by the refresh accepted), full by reason:%s, T1 fallback by reason:%s, proofs verified %llu; fast-fail pending image: own 0 (the query excepts the own object), foreign %llu, snapshot %llu, T1 eligible %llu; keys proven: %llu sampled, %llu storage; epoch gate: %llu registry scans skipped, %llu import loops skipped\n", static_cast(profile.calls.load()), profile.nanoseconds.load() / 1e6, static_cast(profile.fast.load()), static_cast(profile.full.load()), static_cast(profile.failed.load()), reasons.c_str(), static_cast(profile.ownRefreshed.load()), static_cast(profile.ownStorageRefreshes.load()), static_cast(profile.ownViewRefreshes.load()), static_cast(profile.ownSourceViews.load()), static_cast(profile.refreshedOverlaps.load()), fullReasons.c_str(), fallbacks.c_str(), static_cast(profile.proofsVerified.load()), static_cast(profile.pendingForeign.load()), static_cast(profile.pendingSnapshot.load()), static_cast(profile.pendingT1Eligible.load()), static_cast(profile.keysProven.load()), static_cast(profile.storageKeysProven.load()), static_cast(profile.serialSkips.load()), static_cast(profile.importSkips.load())); + AgcDriver::ProfilePrint_nid_no_patch("[rescache] revalidate %llu calls %.1f ms: fast %llu, full %llu, failed %llu; fast-fail by reason:%s; full walks: T1 refreshed %llu (%llu storage images, %llu view sources, %llu views served by their own pending source, %llu overlaps left by the refresh accepted), full by reason:%s, T1 fallback by reason:%s, proofs verified %llu; fast-fail pending image: own 0 (the query excepts the own object), foreign %llu, snapshot %llu, T1 eligible %llu; keys proven: %llu sampled, %llu storage; epoch gate: %llu registry scans skipped, %llu import loops skipped\n", static_cast(profile.calls.load()), profile.nanoseconds.load() / 1e6, static_cast(profile.fast.load()), static_cast(profile.full.load()), static_cast(profile.failed.load()), reasons.c_str(), static_cast(profile.ownRefreshed.load()), static_cast(profile.ownStorageRefreshes.load()), static_cast(profile.ownViewRefreshes.load()), static_cast(profile.ownSourceViews.load()), static_cast(profile.refreshedOverlaps.load()), fullReasons.c_str(), fallbacks.c_str(), static_cast(profile.proofsVerified.load()), static_cast(profile.pendingForeign.load()), static_cast(profile.pendingSnapshot.load()), static_cast(profile.pendingT1Eligible.load()), static_cast(profile.keysProven.load()), static_cast(profile.storageKeysProven.load()), static_cast(profile.serialSkips.load()), static_cast(profile.importSkips.load())); } // APS5_NO_EPOCH_REVALIDATE=1: the per-element registry, cache and stamp checks and the per-region @@ -1991,7 +1992,7 @@ void ResourceCache::noteMiss(const Key& key) { } std::snprintf(item, sizeof(item), "; layout %llu, draw target/index %llu, same key %llu (not inserted or evicted), first seen %llu", static_cast(churn.layout), static_cast(churn.drawWords), static_cast(churn.sameKey), static_cast(churn.firstSeen)); line += item; - std::fprintf(stderr, "%s\n", line.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", line.c_str()); }; report("dispatch", churn.dispatch); report("draws", churn.draws); @@ -2828,7 +2829,7 @@ void ShaderResources::MarkGpuWrites(Recorder& recorder) { if (nowMs - last < 10000 || !counters.lastReport.compare_exchange_strong(last, nowMs)) return; const auto elements = counters.elements.load(); const auto readOnly = counters.readOnly.load(); - std::fprintf(stderr, "[buffers] descriptor elements bound: %llu total, %llu written, %llu read-only; %llu pending-write notes skipped\n", static_cast(elements), static_cast(elements - readOnly), static_cast(readOnly), static_cast(counters.notesSkipped.load())); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] descriptor elements bound: %llu total, %llu written, %llu read-only; %llu pending-write notes skipped\n", static_cast(elements), static_cast(elements - readOnly), static_cast(readOnly), static_cast(counters.notesSkipped.load())); } void ShaderResources::WriteBackBuffers() { diff --git a/core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp b/core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp new file mode 100644 index 000000000..5ac7e3ee0 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp @@ -0,0 +1,121 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" +#include +#include +#include +#include +#include + +namespace { + +void Check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void FormatAndDrain() { + std::string written; + const std::string longLine(6000, 'x'); + { + AgcDriver::ProfileOutput output([&](std::string_view text) { written += text; }); + output.Print("%s %.2f %llu\n", "shader", 1.25, 42ull); + output.Print("%s\n", longLine.c_str()); + } + Check(written == "shader 1.25 42\n" + longLine + "\n", "formatting or shutdown drain changed the output"); +} + +void SlowWriter() { + std::mutex mutex; + std::condition_variable release; + bool released = false; + std::promise entered; + bool first = true; + std::string written; + AgcDriver::ProfileOutput output([&](std::string_view text) { + if (first) { + first = false; + entered.set_value(); + std::unique_lock lock(mutex); + release.wait(lock, [&] { return released; }); + } + written += text; + }, 16); + std::future producer; + struct Release { + std::mutex& mutex; + std::condition_variable& changed; + bool& released; + ~Release() { + { + std::lock_guard lock(mutex); + released = true; + } + changed.notify_one(); + } + } cleanup{mutex, release, released}; + Check(output.Write("12345678"), "first write was rejected"); + Check(entered.get_future().wait_for(std::chrono::seconds(2)) == std::future_status::ready, "writer did not start"); + producer = std::async(std::launch::async, [&] { return output.Write("abcdefgh"); }); + Check(producer.wait_for(std::chrono::seconds(2)) == std::future_status::ready, "producer blocked behind the diagnostic writer"); + Check(producer.get(), "write within the bound was rejected"); + Check(!output.Write("z"), "queue bound did not include the in-flight output"); + { + std::lock_guard lock(mutex); + released = true; + } + release.notify_one(); + output.Flush(); + Check(written.starts_with("12345678abcdefgh"), "accepted chunks changed order"); + Check(written.find("[profile-output] dropped 1 chunks") != std::string::npos, "bounded overflow was not reported"); +} + +void ConcurrentWriters() { + std::string written; + AgcDriver::ProfileOutput output([&](std::string_view text) { written += text; }); + std::vector producers; + for (int thread = 0; thread < 8; ++thread) { + producers.emplace_back([&, thread] { + for (int item = 0; item < 100; ++item) output.Print("%d:%d\n", thread, item); + }); + } + for (auto& producer : producers) producer.join(); + output.Flush(); + std::istringstream stream(written); + std::vector lines; + for (std::string line; std::getline(stream, line);) lines.push_back(line); + std::sort(lines.begin(), lines.end()); + Check(lines.size() == 800 && std::adjacent_find(lines.begin(), lines.end()) == lines.end(), "concurrent writes lost or duplicated chunks"); + for (int thread = 0; thread < 8; ++thread) { + for (int item = 0; item < 100; ++item) + Check(std::binary_search(lines.begin(), lines.end(), std::to_string(thread) + ":" + std::to_string(item)), "concurrent formatting changed a chunk"); + } +} + +void WriterFailure() { + AgcDriver::ProfileOutput output([](std::string_view) { throw std::runtime_error("test writer failure"); }); + output.Write("test"); + for (int operation = 0; operation < 2; ++operation) { + bool failed = false; + try { + if (operation == 0) output.Flush(); + else output.Write("next"); + } catch (const std::runtime_error& error) { + failed = std::string(error.what()) == "test writer failure"; + } + Check(failed, "writer failure was not propagated"); + } +} + +} + +int main() { + try { + FormatAndDrain(); + SlowWriter(); + ConcurrentWriters(); + WriterFailure(); + std::cout << "profile output tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 4a43d433e04714007c44184cd9887eac9088979e Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:41:00 -0300 Subject: [PATCH 28/42] fix(agc): defer remaining periodic profiling reports --- .../Execution/src/Driver/Dispatch/Dispatch.cpp | 3 ++- .../Execution/src/Driver/Draw/DrawCacheStatistics.cpp | 5 +++-- .../libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp | 3 ++- .../Execution/src/Driver/Memory/CaptureDiagnostics.cpp | 3 ++- .../Execution/src/Driver/Packets/PacketExecution.cpp | 3 ++- .../Execution/src/Driver/Packets/PacketTiming.cpp | 5 +++-- .../libSceAgcDriver/Execution/src/Driver/Presentation.cpp | 3 ++- .../src/Driver/Synchronization/SynchronizationStatistics.cpp | 3 ++- core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp | 4 ++-- core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp | 3 ++- core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp | 3 ++- core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp | 3 ++- 12 files changed, 26 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 25c05fb21..8be671d55 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" @@ -360,7 +361,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, pending.ms = phaseMs; pending.tailAt = phaseLap; } - if (profile && ++dispatches % 100 == 0) std::fprintf(stderr, "[gpu] %llu dispatches (%llu dispatch cache hits, %llu evictions, %llu recompile cache hits): capture %.1f s, cache key %.1f s, recompile %.1f s, device %.1f s\n", static_cast(dispatches), static_cast(dispatchCacheHits), static_cast(dispatchCacheEvictions), static_cast(cacheHits), captureMs / 1000, keyMs / 1000, recompileMs / 1000, deviceMs / 1000); + if (profile && ++dispatches % 100 == 0) AgcDriver::ProfilePrint_nid_no_patch( "[gpu] %llu dispatches (%llu dispatch cache hits, %llu evictions, %llu recompile cache hits): capture %.1f s, cache key %.1f s, recompile %.1f s, device %.1f s\n", static_cast(dispatches), static_cast(dispatchCacheHits), static_cast(dispatchCacheEvictions), static_cast(cacheHits), captureMs / 1000, keyMs / 1000, recompileMs / 1000, deviceMs / 1000); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp index 6282bc2a7..9d82d8550 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" namespace AgcDriver::DriverDetail { @@ -12,8 +13,8 @@ void Driver::reportDrawCache(DrawEntryCounters& counters) { std::snprintf(text, sizeof(text), "%s%llu", rank == 0 ? "" : " / ", count(counters.variantHitsByRank[rank])); ranks += text; } - std::fprintf(stderr, "[draw-cache] %llu lookups (10 s): %llu no entry, %llu validated in %.1f us each (key, lookup and every stage): %llu hits (every stage equal; stage hits by variant rank 1..k %s), misses by reason: front stage differing %llu, fragment differing %llu, other stage differing %llu, layout (push offset) %llu, gate %llu, stage count %llu; %llu stage validations (%llu equal, %.2f variants compared each); %llu inserts (%llu variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB), %llu evictions in total, %llu LRU moves; verify: %llu hits captured again, %llu stages differed\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.hits), ranks.c_str(), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.stageValidations), count(counters.stageEqual), counters.stageValidations != 0 ? static_cast(counters.variantsCompared) / static_cast(counters.stageValidations) : 0.0, count(counters.inserts), count(counters.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast(drawCacheVariantBytes) / (1024.0 * 1024.0), count(drawCacheEvictions), count(counters.touches), count(counters.verifyHits), count(counters.verifyMismatches)); - std::fprintf(stderr, "[draw-cache] register key (10 s): %llu lookups, %llu hits, key build %.1f us each; decode skipped %llu, partial (state/pixel/programs from the entry) %llu; facade log != table %llu; verify: %llu decodes compared, %llu differed\n", count(counters.registerKeyLookups), count(counters.registerKeyHits), counters.registerKeyLookups != 0 ? counters.keyUs / static_cast(counters.registerKeyLookups) : 0.0, count(counters.decodeSkipped), count(counters.decodePartial), count(counters.facadeMismatches), count(counters.verifyDecodes), count(counters.verifyDecodeMismatches)); + AgcDriver::ProfilePrint_nid_no_patch( "[draw-cache] %llu lookups (10 s): %llu no entry, %llu validated in %.1f us each (key, lookup and every stage): %llu hits (every stage equal; stage hits by variant rank 1..k %s), misses by reason: front stage differing %llu, fragment differing %llu, other stage differing %llu, layout (push offset) %llu, gate %llu, stage count %llu; %llu stage validations (%llu equal, %.2f variants compared each); %llu inserts (%llu variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB), %llu evictions in total, %llu LRU moves; verify: %llu hits captured again, %llu stages differed\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.hits), ranks.c_str(), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.stageValidations), count(counters.stageEqual), counters.stageValidations != 0 ? static_cast(counters.variantsCompared) / static_cast(counters.stageValidations) : 0.0, count(counters.inserts), count(counters.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast(drawCacheVariantBytes) / (1024.0 * 1024.0), count(drawCacheEvictions), count(counters.touches), count(counters.verifyHits), count(counters.verifyMismatches)); + AgcDriver::ProfilePrint_nid_no_patch( "[draw-cache] register key (10 s): %llu lookups, %llu hits, key build %.1f us each; decode skipped %llu, partial (state/pixel/programs from the entry) %llu; facade log != table %llu; verify: %llu decodes compared, %llu differed\n", count(counters.registerKeyLookups), count(counters.registerKeyHits), counters.registerKeyLookups != 0 ? counters.keyUs / static_cast(counters.registerKeyLookups) : 0.0, count(counters.decodeSkipped), count(counters.decodePartial), count(counters.facadeMismatches), count(counters.verifyDecodes), count(counters.verifyDecodeMismatches)); counters = DrawEntryCounters{}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp index bd973c611..bfc4731ce 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawTiming.hpp" @@ -26,7 +27,7 @@ void Driver::addDrawPhases(const std::array& ms, b report += text; total += totals.ms[i]; } - std::fprintf(stderr, "[draw] driver phases (10 s, %llu draw packets, %llu drawn, %llu captures), us per packet:%s, total %.1f (%.1f ms; Graphics::Draw %.1f ms, skipped %.1f ms)\n", static_cast(totals.packets), static_cast(totals.drawn), static_cast(totals.captures), report.c_str(), total * 1000 / static_cast(totals.packets), total, totals.ms[DrawRowGraphics], totals.ms[DrawRowSkipped]); + AgcDriver::ProfilePrint_nid_no_patch( "[draw] driver phases (10 s, %llu draw packets, %llu drawn, %llu captures), us per packet:%s, total %.1f (%.1f ms; Graphics::Draw %.1f ms, skipped %.1f ms)\n", static_cast(totals.packets), static_cast(totals.drawn), static_cast(totals.captures), report.c_str(), total * 1000 / static_cast(totals.packets), total, totals.ms[DrawRowGraphics], totals.ms[DrawRowSkipped]); totals.ms = {}; totals.packets = totals.drawn = totals.captures = 0; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp index 10c4b53ff..ddab9c7aa 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" namespace AgcDriver::DriverDetail { @@ -30,7 +31,7 @@ void Driver::reportValidation(ValidateCounters& counters) { if (evidence.streak >= writeEvidenceAfter()) ++eligible; } } - std::fprintf(stderr, "[validate] dispatch-cache compares over pending GPU writes (10 s): %llu; missed without the sync %llu, skipped the sync %llu, synced %llu waiting %.0f ms (no dispatch writer %llu, foreign writer %llu, larger range %llu, label %llu, evidence short %llu, writer changed %llu, sampled %llu, image %llu, shadow %llu, off %llu); known-value reads %llu; verify: %llu would-skip compares synced anyway (%.0f ms), %llu mismatches, %llu misses a sync made hits; dwords observed over waits: %llu unchanged, %llu changed (regions not observed: %llu after no GPU wait, %llu not compared); %zu tracked, %zu with a streak\n", count(counters.pending), count(counters.unsyncedMisses), count(counters.skipped), count(counters.syncedNoWriter + counters.syncedForeign + counters.syncedLargeRange + counters.syncedLabel + counters.syncedEvidence + counters.syncedWriterChanged + counters.syncedSample + counters.syncedImage + counters.syncedShadow + counters.syncedOff), counters.syncedWaitMs, count(counters.syncedNoWriter), count(counters.syncedForeign), count(counters.syncedLargeRange), count(counters.syncedLabel), count(counters.syncedEvidence), count(counters.syncedWriterChanged), count(counters.syncedSample), count(counters.syncedImage), count(counters.syncedShadow), count(counters.syncedOff), count(counters.knownValue), count(counters.verified), counters.verifiedWaitMs, count(counters.mismatches), count(counters.verifiedMissesHit), count(observedUnchanged.exchange(0)), count(observedChanged.exchange(0)), count(observationsNoWait.exchange(0)), count(observationsNotReached.exchange(0)), tracked, eligible); + AgcDriver::ProfilePrint_nid_no_patch( "[validate] dispatch-cache compares over pending GPU writes (10 s): %llu; missed without the sync %llu, skipped the sync %llu, synced %llu waiting %.0f ms (no dispatch writer %llu, foreign writer %llu, larger range %llu, label %llu, evidence short %llu, writer changed %llu, sampled %llu, image %llu, shadow %llu, off %llu); known-value reads %llu; verify: %llu would-skip compares synced anyway (%.0f ms), %llu mismatches, %llu misses a sync made hits; dwords observed over waits: %llu unchanged, %llu changed (regions not observed: %llu after no GPU wait, %llu not compared); %zu tracked, %zu with a streak\n", count(counters.pending), count(counters.unsyncedMisses), count(counters.skipped), count(counters.syncedNoWriter + counters.syncedForeign + counters.syncedLargeRange + counters.syncedLabel + counters.syncedEvidence + counters.syncedWriterChanged + counters.syncedSample + counters.syncedImage + counters.syncedShadow + counters.syncedOff), counters.syncedWaitMs, count(counters.syncedNoWriter), count(counters.syncedForeign), count(counters.syncedLargeRange), count(counters.syncedLabel), count(counters.syncedEvidence), count(counters.syncedWriterChanged), count(counters.syncedSample), count(counters.syncedImage), count(counters.syncedShadow), count(counters.syncedOff), count(counters.knownValue), count(counters.verified), counters.verifiedWaitMs, count(counters.mismatches), count(counters.verifiedMissesHit), count(observedUnchanged.exchange(0)), count(observedChanged.exchange(0)), count(observationsNoWait.exchange(0)), count(observationsNotReached.exchange(0)), tracked, eligible); counters = ValidateCounters{}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp index 3c5dcd148..af3361308 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" @@ -24,7 +25,7 @@ void Driver::timed(double WorkerProfile::*bucket, TWork&& work) { static const bool report = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (report && end - profile.reported > std::chrono::seconds(10)) { profile.reported = end; - std::fprintf(stderr, "[gpu] worker at %.0f s: dispatch %.1f s, draw %.1f s, wait %.1f s\n", std::chrono::duration(end - profile.start).count(), profile.dispatchMs / 1000, profile.drawMs / 1000, profile.waitMs / 1000); + AgcDriver::ProfilePrint_nid_no_patch( "[gpu] worker at %.0f s: dispatch %.1f s, draw %.1f s, wait %.1f s\n", std::chrono::duration(end - profile.start).count(), profile.dispatchMs / 1000, profile.drawMs / 1000, profile.waitMs / 1000); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp index 5c6e70eff..40461f1a5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Packets/PacketTiming.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" @@ -40,9 +41,9 @@ PacketTimer::~PacketTimer() { outcomes += text; } auto& poll = Driver::pollStats(); - std::fprintf(stderr, "[poll] queue 0x%x (10 s): ticks %llu, table hits %llu, tries %llu / failed %llu, submits %llu, reaps %llu (%llu with work; by reason: behind completion %llu / other %llu), refusals: %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; longest try hold %.1f us, try holds %.1f ms\n", queue, static_cast(poll.ticks), static_cast(poll.tableHits), static_cast(poll.tries), static_cast(poll.triesFailed), static_cast(poll.submits), static_cast(poll.reaps), static_cast(poll.reapsWithWork), static_cast(poll.reapsBehindCompletion), static_cast(poll.reapsOther), LabelRefusalNames[1], static_cast(poll.refusals[1]), LabelRefusalNames[2], static_cast(poll.refusals[2]), LabelRefusalNames[3], static_cast(poll.refusals[3]), LabelRefusalNames[4], static_cast(poll.refusals[4]), LabelRefusalNames[5], static_cast(poll.refusals[5]), poll.longestTryHoldUs, poll.tryHoldUs / 1000.0); + AgcDriver::ProfilePrint_nid_no_patch( "[poll] queue 0x%x (10 s): ticks %llu, table hits %llu, tries %llu / failed %llu, submits %llu, reaps %llu (%llu with work; by reason: behind completion %llu / other %llu), refusals: %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; longest try hold %.1f us, try holds %.1f ms\n", queue, static_cast(poll.ticks), static_cast(poll.tableHits), static_cast(poll.tries), static_cast(poll.triesFailed), static_cast(poll.submits), static_cast(poll.reaps), static_cast(poll.reapsWithWork), static_cast(poll.reapsBehindCompletion), static_cast(poll.reapsOther), LabelRefusalNames[1], static_cast(poll.refusals[1]), LabelRefusalNames[2], static_cast(poll.refusals[2]), LabelRefusalNames[3], static_cast(poll.refusals[3]), LabelRefusalNames[4], static_cast(poll.refusals[4]), LabelRefusalNames[5], static_cast(poll.refusals[5]), poll.longestTryHoldUs, poll.tryHoldUs / 1000.0); poll = PollStats{}; - std::fprintf(stderr, "[packets] queue 0x%x %llu submissions, time by packet (10 s):%s, flush %.0fms; DISPATCH_DIRECT by outcome:%s; per submission (%llu submitted): validate %.1f us, copy %.1f us, dequeue %.1f us, complete %.1f us; suspend points %llu x %.1f us, %llu skipped (nothing open); end submits %llu made, %llu skipped, %llu notifies skipped; waits satisfied: at entry %llu, from recorder %llu (%llu while polling, same queue %llu, %llu without the GPU mutex, %llu late-trusted), polled %llu (%llu entered without the GPU mutex, %llu entry tries failed; late candidates %llu: refused cpu-store %llu, overwritten %llu, unclosed %llu, queued %llu), timed out %llu; poll submits %llu, poll reaps %llu; epoch bumps: submissions %llu, waits %llu, drains %llu, reaps %llu, packets %llu\n", queue, static_cast(profile.submissions), report.c_str(), profile.flushMs, outcomes.c_str(), static_cast(submitted), validateUs, copyUs, dequeueUs, completeUs, static_cast(suspends), suspendUs, static_cast(costs.suspendsSkipped.exchange(0)), static_cast(costs.endSubmits.exchange(0)), static_cast(costs.endSkipped.exchange(0)), static_cast(costs.notifiesSkipped.exchange(0)), static_cast(waits.atEntry), static_cast(waits.fromRecorder + waits.fromRecorderPolling), static_cast(waits.fromRecorderPolling), static_cast(waits.fromRecorderSameQueue), static_cast(waits.fromRecorderUnlocked), static_cast(waits.fromRecorderLate), static_cast(waits.polled), static_cast(waits.entriesUnlocked), static_cast(waits.entryTriesFailed), static_cast(late.candidates - lateSeen.candidates), static_cast(waits.lateRefusedCpuStore), static_cast(late.overwritten - lateSeen.overwritten), static_cast(late.unclosed - lateSeen.unclosed), static_cast(late.queued - lateSeen.queued), static_cast(waits.timedOut), static_cast(waits.pollSubmits), static_cast(waits.pollReaps), static_cast(epochs.submissions), static_cast(epochs.waits), static_cast(epochs.drains), static_cast(epochs.reaps), static_cast(epochs.packets)); + AgcDriver::ProfilePrint_nid_no_patch( "[packets] queue 0x%x %llu submissions, time by packet (10 s):%s, flush %.0fms; DISPATCH_DIRECT by outcome:%s; per submission (%llu submitted): validate %.1f us, copy %.1f us, dequeue %.1f us, complete %.1f us; suspend points %llu x %.1f us, %llu skipped (nothing open); end submits %llu made, %llu skipped, %llu notifies skipped; waits satisfied: at entry %llu, from recorder %llu (%llu while polling, same queue %llu, %llu without the GPU mutex, %llu late-trusted), polled %llu (%llu entered without the GPU mutex, %llu entry tries failed; late candidates %llu: refused cpu-store %llu, overwritten %llu, unclosed %llu, queued %llu), timed out %llu; poll submits %llu, poll reaps %llu; epoch bumps: submissions %llu, waits %llu, drains %llu, reaps %llu, packets %llu\n", queue, static_cast(profile.submissions), report.c_str(), profile.flushMs, outcomes.c_str(), static_cast(submitted), validateUs, copyUs, dequeueUs, completeUs, static_cast(suspends), suspendUs, static_cast(costs.suspendsSkipped.exchange(0)), static_cast(costs.endSubmits.exchange(0)), static_cast(costs.endSkipped.exchange(0)), static_cast(costs.notifiesSkipped.exchange(0)), static_cast(waits.atEntry), static_cast(waits.fromRecorder + waits.fromRecorderPolling), static_cast(waits.fromRecorderPolling), static_cast(waits.fromRecorderSameQueue), static_cast(waits.fromRecorderUnlocked), static_cast(waits.fromRecorderLate), static_cast(waits.polled), static_cast(waits.entriesUnlocked), static_cast(waits.entryTriesFailed), static_cast(late.candidates - lateSeen.candidates), static_cast(waits.lateRefusedCpuStore), static_cast(late.overwritten - lateSeen.overwritten), static_cast(late.unclosed - lateSeen.unclosed), static_cast(late.queued - lateSeen.queued), static_cast(waits.timedOut), static_cast(waits.pollSubmits), static_cast(waits.pollReaps), static_cast(epochs.submissions), static_cast(epochs.waits), static_cast(epochs.drains), static_cast(epochs.reaps), static_cast(epochs.packets)); lateSeen = late; waits = WaitOutcomes{}; epochs = EpochBumps{}; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp index 994626128..e42553239 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Queues/WorkerAffinity.hpp" @@ -150,7 +151,7 @@ void Driver::reportPresents(double waitedMs, std::size_t inFlight) { const auto flips = flipsCounted.load() - previousFlips; const double perFlip = flips != 0 ? 1.0 / static_cast(flips) : 0.0; const auto serial = flipSerial.load(); - std::fprintf(stderr, "[present] %llu presents over 10 s (%zu may trail on the GPU); %s p50 %.2f ms, p90 %.2f ms, max %.2f ms over %zu; per present: GPU busy %.1f ms, idle gaps %.1f ms (%llu batches without a completion record); per flip: %.1f batches recorded (%.1f unsignaled at the flip); per present: %.1f batches ahead of the blit, %.1f after it; after the flip packet: last submit %.1f ms, blit submit %.1f ms; in-place reads overwritten before execution: %llu of %llu checked\n", static_cast(presents), inFlight, inFlight != 0 ? "inflight_wait" : "render_fence_wait", percentile(0.5), percentile(0.9), waits.empty() ? 0.0 : waits.back(), waits.size(), (counts.gpuBusyMs - previous.gpuBusyMs) * perPresent, (counts.gpuGapMs - previous.gpuGapMs) * perPresent, static_cast(counts.gpuUnread - previous.gpuUnread), static_cast(serial - windowSerial) * perFlip, static_cast(flipBatchesUnsignaled.load() - previousUnsignaled) * perFlip, static_cast(counts.batchesAheadOfBlit - previous.batchesAheadOfBlit) * perPresent, static_cast(counts.batchesAfterFlip - previous.batchesAfterFlip) * perPresent, (counts.lastSubmitAfterFlipMs - previous.lastSubmitAfterFlipMs) * perPresent, (counts.blitSubmitAfterFlipMs - previous.blitSubmitAfterFlipMs) * perPresent, static_cast(counts.readsOverwritten - previous.readsOverwritten), static_cast(counts.readsChecked - previous.readsChecked)); + AgcDriver::ProfilePrint_nid_no_patch( "[present] %llu presents over 10 s (%zu may trail on the GPU); %s p50 %.2f ms, p90 %.2f ms, max %.2f ms over %zu; per present: GPU busy %.1f ms, idle gaps %.1f ms (%llu batches without a completion record); per flip: %.1f batches recorded (%.1f unsignaled at the flip); per present: %.1f batches ahead of the blit, %.1f after it; after the flip packet: last submit %.1f ms, blit submit %.1f ms; in-place reads overwritten before execution: %llu of %llu checked\n", static_cast(presents), inFlight, inFlight != 0 ? "inflight_wait" : "render_fence_wait", percentile(0.5), percentile(0.9), waits.empty() ? 0.0 : waits.back(), waits.size(), (counts.gpuBusyMs - previous.gpuBusyMs) * perPresent, (counts.gpuGapMs - previous.gpuGapMs) * perPresent, static_cast(counts.gpuUnread - previous.gpuUnread), static_cast(serial - windowSerial) * perFlip, static_cast(flipBatchesUnsignaled.load() - previousUnsignaled) * perFlip, static_cast(counts.batchesAheadOfBlit - previous.batchesAheadOfBlit) * perPresent, static_cast(counts.batchesAfterFlip - previous.batchesAfterFlip) * perPresent, (counts.lastSubmitAfterFlipMs - previous.lastSubmitAfterFlipMs) * perPresent, (counts.blitSubmitAfterFlipMs - previous.blitSubmitAfterFlipMs) * perPresent, static_cast(counts.readsOverwritten - previous.readsOverwritten), static_cast(counts.readsChecked - previous.readsChecked)); previous = counts; previousFlips = flipsCounted.load(); previousUnsignaled = flipBatchesUnsignaled.load(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp index 07304acfe..dfb31f4b7 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" @@ -38,7 +39,7 @@ SubmissionCosts& submissionCosts(std::uint32_t queue) { void reportSync() { std::string report; for (const auto& [code, count] : drainCounts) report += " " + (code == 0xffffu ? std::string("flip") : Pm4::Name(code << 8u)) + "=" + std::to_string(count); - std::fprintf(stderr, "[sync] %llu device drains by packet:%s (%llu waited without the GPU mutex); %llu labels written on the GPU, %llu deferred behind completions, %llu deferred not imported, %llu no-op, fallbacks: idle %llu, completions %llu, not imported %llu, undecodable %llu; %llu labels queued per worker, recorded in %llu groups, %llu recorded at once; stores: %llu recorded on the GPU, %llu behind completions, %llu on the CPU (idle), %llu synced (drained)\n", static_cast(drainTotal), report.c_str(), static_cast(unlockedDrains.load()), static_cast(gpuLabels.load()), static_cast(completionLabels.load()), static_cast(notImportedLabels.load()), static_cast(noOpLabels.load()), static_cast(labelFallbacks[1].load()), static_cast(labelFallbacks[2].load()), static_cast(labelFallbacks[3].load()), static_cast(labelFallbacks[4].load()), static_cast(queuedLabels.load()), static_cast(labelGroups.load()), static_cast(immediateLabels.load()), static_cast(storesOnGpu.load()), static_cast(storesBehindCompletions.load()), static_cast(storesOnCpu.load()), static_cast(storesDrained.load())); + AgcDriver::ProfilePrint_nid_no_patch("[sync] %llu device drains by packet:%s (%llu waited without the GPU mutex); %llu labels written on the GPU, %llu deferred behind completions, %llu deferred not imported, %llu no-op, fallbacks: idle %llu, completions %llu, not imported %llu, undecodable %llu; %llu labels queued per worker, recorded in %llu groups, %llu recorded at once; stores: %llu recorded on the GPU, %llu behind completions, %llu on the CPU (idle), %llu synced (drained)\n", static_cast(drainTotal), report.c_str(), static_cast(unlockedDrains.load()), static_cast(gpuLabels.load()), static_cast(completionLabels.load()), static_cast(notImportedLabels.load()), static_cast(noOpLabels.load()), static_cast(labelFallbacks[1].load()), static_cast(labelFallbacks[2].load()), static_cast(labelFallbacks[3].load()), static_cast(labelFallbacks[4].load()), static_cast(queuedLabels.load()), static_cast(labelGroups.load()), static_cast(immediateLabels.load()), static_cast(storesOnGpu.load()), static_cast(storesBehindCompletions.load()), static_cast(storesOnCpu.load()), static_cast(storesDrained.load())); } void countLabelOutcome(int reason) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 8bea6b6a1..a9427ddc0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -1505,8 +1505,8 @@ void GpuMutexType::lock() { char counts[160]; std::snprintf(counts, sizeof(counts), "; lock() %llu / try %llu / try failed %llu; locked GPU waits %llu / %.0f ms", static_cast(stats.acquisitions), static_cast(stats.tries), static_cast(stats.triesFailed), static_cast(stats.lockedGpuWaits), stats.lockedGpuWaitMs); holds += counts; - if (stats.tag == 0xffffffffu) std::fprintf(stderr, "[lock] %s waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.holderColumn == PresenterColumn ? "presenter" : "untagged thread", stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); - else std::fprintf(stderr, "[lock] queue 0x%x waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.tag, stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); + if (stats.tag == 0xffffffffu) AgcDriver::ProfilePrint_nid_no_patch("[lock] %s waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.holderColumn == PresenterColumn ? "presenter" : "untagged thread", stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); + else AgcDriver::ProfilePrint_nid_no_patch("[lock] queue 0x%x waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.tag, stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); stats.waitedMs = 0; stats.waits = 0; stats.acquisitions = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp index 78bc557d7..f624288af 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "Optimization/RequestMemoryView.hpp" @@ -240,7 +241,7 @@ std::shared_ptr ShaderMemory::Capture(c const auto specializationNs = ShaderRecompiler::ResourceMaterializer::SpecializationNanoseconds(); const auto hookNs = totals.hookWaitNanoseconds.load(); const auto walkNs = captureNs > resolveNs + pageNs + wordNs + specializationNs ? captureNs - resolveNs - pageNs - wordNs - specializationNs : 0; - std::fprintf(stderr, "[capture] %llu captures: %llu word reads, %llu pages fetched (%llu read word by word over pending GPU writes: %llu words waited %.2f s, %llu read raw on evidence, %llu verified with %llu mismatches, %llu served from known values, %llu hook reads not observed: no GPU wait), capture (plan lookup + materialize) %.1f s, %llu KiB registered code this capture; sub-phases (s, us per capture): source resolve %.2f/%.1f, walk %.2f/%.1f, specialization (every materialize) %.2f/%.1f, page reads %.2f/%.1f, word reads %.2f/%.1f, hook GPU waits inside %.2f/%.1f; source handle memo %llu hits, %llu resolves\n", static_cast(totals.captures.load()), static_cast(totals.reads.load()), static_cast(totals.pages.load()), static_cast(totals.pagesWordwise.load()), static_cast(totals.wordWaits.load()), totals.wordWaitNanoseconds.load() / 1e9, static_cast(totals.wordsRaw.load()), static_cast(totals.wordsVerified.load()), static_cast(totals.wordMismatches.load()), static_cast(totals.wordsKnown.load()), static_cast(totals.observationsSkipped.load()), captureNs / 1e9, static_cast(initialBytes / 1024), resolveNs / 1e9, resolveNs / captures / 1e3, walkNs / 1e9, walkNs / captures / 1e3, specializationNs / 1e9, specializationNs / captures / 1e3, pageNs / 1e9, pageNs / captures / 1e3, wordNs / 1e9, wordNs / captures / 1e3, hookNs / 1e9, hookNs / captures / 1e3, static_cast(totals.handleHits.load()), static_cast(totals.handleMisses.load())); + AgcDriver::ProfilePrint_nid_no_patch( "[capture] %llu captures: %llu word reads, %llu pages fetched (%llu read word by word over pending GPU writes: %llu words waited %.2f s, %llu read raw on evidence, %llu verified with %llu mismatches, %llu served from known values, %llu hook reads not observed: no GPU wait), capture (plan lookup + materialize) %.1f s, %llu KiB registered code this capture; sub-phases (s, us per capture): source resolve %.2f/%.1f, walk %.2f/%.1f, specialization (every materialize) %.2f/%.1f, page reads %.2f/%.1f, word reads %.2f/%.1f, hook GPU waits inside %.2f/%.1f; source handle memo %llu hits, %llu resolves\n", static_cast(totals.captures.load()), static_cast(totals.reads.load()), static_cast(totals.pages.load()), static_cast(totals.pagesWordwise.load()), static_cast(totals.wordWaits.load()), totals.wordWaitNanoseconds.load() / 1e9, static_cast(totals.wordsRaw.load()), static_cast(totals.wordsVerified.load()), static_cast(totals.wordMismatches.load()), static_cast(totals.wordsKnown.load()), static_cast(totals.observationsSkipped.load()), captureNs / 1e9, static_cast(initialBytes / 1024), resolveNs / 1e9, resolveNs / captures / 1e3, walkNs / 1e9, walkNs / captures / 1e3, specializationNs / 1e9, specializationNs / captures / 1e3, pageNs / 1e9, pageNs / captures / 1e3, wordNs / 1e9, wordNs / captures / 1e3, hookNs / 1e9, hookNs / captures / 1e3, static_cast(totals.handleHits.load()), static_cast(totals.handleMisses.load())); } } return capture; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 3d56df8c9..e77279db5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp" #include @@ -499,7 +500,7 @@ void reportPipelines(PipelineStore& store) { if (now - store.lastReport < std::chrono::seconds(10)) return; store.lastReport = now; const auto lookups = store.hits + store.misses + store.uncached; - std::fprintf(stderr, "[pipecache] %llu lookups over 10 s: %llu hits (%.0f%%), %llu misses, %llu private (no variant id), %llu evicted, %zu cached\n", static_cast(lookups), static_cast(store.hits), lookups != 0 ? 100.0 * static_cast(store.hits) / static_cast(lookups) : 0.0, static_cast(store.misses), static_cast(store.uncached), static_cast(store.evicted), store.entries.size()); + AgcDriver::ProfilePrint_nid_no_patch( "[pipecache] %llu lookups over 10 s: %llu hits (%.0f%%), %llu misses, %llu private (no variant id), %llu evicted, %zu cached\n", static_cast(lookups), static_cast(store.hits), lookups != 0 ? 100.0 * static_cast(store.hits) / static_cast(lookups) : 0.0, static_cast(store.misses), static_cast(store.uncached), static_cast(store.evicted), store.entries.size()); store.hits = store.misses = store.uncached = store.evicted = 0; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 2bb762263..a6e017329 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/General.hpp" @@ -125,7 +126,7 @@ void reportStorageTraffic(StorageTraffic& traffic) { const auto take = [](std::atomic& counter) { return static_cast(counter.exchange(0, std::memory_order_relaxed)); }; const auto partialUploadCount = take(partialUploads), partialWriteBackCount = take(partialWriteBacks); const auto uploadMiB = take(partialUploadBytes) / 1048576.0, writeBackMiB = take(partialWriteBackBytes) / 1048576.0; - std::fprintf(stderr, "[storage] uploads by path (count/MiB, 10 s):%s; %llu write-backs GPU-direct, %llu stored nothing; block units: partial uploads %llu/%.1f, partial write-backs %llu/%.1f, %llu widened to every pending unit, units dropped %llu, superseded %llu, dropped unregistered %llu, kept over a key flip %llu%s, pretest skipped %llu, evicted stale %llu\n", line.c_str(), static_cast(traffic.directWriteBacks), take(emptyWriteBacks), partialUploadCount, uploadMiB, partialWriteBackCount, writeBackMiB, take(coalescedWriteBacks), take(unitsDropped), take(unitsSuperseded), take(unregisteredDropped), take(keyFlipKept), ShadowReport().c_str(), take(pretestSkipped), take(staleEvicted)); + AgcDriver::ProfilePrint_nid_no_patch( "[storage] uploads by path (count/MiB, 10 s):%s; %llu write-backs GPU-direct, %llu stored nothing; block units: partial uploads %llu/%.1f, partial write-backs %llu/%.1f, %llu widened to every pending unit, units dropped %llu, superseded %llu, dropped unregistered %llu, kept over a key flip %llu%s, pretest skipped %llu, evicted stale %llu\n", line.c_str(), static_cast(traffic.directWriteBacks), take(emptyWriteBacks), partialUploadCount, uploadMiB, partialWriteBackCount, writeBackMiB, take(coalescedWriteBacks), take(unitsDropped), take(unitsSuperseded), take(unregisteredDropped), take(keyFlipKept), ShadowReport().c_str(), take(pretestSkipped), take(staleEvicted)); traffic.writeBacks.clear(); traffic.uploadReasons.clear(); traffic.directWriteBacks = 0; From 670ffb9da3e2ac21c9853e6863e6b1334118ecbc Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 6 Oct 2026 09:24:35 +0530 Subject: [PATCH 29/42] feat(libkernel): implement sceKernelGetAvailableCpumask Returns the CPU mask threads get by default (DEFAULT_THREAD_AFFINITY, 0x1FFF), the value itself rather than an error code. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libkernel/CMakeLists.txt | 10 +++ .../libs/prx/libkernel/Pthread/src/Thread.cpp | 4 ++ core/libs/tests/GuestAvailableCpumask.cpp | 65 +++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 4 files changed, 80 insertions(+) create mode 100644 core/libs/tests/GuestAvailableCpumask.cpp diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 43949deb4..a2021c427 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -264,6 +264,16 @@ if(BUILD_TESTING) set_tests_properties(guest_sync_on_address PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(guest_available_cpumask_tests ${LIBS_INCLUDE_DIR}/tests/GuestAvailableCpumask.cpp) + target_include_directories(guest_available_cpumask_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_available_cpumask_tests PRIVATE libkernel libc) + configure_windows_unwind(guest_available_cpumask_tests) + add_test(NAME guest_available_cpumask COMMAND guest_available_cpumask_tests) + set_tests_properties(guest_available_cpumask PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_available_cpumask PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test_executable(guest_kernel_error_tests ${LIBS_INCLUDE_DIR}/tests/GuestKernelErrors.cpp) target_include_directories(guest_kernel_error_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_kernel_error_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/Pthread/src/Thread.cpp b/core/libs/prx/libkernel/Pthread/src/Thread.cpp index 23b69cf56..a4798f886 100644 --- a/core/libs/prx/libkernel/Pthread/src/Thread.cpp +++ b/core/libs/prx/libkernel/Pthread/src/Thread.cpp @@ -379,6 +379,10 @@ int APS5_VABI scePthreadEqual(Pthread thread1, Pthread thread2) { return thread1 == thread2 ? 1 : 0; } +KernelCpumask APS5_VABI sceKernelGetAvailableCpumask(void) { + return DEFAULT_THREAD_AFFINITY; +} + int APS5_VABI scePthreadGetaffinity(Pthread thread, KernelCpumask* mask) { if (!thread || !mask) return SCE_KERNEL_ERROR_EINVAL; *mask = thread->affinity.load(std::memory_order_relaxed); diff --git a/core/libs/tests/GuestAvailableCpumask.cpp b/core/libs/tests/GuestAvailableCpumask.cpp new file mode 100644 index 000000000..7cc506661 --- /dev/null +++ b/core/libs/tests/GuestAvailableCpumask.cpp @@ -0,0 +1,65 @@ +#include "SceTypes.hpp" +#include +#include + +extern "C" { +KernelCpumask APS5_VABI sceKernelGetAvailableCpumask(void); +int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name); +int APS5_VABI scePthreadJoin(Pthread thread, void** retval); +int APS5_VABI scePthreadGetaffinity(Pthread thread, KernelCpumask* mask); +int APS5_VABI scePthreadSetaffinity(Pthread thread, KernelCpumask mask); +int APS5_VABI scePthreadAttrInit(PthreadAttr* attr); +int APS5_VABI scePthreadAttrDestroy(PthreadAttr* attr); +int APS5_VABI scePthreadAttrGetaffinity(const PthreadAttr* attr, KernelCpumask* mask); +} + +static constexpr int SCE_OK = 0; +static constexpr int PS5_LOGICAL_CPUS = 16; + +static void Require(bool value) { if (!value) std::abort(); } + +static void* APS5_VABI Worker(void* arg) { + static_cast*>(arg)->get(); + return nullptr; +} + +static void* APS5_VABI ReportMask(void* arg) { + *static_cast(arg) = sceKernelGetAvailableCpumask(); + return nullptr; +} + +int main() { + const KernelCpumask available = sceKernelGetAvailableCpumask(); + Require(available != 0); + Require((available >> PS5_LOGICAL_CPUS) == 0); + Require(sceKernelGetAvailableCpumask() == available); + + PthreadAttr attr = nullptr; + Require(scePthreadAttrInit(&attr) == SCE_OK); + KernelCpumask defaultAffinity = 0; + Require(scePthreadAttrGetaffinity(&attr, &defaultAffinity) == SCE_OK); + Require(defaultAffinity == available); + + std::promise release; + auto released = release.get_future(); + Pthread thread = nullptr; + Require(scePthreadCreate(&thread, &attr, Worker, &released, nullptr) == SCE_OK); + KernelCpumask threadAffinity = 0; + Require(scePthreadGetaffinity(thread, &threadAffinity) == SCE_OK); + Require(threadAffinity == available); + + for (KernelCpumask cpu = 1; cpu != 0; cpu <<= 1) { + if ((available & cpu) == 0) continue; + Require(scePthreadSetaffinity(thread, cpu) == SCE_OK); + Require(scePthreadGetaffinity(thread, &threadAffinity) == SCE_OK); + Require(threadAffinity == cpu); + } + release.set_value(); + Require(scePthreadJoin(thread, nullptr) == SCE_OK); + + KernelCpumask fromThread = 0; + Require(scePthreadCreate(&thread, &attr, ReportMask, &fromThread, nullptr) == SCE_OK); + Require(scePthreadJoin(thread, nullptr) == SCE_OK); + Require(fromThread == available); + Require(scePthreadAttrDestroy(&attr) == SCE_OK); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index cd0f433c1..2d94432c9 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -65,6 +65,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelInternalMemoryGetModuleSegmentInfo](../../core/libs/prx/libkernel/Module/src/Module.cpp) (libkernel) - unknown signature - [sceKernelSyncOnAddressWait](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - the only known caller passes a null timeout and a name string as the fourth argument; the timeout is assumed to point to microseconds like the other kernel waits, and the name is ignored - [sceKernelSyncOnAddressWait8 / sceKernelSyncOnAddressWait16 / sceKernelSyncOnAddressWait32 / sceKernelSyncOnAddressWait64](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - libc's `__std_atomic_wait_direct_8/16/32/64` pass a microsecond timeout or null and ignore the result; the by-value comparand, return values and the 2- and 8-byte alignment of Wait16 and Wait64 are assumed +- [sceKernelGetAvailableCpumask](../../core/libs/prx/libkernel/Pthread/src/Thread.cpp) (libkernel) - returns the default thread affinity, 0x1FFF (CPUs 0 to 12), as KytyPS5 does. Titles pin threads within it (PPSA02664 passes 0x1FFB, Hades II PPSA36082 0x3 and 0x3F); whether CPU 13 is available to a title is not confirmed - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 unknown; only the sceKernelMapNamedFlexibleMemory flags are accepted - [Guest arena](../../core/libs/prx/libc/src/GuestArena.cpp) (libc) - the application map area is assumed to end at 0xFC_0000_0000, as `SCE_KERNEL_APP_MAP_AREA_END_ADDR` does on the PS4. On Windows, host allocations made in the arena before libc loads stay, and a fixed guest mapping over one throws - [sceLibcInternalBacktraceForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature From 958b856832c976bc90df28abe1799a2bc389f766 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 6 Oct 2026 10:06:13 +0530 Subject: [PATCH 30/42] feat(libSceVideoOut): implement sceVideoOutAllowOutputResolutionWqhdDetection Lets an open port report 2560x1440 output (resolution 4). The output status here is 1080p or 2160p, so the call changes nothing it reports. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceVideoOut/CMakeLists.txt | 13 +++++ .../prx/libSceVideoOut/include/Output.hpp | 1 + core/libs/prx/libSceVideoOut/src/Output.cpp | 9 ++++ .../libs/tests/GuestVideoOutWqhdDetection.cpp | 52 +++++++++++++++++++ 4 files changed, 75 insertions(+) create mode 100644 core/libs/tests/GuestVideoOutWqhdDetection.cpp diff --git a/core/libs/prx/libSceVideoOut/CMakeLists.txt b/core/libs/prx/libSceVideoOut/CMakeLists.txt index d8e45a1df..075b2aab4 100644 --- a/core/libs/prx/libSceVideoOut/CMakeLists.txt +++ b/core/libs/prx/libSceVideoOut/CMakeLists.txt @@ -38,6 +38,19 @@ if(BUILD_TESTING) add_test(NAME pad_sdl COMMAND pad_sdl_tests) endif() +if(BUILD_TESTING) + add_test_executable(guest_video_out_wqhd_detection_tests ${LIBS_INCLUDE_DIR}/tests/GuestVideoOutWqhdDetection.cpp) + target_include_directories(guest_video_out_wqhd_detection_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_video_out_wqhd_detection_tests PRIVATE libSceVideoOut libSceAgcDriver libkernel libc) + configure_windows_unwind(guest_video_out_wqhd_detection_tests) + add_test(NAME guest_video_out_wqhd_detection COMMAND guest_video_out_wqhd_detection_tests) + set_tests_properties(guest_video_out_wqhd_detection PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_video_out_wqhd_detection PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() + if(BUILD_TESTING) add_test_executable(guest_buffer_reuse_tests ${LIBS_INCLUDE_DIR}/tests/GuestBufferReuse.cpp) target_include_directories(guest_buffer_reuse_tests PRIVATE ${LIBS_INCLUDE_DIR}) diff --git a/core/libs/prx/libSceVideoOut/include/Output.hpp b/core/libs/prx/libSceVideoOut/include/Output.hpp index 915ffe34b..91689f906 100644 --- a/core/libs/prx/libSceVideoOut/include/Output.hpp +++ b/core/libs/prx/libSceVideoOut/include/Output.hpp @@ -12,6 +12,7 @@ int APS5_VABI sceVideoOutClose(int handle); int APS5_VABI sceVideoOutConfigureOutput(int handle, uint64_t mode, const VideoOutOutputOptions* options, void* reserved_ptr, uint64_t reserved); int APS5_VABI sceVideoOutIsOutputSupported(int handle, uint64_t mode, const VideoOutOutputOptions* options, void* reserved_ptr, uint64_t reserved); int APS5_VABI sceVideoOutInitializeOutputOptions(VideoOutOutputOptions* options); +int APS5_VABI sceVideoOutAllowOutputResolutionWqhdDetection(int handle); int APS5_VABI sceVideoOutSetFlipRate(int handle, int rate); int APS5_VABI sceVideoOutSetWindowModeMargins(int handle, int top, int bottom); int APS5_VABI sceVideoOutGetFlipStatus(int handle, VideoOutFlipStatus* status); diff --git a/core/libs/prx/libSceVideoOut/src/Output.cpp b/core/libs/prx/libSceVideoOut/src/Output.cpp index c595e3022..cf471691d 100644 --- a/core/libs/prx/libSceVideoOut/src/Output.cpp +++ b/core/libs/prx/libSceVideoOut/src/Output.cpp @@ -80,6 +80,15 @@ int APS5_VABI sceVideoOutClose(int handle) try { LibcAwaitExit_nid_postfix(); } +int APS5_VABI sceVideoOutAllowOutputResolutionWqhdDetection(int handle) try { + if (!VideoOutDriver::Get().IsOpen(handle)) { + throw std::runtime_error(std::string(__func__) + ": VIDEO_OUT_ERROR_INVALID_HANDLE"); + } + return 0; +} catch (const ProcessShutdown&) { + LibcAwaitExit_nid_postfix(); +} + int APS5_VABI sceVideoOutSetFlipRate(int handle, int rate) try { auto cfg = VideoOutDriver::Get().GetConfig(handle); if (cfg == nullptr) { diff --git a/core/libs/tests/GuestVideoOutWqhdDetection.cpp b/core/libs/tests/GuestVideoOutWqhdDetection.cpp new file mode 100644 index 000000000..d0196accf --- /dev/null +++ b/core/libs/tests/GuestVideoOutWqhdDetection.cpp @@ -0,0 +1,52 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/Shutdown.hpp" +#include +#include +#include + +extern "C" { +int APS5_VABI sceVideoOutOpen(int userId, int busType, int index, const void* param); +int APS5_VABI sceVideoOutClose(int handle); +int APS5_VABI sceVideoOutGetOutputStatus(int handle, VideoOutOutputStatus* status); +int APS5_VABI sceVideoOutAllowOutputResolutionWqhdDetection(int handle); +} + +static constexpr int SYSTEM_USER = 255; +static constexpr int MAIN_BUS = 0; +static constexpr int NEVER_OPENED_HANDLE = 2; + +static void Require(bool value) { if (!value) std::abort(); } + +static bool RejectsHandle(int handle) { + try { + sceVideoOutAllowOutputResolutionWqhdDetection(handle); + } catch (const std::runtime_error&) { + return true; + } + return false; +} + +static bool SameStatus(const VideoOutOutputStatus& a, const VideoOutOutputStatus& b) { + return std::memcmp(&a, &b, sizeof(a)) == 0; +} + +int main() { + const int handle = sceVideoOutOpen(SYSTEM_USER, MAIN_BUS, 0, nullptr); + Require(handle > 0); + + VideoOutOutputStatus before{}; + Require(sceVideoOutGetOutputStatus(handle, &before) == 0); + Require(sceVideoOutAllowOutputResolutionWqhdDetection(handle) == 0); + Require(sceVideoOutAllowOutputResolutionWqhdDetection(handle) == 0); + VideoOutOutputStatus after{}; + Require(sceVideoOutGetOutputStatus(handle, &after) == 0); + Require(SameStatus(before, after)); + + Require(RejectsHandle(0)); + Require(RejectsHandle(-1)); + Require(RejectsHandle(NEVER_OPENED_HANDLE)); + + Require(sceVideoOutClose(handle) == 0); + Require(RejectsHandle(handle)); + LibcRunShutdown_nid_postfix(); +} From 79057e9160eafee6655ef8b19760cca6f8470d41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Mon, 5 Oct 2026 16:50:22 +0200 Subject: [PATCH 31/42] refactor(libs): drop replacements of modules that titles ship themselves Co-Authored-By: Claude --- CONTRIBUTING.md | 1 + core/libs/CMakeLists.txt | 21 - core/libs/prx/libREDGalaxy64/Export.cpp | 196 -- core/libs/prx/libRenoirCore.PS5/Export.cpp | 145 -- .../libs/prx/libSceNpCppWebApi/CMakeLists.txt | 21 - core/libs/prx/libSceNpCppWebApi/Export.cpp | 1194 ----------- core/libs/prx/libcohtml/CMakeLists.txt | 6 - core/libs/prx/libcohtml/DEPLOY.md | 16 - core/libs/prx/libcohtml/Export.cpp | 307 --- core/libs/prx/libfmod/CMakeLists.txt | 11 - core/libs/prx/libfmod/Export.cpp | 1902 ----------------- core/libs/prx/libfmodstudio/CMakeLists.txt | 10 - core/libs/prx/libfmodstudio/Export.cpp | 1007 --------- .../tests/GuestNpCppWebApiIntrusivePtr.cpp | 256 --- core/libs/tests/GuestNpCppWebApiString.cpp | 112 - docs/dev/TechnicalDebt.md | 2 - tools/package_release.py | 1 - 17 files changed, 1 insertion(+), 5207 deletions(-) delete mode 100644 core/libs/prx/libREDGalaxy64/Export.cpp delete mode 100644 core/libs/prx/libRenoirCore.PS5/Export.cpp delete mode 100644 core/libs/prx/libSceNpCppWebApi/CMakeLists.txt delete mode 100644 core/libs/prx/libSceNpCppWebApi/Export.cpp delete mode 100644 core/libs/prx/libcohtml/CMakeLists.txt delete mode 100644 core/libs/prx/libcohtml/DEPLOY.md delete mode 100644 core/libs/prx/libcohtml/Export.cpp delete mode 100644 core/libs/prx/libfmod/CMakeLists.txt delete mode 100644 core/libs/prx/libfmod/Export.cpp delete mode 100644 core/libs/prx/libfmodstudio/CMakeLists.txt delete mode 100644 core/libs/prx/libfmodstudio/Export.cpp delete mode 100644 core/libs/tests/GuestNpCppWebApiIntrusivePtr.cpp delete mode 100644 core/libs/tests/GuestNpCppWebApiString.cpp diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a34bd71a5..c12a36055 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,6 +7,7 @@ - A silent stub is allowed only when it unblocks a title and only affects the UI; add it to [silent stubs](docs/dev/TechnicalDebt.md#silent-stubs). - Missing imports fail at startup with a clear error; don't replace them with fallbacks that keep running. - Implement the general behaviour of a function, not what one title happens to need. +- Don't add replacements for modules that titles ship themselves in `sce_module/`, `sce_modules/` or `prx/`: engine or middleware modules (Cohtml, FMOD, GOG Galaxy) and SDK libraries that only wrap other system libraries (NpCppWebApi over NpWebApi2). The relinker converts and loads the title's own module, and a host library with the same name is left out of `DT_NEEDED`. Only system libraries, which reach the kernel or the hardware, are reimplemented in [core/libs/prx](core/libs/prx). - Avoid non-standard extensions (`__attribute__`, etc.) where standard C++ is enough. Helper symbols that must not become NIDs use the `_nid_no_patch` or `_nid_no_patch_cut` suffix. - The relinker uses only the C++20 standard library. - Third-party code is added as a submodule under `3rdparty/` and built from source, not found on the system. diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 510110335..dfe86ccd6 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -118,17 +118,6 @@ foreach(LIB_DIR ${LIBS_DIRS}) endif() endforeach() -set(LIBCOHTML_PATCHED ${PATCHED_DIR}/libcohtml.prx) -set(LIBCOHTML_PROSPERO_PATCHED ${PATCHED_DIR}/libcohtml.Prospero.prx) -add_custom_command( - OUTPUT ${LIBCOHTML_PROSPERO_PATCHED} - COMMAND ${CMAKE_COMMAND} -E copy "${LIBCOHTML_PATCHED}" "${LIBCOHTML_PROSPERO_PATCHED}" - DEPENDS ${LIBCOHTML_PATCHED} - VERBATIM -) -add_custom_target(libcohtml_prospero DEPENDS ${LIBCOHTML_PROSPERO_PATCHED}) -list(APPEND PATCHED_OUTPUTS ${LIBCOHTML_PROSPERO_PATCHED}) - add_custom_target(libs DEPENDS ${PATCHED_OUTPUTS}) if(BUILD_TESTING) @@ -170,16 +159,6 @@ if(BUILD_TESTING) add_test(NAME host_thread_local COMMAND host_thread_local_tests) set_tests_properties(host_thread_local PROPERTIES TIMEOUT 15) - add_test_executable(guest_np_cpp_web_api_intrusive_ptr_tests tests/GuestNpCppWebApiIntrusivePtr.cpp) - target_include_directories(guest_np_cpp_web_api_intrusive_ptr_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) - target_link_libraries(guest_np_cpp_web_api_intrusive_ptr_tests PRIVATE libSceNpCppWebApi libc) - configure_windows_unwind(guest_np_cpp_web_api_intrusive_ptr_tests) - add_test(NAME guest_np_cpp_web_api_intrusive_ptr COMMAND guest_np_cpp_web_api_intrusive_ptr_tests) - if(WIN32) - set_tests_properties(guest_np_cpp_web_api_intrusive_ptr PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() - add_test_executable(savedata_core_write_replacement_tests tests/SaveDataWriteReplacement.cpp) target_include_directories(savedata_core_write_replacement_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(savedata_core_write_replacement_tests PRIVATE libSceSaveData) diff --git a/core/libs/prx/libREDGalaxy64/Export.cpp b/core/libs/prx/libREDGalaxy64/Export.cpp deleted file mode 100644 index bf5c6235f..000000000 --- a/core/libs/prx/libREDGalaxy64/Export.cpp +++ /dev/null @@ -1,196 +0,0 @@ -#include -#include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" - -extern "C" { - -// CD Projekt RED GOG Galaxy wrapper, bundled with the game as -// modules/libREDGalaxy64.prx (seen in Cyberpunk 2077 PPSA04029). -// Online Galaxy services cannot work under emulation: Init/Shutdown/ -// ProcessData are accepted and ignored, interface getters return null -// (all observed engine call sites null-check the result). -// Roles below were reversed from the module's own export bodies: -// Init references clientID/clientSecret/configFilePath, Shutdown -// releases the facade singletons, ProcessData throttles facade -// ProcessData calls, GetErrorString formats Gog/Std exceptions. - -APS5_EXPORT("1icN9EO2WSg", redGalaxy64Init); -std::uint64_t APS5_VABI redGalaxy64Init(const void* options) { - (void)options; - NotImplemented_nid_no_patch(__func__); - return 1; -} - -APS5_EXPORT("SA7aCTRE5zg", redGalaxy64Shutdown); -void APS5_VABI redGalaxy64Shutdown(void) { - NotImplemented_nid_no_patch(__func__); -} - -APS5_EXPORT("ZVPOpEqpUvo", redGalaxy64ProcessData); -void APS5_VABI redGalaxy64ProcessData(void) { - NotImplemented_nid_no_patch(__func__); -} - -APS5_EXPORT("4trn+7BssaY", redGalaxy64GetErrorString); -const char* APS5_VABI redGalaxy64GetErrorString(void) { - NotImplemented_nid_no_patch(__func__); - return ""; -} - -APS5_EXPORT("DQAUzFVaGl8", redGalaxy64GameServerInit); -std::uint64_t APS5_VABI redGalaxy64GameServerInit(const void* options) { - (void)options; - NotImplemented_nid_no_patch(__func__); - return 1; -} - -APS5_EXPORT("GKomji4WVHw", redGalaxy64ProcessGameServerData); -void APS5_VABI redGalaxy64ProcessGameServerData(void) { - NotImplemented_nid_no_patch(__func__); -} - -APS5_EXPORT("36lort-kFp4", redgalaxy_stub_00); -std::uint64_t APS5_VABI redgalaxy_stub_00(std::uint64_t a0, std::uint64_t a1, std::uint64_t a2) { - (void)a0; - (void)a1; - (void)a2; - NotImplemented_nid_no_patch("36lort-kFp4"); - return 0; -} - -APS5_EXPORT("NgDLhCc6F7Y", redgalaxy_stub_01); -std::uint64_t APS5_VABI redgalaxy_stub_01(const void* a0, const char* a1, std::uint64_t a2) { - (void)a0; - (void)a1; - (void)a2; - NotImplemented_nid_no_patch("NgDLhCc6F7Y"); - return 0; -} - -APS5_EXPORT("huJ+beHcWBE", redgalaxy_stub_02); -std::uint64_t APS5_VABI redgalaxy_stub_02(void) { - NotImplemented_nid_no_patch("huJ+beHcWBE"); - return 0; -} - -APS5_EXPORT("sxiZFliOEDU", redgalaxy_stub_03); -std::uint64_t APS5_VABI redgalaxy_stub_03(void) { - NotImplemented_nid_no_patch("sxiZFliOEDU"); - return 0; -} - -APS5_EXPORT("49Bdn1OOJ90", redgalaxy_stub_04); -std::uint64_t APS5_VABI redgalaxy_stub_04(void) { - NotImplemented_nid_no_patch("49Bdn1OOJ90"); - return 0; -} - -APS5_EXPORT("8ahh9DUqZLY", redgalaxy_stub_05); -std::uint64_t APS5_VABI redgalaxy_stub_05(void) { - NotImplemented_nid_no_patch("8ahh9DUqZLY"); - return 0; -} - -APS5_EXPORT("Ard4nEfw5Vs", redgalaxy_stub_06); -std::uint64_t APS5_VABI redgalaxy_stub_06(void) { - NotImplemented_nid_no_patch("Ard4nEfw5Vs"); - return 0; -} - -APS5_EXPORT("AzO2fwK+MUs", redgalaxy_stub_07); -std::uint64_t APS5_VABI redgalaxy_stub_07(void) { - NotImplemented_nid_no_patch("AzO2fwK+MUs"); - return 0; -} - -APS5_EXPORT("HKIwQPq45o4", redgalaxy_stub_08); -std::uint64_t APS5_VABI redgalaxy_stub_08(void) { - NotImplemented_nid_no_patch("HKIwQPq45o4"); - return 0; -} - -APS5_EXPORT("IXRuom5imkM", redgalaxy_stub_09); -std::uint64_t APS5_VABI redgalaxy_stub_09(void) { - NotImplemented_nid_no_patch("IXRuom5imkM"); - return 0; -} - -APS5_EXPORT("LjDqfncevos", redgalaxy_stub_10); -std::uint64_t APS5_VABI redgalaxy_stub_10(void) { - NotImplemented_nid_no_patch("LjDqfncevos"); - return 0; -} - -APS5_EXPORT("Onwg0aGsFhM", redgalaxy_stub_11); -std::uint64_t APS5_VABI redgalaxy_stub_11(void) { - NotImplemented_nid_no_patch("Onwg0aGsFhM"); - return 0; -} - -APS5_EXPORT("oSyqfoYcK40", redgalaxy_stub_12); -std::uint64_t APS5_VABI redgalaxy_stub_12(void) { - NotImplemented_nid_no_patch("oSyqfoYcK40"); - return 0; -} - -APS5_EXPORT("qoS0gqW7RxI", redgalaxy_stub_13); -std::uint64_t APS5_VABI redgalaxy_stub_13(void) { - NotImplemented_nid_no_patch("qoS0gqW7RxI"); - return 0; -} - -APS5_EXPORT("SOtPNNwajSw", redgalaxy_stub_14); -std::uint64_t APS5_VABI redgalaxy_stub_14(void) { - NotImplemented_nid_no_patch("SOtPNNwajSw"); - return 0; -} - -APS5_EXPORT("udfpd9vbE+w", redgalaxy_stub_15); -std::uint64_t APS5_VABI redgalaxy_stub_15(void) { - NotImplemented_nid_no_patch("udfpd9vbE+w"); - return 0; -} - -APS5_EXPORT("vuGujcpcUEk", redgalaxy_stub_16); -std::uint64_t APS5_VABI redgalaxy_stub_16(void) { - NotImplemented_nid_no_patch("vuGujcpcUEk"); - return 0; -} - -APS5_EXPORT("VXUTdiaHbD4", redgalaxy_stub_17); -std::uint64_t APS5_VABI redgalaxy_stub_17(void) { - NotImplemented_nid_no_patch("VXUTdiaHbD4"); - return 0; -} - -APS5_EXPORT("w5-trCio4bQ", redgalaxy_stub_18); -std::uint64_t APS5_VABI redgalaxy_stub_18(void) { - NotImplemented_nid_no_patch("w5-trCio4bQ"); - return 0; -} - -APS5_EXPORT("YpZjREtZb20", redgalaxy_stub_19); -std::uint64_t APS5_VABI redgalaxy_stub_19(void) { - NotImplemented_nid_no_patch("YpZjREtZb20"); - return 0; -} - -APS5_EXPORT("gPJN5c9XCec", redgalaxy_stub_20); -std::uint64_t APS5_VABI redgalaxy_stub_20(void) { - NotImplemented_nid_no_patch("gPJN5c9XCec"); - return 0; -} - -APS5_EXPORT("z4SpWc89no8", redgalaxy_stub_21); -std::uint64_t APS5_VABI redgalaxy_stub_21(void) { - NotImplemented_nid_no_patch("z4SpWc89no8"); - return 0; -} - -APS5_EXPORT("zdzopKdBeU4", redgalaxy_stub_22); -std::uint64_t APS5_VABI redgalaxy_stub_22(void) { - NotImplemented_nid_no_patch("zdzopKdBeU4"); - return 0; -} - -} diff --git a/core/libs/prx/libRenoirCore.PS5/Export.cpp b/core/libs/prx/libRenoirCore.PS5/Export.cpp deleted file mode 100644 index c0cf955a3..000000000 --- a/core/libs/prx/libRenoirCore.PS5/Export.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include -#include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" - -extern "C" { - -APS5_EXPORT("0DsDTr534gc", renoirStub00); -uint64_t APS5_VABI renoirStub00(void) { - NotImplemented_nid_no_patch("0DsDTr534gc"); - return 0; -} - -APS5_EXPORT("2T56HgbPW08", renoirStub01); -uint64_t APS5_VABI renoirStub01(void) { - NotImplemented_nid_no_patch("2T56HgbPW08"); - return 0; -} - -APS5_EXPORT("3HnCozh8Az8", renoirStub02); -uint64_t APS5_VABI renoirStub02(void) { - NotImplemented_nid_no_patch("3HnCozh8Az8"); - return 0; -} - -APS5_EXPORT("5Ysce+s-CWU", renoirStub03); -uint64_t APS5_VABI renoirStub03(void) { - NotImplemented_nid_no_patch("5Ysce+s-CWU"); - return 0; -} - -APS5_EXPORT("AdlSqA4lGS8", renoirStub04); -uint64_t APS5_VABI renoirStub04(void) { - NotImplemented_nid_no_patch("AdlSqA4lGS8"); - return 0; -} - -APS5_EXPORT("bC37hk7rHqs", renoirStub05); -uint64_t APS5_VABI renoirStub05(void) { - NotImplemented_nid_no_patch("bC37hk7rHqs"); - return 0; -} - -APS5_EXPORT("dfPK9R6M0qM", renoirStub06); -uint64_t APS5_VABI renoirStub06(void) { - NotImplemented_nid_no_patch("dfPK9R6M0qM"); - return 0; -} - -APS5_EXPORT("fZiBbVa2ZDU", renoirStub07); -uint64_t APS5_VABI renoirStub07(void) { - NotImplemented_nid_no_patch("fZiBbVa2ZDU"); - return 0; -} - -APS5_EXPORT("hkWBH8-WfW4", renoirStub08); -uint64_t APS5_VABI renoirStub08(void) { - NotImplemented_nid_no_patch("hkWBH8-WfW4"); - return 0; -} - -APS5_EXPORT("hUxvGdi64Io", renoirStub09); -uint64_t APS5_VABI renoirStub09(void) { - NotImplemented_nid_no_patch("hUxvGdi64Io"); - return 0; -} - -APS5_EXPORT("NxqsZxGisrA", renoirStub10); -uint64_t APS5_VABI renoirStub10(void) { - NotImplemented_nid_no_patch("NxqsZxGisrA"); - return 0; -} - -APS5_EXPORT("OgZVIkaNmb0", renoirStub11); -uint64_t APS5_VABI renoirStub11(void) { - NotImplemented_nid_no_patch("OgZVIkaNmb0"); - return 0; -} - -APS5_EXPORT("ojLQdRUnVgA", renoirStub12); -uint64_t APS5_VABI renoirStub12(void) { - NotImplemented_nid_no_patch("ojLQdRUnVgA"); - return 0; -} - -APS5_EXPORT("s0qDfgsAgVg", renoirStub13); -uint64_t APS5_VABI renoirStub13(void) { - NotImplemented_nid_no_patch("s0qDfgsAgVg"); - return 0; -} - -APS5_EXPORT("sgrd-r1Nw60", renoirStub14); -uint64_t APS5_VABI renoirStub14(void) { - NotImplemented_nid_no_patch("sgrd-r1Nw60"); - return 0; -} - -APS5_EXPORT("sjTRb8YD7dQ", renoirStub15); -uint64_t APS5_VABI renoirStub15(void) { - NotImplemented_nid_no_patch("sjTRb8YD7dQ"); - return 0; -} - -APS5_EXPORT("tG86XGc2VtE", renoirStub16); -uint64_t APS5_VABI renoirStub16(void) { - NotImplemented_nid_no_patch("tG86XGc2VtE"); - return 0; -} - -APS5_EXPORT("umlGxOcNzgc", renoirStub17); -uint64_t APS5_VABI renoirStub17(void) { - NotImplemented_nid_no_patch("umlGxOcNzgc"); - return 0; -} - -APS5_EXPORT("vPxA9OFW0os", renoirStub18); -uint64_t APS5_VABI renoirStub18(void) { - NotImplemented_nid_no_patch("vPxA9OFW0os"); - return 0; -} - -APS5_EXPORT("X2qEBlOLkNo", renoirStub19); -uint64_t APS5_VABI renoirStub19(void) { - NotImplemented_nid_no_patch("X2qEBlOLkNo"); - return 0; -} - -APS5_EXPORT("ynh4E+BIaqY", renoirStub20); -uint64_t APS5_VABI renoirStub20(void) { - NotImplemented_nid_no_patch("ynh4E+BIaqY"); - return 0; -} - -APS5_EXPORT("YXe6ABbHZPs", renoirStub21); -uint64_t APS5_VABI renoirStub21(void) { - NotImplemented_nid_no_patch("YXe6ABbHZPs"); - return 0; -} - -APS5_EXPORT("z0jsXZVz75I", renoirStub22); -uint64_t APS5_VABI renoirStub22(void) { - NotImplemented_nid_no_patch("z0jsXZVz75I"); - return 0; -} - -} diff --git a/core/libs/prx/libSceNpCppWebApi/CMakeLists.txt b/core/libs/prx/libSceNpCppWebApi/CMakeLists.txt deleted file mode 100644 index 2519e8cc8..000000000 --- a/core/libs/prx/libSceNpCppWebApi/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -add_library(libSceNpCppWebApi SHARED EXCLUDE_FROM_ALL Export.cpp) -target_include_directories(libSceNpCppWebApi PRIVATE ${LIBS_INCLUDE_DIR}) -configure_windows_unwind(libSceNpCppWebApi) - -if(MINGW) - foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static) - string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}") - endforeach() -endif() - -if(BUILD_TESTING) - add_test_executable(guest_np_cpp_web_api_string_tests ${LIBS_INCLUDE_DIR}/tests/GuestNpCppWebApiString.cpp) - target_include_directories(guest_np_cpp_web_api_string_tests PRIVATE ${LIBS_INCLUDE_DIR}) - target_link_libraries(guest_np_cpp_web_api_string_tests PRIVATE libSceNpCppWebApi libc) - configure_windows_unwind(guest_np_cpp_web_api_string_tests) - add_test(NAME guest_np_cpp_web_api_string COMMAND guest_np_cpp_web_api_string_tests) - if(WIN32) - set_tests_properties(guest_np_cpp_web_api_string PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() -endif() diff --git a/core/libs/prx/libSceNpCppWebApi/Export.cpp b/core/libs/prx/libSceNpCppWebApi/Export.cpp deleted file mode 100644 index 75caf2847..000000000 --- a/core/libs/prx/libSceNpCppWebApi/Export.cpp +++ /dev/null @@ -1,1194 +0,0 @@ -#include -#include -#include -#include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" - -static constexpr int SCE_NP_WEBAPI_ERROR_UNAVAILABLE = static_cast(0x80552901); - -// Offline PSN: request entry points (API calls, transaction start/readData, factories) fail with -// SCE_NP_WEBAPI_ERROR_UNAVAILABLE; parameter bookkeeping succeeds; response accessors stay unimplemented -// because a failed request never produces a response. -extern "C" { - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V111UserFactory6createEPNS1_6Common10LibContextEPNS5_12IntrusivePtrINS3_4UserEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V121GetRankingRequestBody18setStartSerialRankERKi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V121GetRankingRequestBody8setGroupERKNS3_5GroupE() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V121GetRankingRequestBody8setLimitERKi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V121GetRankingRequestBody8setUsersERKNS1_6Common6VectorINS5_12IntrusivePtrINS3_4UserEEEEE() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V121GetRankingRequestBody9setOffsetERKi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V122GetRankingResponseBody10getEntriesEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V122RecordScoreRequestBody10setCommentEPKc() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V122RecordScoreRequestBody12setSmallDataEPKvm() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V122RecordScoreRequestBody15setNeedsTmpRankERKb() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V122RecordScoreRequestBody19setComparedDateTimeERK10SceRtcTick() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V122RecordScoreRequestBody7setPcIdERKi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V128GetRankingRequestBodyFactory6createEPNS1_6Common10LibContextEPNS5_12IntrusivePtrINS3_21GetRankingRequestBodyEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V129RecordScoreRequestBodyFactory6createEPNS1_6Common10LibContextElPNS5_12IntrusivePtrINS3_22RecordScoreRequestBodyEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V14User12setAccountIdERKm() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V14User7setPcIdERKi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi10getRankingEiRKNS4_21ParameterToGetRankingERNS1_6Common11TransactionINS8_12IntrusivePtrINS3_22GetRankingResponseBodyEEENSA_INS8_18ResponseHeaderBaseEEEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi21ParameterToGetRanking10initializeEPNS1_6Common10LibContextEi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi21ParameterToGetRanking24setgetRankingRequestBodyENS1_6Common12IntrusivePtrINS3_21GetRankingRequestBodyEEE() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi21ParameterToGetRanking9terminateEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi21ParameterToGetRankingC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi21ParameterToGetRankingD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi22getLargeDataByObjectIdEiRKNS4_33ParameterToGetLargeDataByObjectIdERNS1_6Common21DownStreamTransactionINS8_12IntrusivePtrINS4_37GetLargeDataByObjectIdResponseHeadersEEEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi33ParameterToGetLargeDataByObjectId10initializeEPNS1_6Common10LibContextEPKc() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi33ParameterToGetLargeDataByObjectId9terminateEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi33ParameterToGetLargeDataByObjectIdC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V17ViewApi33ParameterToGetLargeDataByObjectIdD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19BoardsApi18getBoardDefinitionEiRKNS4_29ParameterToGetBoardDefinitionERNS1_6Common11TransactionINS8_12IntrusivePtrINS3_30GetBoardDefinitionResponseBodyEEENSA_INS8_18ResponseHeaderBaseEEEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19BoardsApi29ParameterToGetBoardDefinition10initializeEPNS1_6Common10LibContextEi() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19BoardsApi29ParameterToGetBoardDefinition9terminateEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19BoardsApi29ParameterToGetBoardDefinitionC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19BoardsApi29ParameterToGetBoardDefinitionD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi11recordScoreEiRKNS4_22ParameterToRecordScoreERNS1_6Common11TransactionINS8_12IntrusivePtrINS3_23RecordScoreResponseBodyEEENSA_INS4_26RecordScoreResponseHeadersEEEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi15recordLargeDataEiRKNS4_26ParameterToRecordLargeDataERNS1_6Common19UpStreamTransactionINS8_12IntrusivePtrINS3_27RecordLargeDataResponseBodyEEENSA_INS8_18ResponseHeaderBaseEEEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi22ParameterToRecordScore10initializeEPNS1_6Common10LibContextEiNS6_12IntrusivePtrINS3_22RecordScoreRequestBodyEEE() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi22ParameterToRecordScore22setxPsnAtomicOperationENS5_19XPsnAtomicOperationE() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi22ParameterToRecordScore9terminateEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi22ParameterToRecordScoreC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi22ParameterToRecordScoreD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi26ParameterToRecordLargeData10initializeEPNS1_6Common10LibContextEiNS5_19XPsnAtomicOperationEPKc() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi26ParameterToRecordLargeData9terminateEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi26ParameterToRecordLargeDataC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi12Leaderboards2V19RecordApi26ParameterToRecordLargeDataD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi17TitleCloudStorage2V17DataApi12downloadDataEiRKNS4_23ParameterToDownloadDataERNS1_6Common21DownStreamTransactionINS8_12IntrusivePtrINS4_27DownloadDataResponseHeadersEEEEE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi17TitleCloudStorage2V17DataApi23ParameterToDownloadData10initializeEPNS1_6Common10LibContextEPKci() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi17TitleCloudStorage2V17DataApi23ParameterToDownloadData9terminateEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi17TitleCloudStorage2V17DataApi23ParameterToDownloadDataC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi17TitleCloudStorage2V17DataApi23ParameterToDownloadDataD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common10InitParamsC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common10InitParamsD1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common10LibContextC1Ev(uint64_t* self) { - *self = 0; - return 0; -} - -// Initialization succeeds as on an offline console (see libSceJson2); individual requests fail. -int APS5_VABI _ZN3sce2Np9CppWebApi6Common10initializeERKNS2_10InitParamsERNS2_10LibContextE(const void* params, uint64_t* context) { - (void)params; - if (context) *context = 1; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEEC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEED1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEENS4_INS6_9RecordApi26RecordScoreResponseHeadersEEEEC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEENS4_INS6_9RecordApi26RecordScoreResponseHeadersEEEED1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEEC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEED1Ev(void* self) { - (void)self; - return 0; -} - -struct IntrusivePtr { - void* object; - void (APS5_VABI* deleter)(void*); - void* libContext; -}; -static_assert(sizeof(IntrusivePtr) == 0x18); - -static constexpr std::size_t ReferenceCountOffset = 0; -static constexpr std::size_t VectorReferenceCountOffset = 0x30; - -static std::atomic_ref ReferenceCount(void* object, const std::size_t offset) { - return std::atomic_ref(*reinterpret_cast(static_cast(object) + offset)); -} - -static void CopyIntrusivePtr(IntrusivePtr* self, const IntrusivePtr* source, const std::size_t referenceCountOffset) { - *self = *source; - if (self->object) ReferenceCount(self->object, referenceCountOffset).fetch_add(1); -} - -static void ReleaseIntrusivePtr(IntrusivePtr* self, const std::size_t referenceCountOffset, const char* function) { - if (!self->object) return; - if (ReferenceCount(self->object, referenceCountOffset).fetch_sub(1) != 1) return; - if (!self->deleter) NotImplemented_nid_no_patch(function); - self->deleter(self->object); - self->object = nullptr; - self->deleter = nullptr; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEC1ERS7_(IntrusivePtr* self, const IntrusivePtr* source) { - CopyIntrusivePtr(self, source, ReferenceCountOffset); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1ERS7_(IntrusivePtr* self, const IntrusivePtr* source) { - CopyIntrusivePtr(self, source, ReferenceCountOffset); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEEC1Ev(IntrusivePtr* self) { - *self = {}; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, ReferenceCountOffset, __func__); -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6VectorINS3_INS1_12Leaderboards2V15EntryEEEEEED1Ev(IntrusivePtr* self) { - ReleaseIntrusivePtr(self, VectorReferenceCountOffset, __func__); -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common13ConstIteratorINS2_12IntrusivePtrINS1_12Leaderboards2V15EntryEEEED2Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE5startEPNS2_10LibContextE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE6finishEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEENS4_INS6_9RecordApi26RecordScoreResponseHeadersEEEE5startEPNS2_10LibContextE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEENS4_INS6_9RecordApi26RecordScoreResponseHeadersEEEE6finishEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V127RecordLargeDataResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE6finishEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE5startEPNS2_10LibContextE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE6finishEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common19UpStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V127RecordLargeDataResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE5startEPNS2_10LibContextEm() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common19UpStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V127RecordLargeDataResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE8sendDataEPKvm() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common19UpStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V127RecordLargeDataResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEEC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common19UpStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V127RecordLargeDataResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEED1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V17ViewApi37GetLargeDataByObjectIdResponseHeadersEEEE5startEPNS2_10LibContextE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V17ViewApi37GetLargeDataByObjectIdResponseHeadersEEEE6finishEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V17ViewApi37GetLargeDataByObjectIdResponseHeadersEEEE8readDataEPcm() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V17ViewApi37GetLargeDataByObjectIdResponseHeadersEEEEC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_12Leaderboards2V17ViewApi37GetLargeDataByObjectIdResponseHeadersEEEED1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_17TitleCloudStorage2V17DataApi27DownloadDataResponseHeadersEEEE5startEPNS2_10LibContextE() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_17TitleCloudStorage2V17DataApi27DownloadDataResponseHeadersEEEE6finishEv() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_17TitleCloudStorage2V17DataApi27DownloadDataResponseHeadersEEEE8readDataEPcm() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_17TitleCloudStorage2V17DataApi27DownloadDataResponseHeadersEEEEC1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common21DownStreamTransactionINS2_12IntrusivePtrINS1_17TitleCloudStorage2V17DataApi27DownloadDataResponseHeadersEEEED1Ev(void* self) { - (void)self; - return 0; -} - -struct CommonString { - std::int32_t referenceCount; - char* buffer; - std::uint64_t bufferSize; - void* libContext; -}; -static_assert(sizeof(CommonString) == 0x20 && offsetof(CommonString, buffer) == 0x08); -static_assert(offsetof(CommonString, bufferSize) == 0x10 && offsetof(CommonString, libContext) == 0x18); - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common6StringC1EPNS2_10LibContextE(CommonString* self, void* libContext) { - self->referenceCount = 0; - self->buffer = nullptr; - self->bufferSize = 0; - self->libContext = libContext; -} - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common6StringD1Ev(CommonString* self) { - if (self->buffer != nullptr) NotImplemented_nid_no_patch("sce::Np::CppWebApi::Common::String buffer release"); -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common6VectorINS2_12IntrusivePtrINS1_12Leaderboards2V14UserEEEE8pushBackERKS8_() { - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common6VectorINS2_12IntrusivePtrINS1_12Leaderboards2V14UserEEEEC1EPNS2_10LibContextE(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common6VectorINS2_12IntrusivePtrINS1_12Leaderboards2V14UserEEEED1Ev(void* self) { - (void)self; - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common6VectorINS2_12IntrusivePtrINS1_12Leaderboards2V15EntryEEEE3endEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common6VectorINS2_12IntrusivePtrINS1_12Leaderboards2V15EntryEEEE5beginEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common8IteratorINS2_12IntrusivePtrINS1_12Leaderboards2V15EntryEEEEppEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZN3sce2Np9CppWebApi6Common9terminateERNS2_10LibContextE(uint64_t* context) { - *context = 0; - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V122GetRankingResponseBody22getLastUpdatedDateTimeEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V123RecordScoreResponseBody10getTmpRankEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V123RecordScoreResponseBody16getTmpSerialRankEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody11getSortModeEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody13getEntryLimitEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody13getUpdateModeEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody13sortModeIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody15entryLimitIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody15updateModeIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody16getMaxScoreLimitEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody16getMinScoreLimitEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody18maxScoreLimitIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody18minScoreLimitIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody20getLargeDataNumLimitEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody21getLargeDataSizeLimitEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody22largeDataNumLimitIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V130GetBoardDefinitionResponseBody23largeDataSizeLimitIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry10getCommentEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry11getObjectIdEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry11getOnlineIdEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry12commentIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry12getAccountIdEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry12getSmallDataEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry13getSerialRankEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry13objectIdIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry14getHighestRankEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry14smallDataIsSetEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry20getHighestSerialRankEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry7getPcIdEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry7getRankEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V15Entry8getScoreEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi12Leaderboards2V19RecordApi26RecordScoreResponseHeaders24getXPsnAtomicOperationIdEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE11getResponseERS8_() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEENS4_INS6_9RecordApi26RecordScoreResponseHeadersEEEE11getResponseERS8_() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common11TransactionINS2_12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEENS4_INS2_18ResponseHeaderBaseEEEE11getResponseERS8_() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V15EntryEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6BinaryEEptEv(const IntrusivePtr* self) { - return self->object; -} - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6VectorINS3_INS1_12Leaderboards2V15EntryEEEEEEdeEv(const IntrusivePtr* self) { - return self->object; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common15TransactionBaseINS2_12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEENS4_INS6_9RecordApi26RecordScoreResponseHeadersEEEE18getResponseHeadersERSB_() { - return SCE_NP_WEBAPI_ERROR_UNAVAILABLE; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common6Binary4sizeEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common6Binary9getBinaryEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -const char* APS5_VABI _ZNK3sce2Np9CppWebApi6Common6String5c_strEv(const CommonString* self) { - return self->buffer != nullptr ? self->buffer : ""; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common8IteratorINS2_12IntrusivePtrINS1_12Leaderboards2V15EntryEEEEdeEv() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - -int APS5_VABI _ZNK3sce2Np9CppWebApi6Common8IteratorINS2_12IntrusivePtrINS1_12Leaderboards2V15EntryEEEEneERKS9_() { - NotImplemented_nid_no_patch(__func__); - return 0; -} - - -APS5_EXPORT("+gSMGXHgrPU", sceNpCppWebApiUnknown00); -int APS5_VABI sceNpCppWebApiUnknown00(void) { - NotImplemented_nid_no_patch("+gSMGXHgrPU"); - return 0; -} - -APS5_EXPORT("-XNfwZTFkWw", sceNpCppWebApiUnknown01); -int APS5_VABI sceNpCppWebApiUnknown01(void) { - NotImplemented_nid_no_patch("-XNfwZTFkWw"); - return 0; -} - -APS5_EXPORT("0f5+eBcgB14", sceNpCppWebApiUnknown02); -int APS5_VABI sceNpCppWebApiUnknown02(void) { - NotImplemented_nid_no_patch("0f5+eBcgB14"); - return 0; -} - -APS5_EXPORT("1iq5Jtw4jVs", sceNpCppWebApiUnknown03); -int APS5_VABI sceNpCppWebApiUnknown03(void) { - NotImplemented_nid_no_patch("1iq5Jtw4jVs"); - return 0; -} - -APS5_EXPORT("1wpCXuFzH10", sceNpCppWebApiUnknown04); -int APS5_VABI sceNpCppWebApiUnknown04(void) { - NotImplemented_nid_no_patch("1wpCXuFzH10"); - return 0; -} - -APS5_EXPORT("4AFThLW28xQ", sceNpCppWebApiUnknown05); -int APS5_VABI sceNpCppWebApiUnknown05(void) { - NotImplemented_nid_no_patch("4AFThLW28xQ"); - return 0; -} - -APS5_EXPORT("8-9Y4oS+OuE", sceNpCppWebApiUnknown06); -int APS5_VABI sceNpCppWebApiUnknown06(void) { - NotImplemented_nid_no_patch("8-9Y4oS+OuE"); - return 0; -} - -APS5_EXPORT("8dWkWjo5EeE", sceNpCppWebApiUnknown07); -int APS5_VABI sceNpCppWebApiUnknown07(void) { - NotImplemented_nid_no_patch("8dWkWjo5EeE"); - return 0; -} - -APS5_EXPORT("BHvfIGdarBQ", sceNpCppWebApiUnknown08); -int APS5_VABI sceNpCppWebApiUnknown08(void) { - NotImplemented_nid_no_patch("BHvfIGdarBQ"); - return 0; -} - -APS5_EXPORT("Fxxr5lYBfl4", sceNpCppWebApiUnknown09); -int APS5_VABI sceNpCppWebApiUnknown09(void) { - NotImplemented_nid_no_patch("Fxxr5lYBfl4"); - return 0; -} - -APS5_EXPORT("M1LnjRscx-w", sceNpCppWebApiUnknown10); -int APS5_VABI sceNpCppWebApiUnknown10(void) { - NotImplemented_nid_no_patch("M1LnjRscx-w"); - return 0; -} - -APS5_EXPORT("PsX657reZeo", sceNpCppWebApiUnknown11); -int APS5_VABI sceNpCppWebApiUnknown11(void) { - NotImplemented_nid_no_patch("PsX657reZeo"); - return 0; -} - -APS5_EXPORT("RvH9AZ5rCkQ", sceNpCppWebApiUnknown12); -int APS5_VABI sceNpCppWebApiUnknown12(void) { - NotImplemented_nid_no_patch("RvH9AZ5rCkQ"); - return 0; -} - -APS5_EXPORT("SR3BKonD8yk", sceNpCppWebApiUnknown13); -int APS5_VABI sceNpCppWebApiUnknown13(void) { - NotImplemented_nid_no_patch("SR3BKonD8yk"); - return 0; -} - -APS5_EXPORT("TSoQhYKyq5g", sceNpCppWebApiUnknown14); -int APS5_VABI sceNpCppWebApiUnknown14(void) { - NotImplemented_nid_no_patch("TSoQhYKyq5g"); - return 0; -} - -APS5_EXPORT("TgsJjQqp+2k", sceNpCppWebApiUnknown15); -int APS5_VABI sceNpCppWebApiUnknown15(void) { - NotImplemented_nid_no_patch("TgsJjQqp+2k"); - return 0; -} - -APS5_EXPORT("UHQxE3HhTXA", sceNpCppWebApiUnknown16); -int APS5_VABI sceNpCppWebApiUnknown16(void) { - NotImplemented_nid_no_patch("UHQxE3HhTXA"); - return 0; -} - -APS5_EXPORT("ZN-glpk0Rug", sceNpCppWebApiUnknown17); -int APS5_VABI sceNpCppWebApiUnknown17(void) { - NotImplemented_nid_no_patch("ZN-glpk0Rug"); - return 0; -} - -APS5_EXPORT("ZQzXwokCnUE", sceNpCppWebApiUnknown18); -int APS5_VABI sceNpCppWebApiUnknown18(void) { - NotImplemented_nid_no_patch("ZQzXwokCnUE"); - return 0; -} - -APS5_EXPORT("ZwjmbSr4Cxc", sceNpCppWebApiUnknown19); -int APS5_VABI sceNpCppWebApiUnknown19(void) { - NotImplemented_nid_no_patch("ZwjmbSr4Cxc"); - return 0; -} - -APS5_EXPORT("b7leY-LNVnI", sceNpCppWebApiUnknown20); -int APS5_VABI sceNpCppWebApiUnknown20(void) { - NotImplemented_nid_no_patch("b7leY-LNVnI"); - return 0; -} - -APS5_EXPORT("c3J9K9XbQqE", sceNpCppWebApiUnknown21); -int APS5_VABI sceNpCppWebApiUnknown21(void) { - NotImplemented_nid_no_patch("c3J9K9XbQqE"); - return 0; -} - -APS5_EXPORT("cSLbQUQO2Ns", sceNpCppWebApiUnknown22); -int APS5_VABI sceNpCppWebApiUnknown22(void) { - NotImplemented_nid_no_patch("cSLbQUQO2Ns"); - return 0; -} - -APS5_EXPORT("cqOxjL0ZfFA", sceNpCppWebApiUnknown23); -int APS5_VABI sceNpCppWebApiUnknown23(void) { - NotImplemented_nid_no_patch("cqOxjL0ZfFA"); - return 0; -} - -APS5_EXPORT("d1eEjWR60wk", sceNpCppWebApiUnknown24); -int APS5_VABI sceNpCppWebApiUnknown24(void) { - NotImplemented_nid_no_patch("d1eEjWR60wk"); - return 0; -} - -APS5_EXPORT("epwr+cBCIFs", sceNpCppWebApiUnknown25); -int APS5_VABI sceNpCppWebApiUnknown25(void) { - NotImplemented_nid_no_patch("epwr+cBCIFs"); - return 0; -} - -APS5_EXPORT("eruduJ0KrT0", sceNpCppWebApiUnknown26); -int APS5_VABI sceNpCppWebApiUnknown26(void) { - NotImplemented_nid_no_patch("eruduJ0KrT0"); - return 0; -} - -APS5_EXPORT("fG06a38iao8", sceNpCppWebApiUnknown27); -int APS5_VABI sceNpCppWebApiUnknown27(void) { - NotImplemented_nid_no_patch("fG06a38iao8"); - return 0; -} - -APS5_EXPORT("jfpSx14AeLc", sceNpCppWebApiUnknown28); -int APS5_VABI sceNpCppWebApiUnknown28(void) { - NotImplemented_nid_no_patch("jfpSx14AeLc"); - return 0; -} - -APS5_EXPORT("kBxwE4YfbIM", sceNpCppWebApiUnknown29); -int APS5_VABI sceNpCppWebApiUnknown29(void) { - NotImplemented_nid_no_patch("kBxwE4YfbIM"); - return 0; -} - -APS5_EXPORT("kz2Z38yTLq0", sceNpCppWebApiUnknown30); -int APS5_VABI sceNpCppWebApiUnknown30(void) { - NotImplemented_nid_no_patch("kz2Z38yTLq0"); - return 0; -} - -APS5_EXPORT("lB8driFKaoU", sceNpCppWebApiUnknown31); -int APS5_VABI sceNpCppWebApiUnknown31(void) { - NotImplemented_nid_no_patch("lB8driFKaoU"); - return 0; -} - -APS5_EXPORT("mCsV7izOkjY", sceNpCppWebApiUnknown32); -int APS5_VABI sceNpCppWebApiUnknown32(void) { - NotImplemented_nid_no_patch("mCsV7izOkjY"); - return 0; -} - -APS5_EXPORT("n1yCLMxpseQ", sceNpCppWebApiUnknown33); -int APS5_VABI sceNpCppWebApiUnknown33(void) { - NotImplemented_nid_no_patch("n1yCLMxpseQ"); - return 0; -} - -APS5_EXPORT("nL9vSVq-29s", sceNpCppWebApiUnknown34); -int APS5_VABI sceNpCppWebApiUnknown34(void) { - NotImplemented_nid_no_patch("nL9vSVq-29s"); - return 0; -} - -APS5_EXPORT("nmz5JYKcMfY", sceNpCppWebApiUnknown35); -int APS5_VABI sceNpCppWebApiUnknown35(void) { - NotImplemented_nid_no_patch("nmz5JYKcMfY"); - return 0; -} - -APS5_EXPORT("oHRl7a+zdMU", sceNpCppWebApiUnknown36); -int APS5_VABI sceNpCppWebApiUnknown36(void) { - NotImplemented_nid_no_patch("oHRl7a+zdMU"); - return 0; -} - -APS5_EXPORT("pSpO3hPNv64", sceNpCppWebApiUnknown37); -int APS5_VABI sceNpCppWebApiUnknown37(void) { - NotImplemented_nid_no_patch("pSpO3hPNv64"); - return 0; -} - -APS5_EXPORT("q4UFICay6Hk", sceNpCppWebApiUnknown38); -int APS5_VABI sceNpCppWebApiUnknown38(void) { - NotImplemented_nid_no_patch("q4UFICay6Hk"); - return 0; -} - -APS5_EXPORT("qiD2PU2Jstc", sceNpCppWebApiUnknown39); -int APS5_VABI sceNpCppWebApiUnknown39(void) { - NotImplemented_nid_no_patch("qiD2PU2Jstc"); - return 0; -} - -APS5_EXPORT("tFe964qzGEM", sceNpCppWebApiUnknown40); -int APS5_VABI sceNpCppWebApiUnknown40(void) { - NotImplemented_nid_no_patch("tFe964qzGEM"); - return 0; -} - -APS5_EXPORT("tHaO36kincQ", sceNpCppWebApiUnknown41); -int APS5_VABI sceNpCppWebApiUnknown41(void) { - NotImplemented_nid_no_patch("tHaO36kincQ"); - return 0; -} - -APS5_EXPORT("umm5m+mXiZs", sceNpCppWebApiUnknown42); -int APS5_VABI sceNpCppWebApiUnknown42(void) { - NotImplemented_nid_no_patch("umm5m+mXiZs"); - return 0; -} - -APS5_EXPORT("uwhztB49KOQ", sceNpCppWebApiUnknown43); -int APS5_VABI sceNpCppWebApiUnknown43(void) { - NotImplemented_nid_no_patch("uwhztB49KOQ"); - return 0; -} - -APS5_EXPORT("w4K4nTYwhVE", sceNpCppWebApiUnknown44); -int APS5_VABI sceNpCppWebApiUnknown44(void) { - NotImplemented_nid_no_patch("w4K4nTYwhVE"); - return 0; -} - -APS5_EXPORT("wFcm6bgWB9Q", sceNpCppWebApiUnknown45); -int APS5_VABI sceNpCppWebApiUnknown45(void) { - NotImplemented_nid_no_patch("wFcm6bgWB9Q"); - return 0; -} - -APS5_EXPORT("wp8+c84G5Xw", sceNpCppWebApiUnknown46); -int APS5_VABI sceNpCppWebApiUnknown46(void) { - NotImplemented_nid_no_patch("wp8+c84G5Xw"); - return 0; -} - -APS5_EXPORT("zjqTmP0ST9A", sceNpCppWebApiUnknown47); -int APS5_VABI sceNpCppWebApiUnknown47(void) { - NotImplemented_nid_no_patch("zjqTmP0ST9A"); - return 0; -} - -APS5_EXPORT("zzO8ZGJ74ng", sceNpCppWebApiUnknown48); -int APS5_VABI sceNpCppWebApiUnknown48(void) { - NotImplemented_nid_no_patch("zzO8ZGJ74ng"); - return 0; -} - -APS5_EXPORT("12wY179+CE8", sceNpCppWebApiUnknown49); -int APS5_VABI sceNpCppWebApiUnknown49(void) { - NotImplemented_nid_no_patch("12wY179+CE8"); - return 0; -} - -APS5_EXPORT("3bjEFf8OhTs", sceNpCppWebApiUnknown50); -int APS5_VABI sceNpCppWebApiUnknown50(void) { - NotImplemented_nid_no_patch("3bjEFf8OhTs"); - return 0; -} - -APS5_EXPORT("6FK4IOnANkc", sceNpCppWebApiUnknown51); -int APS5_VABI sceNpCppWebApiUnknown51(void) { - NotImplemented_nid_no_patch("6FK4IOnANkc"); - return 0; -} - -APS5_EXPORT("EJAOHYWUki4", sceNpCppWebApiUnknown52); -int APS5_VABI sceNpCppWebApiUnknown52(void) { - NotImplemented_nid_no_patch("EJAOHYWUki4"); - return 0; -} - -APS5_EXPORT("FlagLhjAEmc", sceNpCppWebApiUnknown53); -int APS5_VABI sceNpCppWebApiUnknown53(void) { - NotImplemented_nid_no_patch("FlagLhjAEmc"); - return 0; -} - -APS5_EXPORT("G3h-NDHnyW4", sceNpCppWebApiUnknown54); -int APS5_VABI sceNpCppWebApiUnknown54(void) { - NotImplemented_nid_no_patch("G3h-NDHnyW4"); - return 0; -} - -APS5_EXPORT("H0XjNhflED4", sceNpCppWebApiUnknown55); -int APS5_VABI sceNpCppWebApiUnknown55(void) { - NotImplemented_nid_no_patch("H0XjNhflED4"); - return 0; -} - -APS5_EXPORT("IbWx007Acn4", sceNpCppWebApiUnknown56); -int APS5_VABI sceNpCppWebApiUnknown56(void) { - NotImplemented_nid_no_patch("IbWx007Acn4"); - return 0; -} - -APS5_EXPORT("Is+nI7Hq9jU", sceNpCppWebApiUnknown57); -int APS5_VABI sceNpCppWebApiUnknown57(void) { - NotImplemented_nid_no_patch("Is+nI7Hq9jU"); - return 0; -} - -APS5_EXPORT("Kc4x2uy0FFk", sceNpCppWebApiUnknown58); -int APS5_VABI sceNpCppWebApiUnknown58(void) { - NotImplemented_nid_no_patch("Kc4x2uy0FFk"); - return 0; -} - -APS5_EXPORT("OK+Ggpve7B0", sceNpCppWebApiUnknown59); -int APS5_VABI sceNpCppWebApiUnknown59(void) { - NotImplemented_nid_no_patch("OK+Ggpve7B0"); - return 0; -} - -APS5_EXPORT("P3daBLFFREw", sceNpCppWebApiUnknown60); -int APS5_VABI sceNpCppWebApiUnknown60(void) { - NotImplemented_nid_no_patch("P3daBLFFREw"); - return 0; -} - -APS5_EXPORT("RZcseJ3THfY", sceNpCppWebApiUnknown61); -int APS5_VABI sceNpCppWebApiUnknown61(void) { - NotImplemented_nid_no_patch("RZcseJ3THfY"); - return 0; -} - -APS5_EXPORT("RbvteD35X-8", sceNpCppWebApiUnknown62); -int APS5_VABI sceNpCppWebApiUnknown62(void) { - NotImplemented_nid_no_patch("RbvteD35X-8"); - return 0; -} - -APS5_EXPORT("XCtf+23QT0k", sceNpCppWebApiUnknown63); -int APS5_VABI sceNpCppWebApiUnknown63(void) { - NotImplemented_nid_no_patch("XCtf+23QT0k"); - return 0; -} - -APS5_EXPORT("a4q15LI1a4E", sceNpCppWebApiUnknown64); -int APS5_VABI sceNpCppWebApiUnknown64(void) { - NotImplemented_nid_no_patch("a4q15LI1a4E"); - return 0; -} - -APS5_EXPORT("eT4TQB7OsLA", sceNpCppWebApiUnknown65); -int APS5_VABI sceNpCppWebApiUnknown65(void) { - NotImplemented_nid_no_patch("eT4TQB7OsLA"); - return 0; -} - -APS5_EXPORT("g2dEqFnhFuw", sceNpCppWebApiUnknown66); -int APS5_VABI sceNpCppWebApiUnknown66(void) { - NotImplemented_nid_no_patch("g2dEqFnhFuw"); - return 0; -} - -APS5_EXPORT("lPAMjFZEpt8", sceNpCppWebApiUnknown67); -int APS5_VABI sceNpCppWebApiUnknown67(void) { - NotImplemented_nid_no_patch("lPAMjFZEpt8"); - return 0; -} - -APS5_EXPORT("mBagn+lW-iM", sceNpCppWebApiUnknown68); -int APS5_VABI sceNpCppWebApiUnknown68(void) { - NotImplemented_nid_no_patch("mBagn+lW-iM"); - return 0; -} - -APS5_EXPORT("mkWsKEh0h0o", sceNpCppWebApiUnknown69); -int APS5_VABI sceNpCppWebApiUnknown69(void) { - NotImplemented_nid_no_patch("mkWsKEh0h0o"); - return 0; -} - -APS5_EXPORT("nE0ooeCMRm8", sceNpCppWebApiUnknown70); -int APS5_VABI sceNpCppWebApiUnknown70(void) { - NotImplemented_nid_no_patch("nE0ooeCMRm8"); - return 0; -} - -APS5_EXPORT("qf2I9BlKXis", sceNpCppWebApiUnknown71); -int APS5_VABI sceNpCppWebApiUnknown71(void) { - NotImplemented_nid_no_patch("qf2I9BlKXis"); - return 0; -} - -APS5_EXPORT("xwy1I52dE8o", sceNpCppWebApiUnknown72); -int APS5_VABI sceNpCppWebApiUnknown72(void) { - NotImplemented_nid_no_patch("xwy1I52dE8o"); - return 0; -} -} diff --git a/core/libs/prx/libcohtml/CMakeLists.txt b/core/libs/prx/libcohtml/CMakeLists.txt deleted file mode 100644 index 842799d34..000000000 --- a/core/libs/prx/libcohtml/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_library(libcohtml SHARED EXCLUDE_FROM_ALL - ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp -) -target_include_directories(libcohtml PRIVATE ${LIBS_INCLUDE_DIR}) -set_target_properties(libcohtml PROPERTIES CXX_EXTENSIONS OFF) -configure_windows_unwind(libcohtml) diff --git a/core/libs/prx/libcohtml/DEPLOY.md b/core/libs/prx/libcohtml/DEPLOY.md deleted file mode 100644 index 0b4cbdc5d..000000000 --- a/core/libs/prx/libcohtml/DEPLOY.md +++ /dev/null @@ -1,16 +0,0 @@ -# libcohtml — deploy note - -Game `DT_NEEDED` expects exactly: `libcohtml.Prospero.prx`. - -Copy next to the relinked eboot (same directory): - -- `build/core/libs/libs/libcohtml.Prospero.prx` (patched build output, 50 NIDs) — required. -- `libgcc_s_seh-1.dll`, `libstdc++-6.dll`, `libwinpthread-1.dll` from `winlibs-gcc15/mingw64/bin` — required on Windows (see [technical debt](../../../../docs/dev/TechnicalDebt.md)). - -Do NOT deploy: - -- `libcohtml.prx` (build intermediate kept for the NID-patch pipeline, wrong `DT_NEEDED` name). -- Anything under `build/core/libs/libs/unpatched/` (NIDs not patched). -- `libc.prx` / `libkernel.prx` are not runtime imports of this module (no such DLL dependency); the game may need its other modules separately (out of scope). - -Scope: raw-NID stubs only; real Cohtml rendering stays out of scope. diff --git a/core/libs/prx/libcohtml/Export.cpp b/core/libs/prx/libcohtml/Export.cpp deleted file mode 100644 index 4ae1996b4..000000000 --- a/core/libs/prx/libcohtml/Export.cpp +++ /dev/null @@ -1,307 +0,0 @@ -#include -#include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" - -extern "C" { - -APS5_EXPORT("1fOA53oGwU8", cohtml_stub_00); -std::uint64_t APS5_VABI cohtml_stub_00(void) { - NotImplemented_nid_no_patch("1fOA53oGwU8"); - return 0; -} - -APS5_EXPORT("2vxXHkZlhbw", cohtml_stub_01); -std::uint64_t APS5_VABI cohtml_stub_01(void) { - NotImplemented_nid_no_patch("2vxXHkZlhbw"); - return 0; -} - -APS5_EXPORT("3rew70M0SmY", cohtml_stub_02); -std::uint64_t APS5_VABI cohtml_stub_02(void) { - NotImplemented_nid_no_patch("3rew70M0SmY"); - return 0; -} - -APS5_EXPORT("4Le0SBPvnF8", cohtml_stub_03); -std::uint64_t APS5_VABI cohtml_stub_03(void) { - NotImplemented_nid_no_patch("4Le0SBPvnF8"); - return 0; -} - -APS5_EXPORT("53ZTBeo2a54", cohtml_stub_04); -std::uint64_t APS5_VABI cohtml_stub_04(void) { - NotImplemented_nid_no_patch("53ZTBeo2a54"); - return 0; -} - -APS5_EXPORT("6PaNuQipllM", cohtml_stub_05); -std::uint64_t APS5_VABI cohtml_stub_05(void) { - NotImplemented_nid_no_patch("6PaNuQipllM"); - return 0; -} - -APS5_EXPORT("7hn5DAs2bLk", cohtml_stub_06); -std::uint64_t APS5_VABI cohtml_stub_06(void) { - NotImplemented_nid_no_patch("7hn5DAs2bLk"); - return 0; -} - -APS5_EXPORT("8EYWdAM2-R0", cohtml_stub_07); -std::uint64_t APS5_VABI cohtml_stub_07(void) { - NotImplemented_nid_no_patch("8EYWdAM2-R0"); - return 0; -} - -APS5_EXPORT("9bGvfp1zbKo", cohtml_stub_08); -std::uint64_t APS5_VABI cohtml_stub_08(void) { - NotImplemented_nid_no_patch("9bGvfp1zbKo"); - return 0; -} - -APS5_EXPORT("a4E5dJh0onE", cohtml_stub_09); -std::uint64_t APS5_VABI cohtml_stub_09(void) { - NotImplemented_nid_no_patch("a4E5dJh0onE"); - return 0; -} - -APS5_EXPORT("BhL-ZtSHmB8", cohtml_stub_10); -std::uint64_t APS5_VABI cohtml_stub_10(void) { - NotImplemented_nid_no_patch("BhL-ZtSHmB8"); - return 0; -} - -APS5_EXPORT("blvwzOvsEAA", cohtml_stub_11); -std::uint64_t APS5_VABI cohtml_stub_11(void) { - NotImplemented_nid_no_patch("blvwzOvsEAA"); - return 0; -} - -APS5_EXPORT("dko-cMqv5yw", cohtml_stub_12); -std::uint64_t APS5_VABI cohtml_stub_12(void) { - NotImplemented_nid_no_patch("dko-cMqv5yw"); - return 0; -} - -APS5_EXPORT("EG4kqkxLU3Q", cohtml_stub_13); -std::uint64_t APS5_VABI cohtml_stub_13(void) { - NotImplemented_nid_no_patch("EG4kqkxLU3Q"); - return 0; -} - -APS5_EXPORT("-El4B0xJF2U", cohtml_stub_14); -std::uint64_t APS5_VABI cohtml_stub_14(void) { - NotImplemented_nid_no_patch("-El4B0xJF2U"); - return 0; -} - -APS5_EXPORT("EMhQNylkSwk", cohtml_stub_15); -std::uint64_t APS5_VABI cohtml_stub_15(void) { - NotImplemented_nid_no_patch("EMhQNylkSwk"); - return 0; -} - -APS5_EXPORT("-eNSKAypRz0", cohtml_stub_16); -std::uint64_t APS5_VABI cohtml_stub_16(void) { - NotImplemented_nid_no_patch("-eNSKAypRz0"); - return 0; -} - -APS5_EXPORT("FG9VRZfson0", cohtml_stub_17); -std::uint64_t APS5_VABI cohtml_stub_17(void) { - NotImplemented_nid_no_patch("FG9VRZfson0"); - return 0; -} - -APS5_EXPORT("fNvtExaHN4U", cohtml_stub_18); -std::uint64_t APS5_VABI cohtml_stub_18(void) { - NotImplemented_nid_no_patch("fNvtExaHN4U"); - return 0; -} - -APS5_EXPORT("g10DkPARoa8", cohtml_stub_19); -std::uint64_t APS5_VABI cohtml_stub_19(void) { - NotImplemented_nid_no_patch("g10DkPARoa8"); - return 0; -} - -APS5_EXPORT("gwQczxoDmG0", cohtml_stub_20); -std::uint64_t APS5_VABI cohtml_stub_20(void) { - NotImplemented_nid_no_patch("gwQczxoDmG0"); - return 0; -} - -APS5_EXPORT("HQF4O9D+Di4", cohtml_stub_21); -std::uint64_t APS5_VABI cohtml_stub_21(void) { - NotImplemented_nid_no_patch("HQF4O9D+Di4"); - return 0; -} - -APS5_EXPORT("igt3a6Q0VMc", cohtml_stub_22); -std::uint64_t APS5_VABI cohtml_stub_22(void) { - NotImplemented_nid_no_patch("igt3a6Q0VMc"); - return 0; -} - -APS5_EXPORT("kyApuhEHHxQ", cohtml_stub_23); -std::uint64_t APS5_VABI cohtml_stub_23(void) { - NotImplemented_nid_no_patch("kyApuhEHHxQ"); - return 0; -} - -APS5_EXPORT("Ljp75QXUi7s", cohtml_stub_24); -std::uint64_t APS5_VABI cohtml_stub_24(void) { - NotImplemented_nid_no_patch("Ljp75QXUi7s"); - return 0; -} - -APS5_EXPORT("loJ5Ef3MZrs", cohtml_stub_25); -std::uint64_t APS5_VABI cohtml_stub_25(void) { - NotImplemented_nid_no_patch("loJ5Ef3MZrs"); - return 0; -} - -APS5_EXPORT("LWe+u8SHKgU", cohtml_stub_26); -std::uint64_t APS5_VABI cohtml_stub_26(void) { - NotImplemented_nid_no_patch("LWe+u8SHKgU"); - return 0; -} - -APS5_EXPORT("nhn1ds+I2t4", cohtml_stub_27); -std::uint64_t APS5_VABI cohtml_stub_27(void) { - NotImplemented_nid_no_patch("nhn1ds+I2t4"); - return 0; -} - -APS5_EXPORT("NmVsRWgsKt4", cohtml_stub_28); -std::uint64_t APS5_VABI cohtml_stub_28(void) { - NotImplemented_nid_no_patch("NmVsRWgsKt4"); - return 0; -} - -APS5_EXPORT("ONEnhMinebs", cohtml_stub_29); -std::uint64_t APS5_VABI cohtml_stub_29(void) { - NotImplemented_nid_no_patch("ONEnhMinebs"); - return 0; -} - -APS5_EXPORT("PdOmR8dy1fM", cohtml_stub_30); -std::uint64_t APS5_VABI cohtml_stub_30(void) { - NotImplemented_nid_no_patch("PdOmR8dy1fM"); - return 0; -} - -APS5_EXPORT("PSwGBN5Icv8", cohtml_stub_31); -std::uint64_t APS5_VABI cohtml_stub_31(void) { - NotImplemented_nid_no_patch("PSwGBN5Icv8"); - return 0; -} - -APS5_EXPORT("RalyfwiTt8o", cohtml_stub_32); -std::uint64_t APS5_VABI cohtml_stub_32(void) { - NotImplemented_nid_no_patch("RalyfwiTt8o"); - return 0; -} - -APS5_EXPORT("t+OHUjVWIwU", cohtml_stub_33); -std::uint64_t APS5_VABI cohtml_stub_33(void) { - NotImplemented_nid_no_patch("t+OHUjVWIwU"); - return 0; -} - -APS5_EXPORT("Ter8YCVZ9tQ", cohtml_stub_34); -std::uint64_t APS5_VABI cohtml_stub_34(void) { - NotImplemented_nid_no_patch("Ter8YCVZ9tQ"); - return 0; -} - -APS5_EXPORT("tG3LJfAOH3k", cohtml_stub_35); -std::uint64_t APS5_VABI cohtml_stub_35(void) { - NotImplemented_nid_no_patch("tG3LJfAOH3k"); - return 0; -} - -APS5_EXPORT("ukSFhKPmCTg", cohtml_stub_36); -std::uint64_t APS5_VABI cohtml_stub_36(void) { - NotImplemented_nid_no_patch("ukSFhKPmCTg"); - return 0; -} - -APS5_EXPORT("V7KGze2XjJc", cohtml_stub_37); -std::uint64_t APS5_VABI cohtml_stub_37(void) { - NotImplemented_nid_no_patch("V7KGze2XjJc"); - return 0; -} - -APS5_EXPORT("vlmAvJqR7mQ", cohtml_stub_38); -std::uint64_t APS5_VABI cohtml_stub_38(void) { - NotImplemented_nid_no_patch("vlmAvJqR7mQ"); - return 0; -} - -APS5_EXPORT("VzhxjXDzYSI", cohtml_stub_39); -std::uint64_t APS5_VABI cohtml_stub_39(void) { - NotImplemented_nid_no_patch("VzhxjXDzYSI"); - return 0; -} - -APS5_EXPORT("X3FzDPzpD2Y", cohtml_stub_40); -std::uint64_t APS5_VABI cohtml_stub_40(void) { - NotImplemented_nid_no_patch("X3FzDPzpD2Y"); - return 0; -} - -APS5_EXPORT("x68HPh+vxsE", cohtml_stub_41); -std::uint64_t APS5_VABI cohtml_stub_41(void) { - NotImplemented_nid_no_patch("x68HPh+vxsE"); - return 0; -} - -APS5_EXPORT("XUe8OAKB-vQ", cohtml_stub_42); -std::uint64_t APS5_VABI cohtml_stub_42(void) { - NotImplemented_nid_no_patch("XUe8OAKB-vQ"); - return 0; -} - -APS5_EXPORT("y6UNQtnr0wY", cohtml_stub_43); -std::uint64_t APS5_VABI cohtml_stub_43(void) { - NotImplemented_nid_no_patch("y6UNQtnr0wY"); - return 0; -} - -APS5_EXPORT("YoHAXkBV06c", cohtml_stub_44); -std::uint64_t APS5_VABI cohtml_stub_44(void) { - NotImplemented_nid_no_patch("YoHAXkBV06c"); - return 0; -} - -APS5_EXPORT("Z9XFJCfmId4", cohtml_stub_45); -std::uint64_t APS5_VABI cohtml_stub_45(void) { - NotImplemented_nid_no_patch("Z9XFJCfmId4"); - return 0; -} - -APS5_EXPORT("zEniuuzG2W0", cohtml_stub_46); -std::uint64_t APS5_VABI cohtml_stub_46(void) { - NotImplemented_nid_no_patch("zEniuuzG2W0"); - return 0; -} - -APS5_EXPORT("zH9Z2nK1fmA", cohtml_stub_47); -std::uint64_t APS5_VABI cohtml_stub_47(void) { - NotImplemented_nid_no_patch("zH9Z2nK1fmA"); - return 0; -} - -APS5_EXPORT("ZHGgdWeYTo8", cohtml_stub_48); -std::uint64_t APS5_VABI cohtml_stub_48(void) { - NotImplemented_nid_no_patch("ZHGgdWeYTo8"); - return 0; -} - -APS5_EXPORT("ZWftPxZ4E6k", cohtml_stub_49); -std::uint64_t APS5_VABI cohtml_stub_49(void) { - NotImplemented_nid_no_patch("ZWftPxZ4E6k"); - return 0; -} - -} diff --git a/core/libs/prx/libfmod/CMakeLists.txt b/core/libs/prx/libfmod/CMakeLists.txt deleted file mode 100644 index 5d1cb47f7..000000000 --- a/core/libs/prx/libfmod/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -add_library(libfmod SHARED EXCLUDE_FROM_ALL - ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp -) - -target_include_directories(libfmod PRIVATE - ${LIBS_INCLUDE_DIR} - ${CMAKE_SOURCE_DIR}/3rdparty/SDL2/include -) -target_link_libraries(libfmod PRIVATE libkernel libc SDL2-static) -target_compile_options(libfmod PRIVATE -fkeep-inline-functions) -configure_windows_unwind(libfmod) diff --git a/core/libs/prx/libfmod/Export.cpp b/core/libs/prx/libfmod/Export.cpp deleted file mode 100644 index bd7545a64..000000000 --- a/core/libs/prx/libfmod/Export.cpp +++ /dev/null @@ -1,1902 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" -#include "SDL.h" - -// FMOD_MODE bits (subset, from fmod_common.h) — used to detect memory buffers. -constexpr unsigned FMOD_LOOP_OFF = 0x00000001u; -constexpr unsigned FMOD_LOOP_NORMAL = 0x00000002u; -constexpr unsigned FMOD_LOOP_BIDI = 0x00000004u; -constexpr unsigned FMOD_2D_FLAG = 0x00000008u; -constexpr unsigned FMOD_3D_FLAG = 0x00000010u; -constexpr unsigned FMOD_CREATESTREAM_FLAG = 0x00000080u; -constexpr unsigned FMOD_OPENMEMORY_FLAG = 0x00000800u; -constexpr unsigned FMOD_OPENMEMORY_POINT_FLAG = 0x10000000u; -constexpr unsigned FMOD_OPENRAW_FLAG = 0x00001000u; -constexpr unsigned FMOD_NONBLOCKING_FLAG = 0x00010000u; - -enum FMOD_OUTPUTTYPE { - FMOD_OUTPUTTYPE_AUTODETECT = 0, - FMOD_OUTPUTTYPE_UNKNOWN = 1, - FMOD_OUTPUTTYPE_NOSOUND = 2, - FMOD_OUTPUTTYPE_WAVWRITER = 3, - FMOD_OUTPUTTYPE_NOSOUND_NRT = 4, - FMOD_OUTPUTTYPE_WAVWRITER_NRT = 5, - FMOD_OUTPUTTYPE_WASAPI = 6, - FMOD_OUTPUTTYPE_ASIO = 7, - FMOD_OUTPUTTYPE_PULSEAUDIO = 8, - FMOD_OUTPUTTYPE_ALSA = 9, - FMOD_OUTPUTTYPE_COREAUDIO = 10, - FMOD_OUTPUTTYPE_AUDIOTRACK = 11, - FMOD_OUTPUTTYPE_OPENSL = 12, - FMOD_OUTPUTTYPE_AUDIOOUT = 13, - FMOD_OUTPUTTYPE_AUDIO3D = 14, - FMOD_OUTPUTTYPE_MAX = 15 -}; - -enum FMOD_SPEAKERMODE { - FMOD_SPEAKERMODE_DEFAULT = 0, - FMOD_SPEAKERMODE_RAW = 1, - FMOD_SPEAKERMODE_MONO = 2, - FMOD_SPEAKERMODE_STEREO = 3, - FMOD_SPEAKERMODE_QUAD = 4, - FMOD_SPEAKERMODE_SURROUND = 5, - FMOD_SPEAKERMODE_5POINT1 = 6, - FMOD_SPEAKERMODE_7POINT1 = 7, - FMOD_SPEAKERMODE_7POINT1POINT4 = 8, - FMOD_SPEAKERMODE_MAX = 9 -}; - -enum FMOD_SOUND_TYPE { - FMOD_SOUND_TYPE_UNKNOWN = 0, - FMOD_SOUND_TYPE_AIFF = 1, - FMOD_SOUND_TYPE_ASF = 2, - FMOD_SOUND_TYPE_DLS = 3, - FMOD_SOUND_TYPE_FLAC = 4, - FMOD_SOUND_TYPE_FSB = 5, - FMOD_SOUND_TYPE_IT = 6, - FMOD_SOUND_TYPE_MIDI = 7, - FMOD_SOUND_TYPE_MOD = 8, - FMOD_SOUND_TYPE_MPEG = 9, - FMOD_SOUND_TYPE_OGGVORBIS = 10, - FMOD_SOUND_TYPE_PLAYLIST = 11, - FMOD_SOUND_TYPE_RAW = 12, - FMOD_SOUND_TYPE_S3M = 13, - FMOD_SOUND_TYPE_USER = 14, - FMOD_SOUND_TYPE_XM = 15, - FMOD_SOUND_TYPE_XMA = 16, - FMOD_SOUND_TYPE_AUDIOQUEUE = 17, - FMOD_SOUND_TYPE_AT9 = 18, - FMOD_SOUND_TYPE_VB = 19, - FMOD_SOUND_TYPE_MAX = 20 -}; - -enum FMOD_SOUND_FORMAT { - FMOD_SOUND_FORMAT_NONE = 0, - FMOD_SOUND_FORMAT_PCM8 = 1, - FMOD_SOUND_FORMAT_PCM16 = 2, - FMOD_SOUND_FORMAT_PCM24 = 3, - FMOD_SOUND_FORMAT_PCM32 = 4, - FMOD_SOUND_FORMAT_PCMFLOAT = 5, - FMOD_SOUND_FORMAT_BITSTREAM = 6, - FMOD_SOUND_FORMAT_MAX = 7 -}; - -enum FMOD_OPENSTATE { - FMOD_OPENSTATE_READY = 0, - FMOD_OPENSTATE_LOADING = 1, - FMOD_OPENSTATE_ERROR = 2, - FMOD_OPENSTATE_CONNECTING = 3, - FMOD_OPENSTATE_BUFFERING = 4, - FMOD_OPENSTATE_SEEKING = 5, - FMOD_OPENSTATE_PLAYING = 6, - FMOD_OPENSTATE_SETPOSITION = 7, - FMOD_OPENSTATE_MAX = 8 -}; - -enum FMOD_SOUNDGROUP_BEHAVIOR { - FMOD_SOUNDGROUP_BEHAVIOR_FAIL = 0, - FMOD_SOUNDGROUP_BEHAVIOR_MUTE = 1, - FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST = 2, - FMOD_SOUNDGROUP_BEHAVIOR_MAX = 3 -}; - -enum FMOD_DSP_TYPE { - FMOD_DSP_TYPE_UNKNOWN = 0, - FMOD_DSP_TYPE_MIXER = 1, - FMOD_DSP_TYPE_OSCILLATOR = 2, - FMOD_DSP_TYPE_LOWPASS = 3, - FMOD_DSP_TYPE_ITLOWPASS = 4, - FMOD_DSP_TYPE_HIGHPASS = 5, - FMOD_DSP_TYPE_ECHO = 6, - FMOD_DSP_TYPE_FADER = 7, - FMOD_DSP_TYPE_FLANGE = 8, - FMOD_DSP_TYPE_DISTORTION = 9, - FMOD_DSP_TYPE_NORMALIZE = 10, - FMOD_DSP_TYPE_LIMITER = 11, - FMOD_DSP_TYPE_PARAMEQ = 12, - FMOD_DSP_TYPE_PITCHSHIFT = 13, - FMOD_DSP_TYPE_CHORUS = 14, - FMOD_DSP_TYPE_VSTPLUGIN = 15, - FMOD_DSP_TYPE_WINAMPPLUGIN = 16, - FMOD_DSP_TYPE_ITECHO = 17, - FMOD_DSP_TYPE_COMPRESSOR = 18, - FMOD_DSP_TYPE_SFXREVERB = 19, - FMOD_DSP_TYPE_LOWPASS_SIMPLE = 20, - FMOD_DSP_TYPE_DELAY = 21, - FMOD_DSP_TYPE_TREMOLO = 22, - FMOD_DSP_TYPE_SEND = 24, - FMOD_DSP_TYPE_RETURN = 25, - FMOD_DSP_TYPE_HIGHPASS_SIMPLE = 26, - FMOD_DSP_TYPE_PAN = 27, - FMOD_DSP_TYPE_THREE_EQ = 28, - FMOD_DSP_TYPE_FFT = 29, - FMOD_DSP_TYPE_LOUDNESS_METER = 30, - FMOD_DSP_TYPE_ENVELOPEFOLLOWER = 31, - FMOD_DSP_TYPE_CONVOLUTIONREVERB = 32, - FMOD_DSP_TYPE_TRANSCEIVER = 33, - FMOD_DSP_TYPE_MAX = 34 -}; - -enum FMOD_DSPCONNECTION_TYPE { - FMOD_DSPCONNECTION_TYPE_STANDARD = 0, - FMOD_DSPCONNECTION_TYPE_SIDECHAIN = 1, - FMOD_DSPCONNECTION_TYPE_SEND = 2, - FMOD_DSPCONNECTION_TYPE_SEND_SIDECHAIN = 3, - FMOD_DSPCONNECTION_TYPE_MAX = 4 -}; - -enum FMOD_DSP_FFT_WINDOW { - FMOD_DSP_FFT_WINDOW_RECT = 0, - FMOD_DSP_FFT_WINDOW_TRIANGLE = 1, - FMOD_DSP_FFT_WINDOW_HAMMING = 2, - FMOD_DSP_FFT_WINDOW_HANNING = 3, - FMOD_DSP_FFT_WINDOW_BLACKMAN = 4, - FMOD_DSP_FFT_WINDOW_BLACKMANHARRIS = 5, - FMOD_DSP_FFT_WINDOW_MAX = 6 -}; - -enum FMOD_PLUGINTYPE { - FMOD_PLUGINTYPE_OUTPUT = 0, - FMOD_PLUGINTYPE_CODEC = 1, - FMOD_PLUGINTYPE_DSP = 2, - FMOD_PLUGINTYPE_MAX = 3 -}; - -enum FMOD_DRIVER_STATE { - FMOD_DRIVER_STATE_CONNECTED = 1, - FMOD_DRIVER_STATE_DEFAULT = 2 -}; - -enum FMOD_PORT_TYPE { - FMOD_PORT_TYPE_MUSIC = 0, - FMOD_PORT_TYPE_COPY = 1, - FMOD_PORT_TYPE_SPLIT = 2, - FMOD_PORT_TYPE_FEEDBACK = 3, - FMOD_PORT_TYPE_MAX = 4 -}; - -enum FMOD_SYSTEM_CALLBACK_TYPE { - FMOD_SYSTEM_CALLBACK_DEVICELISTCHANGED = 1, - FMOD_SYSTEM_CALLBACK_DEVICELOST = 2, - FMOD_SYSTEM_CALLBACK_MEMORYALLOCATIONFAILED = 4, - FMOD_SYSTEM_CALLBACK_THREADCREATED = 8, - FMOD_SYSTEM_CALLBACK_BADDSPCONNECTION = 16, - FMOD_SYSTEM_CALLBACK_PREMIX = 32, - FMOD_SYSTEM_CALLBACK_POSTMIX = 64, - FMOD_SYSTEM_CALLBACK_ERROR = 128, - FMOD_SYSTEM_CALLBACK_MIDMIX = 256, - FMOD_SYSTEM_CALLBACK_THREADDESTROYED = 512, - FMOD_SYSTEM_CALLBACK_PREUPDATE = 1024, - FMOD_SYSTEM_CALLBACK_POSTUPDATE = 2048, - FMOD_SYSTEM_CALLBACK_ALL = 0xFFFFFFFF -}; - -enum FMOD_CHANNELCONTROL_TYPE { - FMOD_CHANNELCONTROL_CHANNEL = 0, - FMOD_CHANNELCONTROL_CHANNELGROUP = 1, - FMOD_CHANNELCONTROL_MAX = 2 -}; - -enum FMOD_CHANNELCONTROL_CALLBACK_TYPE { - FMOD_CHANNELCONTROL_CALLBACK_END = 0, - FMOD_CHANNELCONTROL_CALLBACK_VIRTUALVOICE = 1, - FMOD_CHANNELCONTROL_CALLBACK_SYNCPOINT = 2, - FMOD_CHANNELCONTROL_CALLBACK_OCCLUSION = 3, - FMOD_CHANNELCONTROL_CALLBACK_MAX = 4 -}; - -enum FMOD_TAGTYPE { - FMOD_TAGTYPE_UNKNOWN = 0, - FMOD_TAGTYPE_ID3V1 = 1, - FMOD_TAGTYPE_ID3V2 = 2, - FMOD_TAGTYPE_VORBISCOMMENT = 3, - FMOD_TAGTYPE_SHOUTCAST = 4, - FMOD_TAGTYPE_ICECAST = 5, - FMOD_TAGTYPE_ASF = 6, - FMOD_TAGTYPE_MIDI = 7, - FMOD_TAGTYPE_PLAYLIST = 8, - FMOD_TAGTYPE_FMOD = 9, - FMOD_TAGTYPE_USER = 10, - FMOD_TAGTYPE_MAX = 11 -}; - -enum FMOD_TAGDATATYPE { - FMOD_TAGDATATYPE_BINARY = 0, - FMOD_TAGDATATYPE_INT = 1, - FMOD_TAGDATATYPE_FLOAT = 2, - FMOD_TAGDATATYPE_STRING = 3, - FMOD_TAGDATATYPE_STRING_UTF16 = 4, - FMOD_TAGDATATYPE_STRING_UTF16BE = 5, - FMOD_TAGDATATYPE_STRING_UTF8 = 6, - FMOD_TAGDATATYPE_CDTOC = 7, - FMOD_TAGDATATYPE_MAX = 8 -}; - -struct FMOD_GUID { - unsigned Data1; - unsigned short Data2; - unsigned short Data3; - unsigned char Data4[8]; -}; - -struct FMOD_VECTOR { - float x; - float y; - float z; -}; - -struct FMOD_3D_ATTRIBUTES { - FMOD_VECTOR position; - FMOD_VECTOR velocity; - FMOD_VECTOR forward; - FMOD_VECTOR up; -}; - -struct FMOD_CREATESOUNDEXINFO { - int cbsize; - unsigned length; - unsigned fileoffset; - int numchannels; - int defaultfrequency; - FMOD_SOUND_FORMAT format; - unsigned decodebuffersize; - int initialsubsound; - int numsubsounds; - void* inclusionlist; - unsigned inclusionlistnum; - unsigned char dlsrawdata[8]; - char* encryptionkey; -}; - -struct FMOD_REVERB_PROPERTIES { - int Instance; - float Environment; - float EnvSize; - float EnvDiffusion; - int Room; - int RoomHF; - int RoomLF; - float DecayTime; - float DecayHFRatio; - float DecayLFRatio; - int Reflections; - float ReflectionsDelay; - int Reverb; - float ReverbDelay; - float EchoTime; - float EchoDepth; - float ModulationTime; - float ModulationDepth; - float AirAbsorptionHF; - float HFReference; - float LFReference; - float RoomRolloffFactor; - float Diffusion; - float Density; - unsigned Flags; -}; - -struct FMOD_ADVANCEDSETTINGS { - int cbSize; - unsigned maxMPEGCodecs; - unsigned maxADPCMCodecs; - unsigned maxXMACodecs; - unsigned maxVorbisCodecs; - unsigned maxAT9Codecs; - unsigned maxFADPCMCodecs; - unsigned maxPCMCodecs; - unsigned ASIONumChannels; - char* ASIOChannelList; - char* ASIOSpeakerList; - float vol0virtualvol; - unsigned defaultDecodeBufferSize; - unsigned short profilePort; - unsigned geometryMaxFadeTime; - float distanceFilterCenterFreq; - int reverb3Dinstance; - unsigned DSPBufferPoolSize; - unsigned stackSizeStream; - unsigned stackSizeNonBlocking; - unsigned stackSizeMixer; - int resamplerMethod; - unsigned commandQueueSize; - unsigned handleInitialSize; -}; - -struct FMOD_CPU_USAGE { - float dsp; - float stream; - float geometry; - float update; - float convolution1; - float convolution2; -}; - -struct FMOD_TAG { - FMOD_TAGTYPE type; - FMOD_TAGDATATYPE datatype; - char* name; - void* data; - unsigned datalen; - bool updated; -}; - -struct FMOD_SYNC_POINT { - void* opaque; -}; - -struct FMOD_DSP_DESCRIPTION { - unsigned pluginsdkversion; - char name[32]; - unsigned version; - int numinputbuffers; - int numoutputbuffers; - void* create; - void* release; - void* reset; - void* read; - void* process; - void* setposition; - int numparameters; - void* paramdesc; - void* setparameterfloat; - void* setparameterint; - void* setparameterbool; - void* setparameterdata; - void* getparameterfloat; - void* getparameterint; - void* getparameterbool; - void* getparameterdata; - void* shouldiprocess; - void* userdata; - void* sys_register; - void* sys_deregister; - void* sys_mix; -}; - -struct FMOD_DSP_PARAMETER_DESC { - int type; - char name[16]; - char label[16]; - char* description; -}; - -struct FMOD_DSP_METERING_INFO { - int numsamples; - float peaklevel[32]; - float rmslevel[32]; - short numchannels; -}; - -struct FMOD_DSP_BUFFER_ARRAY { - int numbuffers; - int* buffernumchannels; - int* bufferchannelmask; - float** buffers; - FMOD_SPEAKERMODE speakermode; -}; - -struct FMOD_DSP_STATE { - void* instance; - void* plugindata; - int channelmask; - FMOD_SPEAKERMODE source_speakermode; - float* sidechaindata; - int sidechainchannels; - void* callbacks; - int systemobject; -}; - -struct FMOD_SYSTEM { - int unused; -}; - -struct FMOD_CHANNELCONTROL { - int unused; -}; - -struct FMOD_CHANNELGROUP { - int unused; -}; - -typedef int (*FMOD_SYSTEM_CALLBACK)(FMOD_SYSTEM* system, FMOD_SYSTEM_CALLBACK_TYPE type, void* commanddata1, void* commanddata2, void* userdata); -typedef int (*FMOD_CHANNELCONTROL_CALLBACK)(FMOD_CHANNELCONTROL* channelcontrol, FMOD_CHANNELCONTROL_TYPE controltype, FMOD_CHANNELCONTROL_CALLBACK_TYPE callbacktype, void* commanddata1, void* commanddata2); - -namespace { - -std::mutex gFmodMutex; - -constexpr int FMOD_OK = 0; -constexpr unsigned FMOD_VERSION_CURRENT = 0x00020206; - -// ---- Real-audio backend (SDL queue, mirrors libSceAudioOut) ---- -// Silent fallback is kept via ANYPS5_FMOD_SILENT=1 or NOSOUND output type -// or when SDL cannot be opened. When silent, update() is a no-op and -// isPlaying() keeps the previous sticky behaviour so the old smoke test -// (playSound(nullptr) -> playing==true) still passes. -constexpr int kFmodOutRate = 48000; -constexpr int kFmodOutCh = 2; -constexpr int kFmodMixFrames = 1024; - -static SDL_AudioDeviceID gFmodDevice = 0; -static SDL_AudioSpec gFmodSpec = {}; -static bool gFmodSdlTried = false; -static bool gFmodSilent = false; - -static bool FmodSilentRequested() { - const char* s = std::getenv("ANYPS5_FMOD_SILENT"); - if (s && (s[0] == '1' || s[0] == 'y' || s[0] == 'Y')) return true; - s = std::getenv("ANYPS5_FMOD_NOSOUND"); - if (s && (s[0] == '1' || s[0] == 'y' || s[0] == 'Y')) return true; - return false; -} - -static bool FmodEnsureDevice() { - if (gFmodDevice != 0) return true; - if (gFmodSdlTried) return gFmodDevice != 0; - gFmodSdlTried = true; - if (FmodSilentRequested()) { - gFmodSilent = true; - return false; - } - if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { - gFmodSilent = true; - return false; - } - SDL_AudioSpec desired{}; - desired.freq = kFmodOutRate; - desired.format = AUDIO_F32SYS; - desired.channels = static_cast(kFmodOutCh); - desired.samples = 1024; - desired.callback = nullptr; - SDL_AudioSpec obtained{}; - gFmodDevice = SDL_OpenAudioDevice(nullptr, 0, &desired, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE); - if (gFmodDevice == 0) { - gFmodSilent = true; - return false; - } - gFmodSpec = obtained; - SDL_PauseAudioDevice(gFmodDevice, 0); - return true; -} - -static void FmodMakeSine(std::vector& out, int rate, int ch, float freqHz, float seconds) { - const size_t frames = static_cast(rate * seconds); - out.resize(frames * static_cast(ch)); - const float phaseInc = 2.0f * 3.14159265358979323846f * freqHz / static_cast(rate); - float phase = 0.0f; - for (size_t f = 0; f < frames; f++) { - const float s = std::sin(phase) * 0.25f; - phase += phaseInc; - for (int c = 0; c < ch; c++) out[f * static_cast(ch) + static_cast(c)] = s; - } -} - -// Minimal WAV (RIFF/WAVE) parser -> float stereo 48k. Returns false if not WAV. -static bool FmodParseWav(const uint8_t* data, size_t len, std::vector& outPcm, int& outRate, int& outCh) { - if (len < 44 || std::memcmp(data, "RIFF", 4) != 0 || std::memcmp(data + 8, "WAVE", 4) != 0) return false; - uint16_t audioFmt = 0, numCh = 0, bitsPerSample = 0; - uint32_t sampleRate = 0; - const uint8_t* snd = nullptr; - size_t sndLen = 0; - size_t off = 12; - auto rd16 = [](const uint8_t* p) -> uint16_t { return static_cast(p[0] | (p[1] << 8)); }; - auto rd32 = [](const uint8_t* p) -> uint32_t { return static_cast(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)); }; - while (off + 8 <= len) { - const uint8_t* chunk = data + off; - uint32_t chunkLen = rd32(chunk + 4); - if (off + 8 + chunkLen > len) break; - if (std::memcmp(chunk, "fmt ", 4) == 0 && chunkLen >= 16) { - audioFmt = rd16(chunk + 8); - numCh = rd16(chunk + 10); - sampleRate = rd32(chunk + 12); - bitsPerSample = rd16(chunk + 22); - } else if (std::memcmp(chunk, "data", 4) == 0) { - snd = chunk + 8; - sndLen = chunkLen; - } - off += 8 + ((chunkLen + 1) & ~static_cast(1)); - } - if (!snd || sndLen == 0 || numCh == 0 || sampleRate == 0) return false; - if (audioFmt != 1 && audioFmt != 3) return false; // PCM or FLOAT - int bytesPerSamp = bitsPerSample / 8; - if (bytesPerSamp <= 0) return false; - size_t frames = sndLen / (static_cast(numCh) * static_cast(bytesPerSamp)); - if (frames == 0) return false; - if (frames > 48000u * 30u) frames = 48000u * 30u; // cap 30s - std::vector tmp; - tmp.reserve(frames * 2); - for (size_t f = 0; f < frames; f++) { - float l = 0.0f, r = 0.0f; - for (int c = 0; c < numCh && c < 8; c++) { - const uint8_t* p = snd + (f * numCh + c) * bytesPerSamp; - float s = 0.0f; - if (audioFmt == 1) { - if (bitsPerSample == 8) s = (static_cast(p[0]) - 128) / 128.0f; - else if (bitsPerSample == 16) { int16_t v; std::memcpy(&v, p, 2); s = v / 32768.0f; } - else if (bitsPerSample == 24) { int32_t v = (p[0] | (p[1] << 8) | (p[2] << 16)); if (v & 0x800000) v |= ~0xFFFFFF; s = v / 8388608.0f; } - else if (bitsPerSample == 32) { int32_t v; std::memcpy(&v, p, 4); s = v / 2147483648.0f; } - else return false; - } else { - if (bitsPerSample == 32) { float v; std::memcpy(&v, p, 4); s = v; } - else return false; - } - if (c == 0) l = s; - else if (c == 1) r = s; - else { l += s; r += s; } - } - if (numCh == 1) r = l; - tmp.push_back(l); - tmp.push_back(r); - } - // Resample to 48k if needed (linear). - if (sampleRate != static_cast(kFmodOutRate)) { - const size_t inFrames = tmp.size() / 2; - const size_t outFrames = static_cast((static_cast(inFrames) * kFmodOutRate) / sampleRate); - std::vector rs; - rs.reserve(outFrames * 2); - for (size_t i = 0; i < outFrames; i++) { - double pos = (static_cast(i) * sampleRate) / kFmodOutRate; - size_t i0 = static_cast(pos); - size_t i1 = i0 + 1 < inFrames ? i0 + 1 : i0; - float t = static_cast(pos - i0); - rs.push_back(tmp[i0 * 2] * (1 - t) + tmp[i1 * 2] * t); - rs.push_back(tmp[i0 * 2 + 1] * (1 - t) + tmp[i1 * 2 + 1] * t); - } - outPcm.swap(rs); - } else { - outPcm.swap(tmp); - } - outRate = kFmodOutRate; - outCh = 2; - return true; -} - -} - -namespace FMOD { - -class System; -class ChannelGroup; -class Channel; -class Sound; -class SoundGroup; -class DSP; -class DSPConnection; -class Geometry; -class Reverb3D; - -class Sound { -public: - std::string name; - unsigned mode = 0; - unsigned length = 0; - int loopCount = 0; - float minDistance = 0.0f; - float maxDistance = 10000.0f; - SoundGroup* soundGroup = nullptr; - void* userData = nullptr; - // Real-audio decoded PCM (float stereo 48k, interleaved). Empty = silent/placeholder. - std::vector pcm; - int pcmRate = kFmodOutRate; - int pcmCh = 2; - int APS5_VABI release(); - int APS5_VABI getSystemObject(System** system); - int APS5_VABI setMode(unsigned mode) { - std::lock_guard lock(gFmodMutex); - this->mode = mode; - return FMOD_OK; - } - int APS5_VABI getMode(unsigned* mode) { - std::lock_guard lock(gFmodMutex); - if (mode) *mode = this->mode; - return FMOD_OK; - } - int APS5_VABI set3DMinMaxDistance(float mindistance, float maxdistance) { - std::lock_guard lock(gFmodMutex); - minDistance = mindistance; - maxDistance = maxdistance; - return FMOD_OK; - } - int APS5_VABI getNumSubSounds(int* numsubsounds) { - std::lock_guard lock(gFmodMutex); - if (numsubsounds) *numsubsounds = 0; - return FMOD_OK; - } - int APS5_VABI getLength(unsigned* length, unsigned lengthtype) { - std::lock_guard lock(gFmodMutex); - if (!length) return FMOD_OK; - if (!pcm.empty()) { - const unsigned frames = static_cast(pcm.size() / 2); - // FMOD_TIMEUNIT: MS=1, PCM=2, PCMBYTES=4, RAWBYTES=8 - if (lengthtype == 1) *length = (frames * 1000u) / static_cast(kFmodOutRate); - else if (lengthtype == 2) *length = frames; - else if (lengthtype == 4 || lengthtype == 8) *length = frames * 2u * sizeof(float); - else *length = frames; - return FMOD_OK; - } - *length = this->length; - return FMOD_OK; - } - int APS5_VABI getFormat(FMOD_SOUND_TYPE* type, FMOD_SOUND_FORMAT* format, int* channels, int* bits) { - std::lock_guard lock(gFmodMutex); - if (!pcm.empty()) { - if (type) *type = FMOD_SOUND_TYPE_UNKNOWN; - if (format) *format = FMOD_SOUND_FORMAT_PCMFLOAT; - if (channels) *channels = 2; - if (bits) *bits = 32; - return FMOD_OK; - } - if (type) *type = FMOD_SOUND_TYPE_UNKNOWN; - if (format) *format = FMOD_SOUND_FORMAT_PCM16; - if (channels) *channels = 2; - if (bits) *bits = 16; - return FMOD_OK; - } - int APS5_VABI getName(char* name, int namelen) { - std::lock_guard lock(gFmodMutex); - if (name && namelen > 0) { - std::strncpy(name, this->name.c_str(), static_cast(namelen - 1)); - name[namelen - 1] = '\0'; - } - return FMOD_OK; - } - int APS5_VABI setLoopCount(int loopcount) { - std::lock_guard lock(gFmodMutex); - loopCount = loopcount; - return FMOD_OK; - } - int APS5_VABI getLoopCount(int* loopcount) { - std::lock_guard lock(gFmodMutex); - if (loopcount) *loopcount = loopCount; - return FMOD_OK; - } - int APS5_VABI setSoundGroup(SoundGroup* soundgroup) { - std::lock_guard lock(gFmodMutex); - soundGroup = soundgroup; - return FMOD_OK; - } - int APS5_VABI getSoundGroup(SoundGroup** soundgroup) { - std::lock_guard lock(gFmodMutex); - if (soundgroup) *soundgroup = soundGroup; - return FMOD_OK; - } - int APS5_VABI getSubSound(int index, Sound** subsound) { - (void)index; - std::lock_guard lock(gFmodMutex); - if (subsound) *subsound = nullptr; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } - int APS5_VABI getOpenState(FMOD_OPENSTATE* openstate, unsigned* percentbuffered, bool* starving, bool* diskbusy) { - std::lock_guard lock(gFmodMutex); - if (openstate) *openstate = FMOD_OPENSTATE_READY; - if (percentbuffered) *percentbuffered = 100; - if (starving) *starving = false; - if (diskbusy) *diskbusy = false; - return FMOD_OK; - } - int APS5_VABI readData(void* buffer, unsigned length, unsigned* read) { - std::lock_guard lock(gFmodMutex); - if (buffer && length) std::memset(buffer, 0, length); - if (read) *read = length; - return FMOD_OK; - } - int APS5_VABI seekData(unsigned pcm) { - (void)pcm; - return FMOD_OK; - } -}; - -class SoundGroup { -public: - int maxAudible = 0; - float volume = 1.0f; - void* userData = nullptr; - int APS5_VABI release() { - std::lock_guard lock(gFmodMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI setMaxAudible(int maxaudible) { - std::lock_guard lock(gFmodMutex); - maxAudible = maxaudible; - return FMOD_OK; - } - int APS5_VABI getMaxAudible(int* maxaudible) { - std::lock_guard lock(gFmodMutex); - if (maxaudible) *maxaudible = maxAudible; - return FMOD_OK; - } - int APS5_VABI setVolume(float volume) { - std::lock_guard lock(gFmodMutex); - this->volume = volume; - return FMOD_OK; - } - int APS5_VABI getVolume(float* volume) { - std::lock_guard lock(gFmodMutex); - if (volume) *volume = this->volume; - return FMOD_OK; - } - int APS5_VABI stop() { return FMOD_OK; } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } - int APS5_VABI getNumSounds(int* numsounds) { - std::lock_guard lock(gFmodMutex); - if (numsounds) *numsounds = 0; - return FMOD_OK; - } -}; - -class DSPConnection { -public: - DSP* input = nullptr; - DSP* output = nullptr; - void* userData = nullptr; - int APS5_VABI getInput(DSP** input) { - std::lock_guard lock(gFmodMutex); - if (input) *input = this->input; - return FMOD_OK; - } - int APS5_VABI getOutput(DSP** output) { - std::lock_guard lock(gFmodMutex); - if (output) *output = this->output; - return FMOD_OK; - } - int APS5_VABI getType(FMOD_DSPCONNECTION_TYPE* type) { - std::lock_guard lock(gFmodMutex); - if (type) *type = FMOD_DSPCONNECTION_TYPE_STANDARD; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class DSP { -public: - FMOD_DSP_TYPE type = FMOD_DSP_TYPE_UNKNOWN; - bool active = true; - bool bypass = false; - void* userData = nullptr; - int APS5_VABI release() { - std::lock_guard lock(gFmodMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI setActive(bool active) { - std::lock_guard lock(gFmodMutex); - this->active = active; - return FMOD_OK; - } - int APS5_VABI getActive(bool* active) { - std::lock_guard lock(gFmodMutex); - if (active) *active = this->active; - return FMOD_OK; - } - int APS5_VABI setBypass(bool bypass) { - std::lock_guard lock(gFmodMutex); - this->bypass = bypass; - return FMOD_OK; - } - int APS5_VABI getBypass(bool* bypass) { - std::lock_guard lock(gFmodMutex); - if (bypass) *bypass = this->bypass; - return FMOD_OK; - } - int APS5_VABI reset() { return FMOD_OK; } - int APS5_VABI setParameterFloat(int index, float value) { - (void)index; (void)value; - return FMOD_OK; - } - int APS5_VABI getParameterFloat(int index, float* value) { - (void)index; - std::lock_guard lock(gFmodMutex); - if (value) *value = 0.0f; - return FMOD_OK; - } - int APS5_VABI getType(FMOD_DSP_TYPE* type) { - std::lock_guard lock(gFmodMutex); - if (type) *type = this->type; - return FMOD_OK; - } - int APS5_VABI getInfo(char* name, unsigned* version, int* channels, int* configwidth, int* configheight) { - std::lock_guard lock(gFmodMutex); - if (name) name[0] = '\0'; - if (version) *version = 0; - if (channels) *channels = 0; - if (configwidth) *configwidth = 0; - if (configheight) *configheight = 0; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class ChannelControl { -public: - float volume = 1.0f; - float pitch = 1.0f; - bool paused = false; - bool mute = false; - bool playing = false; - unsigned mode = 0; - bool volumeRamp = false; - void* userData = nullptr; - // Mixer state for real-audio backend (used when this control is a Channel - // with decoded PCM; groups keep mixHasData==false and use sticky flag). - size_t mixCursor = 0; - size_t mixTotal = 0; - bool mixHasData = false; - bool mixLoop = false; - int APS5_VABI setVolume(float volume) { - std::lock_guard lock(gFmodMutex); - this->volume = volume; - return FMOD_OK; - } - int APS5_VABI getVolume(float* volume) { - std::lock_guard lock(gFmodMutex); - if (volume) *volume = this->volume; - return FMOD_OK; - } - int APS5_VABI setPitch(float pitch) { - std::lock_guard lock(gFmodMutex); - this->pitch = pitch; - return FMOD_OK; - } - int APS5_VABI getPitch(float* pitch) { - std::lock_guard lock(gFmodMutex); - if (pitch) *pitch = this->pitch; - return FMOD_OK; - } - int APS5_VABI setPaused(bool paused) { - std::lock_guard lock(gFmodMutex); - this->paused = paused; - return FMOD_OK; - } - int APS5_VABI getPaused(bool* paused) { - std::lock_guard lock(gFmodMutex); - if (paused) *paused = this->paused; - return FMOD_OK; - } - int APS5_VABI setMute(bool mute) { - std::lock_guard lock(gFmodMutex); - this->mute = mute; - return FMOD_OK; - } - int APS5_VABI getMute(bool* mute) { - std::lock_guard lock(gFmodMutex); - if (mute) *mute = this->mute; - return FMOD_OK; - } - int APS5_VABI stop() { - std::lock_guard lock(gFmodMutex); - playing = false; - return FMOD_OK; - } - int APS5_VABI isPlaying(bool* isplaying) { - std::lock_guard lock(gFmodMutex); - if (!isplaying) return FMOD_OK; - if (mixHasData) { - *isplaying = playing && !paused && (mixLoop || mixCursor < mixTotal); - } else { - *isplaying = playing && !paused; - } - return FMOD_OK; - } - int APS5_VABI setMode(unsigned mode) { - std::lock_guard lock(gFmodMutex); - this->mode = mode; - return FMOD_OK; - } - int APS5_VABI getMode(unsigned* mode) { - std::lock_guard lock(gFmodMutex); - if (mode) *mode = this->mode; - return FMOD_OK; - } - int APS5_VABI addFadePoint(unsigned long long dspclock, float volume) { - (void)dspclock; (void)volume; - return FMOD_OK; - } - int APS5_VABI setDelay(unsigned long long dspclock_start, unsigned long long dspclock_end, bool stopchannels) { - (void)dspclock_start; (void)dspclock_end; (void)stopchannels; - return FMOD_OK; - } - int APS5_VABI getDelay(unsigned long long* dspclock_start, unsigned long long* dspclock_end, bool* stopchannels) { - std::lock_guard lock(gFmodMutex); - if (dspclock_start) *dspclock_start = 0; - if (dspclock_end) *dspclock_end = 0; - if (stopchannels) *stopchannels = false; - return FMOD_OK; - } - int APS5_VABI setVolumeRamp(bool ramp) { - std::lock_guard lock(gFmodMutex); - volumeRamp = ramp; - return FMOD_OK; - } - int APS5_VABI getVolumeRamp(bool* ramp) { - std::lock_guard lock(gFmodMutex); - if (ramp) *ramp = volumeRamp; - return FMOD_OK; - } - int APS5_VABI setCallback(FMOD_CHANNELCONTROL_CALLBACK callback) { - (void)callback; - return FMOD_OK; - } - int APS5_VABI isVirtual(bool* isvirtual) { - std::lock_guard lock(gFmodMutex); - if (isvirtual) *isvirtual = false; - return FMOD_OK; - } - int APS5_VABI getIndex(int* index) { - std::lock_guard lock(gFmodMutex); - if (index) *index = 0; - return FMOD_OK; - } - int APS5_VABI getSystemObject(System** system); - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } - int APS5_VABI set3DAttributes(const FMOD_VECTOR* pos, const FMOD_VECTOR* vel) { - (void)pos; (void)vel; - return FMOD_OK; - } - int APS5_VABI setLowPassGain(float gain) { - (void)gain; - return FMOD_OK; - } - int APS5_VABI getLowPassGain(float* gain) { - std::lock_guard lock(gFmodMutex); - if (gain) *gain = 1.0f; - return FMOD_OK; - } - int APS5_VABI setPan(float pan) { - (void)pan; - return FMOD_OK; - } - int APS5_VABI getDSPClock(unsigned long long* dspclock, unsigned long long* parentclock) { - std::lock_guard lock(gFmodMutex); - if (dspclock) *dspclock = 0; - if (parentclock) *parentclock = 0; - return FMOD_OK; - } - int APS5_VABI getDSP(int index, DSP** dsp) { - (void)index; - std::lock_guard lock(gFmodMutex); - if (dsp) *dsp = nullptr; - return FMOD_OK; - } -}; - -class Channel : public ChannelControl { -public: - Sound* sound = nullptr; - ChannelGroup* group = nullptr; - float frequency = 48000.0f; - int priority = 128; - unsigned position = 0; - int loopCount = 0; - System* owner = nullptr; - int APS5_VABI setPriority(int priority) { - std::lock_guard lock(gFmodMutex); - this->priority = priority; - return FMOD_OK; - } - int APS5_VABI getPriority(int* priority) { - std::lock_guard lock(gFmodMutex); - if (priority) *priority = this->priority; - return FMOD_OK; - } - int APS5_VABI setFrequency(float frequency) { - std::lock_guard lock(gFmodMutex); - this->frequency = frequency; - return FMOD_OK; - } - int APS5_VABI getFrequency(float* frequency) { - std::lock_guard lock(gFmodMutex); - if (frequency) *frequency = this->frequency; - return FMOD_OK; - } - int APS5_VABI setPosition(unsigned position, unsigned postype) { - (void)postype; - std::lock_guard lock(gFmodMutex); - this->position = position; - // Keep mixer cursor in sync (PCM frames). postype==2 (PCM) assumed. - mixCursor = static_cast(position); - if (mixHasData && mixCursor > mixTotal) mixCursor = mixTotal; - return FMOD_OK; - } - int APS5_VABI getPosition(unsigned* position, unsigned postype) { - (void)postype; - std::lock_guard lock(gFmodMutex); - if (position) *position = static_cast(mixHasData ? mixCursor : this->position); - return FMOD_OK; - } - int APS5_VABI setChannelGroup(ChannelGroup* channelgroup) { - std::lock_guard lock(gFmodMutex); - group = channelgroup; - return FMOD_OK; - } - int APS5_VABI getChannelGroup(ChannelGroup** channelgroup) { - std::lock_guard lock(gFmodMutex); - if (channelgroup) *channelgroup = group; - return FMOD_OK; - } - int APS5_VABI setLoopCount(int loopcount) { - std::lock_guard lock(gFmodMutex); - loopCount = loopcount; - return FMOD_OK; - } - int APS5_VABI getCurrentSound(Sound** sound) { - std::lock_guard lock(gFmodMutex); - if (sound) *sound = this->sound; - return FMOD_OK; - } -}; - -class ChannelGroup : public ChannelControl { -public: - std::string name; - int APS5_VABI release() { - std::lock_guard lock(gFmodMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI addGroup(ChannelGroup* group, bool propagatedspclock, DSPConnection** connection) { - (void)group; (void)propagatedspclock; - std::lock_guard lock(gFmodMutex); - if (connection) *connection = nullptr; - return FMOD_OK; - } - int APS5_VABI getNumGroups(int* numgroups) { - std::lock_guard lock(gFmodMutex); - if (numgroups) *numgroups = 0; - return FMOD_OK; - } - int APS5_VABI getGroup(int index, ChannelGroup** group) { - (void)index; - std::lock_guard lock(gFmodMutex); - if (group) *group = nullptr; - return FMOD_OK; - } - int APS5_VABI getParentGroup(ChannelGroup** group) { - std::lock_guard lock(gFmodMutex); - if (group) *group = nullptr; - return FMOD_OK; - } - int APS5_VABI getName(char* name, int namelen) { - std::lock_guard lock(gFmodMutex); - if (name && namelen > 0) { - std::strncpy(name, this->name.c_str(), static_cast(namelen - 1)); - name[namelen - 1] = '\0'; - } - return FMOD_OK; - } - int APS5_VABI getNumChannels(int* numchannels) { - std::lock_guard lock(gFmodMutex); - if (numchannels) *numchannels = 0; - return FMOD_OK; - } - int APS5_VABI getChannel(int index, Channel** channel) { - (void)index; - std::lock_guard lock(gFmodMutex); - if (channel) *channel = nullptr; - return FMOD_OK; - } -}; - -class Geometry { -public: - void* userData = nullptr; - int APS5_VABI release() { - std::lock_guard lock(gFmodMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI addPolygon(float directocclusion, float reverbocclusion, bool doublesided, int numvertices, const FMOD_VECTOR* vertices, int* polygonindex) { - (void)directocclusion; (void)reverbocclusion; (void)doublesided; (void)numvertices; (void)vertices; - std::lock_guard lock(gFmodMutex); - if (polygonindex) *polygonindex = 0; - return FMOD_OK; - } - int APS5_VABI setActive(bool active) { - (void)active; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class Reverb3D { -public: - void* userData = nullptr; - int APS5_VABI release() { - std::lock_guard lock(gFmodMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI set3DAttributes(const FMOD_VECTOR* pos, float mindistance, float maxdistance) { - (void)pos; (void)mindistance; (void)maxdistance; - return FMOD_OK; - } - int APS5_VABI setActive(bool active) { - (void)active; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -static std::vector gFmodChannels; - -static int APS5_VABI SoundReleaseImpl(Sound* self) { - std::lock_guard lock(gFmodMutex); - for (Channel* ch : gFmodChannels) { - if (ch && ch->sound == self) { - ch->playing = false; - ch->sound = nullptr; - ch->mixHasData = false; - } - } - delete self; - return FMOD_OK; -} - -int APS5_VABI Sound::release() { return SoundReleaseImpl(this); } - -class System { -public: - bool initialized = false; - int maxChannels = 0; - unsigned initFlags = 0; - int driver = 0; - FMOD_OUTPUTTYPE output = FMOD_OUTPUTTYPE_AUTODETECT; - int softwareChannels = 0; - int numListeners = 1; - float dopplerScale = 1.0f; - float distanceFactor = 1.0f; - float rolloffScale = 1.0f; - void* userData = nullptr; - ChannelGroup* masterChannelGroup = nullptr; - SoundGroup* masterSoundGroup = nullptr; - static int APS5_VABI create(System** system) { - std::lock_guard lock(gFmodMutex); - if (!system) return FMOD_OK; - *system = new System(); - return FMOD_OK; - } - static int APS5_VABI create(System** system, unsigned headerversion) { - (void)headerversion; - return create(system); - } - int APS5_VABI release() { - std::lock_guard lock(gFmodMutex); - // Drop channels owned by this system (game holds raw pointers; mark - // them stopped and free to avoid unbounded growth). - for (auto it = gFmodChannels.begin(); it != gFmodChannels.end();) { - if (*it && (*it)->owner == this) { - delete *it; - it = gFmodChannels.erase(it); - } else { - ++it; - } - } - delete masterChannelGroup; - delete masterSoundGroup; - masterChannelGroup = nullptr; - masterSoundGroup = nullptr; - delete this; - return FMOD_OK; - } - int APS5_VABI init(int maxchannels, unsigned flags, void* extradriverdata) { - (void)extradriverdata; - std::lock_guard lock(gFmodMutex); - maxChannels = maxchannels; - initFlags = flags; - initialized = true; - if (!masterChannelGroup) masterChannelGroup = new ChannelGroup(); - if (!masterSoundGroup) masterSoundGroup = new SoundGroup(); - // Real-audio: try SDL unless NOSOUND output or env requests silent. - // Keep silent backend as fallback (no failure returned). - bool wantSilent = FmodSilentRequested() || - output == FMOD_OUTPUTTYPE_NOSOUND || - output == FMOD_OUTPUTTYPE_NOSOUND_NRT; - if (!wantSilent) { - // Unlock during SDL open (SDL may call back)? FmodEnsureDevice uses - // no FMOD lock internally except SDL, so we can call with lock held - // for simplicity; SDL_OpenAudioDevice does not call into FMOD. - if (!FmodEnsureDevice()) { - APS5_LOG_ERR("%s", "FMOD: SDL audio unavailable, silent fallback"); - } else { - APS5_LOG_OUT("%s", "FMOD: SDL audio output active (48k stereo)"); - } - } - return FMOD_OK; - } - int APS5_VABI close() { - std::lock_guard lock(gFmodMutex); - initialized = false; - return FMOD_OK; - } - int APS5_VABI update() { - std::lock_guard lock(gFmodMutex); - if (!initialized) return FMOD_OK; - if (gFmodSilent || gFmodDevice == 0) return FMOD_OK; // silent fallback - // Throttle like libSceAudioOut: avoid unbounded queue growth. - Uint32 queued = SDL_GetQueuedAudioSize(gFmodDevice); - const Uint32 oneBuf = static_cast(kFmodMixFrames * kFmodOutCh * sizeof(float)); - if (queued > oneBuf * 8u) return FMOD_OK; - float mix[kFmodMixFrames * 2] = {}; - bool anyActive = false; - for (Channel* ch : gFmodChannels) { - if (!ch || ch->owner != this) continue; - if (!ch->playing || ch->paused || ch->mute) continue; - if (!ch->mixHasData || !ch->sound || ch->sound->pcm.empty()) continue; - Sound* s = ch->sound; - const size_t total = ch->mixTotal; - if (total == 0) continue; - size_t cur = ch->mixCursor; - const float vol = ch->volume; - if (vol <= 0.0f) { - // Still advance cursor so silent channels finish. - size_t adv = kFmodMixFrames; - if (!ch->mixLoop) { - if (cur + adv >= total) { cur = total; ch->playing = false; } - else cur += adv; - } else { - cur = (cur + adv) % (total ? total : 1); - } - ch->mixCursor = cur; - ch->position = static_cast(cur); - continue; - } - anyActive = true; - const float* pcm = s->pcm.data(); - size_t pos = cur; - for (int i = 0; i < kFmodMixFrames; i++) { - if (pos >= total) { - if (ch->mixLoop || s->loopCount != 0 || - (s->mode & FMOD_LOOP_NORMAL) != 0) { - pos = 0; - } else { - break; - } - } - mix[i * 2] += pcm[pos * 2] * vol; - mix[i * 2 + 1] += pcm[pos * 2 + 1] * vol; - pos++; - } - // Advance cursor by frames consumed (approx, ignoring loop wrap details above). - size_t adv = static_cast(kFmodMixFrames); - if (!ch->mixLoop && s->loopCount == 0 && (s->mode & FMOD_LOOP_NORMAL) == 0) { - if (cur + adv >= total) { - cur = total; - ch->playing = false; - } else { - cur += adv; - } - } else { - cur = total ? ((cur + adv) % total) : 0; - } - ch->mixCursor = cur; - ch->position = static_cast(cur); - } - if (!anyActive) { - // Still queue silence rarely to keep device alive? No — skip to - // avoid filling queue with silence when nothing plays. - return FMOD_OK; - } - for (int i = 0; i < kFmodMixFrames * 2; i++) { - if (mix[i] > 1.0f) mix[i] = 1.0f; - else if (mix[i] < -1.0f) mix[i] = -1.0f; - } - // Convert to device format if needed. - if (gFmodSpec.format == AUDIO_F32SYS || gFmodSpec.format == 0) { - if (SDL_QueueAudio(gFmodDevice, mix, sizeof(mix)) < 0) { - APS5_LOG_ERR("%s", "FMOD: SDL_QueueAudio failed"); - } - } else { - int16_t tmp[kFmodMixFrames * 2]; - for (int i = 0; i < kFmodMixFrames * 2; i++) { - float v = mix[i] * 32767.0f; - if (v > 32767.0f) v = 32767.0f; - if (v < -32768.0f) v = -32768.0f; - tmp[i] = static_cast(v); - } - // Resample/format convert via SDL if spec differs (channels/rate). - // For minimal path, queue directly when spec is S16 stereo 48k; - // otherwise use SDL_ConvertAudio. - if (gFmodSpec.channels == 2 && gFmodSpec.freq == kFmodOutRate && - (gFmodSpec.format == AUDIO_S16SYS)) { - SDL_QueueAudio(gFmodDevice, tmp, sizeof(tmp)); - } else { - SDL_AudioCVT cvt{}; - if (SDL_BuildAudioCVT(&cvt, AUDIO_F32SYS, 2, kFmodOutRate, - gFmodSpec.format, gFmodSpec.channels, gFmodSpec.freq) >= 0) { - std::vector buf(sizeof(mix) * 4u); - std::memcpy(buf.data(), mix, sizeof(mix)); - cvt.buf = buf.data(); - cvt.len = static_cast(sizeof(mix)); - if (SDL_ConvertAudio(&cvt) == 0) { - SDL_QueueAudio(gFmodDevice, cvt.buf, static_cast(cvt.len_cvt)); - } - } - } - } - return FMOD_OK; - } - int APS5_VABI setOutput(FMOD_OUTPUTTYPE output) { - std::lock_guard lock(gFmodMutex); - this->output = output; - if (output == FMOD_OUTPUTTYPE_NOSOUND || output == FMOD_OUTPUTTYPE_NOSOUND_NRT) { - gFmodSilent = true; - } - return FMOD_OK; - } - int APS5_VABI getOutput(FMOD_OUTPUTTYPE* output) { - std::lock_guard lock(gFmodMutex); - if (output) *output = this->output; - return FMOD_OK; - } - int APS5_VABI getNumDrivers(int* numdrivers) { - std::lock_guard lock(gFmodMutex); - if (numdrivers) *numdrivers = 1; - return FMOD_OK; - } - int APS5_VABI getDriverInfo(int id, char* name, int namelen, FMOD_GUID* guid, int* systemrate, FMOD_SPEAKERMODE* speakermode, int* speakermodechannels) { - (void)id; - std::lock_guard lock(gFmodMutex); - if (name && namelen > 0) { - const char* driverName = (gFmodDevice != 0 && !gFmodSilent) ? "AnyPS5 FMOD Output" : "AnyPS5 Null Output"; - std::strncpy(name, driverName, static_cast(namelen - 1)); - name[namelen - 1] = '\0'; - } - if (guid) std::memset(guid, 0, sizeof(*guid)); - if (systemrate) *systemrate = 48000; - if (speakermode) *speakermode = FMOD_SPEAKERMODE_STEREO; - if (speakermodechannels) *speakermodechannels = 2; - return FMOD_OK; - } - int APS5_VABI setDriver(int driver) { - std::lock_guard lock(gFmodMutex); - this->driver = driver; - return FMOD_OK; - } - int APS5_VABI getDriver(int* driver) { - std::lock_guard lock(gFmodMutex); - if (driver) *driver = this->driver; - return FMOD_OK; - } - int APS5_VABI setSoftwareChannels(int numsoftwarechannels) { - std::lock_guard lock(gFmodMutex); - softwareChannels = numsoftwarechannels; - return FMOD_OK; - } - int APS5_VABI getSoftwareChannels(int* numsoftwarechannels) { - std::lock_guard lock(gFmodMutex); - if (numsoftwarechannels) *numsoftwarechannels = softwareChannels; - return FMOD_OK; - } - int APS5_VABI setSoftwareFormat(int samplerate, FMOD_SPEAKERMODE speakermode, int numrawspeakers) { - (void)samplerate; (void)speakermode; (void)numrawspeakers; - return FMOD_OK; - } - int APS5_VABI getSoftwareFormat(int* samplerate, FMOD_SPEAKERMODE* speakermode, int* numrawspeakers) { - std::lock_guard lock(gFmodMutex); - if (samplerate) *samplerate = 48000; - if (speakermode) *speakermode = FMOD_SPEAKERMODE_STEREO; - if (numrawspeakers) *numrawspeakers = 0; - return FMOD_OK; - } - int APS5_VABI setDSPBufferSize(unsigned bufferlength, int numbuffers) { - (void)bufferlength; (void)numbuffers; - return FMOD_OK; - } - int APS5_VABI getDSPBufferSize(unsigned* bufferlength, int* numbuffers) { - std::lock_guard lock(gFmodMutex); - if (bufferlength) *bufferlength = 1024; - if (numbuffers) *numbuffers = 4; - return FMOD_OK; - } - int APS5_VABI setAdvancedSettings(FMOD_ADVANCEDSETTINGS* settings) { - (void)settings; - return FMOD_OK; - } - int APS5_VABI getAdvancedSettings(FMOD_ADVANCEDSETTINGS* settings) { - std::lock_guard lock(gFmodMutex); - if (settings) std::memset(settings, 0, sizeof(*settings)); - return FMOD_OK; - } - int APS5_VABI setCallback(FMOD_SYSTEM_CALLBACK callback, FMOD_SYSTEM_CALLBACK_TYPE callbackmask) { - (void)callback; (void)callbackmask; - return FMOD_OK; - } - int APS5_VABI setFileSystem(void* useropen, void* userclose, void* userread, void* userseek, void* userasyncread, void* userasynccancel, int blockalign) { - (void)useropen; (void)userclose; (void)userread; (void)userseek; - (void)userasyncread; (void)userasynccancel; (void)blockalign; - return FMOD_OK; - } - int APS5_VABI setPluginPath(const char* pluginpath) { - (void)pluginpath; - return FMOD_OK; - } - int APS5_VABI loadPlugin(const char* filename, unsigned* handle, FMOD_PLUGINTYPE plugintype) { - (void)filename; (void)plugintype; - std::lock_guard lock(gFmodMutex); - if (handle) *handle = 0; - return FMOD_OK; - } - int APS5_VABI getVersion(unsigned* version) { - std::lock_guard lock(gFmodMutex); - if (version) *version = FMOD_VERSION_CURRENT; - return FMOD_OK; - } - int APS5_VABI getOutputHandle(void** handle) { - std::lock_guard lock(gFmodMutex); - if (handle) *handle = nullptr; - return FMOD_OK; - } - int APS5_VABI getChannelsPlaying(int* channels, int* realchannels) { - std::lock_guard lock(gFmodMutex); - int active = 0; - for (Channel* ch : gFmodChannels) { - if (!ch || ch->owner != this) continue; - if (!ch->playing || ch->paused) continue; - if (ch->mixHasData) { - if (ch->mixLoop || ch->mixCursor < ch->mixTotal) active++; - } - // Null/empty sounds (smoke test) are not counted to preserve old - // behaviour (previously always returned 0). - } - if (channels) *channels = active; - if (realchannels) *realchannels = active; - return FMOD_OK; - } - int APS5_VABI getCPUUsage(FMOD_CPU_USAGE* usage) { - std::lock_guard lock(gFmodMutex); - if (usage) std::memset(usage, 0, sizeof(*usage)); - return FMOD_OK; - } - int APS5_VABI getFileUsage(long long* samplebytesread, long long* streambytesread, long long* otherbytesread) { - std::lock_guard lock(gFmodMutex); - if (samplebytesread) *samplebytesread = 0; - if (streambytesread) *streambytesread = 0; - if (otherbytesread) *otherbytesread = 0; - return FMOD_OK; - } - int APS5_VABI getSpectrum(float* spectrumarray, int numvalues, int channeloffset, FMOD_DSP_FFT_WINDOW window) { - (void)channeloffset; (void)window; - std::lock_guard lock(gFmodMutex); - if (spectrumarray && numvalues > 0) std::memset(spectrumarray, 0, sizeof(float) * static_cast(numvalues)); - return FMOD_OK; - } - int APS5_VABI getWaveData(float* wavearray, int numvalues, int channeloffset) { - (void)channeloffset; - std::lock_guard lock(gFmodMutex); - if (wavearray && numvalues > 0) std::memset(wavearray, 0, sizeof(float) * static_cast(numvalues)); - return FMOD_OK; - } - int APS5_VABI createSound(const char* name_or_data, unsigned mode, FMOD_CREATESOUNDEXINFO* exinfo, Sound** sound) { - std::lock_guard lock(gFmodMutex); - if (!sound) return FMOD_OK; - Sound* created = new Sound(); - created->mode = mode; - unsigned exLen = exinfo ? exinfo->length : 0; - if (exLen) created->length = exLen; - const bool isMem = (mode & (FMOD_OPENMEMORY_FLAG | FMOD_OPENMEMORY_POINT_FLAG)) != 0; - const bool isRaw = (mode & FMOD_OPENRAW_FLAG) != 0; - if (isMem && name_or_data && exLen > 0 && exLen < (1u << 30)) { - const uint8_t* buf = reinterpret_cast(name_or_data); - // Keep a copy of the name only for file-based sounds; for memory - // buffers the pointer is binary data (not a C string). - created->name.clear(); - std::vector pcm; - int rate = kFmodOutRate, ch = 2; - bool decoded = false; - if (!isRaw) { - decoded = FmodParseWav(buf, exLen, pcm, rate, ch); - } - if (!decoded && isRaw) { - // OPENRAW: interpret buffer using exinfo (default stereo 48k PCM16). - int rawCh = exinfo ? exinfo->numchannels : 0; - int rawRate = exinfo ? exinfo->defaultfrequency : 0; - int rawFmt = exinfo ? static_cast(exinfo->format) : 2; - if (rawCh <= 0 || rawCh > 8) rawCh = 2; - if (rawRate <= 0) rawRate = kFmodOutRate; - size_t bytesPerSamp = 2; - if (rawFmt == 1) bytesPerSamp = 1; // PCM8 - else if (rawFmt == 2) bytesPerSamp = 2; // PCM16 - else if (rawFmt == 5) bytesPerSamp = 4; // FLOAT - else bytesPerSamp = 2; - size_t frames = exLen / (static_cast(rawCh) * bytesPerSamp); - if (frames > 0 && frames < 48000u * 60u) { - pcm.reserve(frames * 2); - for (size_t f = 0; f < frames; f++) { - float l = 0, r = 0; - for (int c = 0; c < rawCh; c++) { - const uint8_t* p = buf + (f * rawCh + c) * bytesPerSamp; - float s = 0; - if (rawFmt == 1) s = (static_cast(p[0]) - 128) / 128.0f; - else if (rawFmt == 2) { int16_t v; std::memcpy(&v, p, 2); s = v / 32768.0f; } - else if (rawFmt == 5) { float v; std::memcpy(&v, p, 4); s = v; } - if (c == 0) l = s; else if (c == 1) r = s; else { l += s; r += s; } - } - if (rawCh == 1) r = l; - pcm.push_back(l); pcm.push_back(r); - } - // Resample if needed. - if (rawRate != kFmodOutRate && !pcm.empty()) { - size_t inF = pcm.size() / 2; - size_t outF = static_cast((static_cast(inF) * kFmodOutRate) / rawRate); - std::vector rs; rs.reserve(outF * 2); - for (size_t i = 0; i < outF; i++) { - double pos = (static_cast(i) * rawRate) / kFmodOutRate; - size_t i0 = static_cast(pos); - size_t i1 = i0 + 1 < inF ? i0 + 1 : i0; - float t = static_cast(pos - i0); - rs.push_back(pcm[i0 * 2] * (1 - t) + pcm[i1 * 2] * t); - rs.push_back(pcm[i0 * 2 + 1] * (1 - t) + pcm[i1 * 2 + 1] * t); - } - pcm.swap(rs); - } - decoded = !pcm.empty(); - rate = kFmodOutRate; ch = 2; - } - } - if (decoded) { - created->pcm.swap(pcm); - created->pcmRate = rate; - created->pcmCh = ch; - } else { - // Compressed (Vorbis/MP3/FSB/AT9...) or unknown: audible - // placeholder so the mixer path can be heard. Real decoders - // (Vorbis/MP3/AT9) remain future work — see docs/dev/TechnicalDebt. - FmodMakeSine(created->pcm, kFmodOutRate, 2, 440.0f, 1.0f); - created->pcmRate = kFmodOutRate; - created->pcmCh = 2; - } - } else { - if (name_or_data) { - // File-based: store name only (first bytes may still be checked - // for embedded RIFF in case game passes a path that is data). - size_t nlen = std::strlen(name_or_data); - if (nlen < 256) created->name = name_or_data; - } - // Placeholder 0.5s sine so file-based playSound is audible. - FmodMakeSine(created->pcm, kFmodOutRate, 2, 330.0f, 0.5f); - created->pcmRate = kFmodOutRate; - created->pcmCh = 2; - } - *sound = created; - return FMOD_OK; - } - int APS5_VABI createStream(const char* name_or_data, unsigned mode, FMOD_CREATESOUNDEXINFO* exinfo, Sound** sound) { - return createSound(name_or_data, mode, exinfo, sound); - } - int APS5_VABI createDSP(FMOD_DSP_DESCRIPTION* description, DSP** dsp) { - (void)description; - std::lock_guard lock(gFmodMutex); - if (dsp) *dsp = new DSP(); - return FMOD_OK; - } - int APS5_VABI createDSPByType(FMOD_DSP_TYPE type, DSP** dsp) { - std::lock_guard lock(gFmodMutex); - if (dsp) { - *dsp = new DSP(); - (*dsp)->type = type; - } - return FMOD_OK; - } - int APS5_VABI playSound(Sound* sound, ChannelGroup* channelgroup, bool paused, Channel** channel) { - std::lock_guard lock(gFmodMutex); - if (!channel) return FMOD_OK; - Channel* created = new Channel(); - created->sound = sound; - created->group = channelgroup ? channelgroup : masterChannelGroup; - created->paused = paused; - created->playing = true; - created->owner = this; - created->mixCursor = 0; - if (sound && !sound->pcm.empty()) { - created->mixHasData = true; - created->mixTotal = sound->pcm.size() / 2; - const bool loopMode = (sound->mode & FMOD_LOOP_NORMAL) != 0; - created->mixLoop = loopMode || sound->loopCount != 0; - } else { - created->mixHasData = false; - created->mixTotal = 0; - created->mixLoop = false; - } - gFmodChannels.push_back(created); - *channel = created; - return FMOD_OK; - } - int APS5_VABI playDSP(DSP* dsp, ChannelGroup* channelgroup, bool paused, Channel** channel) { - (void)dsp; - std::lock_guard lock(gFmodMutex); - if (!channel) return FMOD_OK; - Channel* created = new Channel(); - created->group = channelgroup ? channelgroup : masterChannelGroup; - created->paused = paused; - created->playing = true; - created->owner = this; - created->mixHasData = false; - gFmodChannels.push_back(created); - *channel = created; - return FMOD_OK; - } - int APS5_VABI getChannel(int channelid, Channel** channel) { - (void)channelid; - std::lock_guard lock(gFmodMutex); - if (channel) *channel = nullptr; - return FMOD_OK; - } - int APS5_VABI getMasterSoundGroup(SoundGroup** soundgroup) { - std::lock_guard lock(gFmodMutex); - if (soundgroup) *soundgroup = masterSoundGroup; - return FMOD_OK; - } - int APS5_VABI getMasterChannelGroup(ChannelGroup** channelgroup) { - std::lock_guard lock(gFmodMutex); - if (channelgroup) *channelgroup = masterChannelGroup; - return FMOD_OK; - } - int APS5_VABI setReverbProperties(int instance, FMOD_REVERB_PROPERTIES* prop) { - (void)instance; (void)prop; - return FMOD_OK; - } - int APS5_VABI getReverbProperties(int instance, FMOD_REVERB_PROPERTIES* prop) { - (void)instance; - std::lock_guard lock(gFmodMutex); - if (prop) std::memset(prop, 0, sizeof(*prop)); - return FMOD_OK; - } - int APS5_VABI createReverb3D(Reverb3D** reverb) { - std::lock_guard lock(gFmodMutex); - if (reverb) *reverb = new Reverb3D(); - return FMOD_OK; - } - int APS5_VABI createGeometry(int maxpolygons, int maxvertices, Geometry** geometry) { - (void)maxpolygons; (void)maxvertices; - std::lock_guard lock(gFmodMutex); - if (geometry) *geometry = new Geometry(); - return FMOD_OK; - } - int APS5_VABI loadGeometry(const void* data, int datasize, Geometry** geometry) { - (void)data; (void)datasize; - std::lock_guard lock(gFmodMutex); - if (geometry) *geometry = new Geometry(); - return FMOD_OK; - } - int APS5_VABI setGeometrySettings(float maxworldsize) { - (void)maxworldsize; - return FMOD_OK; - } - int APS5_VABI getGeometrySettings(float* maxworldsize) { - std::lock_guard lock(gFmodMutex); - if (maxworldsize) *maxworldsize = 0.0f; - return FMOD_OK; - } - int APS5_VABI set3DNumListeners(int numlisteners) { - std::lock_guard lock(gFmodMutex); - numListeners = numlisteners; - return FMOD_OK; - } - int APS5_VABI get3DNumListeners(int* numlisteners) { - std::lock_guard lock(gFmodMutex); - if (numlisteners) *numlisteners = numListeners; - return FMOD_OK; - } - int APS5_VABI set3DListenerAttributes(int listener, const FMOD_VECTOR* pos, const FMOD_VECTOR* vel, const FMOD_VECTOR* forward, const FMOD_VECTOR* up) { - (void)listener; (void)pos; (void)vel; (void)forward; (void)up; - return FMOD_OK; - } - int APS5_VABI mixerSuspend() { return FMOD_OK; } - int APS5_VABI mixerResume() { return FMOD_OK; } - int APS5_VABI set3DSettings(float dopplerscale, float distancefactor, float rolloffscale) { - std::lock_guard lock(gFmodMutex); - dopplerScale = dopplerscale; - distanceFactor = distancefactor; - rolloffScale = rolloffscale; - return FMOD_OK; - } - int APS5_VABI get3DSettings(float* dopplerscale, float* distancefactor, float* rolloffscale) { - std::lock_guard lock(gFmodMutex); - if (dopplerscale) *dopplerscale = dopplerScale; - if (distancefactor) *distancefactor = distanceFactor; - if (rolloffscale) *rolloffscale = rolloffScale; - return FMOD_OK; - } - int APS5_VABI createChannelGroup(const char* name, ChannelGroup** channelgroup) { - std::lock_guard lock(gFmodMutex); - if (!channelgroup) return FMOD_OK; - *channelgroup = new ChannelGroup(); - if (name) (*channelgroup)->name = name; - return FMOD_OK; - } - int APS5_VABI createSoundGroup(SoundGroup** soundgroup) { - std::lock_guard lock(gFmodMutex); - if (soundgroup) *soundgroup = new SoundGroup(); - return FMOD_OK; - } - int APS5_VABI lockDSP() { return FMOD_OK; } - int APS5_VABI unlockDSP() { return FMOD_OK; } - int APS5_VABI getSoundRAM(int* currentalloced, int* maxalloced, int* total) { - std::lock_guard lock(gFmodMutex); - if (currentalloced) *currentalloced = 0; - if (maxalloced) *maxalloced = 0; - if (total) *total = 0; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gFmodMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gFmodMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } - int APS5_VABI setStreamBufferSize(unsigned filebuffersize, unsigned filebuffersizetype) { - (void)filebuffersize; (void)filebuffersizetype; - return FMOD_OK; - } - int APS5_VABI attachChannelGroupToPort(FMOD_PORT_TYPE porttype, unsigned long long portindex, ChannelGroup* channelgroup) { - (void)porttype; (void)portindex; (void)channelgroup; - return FMOD_OK; - } - int APS5_VABI detachChannelGroupFromPort(ChannelGroup* channelgroup) { - (void)channelgroup; - return FMOD_OK; - } - int APS5_VABI setNetworkProxy(const char* proxy) { - (void)proxy; - return FMOD_OK; - } -}; - -int APS5_VABI Sound::getSystemObject(System** system) { - std::lock_guard lock(gFmodMutex); - if (system) *system = nullptr; - return FMOD_OK; -} - -int APS5_VABI ChannelControl::getSystemObject(System** system) { - std::lock_guard lock(gFmodMutex); - if (system) *system = nullptr; - return FMOD_OK; -} - -} - -extern "C" { - -int APS5_VABI FMOD_System_Create(FMOD_SYSTEM** system) { - std::lock_guard lock(gFmodMutex); - if (!system) return 0; - *system = reinterpret_cast(new FMOD::System()); - return 0; -} - -int APS5_VABI FMOD_Memory_Initialize(void* poolmem, int poollen, void* useralloc, void* userrealloc, void* userfree, unsigned memtypeflags) { - (void)poolmem; (void)poollen; (void)useralloc; (void)userrealloc; (void)userfree; (void)memtypeflags; - return 0; -} - -int APS5_VABI FMOD_Memory_GetStats(int* currentalloced, int* maxalloced, int blocking) { - (void)blocking; - std::lock_guard lock(gFmodMutex); - if (currentalloced) *currentalloced = 0; - if (maxalloced) *maxalloced = 0; - return 0; -} - -namespace { - -// Round2 NID identification via real FMOD headers (const-correct manglings). -// VS1Vg5yOLH0 = FMOD::System::setFileSystem(open,close,read,seek,asyncRead,asyncCancel,blockalign) -// WAU72lnwYic = FMOD::System::setCallback(callback,mask) -// Both are ABI-compatible with void*/int (func ptrs are 8B, mask 4B); we keep -// the silent backend (return OK) — file callbacks are not needed for -// OPENMEMORY sounds used by Legends, and callbacks are stored nowhere. -__attribute__((used)) int APS5_VABI fmod_system_setfilesystem(void* self, void* a1, void* a2, void* a3, void* a4, void* a5, void* a6, int a7) { - (void)self; (void)a1; (void)a2; (void)a3; (void)a4; (void)a5; (void)a6; (void)a7; - return 0; -} -__attribute__((used)) int APS5_VABI fmod_system_setcallback(void* self, void* cb, unsigned mask) { - (void)self; (void)cb; (void)mask; - return 0; -} - -} - -APS5_EXPORT("VS1Vg5yOLH0", fmod_system_setfilesystem); -APS5_EXPORT("WAU72lnwYic", fmod_system_setcallback); - -} diff --git a/core/libs/prx/libfmodstudio/CMakeLists.txt b/core/libs/prx/libfmodstudio/CMakeLists.txt deleted file mode 100644 index 38c8ce484..000000000 --- a/core/libs/prx/libfmodstudio/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -add_library(libfmodstudio SHARED EXCLUDE_FROM_ALL - ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp -) - -target_include_directories(libfmodstudio PRIVATE - ${LIBS_INCLUDE_DIR} -) -target_link_libraries(libfmodstudio PRIVATE libkernel libc) -target_compile_options(libfmodstudio PRIVATE -fkeep-inline-functions) -configure_windows_unwind(libfmodstudio) diff --git a/core/libs/prx/libfmodstudio/Export.cpp b/core/libs/prx/libfmodstudio/Export.cpp deleted file mode 100644 index 8f7baefc3..000000000 --- a/core/libs/prx/libfmodstudio/Export.cpp +++ /dev/null @@ -1,1007 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" - -enum FMOD_STUDIO_STOP_MODE { - FMOD_STUDIO_STOP_ALLOWFADEOUT = 0, - FMOD_STUDIO_STOP_IMMEDIATE = 1, - FMOD_STUDIO_STOP_MAX = 2 -}; - -enum FMOD_STUDIO_PLAYBACK_STATE { - FMOD_STUDIO_PLAYBACK_PLAYING = 0, - FMOD_STUDIO_PLAYBACK_SUSTAINING = 1, - FMOD_STUDIO_PLAYBACK_STOPPED = 2, - FMOD_STUDIO_PLAYBACK_STARTING = 3, - FMOD_STUDIO_PLAYBACK_STOPPING = 4, - FMOD_STUDIO_PLAYBACK_MAX = 5 -}; - -enum FMOD_STUDIO_LOADING_STATE { - FMOD_STUDIO_LOADING_STATE_UNLOADING = 0, - FMOD_STUDIO_LOADING_STATE_UNLOADED = 1, - FMOD_STUDIO_LOADING_STATE_LOADING = 2, - FMOD_STUDIO_LOADING_STATE_LOADED = 3, - FMOD_STUDIO_LOADING_STATE_ERROR = 4, - FMOD_STUDIO_LOADING_STATE_MAX = 5 -}; - -enum FMOD_STUDIO_EVENT_PROPERTY { - FMOD_STUDIO_EVENT_PROPERTY_CHANNELPRIORITY = 0, - FMOD_STUDIO_EVENT_PROPERTY_SCHEDULE_DELAY = 1, - FMOD_STUDIO_EVENT_PROPERTY_SCHEDULE_LOOKAHEAD = 2, - FMOD_STUDIO_EVENT_PROPERTY_MINIMUM_DISTANCE = 3, - FMOD_STUDIO_EVENT_PROPERTY_MAXIMUM_DISTANCE = 4, - FMOD_STUDIO_EVENT_PROPERTY_MAX = 5 -}; - -enum FMOD_STUDIO_SYSTEM_CALLBACK_TYPE { - FMOD_STUDIO_SYSTEM_CALLBACK_PREUPDATE = 1, - FMOD_STUDIO_SYSTEM_CALLBACK_POSTUPDATE = 2, - FMOD_STUDIO_SYSTEM_CALLBACK_BANK_UNLOAD = 4, - FMOD_STUDIO_SYSTEM_CALLBACK_ALL = 0xFFFFFFFF -}; - -enum FMOD_STUDIO_EVENT_CALLBACK_TYPE { - FMOD_STUDIO_EVENT_CALLBACK_CREATED = 1, - FMOD_STUDIO_EVENT_CALLBACK_DESTROYED = 2, - FMOD_STUDIO_EVENT_CALLBACK_STARTING = 4, - FMOD_STUDIO_EVENT_CALLBACK_STARTED = 8, - FMOD_STUDIO_EVENT_CALLBACK_RESTARTED = 16, - FMOD_STUDIO_EVENT_CALLBACK_STOPPED = 32, - FMOD_STUDIO_EVENT_CALLBACK_START_FAILED = 64, - FMOD_STUDIO_EVENT_CALLBACK_ALL = 0xFFFFFFFF -}; - -struct FMOD_GUID { - unsigned Data1; - unsigned short Data2; - unsigned short Data3; - unsigned char Data4[8]; -}; - -struct FMOD_VECTOR { - float x; - float y; - float z; -}; - -struct FMOD_3D_ATTRIBUTES { - FMOD_VECTOR position; - FMOD_VECTOR velocity; - FMOD_VECTOR forward; - FMOD_VECTOR up; -}; - -struct FMOD_CHANNELGROUP { - int unused; -}; - -struct FMOD_DSP_DESCRIPTION { - unsigned pluginsdkversion; - char name[32]; - unsigned version; -}; - -struct FMOD_STUDIO_PARAMETER_ID { - unsigned data1; - unsigned data2; -}; - -struct FMOD_STUDIO_PARAMETER_DESCRIPTION { - char name[256]; - float minimum; - float maximum; - float defaultvalue; -}; - -struct FMOD_STUDIO_BANK_INFO { - int size; - void* userdata; - int userdatalength; -}; - -struct FMOD_STUDIO_ADVANCEDSETTINGS { - int cbsize; - unsigned commandqueuesize; - unsigned handleinitialsize; -}; - -struct FMOD_STUDIO_CPU_USAGE { - float update; - float nonstreaming; - float streaming; -}; - -struct FMOD_STUDIO_BUFFER_USAGE { - int studiocommandqueue; - int studiohandle; - int values[6]; -}; - -struct FMOD_STUDIO_MEMORY_USAGE { - int exclusive; - int inclusive; - int sampledata; -}; - -struct FMOD_STUDIO_SOUND_INFO { - const char* name_or_data; - unsigned mode; - int subsoundindex; -}; - -struct FMOD_STUDIO_SYSTEM { - int unused; -}; - -struct FMOD_STUDIO_EVENTINSTANCE { - int unused; -}; - -typedef int (*FMOD_STUDIO_SYSTEM_CALLBACK)(FMOD_STUDIO_SYSTEM* system, FMOD_STUDIO_SYSTEM_CALLBACK_TYPE type, void* commanddata, void* userdata); -typedef int (*FMOD_STUDIO_EVENT_CALLBACK)(FMOD_STUDIO_EVENT_CALLBACK_TYPE type, FMOD_STUDIO_EVENTINSTANCE* event, void* parameters); - -namespace { - -std::mutex gStudioMutex; - -constexpr int FMOD_OK = 0; - -} - -namespace FMOD { -namespace Studio { - -class System; -class Bank; -class EventDescription; -class EventInstance; -class Bus; -class VCA; -class CommandReplay; - -class ID : public FMOD_GUID { -}; - -class Bank { -public: - std::string path; - bool sampleDataLoaded = false; - void* userData = nullptr; - bool APS5_VABI isValid() { - return true; - } - int APS5_VABI getID(ID* id) { - std::lock_guard lock(gStudioMutex); - if (id) std::memset(id, 0, sizeof(*id)); - return FMOD_OK; - } - int APS5_VABI getPath(char* path, int size, int* retrieved) { - std::lock_guard lock(gStudioMutex); - if (path && size > 0) { - std::strncpy(path, this->path.c_str(), static_cast(size - 1)); - path[size - 1] = '\0'; - } - if (retrieved) *retrieved = static_cast(this->path.size() + 1); - return FMOD_OK; - } - int APS5_VABI unload() { - std::lock_guard lock(gStudioMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI loadSampleData() { - std::lock_guard lock(gStudioMutex); - sampleDataLoaded = true; - return FMOD_OK; - } - int APS5_VABI unloadSampleData() { - std::lock_guard lock(gStudioMutex); - sampleDataLoaded = false; - return FMOD_OK; - } - int APS5_VABI getLoadingState(FMOD_STUDIO_LOADING_STATE* state) { - std::lock_guard lock(gStudioMutex); - if (state) *state = FMOD_STUDIO_LOADING_STATE_LOADED; - return FMOD_OK; - } - int APS5_VABI getSampleLoadingState(FMOD_STUDIO_LOADING_STATE* state) { - std::lock_guard lock(gStudioMutex); - if (state) *state = sampleDataLoaded ? FMOD_STUDIO_LOADING_STATE_LOADED : FMOD_STUDIO_LOADING_STATE_UNLOADED; - return FMOD_OK; - } - int APS5_VABI getStringCount(int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getEventCount(int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getEventList(EventDescription** array, int capacity, int* count) { - (void)array; (void)capacity; - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getBusCount(int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getBusList(Bus** array, int capacity, int* count) { - (void)array; (void)capacity; - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getVCACount(int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getVCAList(VCA** array, int capacity, int* count) { - (void)array; (void)capacity; - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class EventDescription { -public: - std::string path; - bool sampleDataLoaded = false; - void* userData = nullptr; - int APS5_VABI isValid() { - return true; - } - int APS5_VABI getID(ID* id) { - std::lock_guard lock(gStudioMutex); - if (id) std::memset(id, 0, sizeof(*id)); - return FMOD_OK; - } - int APS5_VABI getPath(char* path, int size, int* retrieved) { - std::lock_guard lock(gStudioMutex); - if (path && size > 0) { - std::strncpy(path, this->path.c_str(), static_cast(size - 1)); - path[size - 1] = '\0'; - } - if (retrieved) *retrieved = static_cast(this->path.size() + 1); - return FMOD_OK; - } - int APS5_VABI getInstanceCount(int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI getInstanceList(EventInstance** array, int capacity, int* count) { - (void)array; (void)capacity; - std::lock_guard lock(gStudioMutex); - if (count) *count = 0; - return FMOD_OK; - } - int APS5_VABI createInstance(EventInstance** instance); - int APS5_VABI loadSampleData() { - std::lock_guard lock(gStudioMutex); - sampleDataLoaded = true; - return FMOD_OK; - } - int APS5_VABI unloadSampleData() { - std::lock_guard lock(gStudioMutex); - sampleDataLoaded = false; - return FMOD_OK; - } - int APS5_VABI getSampleLoadingState(FMOD_STUDIO_LOADING_STATE* state) { - std::lock_guard lock(gStudioMutex); - if (state) *state = sampleDataLoaded ? FMOD_STUDIO_LOADING_STATE_LOADED : FMOD_STUDIO_LOADING_STATE_UNLOADED; - return FMOD_OK; - } - int APS5_VABI getLength(int* length) { - std::lock_guard lock(gStudioMutex); - if (length) *length = 0; - return FMOD_OK; - } - int APS5_VABI isSnapshot(bool* snapshot) { - std::lock_guard lock(gStudioMutex); - if (snapshot) *snapshot = false; - return FMOD_OK; - } - int APS5_VABI isOneshot(bool* oneshot) { - std::lock_guard lock(gStudioMutex); - if (oneshot) *oneshot = false; - return FMOD_OK; - } - int APS5_VABI isStream(bool* isstream) { - std::lock_guard lock(gStudioMutex); - if (isstream) *isstream = false; - return FMOD_OK; - } - int APS5_VABI is3D(bool* is3d) { - std::lock_guard lock(gStudioMutex); - if (is3d) *is3d = false; - return FMOD_OK; - } - int APS5_VABI hasSustainPoint(bool* sustainpoint) { - std::lock_guard lock(gStudioMutex); - if (sustainpoint) *sustainpoint = false; - return FMOD_OK; - } - int APS5_VABI getMinimumDistance(float* distance) { - std::lock_guard lock(gStudioMutex); - if (distance) *distance = 0.0f; - return FMOD_OK; - } - int APS5_VABI getMaximumDistance(float* distance) { - std::lock_guard lock(gStudioMutex); - if (distance) *distance = 10000.0f; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class EventInstance { -public: - EventDescription* description = nullptr; - bool playing = false; - bool paused = false; - float volume = 1.0f; - float pitch = 1.0f; - void* userData = nullptr; - std::unordered_map paramsByName; - int APS5_VABI isValid() { - return true; - } - int APS5_VABI getDescription(EventDescription** description) { - std::lock_guard lock(gStudioMutex); - if (description) *description = this->description; - return FMOD_OK; - } - int APS5_VABI getVolume(float* volume, float* finalvolume) { - std::lock_guard lock(gStudioMutex); - if (volume) *volume = this->volume; - if (finalvolume) *finalvolume = this->volume; - return FMOD_OK; - } - int APS5_VABI setVolume(float volume) { - std::lock_guard lock(gStudioMutex); - this->volume = volume; - return FMOD_OK; - } - int APS5_VABI getPitch(float* pitch, float* finalpitch) { - std::lock_guard lock(gStudioMutex); - if (pitch) *pitch = this->pitch; - if (finalpitch) *finalpitch = this->pitch; - return FMOD_OK; - } - int APS5_VABI setPitch(float pitch) { - std::lock_guard lock(gStudioMutex); - this->pitch = pitch; - return FMOD_OK; - } - int APS5_VABI getPaused(bool* paused) { - std::lock_guard lock(gStudioMutex); - if (paused) *paused = this->paused; - return FMOD_OK; - } - int APS5_VABI setPaused(bool paused) { - std::lock_guard lock(gStudioMutex); - this->paused = paused; - return FMOD_OK; - } - int APS5_VABI start() { - std::lock_guard lock(gStudioMutex); - playing = true; - return FMOD_OK; - } - int APS5_VABI stop(FMOD_STUDIO_STOP_MODE mode) { - (void)mode; - std::lock_guard lock(gStudioMutex); - playing = false; - return FMOD_OK; - } - int APS5_VABI release() { - std::lock_guard lock(gStudioMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI getPlaybackState(FMOD_STUDIO_PLAYBACK_STATE* state) { - std::lock_guard lock(gStudioMutex); - if (state) *state = playing ? FMOD_STUDIO_PLAYBACK_PLAYING : FMOD_STUDIO_PLAYBACK_STOPPED; - return FMOD_OK; - } - int APS5_VABI setTimelinePosition(int position) { - (void)position; - return FMOD_OK; - } - int APS5_VABI getTimelinePosition(int* position) { - std::lock_guard lock(gStudioMutex); - if (position) *position = 0; - return FMOD_OK; - } - int APS5_VABI setParameterByName(const char* name, float value, bool ignoreseekspeed) { - (void)ignoreseekspeed; - std::lock_guard lock(gStudioMutex); - if (name) paramsByName[name] = value; - return FMOD_OK; - } - int APS5_VABI getParameterByName(const char* name, float* value, float* finalvalue) { - std::lock_guard lock(gStudioMutex); - float stored = 0.0f; - if (name) { - auto it = paramsByName.find(name); - if (it != paramsByName.end()) stored = it->second; - } - if (value) *value = stored; - if (finalvalue) *finalvalue = stored; - return FMOD_OK; - } - int APS5_VABI setParameterByID(FMOD_STUDIO_PARAMETER_ID id, float value, bool ignoreseekspeed) { - (void)id; (void)ignoreseekspeed; - return FMOD_OK; - } - int APS5_VABI keyOff() { return FMOD_OK; } - int APS5_VABI setReverbLevel(int index, float level) { - (void)index; (void)level; - return FMOD_OK; - } - int APS5_VABI set3DAttributes(const FMOD_3D_ATTRIBUTES* attributes) { - (void)attributes; - return FMOD_OK; - } - int APS5_VABI setListenerMask(unsigned mask) { - (void)mask; - return FMOD_OK; - } - int APS5_VABI getChannelGroup(FMOD_CHANNELGROUP** group) { - std::lock_guard lock(gStudioMutex); - if (group) *group = nullptr; - return FMOD_OK; - } - int APS5_VABI setCallback(FMOD_STUDIO_EVENT_CALLBACK callback) { - (void)callback; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } - int APS5_VABI hasSustainPoint(bool* sustainpoint) { - std::lock_guard lock(gStudioMutex); - if (sustainpoint) *sustainpoint = false; - return FMOD_OK; - } - int APS5_VABI triggerCue() { return FMOD_OK; } -}; - -int APS5_VABI EventDescription::createInstance(EventInstance** instance) { - std::lock_guard lock(gStudioMutex); - if (!instance) return FMOD_OK; - *instance = new EventInstance(); - (*instance)->description = this; - return FMOD_OK; -} - -class Bus { -public: - std::string path; - float volume = 1.0f; - bool paused = false; - bool mute = false; - void* userData = nullptr; - int APS5_VABI isValid() { - return true; - } - int APS5_VABI getVolume(float* volume, float* finalvolume) { - std::lock_guard lock(gStudioMutex); - if (volume) *volume = this->volume; - if (finalvolume) *finalvolume = this->volume; - return FMOD_OK; - } - int APS5_VABI setVolume(float volume) { - std::lock_guard lock(gStudioMutex); - this->volume = volume; - return FMOD_OK; - } - int APS5_VABI getPaused(bool* paused) { - std::lock_guard lock(gStudioMutex); - if (paused) *paused = this->paused; - return FMOD_OK; - } - int APS5_VABI setPaused(bool paused) { - std::lock_guard lock(gStudioMutex); - this->paused = paused; - return FMOD_OK; - } - int APS5_VABI getMute(bool* mute) { - std::lock_guard lock(gStudioMutex); - if (mute) *mute = this->mute; - return FMOD_OK; - } - int APS5_VABI setMute(bool mute) { - std::lock_guard lock(gStudioMutex); - this->mute = mute; - return FMOD_OK; - } - int APS5_VABI stopAllEvents(FMOD_STUDIO_STOP_MODE mode) { - (void)mode; - return FMOD_OK; - } - int APS5_VABI getChannelGroup(FMOD_CHANNELGROUP** group) { - std::lock_guard lock(gStudioMutex); - if (group) *group = nullptr; - return FMOD_OK; - } - int APS5_VABI lockChannelGroup() { return FMOD_OK; } - int APS5_VABI unlockChannelGroup() { return FMOD_OK; } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class VCA { -public: - std::string path; - float volume = 1.0f; - void* userData = nullptr; - int APS5_VABI isValid() { - return true; - } - int APS5_VABI getVolume(float* volume, float* finalvolume) { - std::lock_guard lock(gStudioMutex); - if (volume) *volume = this->volume; - if (finalvolume) *finalvolume = this->volume; - return FMOD_OK; - } - int APS5_VABI setVolume(float volume) { - std::lock_guard lock(gStudioMutex); - this->volume = volume; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class CommandReplay { -public: - void* userData = nullptr; - int APS5_VABI isValid() { - return true; - } - int APS5_VABI getLength(float* length) { - std::lock_guard lock(gStudioMutex); - if (length) *length = 0.0f; - return FMOD_OK; - } - int APS5_VABI start() { return FMOD_OK; } - int APS5_VABI stop() { return FMOD_OK; } - int APS5_VABI seekToTime(float time) { - (void)time; - return FMOD_OK; - } - int APS5_VABI release() { - std::lock_guard lock(gStudioMutex); - delete this; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } -}; - -class System { -public: - bool initialized = false; - int maxChannels = 0; - int numListeners = 1; - void* userData = nullptr; - std::unordered_map paramsByName; - std::vector banks; - static int APS5_VABI create(System** system, unsigned headerversion) { - (void)headerversion; - std::lock_guard lock(gStudioMutex); - if (!system) return FMOD_OK; - *system = new System(); - return FMOD_OK; - } - int APS5_VABI isValid() { - return true; - } - int APS5_VABI release() { - std::lock_guard lock(gStudioMutex); - for (Bank* bank : banks) delete bank; - banks.clear(); - delete this; - return FMOD_OK; - } - int APS5_VABI initialize(int maxchannels, unsigned studioflags, unsigned flags, void* extradriverdata) { - (void)studioflags; (void)flags; (void)extradriverdata; - std::lock_guard lock(gStudioMutex); - maxChannels = maxchannels; - initialized = true; - return FMOD_OK; - } - int APS5_VABI update() { return FMOD_OK; } - int APS5_VABI getEvent(const char* pathOrID, EventDescription** event) { - std::lock_guard lock(gStudioMutex); - if (!event) return FMOD_OK; - *event = new EventDescription(); - if (pathOrID) (*event)->path = pathOrID; - return FMOD_OK; - } - int APS5_VABI getBankList(Bank** array, int capacity, int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = static_cast(banks.size()); - if (array && capacity > 0) { - int filled = capacity < static_cast(banks.size()) ? capacity : static_cast(banks.size()); - for (int i = 0; i < filled; i++) array[i] = banks[static_cast(i)]; - } - return FMOD_OK; - } - int APS5_VABI getBankCount(int* count) { - std::lock_guard lock(gStudioMutex); - if (count) *count = static_cast(banks.size()); - return FMOD_OK; - } - int APS5_VABI loadBankFile(const char* filename, unsigned flags, Bank** bank) { - (void)flags; - std::lock_guard lock(gStudioMutex); - if (!bank) return FMOD_OK; - *bank = new Bank(); - if (filename) (*bank)->path = filename; - banks.push_back(*bank); - return FMOD_OK; - } - int APS5_VABI loadBankMemory(const char* buffer, int length, unsigned mode, unsigned flags, Bank** bank) { - (void)buffer; (void)length; (void)mode; (void)flags; - std::lock_guard lock(gStudioMutex); - if (!bank) return FMOD_OK; - *bank = new Bank(); - banks.push_back(*bank); - return FMOD_OK; - } - int APS5_VABI unloadAll() { - std::lock_guard lock(gStudioMutex); - for (Bank* bank : banks) delete bank; - banks.clear(); - return FMOD_OK; - } - int APS5_VABI flushCommands() { return FMOD_OK; } - int APS5_VABI flushSampleLoading() { return FMOD_OK; } - int APS5_VABI setNumListeners(int numlisteners) { - std::lock_guard lock(gStudioMutex); - numListeners = numlisteners; - return FMOD_OK; - } - int APS5_VABI getNumListeners(int* numlisteners) { - std::lock_guard lock(gStudioMutex); - if (numlisteners) *numlisteners = numListeners; - return FMOD_OK; - } - int APS5_VABI setListenerAttributes(int index, const FMOD_3D_ATTRIBUTES* attributes, const FMOD_VECTOR* attenuationposition) { - (void)index; (void)attributes; (void)attenuationposition; - return FMOD_OK; - } - int APS5_VABI getBus(const char* pathOrID, Bus** bus) { - std::lock_guard lock(gStudioMutex); - if (!bus) return FMOD_OK; - *bus = new Bus(); - if (pathOrID) (*bus)->path = pathOrID; - return FMOD_OK; - } - int APS5_VABI getVCA(const char* pathOrID, VCA** vca) { - std::lock_guard lock(gStudioMutex); - if (!vca) return FMOD_OK; - *vca = new VCA(); - if (pathOrID) (*vca)->path = pathOrID; - return FMOD_OK; - } - int APS5_VABI getParameterByName(const char* name, float* value, float* finalvalue) { - std::lock_guard lock(gStudioMutex); - float stored = 0.0f; - if (name) { - auto it = paramsByName.find(name); - if (it != paramsByName.end()) stored = it->second; - } - if (value) *value = stored; - if (finalvalue) *finalvalue = stored; - return FMOD_OK; - } - int APS5_VABI setParameterByName(const char* name, float value, bool ignoreseekspeed) { - (void)ignoreseekspeed; - std::lock_guard lock(gStudioMutex); - if (name) paramsByName[name] = value; - return FMOD_OK; - } - int APS5_VABI setCallback(FMOD_STUDIO_SYSTEM_CALLBACK callback, FMOD_STUDIO_SYSTEM_CALLBACK_TYPE callbackmask) { - (void)callback; (void)callbackmask; - return FMOD_OK; - } - int APS5_VABI registerPlugin(const FMOD_DSP_DESCRIPTION* description) { - (void)description; - return FMOD_OK; - } - int APS5_VABI setUserData(void* userdata) { - std::lock_guard lock(gStudioMutex); - userData = userdata; - return FMOD_OK; - } - int APS5_VABI getUserData(void** userdata) { - std::lock_guard lock(gStudioMutex); - if (userdata) *userdata = userData; - return FMOD_OK; - } - int APS5_VABI getCPUUsage(FMOD_STUDIO_CPU_USAGE* usage) { - std::lock_guard lock(gStudioMutex); - if (usage) std::memset(usage, 0, sizeof(*usage)); - return FMOD_OK; - } - int APS5_VABI getBufferUsage(FMOD_STUDIO_BUFFER_USAGE* usage) { - std::lock_guard lock(gStudioMutex); - if (usage) std::memset(usage, 0, sizeof(*usage)); - return FMOD_OK; - } - int APS5_VABI resetBufferUsage() { return FMOD_OK; } - int APS5_VABI getMemoryUsage(FMOD_STUDIO_MEMORY_USAGE* memoryusage) { - std::lock_guard lock(gStudioMutex); - if (memoryusage) std::memset(memoryusage, 0, sizeof(*memoryusage)); - return FMOD_OK; - } -}; - -} -} - -extern "C" { - -namespace { - -// Round2: 20/25 studio stubs identified via real FMOD headers (const-correct -// Itanium manglings, verified with g++ + c++filt + NidCompute SHA1+suffix). -// Wrappers below are ABI-compatible (this+params, SysV) with the real const -// methods; most delegate to the existing non-const logic (const is -// compile-time only, same calling convention). - -// +V2QcIcvWpw = EventDescription::createInstance(EventInstance**) const -__attribute__((used)) int APS5_VABI fmodstudio_real_createInstance(const void* self, void** out) { - std::lock_guard lock(gStudioMutex); - if (!out) return 0; - auto* desc = const_cast(static_cast(self)); - auto* inst = new FMOD::Studio::EventInstance(); - inst->description = desc; - *out = inst; - return 0; -} -// 2QOSvz5hvAg = EventInstance::getPlaybackState(PLAYBACK_STATE*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getPlaybackState(const void* self, int* state) { - std::lock_guard lock(gStudioMutex); - const auto* inst = static_cast(self); - if (state) *state = (inst && inst->playing) ? 0 : 2; // PLAYING=0, STOPPED=2 - return 0; -} -// 3loRRCoqXfU = EventInstance::isValid() const -__attribute__((used)) int APS5_VABI fmodstudio_real_ei_isValid(const void* self) { - (void)self; - return 1; -} -// 6E6MUTGjxhI = System::getEvent(const char*, EventDescription**) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getEvent(const void* self, const char* path, void** out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (!out) return 0; - auto* ed = new FMOD::Studio::EventDescription(); - if (path) ed->path = path; - *out = ed; - return 0; -} -// 6nWYF1yMOl4 = Bank::getLoadingState(LOADING_STATE*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_bankLoading(const void* self, int* state) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (state) *state = 3; // LOADED - return 0; -} -// 7hd4bRJuLMg = System::getCoreSystem(CoreSystem**) const (placeholder 256B zeroed) -__attribute__((used)) int APS5_VABI fmodstudio_real_getCoreSystem(const void* self, void** out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (!out) return 0; - void* placeholder = std::calloc(1, 256); - *out = placeholder; - return 0; -} -// -7VafNNns2A = EventInstance::getUserData(void**) const -__attribute__((used)) int APS5_VABI fmodstudio_real_ei_getUserData(const void* self, void** out) { - std::lock_guard lock(gStudioMutex); - const auto* inst = static_cast(self); - if (out) *out = inst ? inst->userData : nullptr; - return 0; -} -// AdR01fo-WaM = System::getParameterByName(const char*, float*, float*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_sysGetParam(const void* self, const char* name, float* v, float* fv) { - std::lock_guard lock(gStudioMutex); - const auto* sys = static_cast(self); - float stored = 0.0f; - if (sys && name) { - auto it = sys->paramsByName.find(name); - if (it != sys->paramsByName.end()) stored = it->second; - } - if (v) *v = stored; - if (fv) *fv = stored; - return 0; -} -// alleMuKEWr8 = EventDescription::isOneshot(bool*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_isOneshot(const void* self, bool* out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (out) *out = false; - return 0; -} -// Bu8uFP7ME2k = System::getVCA(const char*, VCA**) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getVCA(const void* self, const char* path, void** out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (!out) return 0; - auto* vca = new FMOD::Studio::VCA(); - if (path) vca->path = path; - *out = vca; - return 0; -} -// DsFsPD0MWNc = System::getSoundInfo(const char*, SOUND_INFO*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getSoundInfo(const void* self, const char* key, void* info) { - (void)self; (void)key; - std::lock_guard lock(gStudioMutex); - if (info) std::memset(info, 0, sizeof(FMOD_STUDIO_SOUND_INFO)); - return 0; -} -// --f9RJwAh1A = EventDescription::getSampleLoadingState(LOADING_STATE*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_edSampleState(const void* self, int* state) { - std::lock_guard lock(gStudioMutex); - const auto* ed = static_cast(self); - if (state) *state = (ed && ed->sampleDataLoaded) ? 3 : 1; // LOADED=3, UNLOADED=1 - return 0; -} -// fbAVXdyBuso = Bank::isValid() const -__attribute__((used)) int APS5_VABI fmodstudio_real_bankIsValid(const void* self) { - (void)self; - return 1; -} -// LG53EJZJDnA = EventInstance::setCallback(callback, mask) (non-const, 2 params) -__attribute__((used)) int APS5_VABI fmodstudio_real_eiSetCallback(void* self, void* cb, unsigned mask) { - (void)self; (void)cb; (void)mask; - return 0; -} -// nhBPjhZ+VWs = EventDescription::is3D(bool*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_is3D(const void* self, bool* out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (out) *out = false; - return 0; -} -// omDBr+dcDVc = EventDescription::getInstanceCount(int*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getInstanceCount(const void* self, int* out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (out) *out = 0; - return 0; -} -// uWXqw4LeM5Q = EventDescription::isValid() const -__attribute__((used)) int APS5_VABI fmodstudio_real_edIsValid(const void* self) { - (void)self; - return 1; -} -// VdQjbIsdhXQ = EventDescription::getLength(int*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_edGetLength(const void* self, int* out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (out) *out = 0; - return 0; -} -// WP51b8simn8 = EventInstance::getTimelinePosition(int*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getTimeline(const void* self, int* out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (out) *out = 0; - return 0; -} -// Zi1n4MvZ3-0 = System::getBufferUsage(BUFFER_USAGE*) const -__attribute__((used)) int APS5_VABI fmodstudio_real_getBufferUsage(const void* self, void* out) { - (void)self; - std::lock_guard lock(gStudioMutex); - if (out) std::memset(out, 0, sizeof(FMOD_STUDIO_BUFFER_USAGE)); - return 0; -} - -__attribute__((used)) int fmodstudio_nid_stub_10() { NotImplemented_nid_no_patch("Cm2cmtCv8cA"); return 0; } -__attribute__((used)) int fmodstudio_nid_stub_12() { NotImplemented_nid_no_patch("EfM9xXvBmxk"); return 0; } -__attribute__((used)) int fmodstudio_nid_stub_15() { NotImplemented_nid_no_patch("Js90KQXVS4s"); return 0; } -__attribute__((used)) int fmodstudio_nid_stub_18() { NotImplemented_nid_no_patch("oCYWES02VPc"); return 0; } -__attribute__((used)) int fmodstudio_nid_stub_22() { NotImplemented_nid_no_patch("vVwA2cZA5e4"); return 0; } - -} - -APS5_EXPORT("+V2QcIcvWpw", fmodstudio_real_createInstance); -APS5_EXPORT("2QOSvz5hvAg", fmodstudio_real_getPlaybackState); -APS5_EXPORT("3loRRCoqXfU", fmodstudio_real_ei_isValid); -APS5_EXPORT("6E6MUTGjxhI", fmodstudio_real_getEvent); -APS5_EXPORT("6nWYF1yMOl4", fmodstudio_real_bankLoading); -APS5_EXPORT("7hd4bRJuLMg", fmodstudio_real_getCoreSystem); -APS5_EXPORT("-7VafNNns2A", fmodstudio_real_ei_getUserData); -APS5_EXPORT("AdR01fo-WaM", fmodstudio_real_sysGetParam); -APS5_EXPORT("alleMuKEWr8", fmodstudio_real_isOneshot); -APS5_EXPORT("Bu8uFP7ME2k", fmodstudio_real_getVCA); -APS5_EXPORT("Cm2cmtCv8cA", fmodstudio_nid_stub_10); -APS5_EXPORT("DsFsPD0MWNc", fmodstudio_real_getSoundInfo); -APS5_EXPORT("EfM9xXvBmxk", fmodstudio_nid_stub_12); -APS5_EXPORT("--f9RJwAh1A", fmodstudio_real_edSampleState); -APS5_EXPORT("fbAVXdyBuso", fmodstudio_real_bankIsValid); -APS5_EXPORT("Js90KQXVS4s", fmodstudio_nid_stub_15); -APS5_EXPORT("LG53EJZJDnA", fmodstudio_real_eiSetCallback); -APS5_EXPORT("nhBPjhZ+VWs", fmodstudio_real_is3D); -APS5_EXPORT("oCYWES02VPc", fmodstudio_nid_stub_18); -APS5_EXPORT("omDBr+dcDVc", fmodstudio_real_getInstanceCount); -APS5_EXPORT("uWXqw4LeM5Q", fmodstudio_real_edIsValid); -APS5_EXPORT("VdQjbIsdhXQ", fmodstudio_real_edGetLength); -APS5_EXPORT("vVwA2cZA5e4", fmodstudio_nid_stub_22); -APS5_EXPORT("WP51b8simn8", fmodstudio_real_getTimeline); -APS5_EXPORT("Zi1n4MvZ3-0", fmodstudio_real_getBufferUsage); - -} diff --git a/core/libs/tests/GuestNpCppWebApiIntrusivePtr.cpp b/core/libs/tests/GuestNpCppWebApiIntrusivePtr.cpp deleted file mode 100644 index 8b5c7b585..000000000 --- a/core/libs/tests/GuestNpCppWebApiIntrusivePtr.cpp +++ /dev/null @@ -1,256 +0,0 @@ -#include "prx/libc/include/general/VabiMacros.hpp" -#include -#include -#include -#include -#include - -using Deleter = void (APS5_VABI*)(void*); - -struct IntrusivePtr { - void* object; - Deleter deleter; - void* libContext; -}; - -using Construct = void (APS5_VABI*)(IntrusivePtr*); -using Copy = void (APS5_VABI*)(IntrusivePtr*, const IntrusivePtr*); -using Destroy = void (APS5_VABI*)(IntrusivePtr*); -using Access = void* (APS5_VABI*)(const IntrusivePtr*); - -extern "C" { -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEC1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEC1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEC1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEC1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEEC1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEEC1Ev(IntrusivePtr*); - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEC1ERS7_(IntrusivePtr*, const IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1ERS7_(IntrusivePtr*, const IntrusivePtr*); - -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEED1Ev(IntrusivePtr*); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6VectorINS3_INS1_12Leaderboards2V15EntryEEEEEED1Ev(IntrusivePtr*); - -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V15EntryEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6BinaryEEptEv(const IntrusivePtr*); -void* APS5_VABI _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6VectorINS3_INS1_12Leaderboards2V15EntryEEEEEEdeEv(const IntrusivePtr*); -} - -static void Require(bool value) { if (!value) std::abort(); } - -static constexpr std::size_t ObjectSize = 0x40; -static constexpr std::size_t VectorReferenceCountOffset = 0x30; - -struct DestroyCase { - Destroy destroy; - std::size_t referenceCountOffset; -}; - -static void* deletedObject = nullptr; -static int deleterCalls = 0; - -static void APS5_VABI RecordDelete(void* object) { - deletedObject = object; - ++deleterCalls; -} - -static std::int32_t ReadCount(const unsigned char* object, const std::size_t offset) { - std::int32_t value; - std::memcpy(&value, object + offset, sizeof(value)); - return value; -} - -static void WriteCount(unsigned char* object, const std::size_t offset, const std::int32_t value) { - std::memcpy(object + offset, &value, sizeof(value)); -} - -static bool OnlyCountChanged(const unsigned char* object, const std::size_t offset) { - for (std::size_t index = 0; index < ObjectSize; ++index) { - if (index >= offset && index < offset + sizeof(std::int32_t)) continue; - if (object[index] != 0x5a) return false; - } - return true; -} - -static void TestConstruct(const Construct construct) { - IntrusivePtr pointer; - std::memset(&pointer, 0xa5, sizeof(pointer)); - construct(&pointer); - Require(pointer.object == nullptr); - Require(pointer.deleter == nullptr); - Require(pointer.libContext == nullptr); -} - -static void TestAccess(const Access access) { - int object = 0; - int context = 0; - const IntrusivePtr empty{nullptr, RecordDelete, &context}; - Require(access(&empty) == nullptr); - const IntrusivePtr filled{&object, nullptr, nullptr}; - Require(access(&filled) == &object); -} - -static void TestCopy(const Copy copy) { - alignas(8) unsigned char object[ObjectSize]; - std::memset(object, 0x5a, sizeof(object)); - WriteCount(object, 0, 1); - int context = 0; - - const IntrusivePtr source{object, RecordDelete, &context}; - IntrusivePtr target; - std::memset(&target, 0xa5, sizeof(target)); - copy(&target, &source); - Require(target.object == object); - Require(target.deleter == RecordDelete); - Require(target.libContext == &context); - Require(source.object == object); - Require(ReadCount(object, 0) == 2); - Require(OnlyCountChanged(object, 0)); - - const IntrusivePtr empty{nullptr, RecordDelete, &context}; - std::memset(&target, 0xa5, sizeof(target)); - copy(&target, &empty); - Require(target.object == nullptr); - Require(target.deleter == RecordDelete); - Require(target.libContext == &context); -} - -static void TestDestroy(const DestroyCase& testCase) { - alignas(8) unsigned char object[ObjectSize]; - std::memset(object, 0x5a, sizeof(object)); - int context = 0; - const std::size_t offset = testCase.referenceCountOffset; - - deleterCalls = 0; - deletedObject = nullptr; - - IntrusivePtr empty{nullptr, RecordDelete, &context}; - testCase.destroy(&empty); - Require(empty.object == nullptr); - Require(empty.deleter == RecordDelete); - Require(empty.libContext == &context); - Require(deleterCalls == 0); - - WriteCount(object, offset, 2); - IntrusivePtr shared{object, RecordDelete, &context}; - testCase.destroy(&shared); - Require(ReadCount(object, offset) == 1); - Require(shared.object == object); - Require(shared.deleter == RecordDelete); - Require(shared.libContext == &context); - Require(deleterCalls == 0); - - IntrusivePtr last{object, RecordDelete, &context}; - testCase.destroy(&last); - Require(ReadCount(object, offset) == 0); - Require(OnlyCountChanged(object, offset)); - Require(deleterCalls == 1); - Require(deletedObject == object); - Require(last.object == nullptr); - Require(last.deleter == nullptr); - Require(last.libContext == &context); - - WriteCount(object, offset, 1); - IntrusivePtr pooled{object, nullptr, &context}; - bool thrown = false; - try { - testCase.destroy(&pooled); - } catch (const std::runtime_error&) { - thrown = true; - } - Require(thrown); - Require(deleterCalls == 1); -} - -static void TestSharedOwnership() { - alignas(8) unsigned char object[ObjectSize]; - std::memset(object, 0x5a, sizeof(object)); - WriteCount(object, 0, 1); - deleterCalls = 0; - deletedObject = nullptr; - - IntrusivePtr owner; - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1Ev(&owner); - owner.object = object; - owner.deleter = RecordDelete; - - IntrusivePtr argument; - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1ERS7_(&argument, &owner); - Require(_ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEptEv(&argument) == object); - Require(ReadCount(object, 0) == 2); - - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEED1Ev(&argument); - Require(ReadCount(object, 0) == 1); - Require(deleterCalls == 0); - - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEED1Ev(&owner); - Require(ReadCount(object, 0) == 0); - Require(deleterCalls == 1); - Require(deletedObject == object); - Require(_ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEptEv(&owner) == nullptr); -} - -int main() { - Require(sizeof(IntrusivePtr) == 0x18); - - const Construct constructors[] = { - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEC1Ev, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEC1Ev, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1Ev, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEC1Ev, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEC1Ev, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEEC1Ev, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEEC1Ev, - }; - for (const auto construct : constructors) TestConstruct(construct); - - const Access accessors[] = { - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V15EntryEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6BinaryEEptEv, - _ZNK3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6VectorINS3_INS1_12Leaderboards2V15EntryEEEEEEdeEv, - }; - for (const auto access : accessors) TestAccess(access); - - const Copy copies[] = { - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEEC1ERS7_, - _ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEEC1ERS7_, - }; - for (const auto copy : copies) TestCopy(copy); - - const DestroyCase destructors[] = { - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V121GetRankingRequestBodyEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122GetRankingResponseBodyEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V122RecordScoreRequestBodyEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V123RecordScoreResponseBodyEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V130GetBoardDefinitionResponseBodyEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V14UserEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS1_12Leaderboards2V19RecordApi26RecordScoreResponseHeadersEED1Ev, 0}, - {_ZN3sce2Np9CppWebApi6Common12IntrusivePtrINS2_6VectorINS3_INS1_12Leaderboards2V15EntryEEEEEED1Ev, VectorReferenceCountOffset}, - }; - for (const auto& testCase : destructors) TestDestroy(testCase); - - TestSharedOwnership(); - return 0; -} diff --git a/core/libs/tests/GuestNpCppWebApiString.cpp b/core/libs/tests/GuestNpCppWebApiString.cpp deleted file mode 100644 index c54ee17c3..000000000 --- a/core/libs/tests/GuestNpCppWebApiString.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include "prx/libc/include/general/VabiMacros.hpp" -#include -#include -#include -#include -#include - -extern "C" { -void APS5_VABI _ZN3sce2Np9CppWebApi6Common6StringC1EPNS2_10LibContextE(void* self, void* libContext); -void APS5_VABI _ZN3sce2Np9CppWebApi6Common6StringD1Ev(void* self); -const char* APS5_VABI _ZNK3sce2Np9CppWebApi6Common6String5c_strEv(const void* self); -} - -namespace { - -void Require(bool value) { if (!value) std::abort(); } - -constexpr std::size_t kStringSize = 0x20; -constexpr std::size_t kGuardSize = 0x10; -constexpr std::size_t kReferenceCountOffset = 0x00; -constexpr std::size_t kBufferOffset = 0x08; -constexpr std::size_t kBufferSizeOffset = 0x10; -constexpr std::size_t kLibContextOffset = 0x18; -constexpr unsigned char kFill = 0xA5; - -struct Storage { - alignas(8) unsigned char bytes[kStringSize + kGuardSize]; -}; - -template -TValue Load(const Storage& storage, std::size_t offset) { - TValue value; - std::memcpy(&value, storage.bytes + offset, sizeof(value)); - return value; -} - -template -void Store(Storage& storage, std::size_t offset, TValue value) { - std::memcpy(storage.bytes + offset, &value, sizeof(value)); -} - -bool GuardIntact(const Storage& storage) { - for (std::size_t i = kStringSize; i < sizeof(storage.bytes); i++) { - if (storage.bytes[i] != kFill) return false; - } - return true; -} - -bool DestructorThrows(Storage& storage) { - try { - _ZN3sce2Np9CppWebApi6Common6StringD1Ev(storage.bytes); - } catch (const std::runtime_error&) { - return true; - } - return false; -} - -void TestConstructedStringIsEmpty() { - std::uint64_t libContext = 1; - Storage storage; - std::memset(storage.bytes, kFill, sizeof(storage.bytes)); - - _ZN3sce2Np9CppWebApi6Common6StringC1EPNS2_10LibContextE(storage.bytes, &libContext); - - Require(Load(storage, kReferenceCountOffset) == 0); - Require(Load(storage, kBufferOffset) == nullptr); - Require(Load(storage, kBufferSizeOffset) == 0); - Require(Load(storage, kLibContextOffset) == &libContext); - Require(GuardIntact(storage)); - - const char* text = _ZNK3sce2Np9CppWebApi6Common6String5c_strEv(storage.bytes); - Require(text != nullptr && text[0] == '\0'); - - Storage before = storage; - _ZN3sce2Np9CppWebApi6Common6StringD1Ev(storage.bytes); - Require(std::memcmp(before.bytes, storage.bytes, sizeof(storage.bytes)) == 0); -} - -void TestNullLibContextIsStored() { - Storage storage; - std::memset(storage.bytes, kFill, sizeof(storage.bytes)); - - _ZN3sce2Np9CppWebApi6Common6StringC1EPNS2_10LibContextE(storage.bytes, nullptr); - - Require(Load(storage, kLibContextOffset) == nullptr); - Require(Load(storage, kBufferOffset) == nullptr); - Require(_ZNK3sce2Np9CppWebApi6Common6String5c_strEv(storage.bytes)[0] == '\0'); - _ZN3sce2Np9CppWebApi6Common6StringD1Ev(storage.bytes); -} - -void TestBufferIsReturnedAndNotDroppedSilently() { - std::uint64_t libContext = 1; - char text[] = "ranking"; - Storage storage; - std::memset(storage.bytes, kFill, sizeof(storage.bytes)); - - _ZN3sce2Np9CppWebApi6Common6StringC1EPNS2_10LibContextE(storage.bytes, &libContext); - Store(storage, kBufferOffset, text); - Store(storage, kBufferSizeOffset, sizeof(text)); - - Require(_ZNK3sce2Np9CppWebApi6Common6String5c_strEv(storage.bytes) == text); - Require(DestructorThrows(storage)); - Require(std::strcmp(text, "ranking") == 0); -} - -} - -int main() { - TestConstructedStringIsEmpty(); - TestNullLibContextIsStored(); - TestBufferIsReturnedAndNotDroppedSilently(); -} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index cd0f433c1..657c1707a 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -108,10 +108,8 @@ Throughout the project, every function at every stage either **does exactly what - [sceHttp2GetMemoryPoolStats](../../core/libs/prx/libSceHttp2/Export.cpp) (libSceHttp2) - unknown signature - [sceNetGetMemoryPoolStats](../../core/libs/prx/libSceNet/Export.cpp) (libSceNet) - unknown signature - [sceHttpSetRequestStatusCallback](../../core/libs/prx/libSceHttp/Export.cpp) (libSceHttp) - no reference implements it (shadPS4 only logs and returns 0); when the callback runs and what status it gets is unknown -- [sce::Np::CppWebApi::Common::IntrusivePtr](../../core/libs/prx/libSceNpCppWebApi/Export.cpp) (libSceNpCppWebApi) - the 0x18-byte layout (object, deleter, `LibContext*`) and the offset of the 32-bit reference count in the pointee (0x00, 0x30 for `Vector`) come from the module bundled with one title (PPSA21564); other SDK versions are not checked. The destructor throws on the last reference of a pointer without a deleter: destroying the object needs its destructor and the `LibContext` allocator, which are not implemented - [sceNpSessionSignalingGetMemoryInfo](../../core/libs/prx/libSceNpSessionSignaling/Export.cpp) (libSceNpSessionSignaling) - unknown signature - [sceNpSessionSignalingGetConnectionStatistics](../../core/libs/prx/libSceNpSessionSignaling/Export.cpp) (libSceNpSessionSignaling) - unknown signature -- [sce::Np::CppWebApi::Common::String](../../core/libs/prx/libSceNpCppWebApi/Export.cpp) (libSceNpCppWebApi) - the 0x20-byte layout (32-bit reference count, buffer at 0x08, buffer size at 0x10, `LibContext*` at 0x18) comes from the module bundled with one title (PPSA21564); other SDK versions are not checked. The destructor throws for a non-null buffer: releasing it needs the `LibContext` allocator, which is not implemented - [sceUserServiceGetAgeLevel](../../core/libs/prx/libSceUserService/Export.cpp) (libSceUserService) - the meaning of the value is unknown; 0 is reported, as for the unset game presets. PPSA12544 (Unity) only stores it for its user profile - [sceGameUpdateGetAddcontLatestVersion](../../core/libs/prx/libSceGameUpdate/Export.cpp) (libSceGameUpdate) - a null `entitlement_label` throws: KytyPS5 accepts it, prosper returns `0x80412803`. Bytes after `found` are zeroed as in KytyPS5; prosper leaves them untouched - [sceSystemServiceDisableMediaPlay](../../core/libs/prx/libSceSystemService/Export.cpp) (libSceSystemService) - unknown signature diff --git a/tools/package_release.py b/tools/package_release.py index 25296672b..53add7365 100644 --- a/tools/package_release.py +++ b/tools/package_release.py @@ -11,7 +11,6 @@ def package(platform, build, output, version): raise ValueError(f"Invalid release tag for asset filenames: {version}") libraries = sorted((build / "core/libs/libs").glob("*.prx")) expected = {f"{directory.name}.prx" for directory in Path("core/libs/prx").iterdir() if directory.is_dir()} - expected.add("libcohtml.Prospero.prx") missing = expected - {library.name for library in libraries} if missing: raise RuntimeError(f"Missing patched libraries: {', '.join(sorted(missing))}") From 4e5a1fe9d44f58550e9302ae417300b286562deb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 01:37:05 +0200 Subject: [PATCH 32/42] feat(rtc): parse RFC 2822 and asctime strings in sceRtcParseDateTime Co-Authored-By: Claude --- core/libs/prx/libSceRtc/Export.cpp | 113 ++++++++++++++++++++++++----- core/libs/tests/GuestRtc.cpp | 17 +++++ docs/dev/TechnicalDebt.md | 2 +- 3 files changed, 113 insertions(+), 19 deletions(-) diff --git a/core/libs/prx/libSceRtc/Export.cpp b/core/libs/prx/libSceRtc/Export.cpp index 08bf4bb06..78cedfc66 100644 --- a/core/libs/prx/libSceRtc/Export.cpp +++ b/core/libs/prx/libSceRtc/Export.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include "SceTypes.hpp" @@ -158,6 +159,97 @@ bool parseZoneSuffix(const char*& cursor, std::int64_t& offsetMinutes) { return false; } +bool parseName(const char*& cursor, const char* const* names, int count, int& index) { + for (index = 0; index < count; ++index) { + if (std::strncmp(cursor, names[index], 3) == 0) { + cursor += 3; + return true; + } + } + return false; +} + +bool parseWeekday(const char*& cursor) { + static constexpr const char* names[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + int index = 0; + return parseName(cursor, names, 7, index); +} + +bool parseMonth(const char*& cursor, int& month) { + static constexpr const char* names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + if (!parseName(cursor, names, 12, month)) return false; + ++month; + return true; +} + +bool parseClock(const char*& cursor, int& hour, int& minute, int& second) { + return parseDigits(cursor, 2, hour) && *cursor++ == ':' && parseDigits(cursor, 2, minute) && *cursor++ == ':' && parseDigits(cursor, 2, second); +} + +RtcDateTime makeDateTime(int year, int month, int day, int hour, int minute, int second, std::uint32_t microsecond) { + return RtcDateTime{static_cast(year), static_cast(month), static_cast(day), + static_cast(hour), static_cast(minute), static_cast(second), microsecond}; +} + +bool parseIsoDateTime(const char* cursor, RtcDateTime& time, std::int64_t& offsetMinutes) { + int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0; + if (!parseDigits(cursor, 4, year) || *cursor++ != '-' || !parseDigits(cursor, 2, month) || *cursor++ != '-' || !parseDigits(cursor, 2, day)) return false; + if (*cursor != 'T' && *cursor != 't' && *cursor != ' ') return false; + ++cursor; + if (!parseClock(cursor, hour, minute, second)) return false; + std::uint32_t microsecond = 0; + if (*cursor == '.') { + ++cursor; + std::uint32_t scale = 100000; + if (*cursor < '0' || *cursor > '9') return false; + for (; *cursor >= '0' && *cursor <= '9'; ++cursor, scale /= 10) microsecond += static_cast(*cursor - '0') * scale; + } + offsetMinutes = 0; + if (*cursor != 0 && !parseZoneSuffix(cursor, offsetMinutes)) return false; + if (*cursor != 0) return false; + time = makeDateTime(year, month, day, hour, minute, second, microsecond); + return true; +} + +bool parseRfc2822DateTime(const char* cursor, RtcDateTime& time, std::int64_t& offsetMinutes) { + int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0; + if (!parseWeekday(cursor) || *cursor++ != ',' || *cursor++ != ' ' || !parseDigits(cursor, 2, day) || *cursor++ != ' ') return false; + if (!parseMonth(cursor, month) || *cursor++ != ' ' || !parseDigits(cursor, 4, year) || *cursor++ != ' ' || !parseClock(cursor, hour, minute, second)) return false; + offsetMinutes = 0; + if (*cursor == ' ') { + ++cursor; + if (std::strcmp(cursor, "GMT") == 0) { + cursor += 3; + } else if (*cursor == '+' || *cursor == '-') { + const int sign = *cursor++ == '-' ? -1 : 1; + int offsetHours = 0, offsetMinute = 0; + if (!parseDigits(cursor, 2, offsetHours) || !parseDigits(cursor, 2, offsetMinute)) return false; + if (offsetHours > 23 || offsetMinute > 59) return false; + offsetMinutes = sign * (offsetHours * 60 + offsetMinute); + } else { + return false; + } + } + if (*cursor != 0) return false; + time = makeDateTime(year, month, day, hour, minute, second, 0); + return true; +} + +bool parseAsctimeDateTime(const char* cursor, RtcDateTime& time, std::int64_t& offsetMinutes) { + int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0; + if (!parseWeekday(cursor) || *cursor++ != ' ' || !parseMonth(cursor, month) || *cursor++ != ' ') return false; + if (*cursor == ' ') { + ++cursor; + if (!parseDigits(cursor, 1, day)) return false; + } else if (!parseDigits(cursor, 2, day)) { + return false; + } + if (*cursor++ != ' ' || !parseClock(cursor, hour, minute, second) || *cursor++ != ' ' || !parseDigits(cursor, 4, year) || *cursor != 0) return false; + offsetMinutes = 0; + time = makeDateTime(year, month, day, hour, minute, second, 0); + return true; +} + } extern "C" { @@ -313,28 +405,13 @@ int APS5_VABI sceRtcParseRFC3339(RtcTick* utc, const char* date_time) { int APS5_VABI sceRtcParseDateTime(RtcTick* utc, const char* date_time) { if (!utc || !date_time) return SCE_RTC_ERROR_INVALID_POINTER; - const char* cursor = date_time; - int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0; - bool ok = parseDigits(cursor, 4, year) && *cursor++ == '-' && parseDigits(cursor, 2, month) && *cursor++ == '-' && parseDigits(cursor, 2, day); - ok = ok && (*cursor == 'T' || *cursor == 't' || *cursor == ' '); - if (ok) ++cursor; - ok = ok && parseDigits(cursor, 2, hour) && *cursor++ == ':' && parseDigits(cursor, 2, minute) && *cursor++ == ':' && parseDigits(cursor, 2, second); - std::uint32_t microsecond = 0; - if (ok && *cursor == '.') { - ++cursor; - std::uint32_t scale = 100000; - ok = *cursor >= '0' && *cursor <= '9'; - for (; ok && *cursor >= '0' && *cursor <= '9'; ++cursor, scale /= 10) microsecond += static_cast(*cursor - '0') * scale; - } + RtcDateTime time{}; std::int64_t offsetMinutes = 0; - if (ok && *cursor != 0) ok = parseZoneSuffix(cursor, offsetMinutes); - if (ok && *cursor != 0) ok = false; - if (!ok) { + if (!parseIsoDateTime(date_time, time, offsetMinutes) && !parseRfc2822DateTime(date_time, time, offsetMinutes) + && !parseAsctimeDateTime(date_time, time, offsetMinutes)) { NotImplemented_nid_no_patch(__func__); return SCE_RTC_ERROR_BAD_PARSE; } - const RtcDateTime time{static_cast(year), static_cast(month), static_cast(day), - static_cast(hour), static_cast(minute), static_cast(second), microsecond}; if (const int result = validate(&time); result != 0) return result; const RtcTick local{toTick(time)}; return addTicks(utc, &local, -offsetMinutes, TICKS_PER_MINUTE); diff --git a/core/libs/tests/GuestRtc.cpp b/core/libs/tests/GuestRtc.cpp index 2d843ebfe..a9d053914 100644 --- a/core/libs/tests/GuestRtc.cpp +++ b/core/libs/tests/GuestRtc.cpp @@ -150,12 +150,29 @@ int main() { Require(sceRtcParseDateTime(&tick, "1970-01-01T00:00:00Z") == 0 && tick.tick == unixEpochTick); Require(sceRtcParseDateTime(&tick, "2023-02-29T00:00:00") == invalidDay); Require(sceRtcParseDateTime(nullptr, "1970-01-01T00:00:00Z") == invalidPointer); + Require(sceRtcParseDateTime(&tick, "Thu, 29 Feb 2024 12:34:56") == 0 && tick.tick == leapDayTick - 789000ull); + Require(sceRtcParseDateTime(&tick, "Thu, 29 Feb 2024 12:34:56 GMT") == 0 && tick.tick == leapDayTick - 789000ull); + Require(sceRtcParseDateTime(&tick, "Thu, 29 Feb 2024 14:04:56 +0130") == 0 && tick.tick == leapDayTick - 789000ull); + Require(sceRtcParseDateTime(&tick, "Thu, 29 Feb 2024 11:04:56 -0130") == 0 && tick.tick == leapDayTick - 789000ull); + Require(sceRtcParseDateTime(&tick, "Thu, 01 Jan 1970 00:00:00 +0000") == 0 && tick.tick == unixEpochTick); + Require(sceRtcParseDateTime(&tick, "Thu, 30 Feb 2024 00:00:00") == invalidDay); + Require(sceRtcParseDateTime(&tick, "Thu Feb 29 12:34:56 2024") == 0 && tick.tick == leapDayTick - 789000ull); + Require(sceRtcParseDateTime(&tick, "Thu Jan 1 00:00:00 1970") == 0 && tick.tick == unixEpochTick); + Require(sceRtcParseDateTime(&tick, "Thu Feb 30 00:00:00 2024") == invalidDay); const char* unparseable[] = { "2024-02-29", "2024/02/29T12:34:56", "2024-02-29T12:34:56Zjunk", "2024-02-29T12:34:56+99:99", "2024-02-29T12:34:56.", + "Thu, 29 Feb 2024 12:34:56 +01:30", + "Thu, 29 Feb 2024 12:34:56 PST", + "Thu, 29 Xyz 2024 12:34:56", + "Xyz, 29 Feb 2024 12:34:56", + "Thu, 29 Feb 2024 12:34:56 +2400", + "Thu Feb 29 12:34:56 2024\n", + "Thu Feb 29 12:34:56 24", + "Thu Feb 29 12:34:56 2024", }; for (const char* text : unparseable) { bool thrown = false; diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index cd0f433c1..06c6f8654 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -33,7 +33,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceVideoOutRegisterBuffers2](../../core/libs/prx/libSceVideoOut/src/Buffer.cpp) (libSceVideoOut) - buffer option 8 (STRICT_COLORIMETRY) is presented as option 0, with the stored values unchanged; what the console changes for it is unknown. Only options 0 and 8 are accepted - [sceVideoOutRegisterBuffers2](../../core/libs/prx/libSceVideoOut/src/Buffer.cpp) (libSceVideoOut) - DCC buffers (category 1): `dcc_control` is taken as the CB_DCC_CONTROL block layout, only bits 0x10026c are accepted; `dcc_cb_register_clear_color` as the register-clear texel, only 32-bit values are presented - [sceVideoOutOpen](../../core/libs/prx/libSceVideoOut/src/Output.cpp) (libSceVideoOut) - the open param's first word is unknown (PPSA21564 passes 16; it is not the byte size, since the affinity mask is at offset 16); only 16 is accepted. Whether the param continues past offset 24 is also unknown -- [sceRtcParseDateTime](../../core/libs/prx/libSceRtc/Export.cpp) (libSceRtc) - accepted format assumed to be the ISO 8601 subset `YYYY-MM-DDTHH:MM:SS[.ffffff]` (T/t/space separator, optional fractional seconds) with the sibling RFC 3339 zone suffix (`Z` or `±HH:MM`); a string without a zone is taken as UTC, and anything outside this shape throws instead of returning a parse error, unverified against hardware +- [sceRtcParseDateTime](../../core/libs/prx/libSceRtc/Export.cpp) (libSceRtc) - accepted format assumed to be the ISO 8601 subset `YYYY-MM-DDTHH:MM:SS[.ffffff]` (T/t/space separator, optional fractional seconds) with the sibling RFC 3339 zone suffix (`Z` or `±HH:MM`), plus the RFC 2822 shape `Ddd, DD Mon YYYY HH:MM:SS[ GMT| ±HHMM]` and the asctime shape `Ddd Mon DD HH:MM:SS YYYY` (day zero- or space-padded) that shadPS4 parses at fixed positions; the weekday name is not checked against the date, a `±HHMM` offset is subtracted to get UTC like the RFC 3339 path (shadPS4 adds it), a string without a zone is taken as UTC, and anything outside these shapes throws instead of returning a parse error, unverified against hardware - [sceAudio3dPortOpen](../../core/libs/prx/libSceAudio3d/Export.cpp) (libSceAudio3d) - buffer modes 0 and 1 (also selected by the 0x10 and 0x18 parameter sizes) and 3 beds depend on an SDK version check in the module ([prosper](https://github.com/mattias800/prosper)) and throw. A repeated `sceAudio3dInitialize` (`NOT_READY` in shadPS4, 0 in prosper) and `sceAudio3dPortAdvance` on a full queue (`NOT_READY` in shadPS4, unhandled in KytyPS5) throw too - [AMPR WriteAddressFromCounterPairOnCompletion](../../core/libs/prx/libSceAmpr/Export.cpp) (libSceAmpr) - the pair of an even counter n is assumed to give counter n in the low 32 bits and n + 1 in the high 32 bits. Wait compare values, wait flush and counter index ranges follow the [ampr_emu](https://github.com/drakmor/ampr_emu) reimplementation; the flush is accepted and has no effect, as commands run in order - [AMPR command sizes](../../core/libs/prx/libSceAmpr/Export.cpp) (libSceAmpr) - commands use the emulator's own encoding with an 8-byte header, so `Nop(n)` takes 8 + 4n bytes where the console record is n dwords including its header (`NopWithData(n)`: (n + 1) dwords). The measure functions agree with the appended sizes, but a title that pads to an exact offset or the end of the buffer with `Nop(remaining / 4)` gets `SCE_AMPR_ERROR_BUFFER_FULL` or a shifted offset. The at-start flag of the `_04_00` writes is ignored; commands run in order, each after the previous one completes From 819c04532750346efbbffa34f2fd689002f30ea2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 01:15:02 +0200 Subject: [PATCH 33/42] feat(libSceNgs2.native): sampler voice low-pass filter Co-Authored-By: Claude --- .../libs/prx/libSceNgs2.native/CMakeLists.txt | 2 +- .../libSceNgs2.native/include/Ngs2Types.hpp | 14 ++ .../libSceNgs2.native/src/Ngs2Internal.hpp | 20 ++ core/libs/prx/libSceNgs2.native/src/Rack.cpp | 1 + .../libs/prx/libSceNgs2.native/src/Render.cpp | 43 ++++- core/libs/prx/libSceNgs2.native/src/Voice.cpp | 37 ++++ .../libSceNgs2.native/tests/Ngs2Filter.cpp | 182 ++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 8 files changed, 297 insertions(+), 3 deletions(-) create mode 100644 core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp diff --git a/core/libs/prx/libSceNgs2.native/CMakeLists.txt b/core/libs/prx/libSceNgs2.native/CMakeLists.txt index 7af3c3299..986014221 100644 --- a/core/libs/prx/libSceNgs2.native/CMakeLists.txt +++ b/core/libs/prx/libSceNgs2.native/CMakeLists.txt @@ -25,7 +25,7 @@ if(MINGW) endif() if(BUILD_TESTING) - foreach(ngs2Test IN ITEMS Render Atrac9) + foreach(ngs2Test IN ITEMS Render Atrac9 Filter) string(TOLOWER ${ngs2Test} testName) add_test_executable(ngs2_${testName}_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/Ngs2${ngs2Test}.cpp) target_include_directories(ngs2_${testName}_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/LibAtrac9/C/src) diff --git a/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp b/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp index aa7752af9..6c99f3f42 100644 --- a/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp +++ b/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp @@ -46,6 +46,7 @@ static constexpr std::uint32_t SCE_NGS2_SAMPLER_VOICE_PARAM_SETUP = 0x10000000; static constexpr std::uint32_t SCE_NGS2_SAMPLER_VOICE_PARAM_ADD_WAVEFORM_BLOCKS = 0x10000001; static constexpr std::uint32_t SCE_NGS2_SAMPLER_VOICE_PARAM_EXIT_LOOP = 0x10000004; static constexpr std::uint32_t SCE_NGS2_SAMPLER_VOICE_PARAM_PITCH = 0x10000005; +static constexpr std::uint32_t SCE_NGS2_SAMPLER_VOICE_PARAM_FILTER = 0x1000000a; static constexpr std::uint32_t SCE_NGS2_SUBMIXER_VOICE_PARAM_SETUP = 0x20000000; static constexpr std::uint32_t SCE_NGS2_MASTERING_VOICE_PARAM_SETUP = 0x30000000; static constexpr std::uint32_t SCE_NGS2_MASTERING_VOICE_PARAM_OUTPUT = 0x30000005; @@ -254,6 +255,19 @@ struct Ngs2SamplerVoicePitchParam { float ratio; }; +struct Ngs2SamplerVoiceFilterParam { + Ngs2VoiceParamHeader header; + std::uint32_t index; + std::uint32_t location; + std::uint32_t type; + std::uint64_t channel_mask; + float frequency; + float q; + float level; + std::uint32_t reserved[3]; +}; +static_assert(sizeof(Ngs2SamplerVoiceFilterParam) == 56); + struct Ngs2SubmixerVoiceSetupParam { Ngs2VoiceParamHeader header; std::uint32_t num_io_channels; diff --git a/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp b/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp index 164934cb9..615380f59 100644 --- a/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp +++ b/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp @@ -47,6 +47,24 @@ struct Ngs2Atrac9 { struct Ngs2Voice; +struct Ngs2FilterHistory { + double x1 = 0.0; + double x2 = 0.0; + double y1 = 0.0; + double y2 = 0.0; +}; + +struct Ngs2Filter { + bool enabled = false; + std::uint64_t bypassMask = 0; + double b0 = 1.0; + double b1 = 0.0; + double b2 = 0.0; + double a1 = 0.0; + double a2 = 0.0; + std::vector history; +}; + struct Ngs2Port { Ngs2Voice* dest = nullptr; float volume = 1.0f; @@ -73,6 +91,7 @@ struct Ngs2Voice { std::uint32_t callbackFlags = 0; std::vector ports; std::vector> matrices; + std::vector filters; std::uint32_t outputId = 0; std::vector samples; bool rendering = false; @@ -88,6 +107,7 @@ struct Ngs2Rack { Ngs2System* system = nullptr; std::uint32_t rackId = 0; std::uint32_t maxChannels = 0; + std::uint32_t maxFilters = 0; Ngs2ContextBufferInfo bufferInfo{}; Ngs2BufferAllocator allocator{}; std::vector voices; diff --git a/core/libs/prx/libSceNgs2.native/src/Rack.cpp b/core/libs/prx/libSceNgs2.native/src/Rack.cpp index 385349f7c..b98f15b96 100644 --- a/core/libs/prx/libSceNgs2.native/src/Rack.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Rack.cpp @@ -93,6 +93,7 @@ static int CreateRack(Ngs2Handle systemHandle, std::uint32_t rackId, const RackO rack->system = system; rack->rackId = rackId; rack->maxChannels = RackMaxChannels(rackId, options); + rack->maxFilters = rackId == SCE_NGS2_RACK_ID_SAMPLER ? options.sampler.max_filters : 0; rack->bufferInfo = bufferInfo; rack->allocator = allocator; rack->voices.resize(options.common.max_voices); diff --git a/core/libs/prx/libSceNgs2.native/src/Render.cpp b/core/libs/prx/libSceNgs2.native/src/Render.cpp index 87f29408c..ba5b520b3 100644 --- a/core/libs/prx/libSceNgs2.native/src/Render.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Render.cpp @@ -99,7 +99,46 @@ static void ConsumeSamples(Ngs2Voice& voice, std::uint32_t grain, std::uint32_t voice.phase &= PHASE_FRACTION; } voice.hasSamples = written != 0; - if (voice.state == Ngs2PlayState::Playing && voice.blocks.empty() && !voice.acceptsBlocks) voice.state = Ngs2PlayState::Empty; +} + +static bool Bypasses(const Ngs2Filter& filter, std::uint32_t channel) { + return channel < 64 && (filter.bypassMask & (std::uint64_t{1} << channel)) != 0; +} + +static bool HasHistory(const Ngs2Filter& filter) { + if (!filter.enabled) return false; + for (std::uint32_t channel = 0; channel < filter.history.size(); channel++) { + const auto& h = filter.history[channel]; + if (!Bypasses(filter, channel) && (h.x1 != 0.0 || h.x2 != 0.0 || h.y1 != 0.0 || h.y2 != 0.0)) return true; + } + return false; +} + +static void ApplyFilter(Ngs2Voice& voice, Ngs2Filter& filter, std::uint32_t grain) { + for (std::uint32_t channel = 0; channel < voice.channels; channel++) { + if (Bypasses(filter, channel)) continue; + auto& h = filter.history[channel]; + for (std::uint32_t i = 0; i < grain; i++) { + auto& sample = voice.samples[channel * grain + i]; + const double x = sample; + double y = filter.b0 * x + filter.b1 * h.x1 + filter.b2 * h.x2 - filter.a1 * h.y1 - filter.a2 * h.y2; + if (std::abs(y) < 1e-20) y = 0.0; + h = {x, h.x1, y, h.y1}; + sample = static_cast(y); + } + } +} + +static void RenderSampler(Ngs2Voice& voice, std::uint32_t grain, std::uint32_t systemRate) { + ConsumeSamples(voice, grain, systemRate); + for (auto& filter : voice.filters) { + if (!filter.enabled || (!voice.hasSamples && !HasHistory(filter))) continue; + ApplyFilter(voice, filter, grain); + voice.hasSamples = true; + } + if (voice.state == Ngs2PlayState::Playing && voice.blocks.empty() && !voice.acceptsBlocks && std::none_of(voice.filters.begin(), voice.filters.end(), HasHistory)) { + voice.state = Ngs2PlayState::Empty; + } } static void RenderVoice(Ngs2Voice& voice, const std::vector& voices, std::uint32_t grain, std::uint32_t systemRate); @@ -135,7 +174,7 @@ static void RenderVoice(Ngs2Voice& voice, const std::vector& voices, voice.samples.assign(static_cast(grain) * voice.channels, 0.0f); voice.hasSamples = false; if (voice.state == Ngs2PlayState::Playing && voice.channels != 0) { - if (voice.rack->rackId == SCE_NGS2_RACK_ID_SAMPLER) ConsumeSamples(voice, grain, systemRate); + if (voice.rack->rackId == SCE_NGS2_RACK_ID_SAMPLER) RenderSampler(voice, grain, systemRate); else MixInputs(voice, voices, grain, systemRate); } voice.rendering = false; diff --git a/core/libs/prx/libSceNgs2.native/src/Voice.cpp b/core/libs/prx/libSceNgs2.native/src/Voice.cpp index 0f2889fed..b92ece2f4 100644 --- a/core/libs/prx/libSceNgs2.native/src/Voice.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Voice.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -47,6 +48,7 @@ void Ngs2Voice::ResetSetup() { SetEvent(SCE_NGS2_VOICE_EVENT_STOP_IMM); std::fill(ports.begin(), ports.end(), Ngs2Port{}); for (auto& matrix : matrices) matrix.clear(); + filters.clear(); channels = 0; sampleRate = 0; waveformType = 0; @@ -178,6 +180,40 @@ static void AddWaveformBlocks(Ngs2Voice& voice, const Ngs2SamplerVoiceWaveformBl } } +static void SetFilter(Ngs2Voice& voice, const Ngs2SamplerVoiceFilterParam& param) { + if (param.index >= voice.rack->maxFilters) APS5_INVALID_ARG_EX; + if (voice.filters.size() <= param.index) voice.filters.resize(param.index + 1); + auto& filter = voice.filters[param.index]; + if (param.type == 0) { + filter = {}; + return; + } + if (param.location != 1 || param.type != 1) { + throw std::runtime_error("NGS2: sampler filter location " + std::to_string(param.location) + " type " + std::to_string(param.type) + " is not implemented"); + } + if (!std::isfinite(param.frequency) || param.frequency < 0.0f || !std::isfinite(param.q) || param.q <= 0.0f || !std::isfinite(param.level) || param.level < 0.0f) { + APS5_INVALID_ARG_EX; + } + const double rate = voice.rack->system->option.sample_rate; + filter.enabled = true; + filter.bypassMask = param.channel_mask; + filter.history.resize(voice.channels); + if (param.frequency == 0.0f || param.frequency >= rate * 0.5) { + filter.b0 = param.frequency == 0.0f ? 0.0 : param.level; + filter.b1 = filter.b2 = filter.a1 = filter.a2 = 0.0; + return; + } + const double omega = 2.0 * std::numbers::pi * param.frequency / rate; + const double cosine = std::cos(omega); + const double alpha = std::sin(omega) / (2.0 * param.q); + const double inverseA0 = 1.0 / (1.0 + alpha); + filter.b0 = (1.0 - cosine) * 0.5 * inverseA0 * param.level; + filter.b1 = 2.0 * filter.b0; + filter.b2 = filter.b0; + filter.a1 = -2.0 * cosine * inverseA0; + filter.a2 = (1.0 - alpha) * inverseA0; +} + static void ApplySamplerParam(Ngs2Voice& voice, const Ngs2VoiceParamHeader& param) { switch (param.id) { case SCE_NGS2_SAMPLER_VOICE_PARAM_SETUP: SetupSampler(voice, ParamAs(param).format); break; @@ -193,6 +229,7 @@ static void ApplySamplerParam(Ngs2Voice& voice, const Ngs2VoiceParamHeader& para voice.pitch = ratio; break; } + case SCE_NGS2_SAMPLER_VOICE_PARAM_FILTER: SetFilter(voice, ParamAs(param)); break; default: throw std::runtime_error("NGS2: sampler voice param " + Ngs2Hex(param.id) + " is not implemented"); } } diff --git a/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp b/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp new file mode 100644 index 000000000..0c7f193c4 --- /dev/null +++ b/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp @@ -0,0 +1,182 @@ +#include "Ngs2Test.hpp" + +#include +#include +#include +#include +#include +#include + +struct Biquad { + double b0, b1, b2, a1, a2; + double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0; + + Biquad(double frequency, double q, double level, double rate) { + const double w = 2.0 * std::numbers::pi * frequency / rate; + const double alpha = std::sin(w) / (2.0 * q); + const double a0 = 1.0 + alpha; + b0 = (1.0 - std::cos(w)) / 2.0 / a0 * level; + b1 = (1.0 - std::cos(w)) / a0 * level; + b2 = b0; + a1 = -2.0 * std::cos(w) / a0; + a2 = (1.0 - alpha) / a0; + } + + float Next(double x) { + const double y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + return static_cast(y); + } +}; + +static Ngs2SamplerVoiceFilterParam Filter(std::uint32_t index, std::uint32_t location, std::uint32_t type, std::uint64_t mask, float frequency, float q, float level) { + Ngs2SamplerVoiceFilterParam param{}; + param.header = {sizeof(param), 0, SCE_NGS2_SAMPLER_VOICE_PARAM_FILTER}; + param.index = index; + param.location = location; + param.type = type; + param.channel_mask = mask; + param.frequency = frequency; + param.q = q; + param.level = level; + return param; +} + +static void SetFilter(uintptr_t voice, const Ngs2SamplerVoiceFilterParam& param) { + Require(sceNgs2VoiceControl(voice, ¶m.header) == SCE_NGS2_OK); +} + +static uintptr_t Sampler(uintptr_t system, const std::vector& pcm, std::uint32_t channels, std::uint32_t rate) { + const auto voice = Voice(CreateRack(system, SCE_NGS2_RACK_ID_SAMPLER)); + Control(voice, SCE_NGS2_SAMPLER_VOICE_PARAM_SETUP, Ngs2SamplerVoiceSetupParam{{}, {SCE_NGS2_WAVEFORM_TYPE_PCM_I16L, channels, rate, 0, 0, 0}}); + const auto frames = static_cast(pcm.size() / channels); + const Ngs2WaveformBlock block{0, pcm.size() * sizeof(std::int16_t), 0, 0, frames, 0, 0}; + Control(voice, SCE_NGS2_SAMPLER_VOICE_PARAM_ADD_WAVEFORM_BLOCKS, Ngs2SamplerVoiceWaveformBlocksParam{{}, pcm.data(), 0, 1, &block}); + return voice; +} + +static std::vector RenderGrain(uintptr_t system, std::uint32_t channels) { + std::vector out(Grain * channels, -1.0f); + const Ngs2RenderBufferInfo info{out.data(), out.size() * sizeof(float), SCE_NGS2_WAVEFORM_TYPE_PCM_F32L, channels}; + Require(sceNgs2SystemRender(system, &info, 1) == SCE_NGS2_OK); + return out; +} + +static void TestLowPassAndTail() { + const auto system = CreateSystem(); + const auto master = Mastering(system, 1); + std::vector pcm(Grain * 2, 0); + pcm[0] = 16384; + pcm[5] = -8192; + const auto sampler = Sampler(system, pcm, 1, 48000); + Patch(sampler, master); + const auto param = Filter(7, 1, 1, 0, 1000.0f, 0.70710678f, 0.75f); + SetFilter(sampler, param); + Event(sampler, SCE_NGS2_VOICE_EVENT_PLAY); + + Biquad reference(1000.0, static_cast(0.70710678f), 0.75, 48000.0); + for (std::uint32_t grain = 0; grain < 4; grain++) { + const auto out = RenderGrain(system, 1); + for (std::uint32_t i = 0; i < Grain; i++) { + const auto frame = grain * Grain + i; + const float expected = reference.Next(frame < pcm.size() ? pcm[frame] / 32768.0 : 0.0); + Require(std::abs(out[i] - expected) <= 1e-7f); + } + Require(out[Grain - 1] != 0.0f); + Require(Flags(sampler) == (SCE_NGS2_VOICE_STATE_FLAG_INUSE | SCE_NGS2_VOICE_STATE_FLAG_PLAYING)); + SetFilter(sampler, param); + } + + SetFilter(sampler, Filter(7, 0, 0, 0, NAN, 0.0f, -1.0f)); + for (float sample : RenderGrain(system, 1)) Require(sample == 0.0f); + Require(Flags(sampler) == 0); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +static void TestBypassMaskAndGain() { + const auto system = CreateSystem(); + const auto master = Mastering(system, 2); + std::vector pcm; + for (std::uint32_t i = 0; i < Grain; i++) { + pcm.push_back(static_cast(i * 1000)); + pcm.push_back(static_cast(-4000 + i * 700)); + } + const auto sampler = Sampler(system, pcm, 2, 48000); + Patch(sampler, master); + SetFilter(sampler, Filter(0, 1, 1, 1, 24000.0f, 1.0f, 0.5f)); + Event(sampler, SCE_NGS2_VOICE_EVENT_PLAY); + + auto out = RenderGrain(system, 2); + for (std::uint32_t i = 0; i < Grain; i++) { + Require(out[i * 2] == pcm[i * 2] / 32768.0f); + Require(out[i * 2 + 1] == pcm[i * 2 + 1] / 32768.0f * 0.5f); + } + Require(Flags(sampler) == (SCE_NGS2_VOICE_STATE_FLAG_INUSE | SCE_NGS2_VOICE_STATE_FLAG_PLAYING)); + out = RenderGrain(system, 2); + for (float sample : out) Require(sample == 0.0f); + Require(Flags(sampler) == 0); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +static void TestSystemRateAndZeroCutoff() { + const auto system = CreateSystem(); + const auto master = Mastering(system, 1); + const std::vector pcm(Grain * 2, 8192); + const auto sampler = Sampler(system, pcm, 1, 24000); + Patch(sampler, master); + SetFilter(sampler, Filter(0, 1, 1, 0, 18000.0f, 0.70710678f, 1.0f)); + SetFilter(sampler, Filter(1, 1, 1, 0, 30000.0f, 0.70710678f, 1.0f)); + Event(sampler, SCE_NGS2_VOICE_EVENT_PLAY); + Biquad reference(18000.0, static_cast(0.70710678f), 1.0, 48000.0); + const auto out = RenderGrain(system, 1); + for (std::uint32_t i = 0; i < Grain; i++) Require(std::abs(out[i] - reference.Next(0.25)) <= 1e-7f); + + SetFilter(sampler, Filter(1, 1, 1, 0, 0.0f, 0.70710678f, 1.0f)); + for (float sample : RenderGrain(system, 1)) Require(sample == 0.0f); + + Control(sampler, SCE_NGS2_SAMPLER_VOICE_PARAM_SETUP, Ngs2SamplerVoiceSetupParam{{}, {SCE_NGS2_WAVEFORM_TYPE_PCM_I16L, 1, 48000, 0, 0, 0}}); + const Ngs2WaveformBlock block{0, pcm.size() * sizeof(std::int16_t), 0, 0, static_cast(pcm.size()), 0, 0}; + Control(sampler, SCE_NGS2_SAMPLER_VOICE_PARAM_ADD_WAVEFORM_BLOCKS, Ngs2SamplerVoiceWaveformBlocksParam{{}, pcm.data(), 0, 1, &block}); + Patch(sampler, master); + Event(sampler, SCE_NGS2_VOICE_EVENT_PLAY); + for (float sample : RenderGrain(system, 1)) Require(sample == 0.25f); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +template +static void RequireRejected(uintptr_t voice, const Ngs2SamplerVoiceFilterParam& param) { + bool rejected = false; + try { + sceNgs2VoiceControl(voice, ¶m.header); + } catch (const TError&) { + rejected = true; + } + Require(rejected); +} + +static void TestRejectedParams() { + const auto system = CreateSystem(); + const auto sampler = Sampler(system, std::vector(Grain, 0), 1, 48000); + RequireRejected(sampler, Filter(8, 1, 1, 0, 1000.0f, 1.0f, 1.0f)); + RequireRejected(sampler, Filter(0, 0, 1, 0, 1000.0f, 1.0f, 1.0f)); + RequireRejected(sampler, Filter(0, 1, 2, 0, 1000.0f, 1.0f, 1.0f)); + RequireRejected(sampler, Filter(0, 1, 1, 0, NAN, 1.0f, 1.0f)); + RequireRejected(sampler, Filter(0, 1, 1, 0, -1.0f, 1.0f, 1.0f)); + RequireRejected(sampler, Filter(0, 1, 1, 0, 1000.0f, 0.0f, 1.0f)); + RequireRejected(sampler, Filter(0, 1, 1, 0, 1000.0f, 1.0f, -0.5f)); + auto small = Filter(0, 1, 1, 0, 1000.0f, 1.0f, 1.0f); + small.header.size = sizeof(small) - 4; + RequireRejected(sampler, small); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +int main() { + TestLowPassAndTail(); + TestBypassMaskAndGain(); + TestSystemRateAndZeroCutoff(); + TestRejectedParams(); + return 0; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index cd0f433c1..b6f5d72b9 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -124,6 +124,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceShareGetCurrentStatus](../../core/libs/prx/libSceShare/Export.cpp) (libSceShare) - validation (feature flag non-zero, status non-null) and the all-zero 16-byte status taken from the [KytyPS5](https://github.com/KytyPS5/KytyPS5) reimplementation, not confirmed on a PS5 title; the meaning of the recording status values is unknown - [sceAgcDcbSetZPassPredicationEnableGetSize, sceAgcDcbSetPredicationDisableGetSize, sceAgcDcbSetBoolPredicationEnableGetSize](../../core/libs/prx/libSceAgc/DcbState/src/Predication.cpp) (libSceAgc) - the builders are inline in the SDK and not exported; the size is assumed to be that of the SET_PREDICATION packet `sceAgcDcbSetPredication` writes (16 bytes) - [Resource registration](../../core/libs/prx/libSceAgcDriver/Resource/src/Registration.cpp) (libSceAgcDriver) - registration always fails with `RESOURCE_REGISTRATION_UNAVAILABLE`, so the owner and resource queries, `sceAgcDriverSetResourceUserData`, `sceAgcDriverFindResourcesPublic` and `sceAgcDriverUnregisterAllResourcesForOwner` return the same error without reading their arguments. Their parameter lists follow the libSceGnmDriver counterparts and are unverified +- [sceNgs2VoiceControl sampler filter](../../core/libs/prx/libSceNgs2.native/src/Voice.cpp) (libSceNgs2.native) - param `0x1000000a`, its layout and meaning follow KytyPS5 only: location 1 type 1 is an RBJ low-pass biquad at the system sample rate after resampling, scaled by `level`, a set `channel_mask` bit bypasses that channel, type 0 turns the filter off. Other locations and types throw. The voice keeps playing a filter tail after its last block until the history is zero, with outputs below 1e-20 flushed to zero (a KytyPS5 choice); the console's tail length is unknown ### Functional From 3515ead91a7c28dd51b0f3d79cbbd50bc129b9b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 07:27:27 +0200 Subject: [PATCH 34/42] feat(rtc): implement sceRtcFormatRFC2822 and the RFC 2822/3339 local-time formatters Co-Authored-By: Claude --- core/libs/prx/libSceRtc/Export.cpp | 29 +++++++++++++++ core/libs/tests/GuestRtc.cpp | 60 ++++++++++++++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 3 files changed, 90 insertions(+) diff --git a/core/libs/prx/libSceRtc/Export.cpp b/core/libs/prx/libSceRtc/Export.cpp index 08bf4bb06..09a4ccbe6 100644 --- a/core/libs/prx/libSceRtc/Export.cpp +++ b/core/libs/prx/libSceRtc/Export.cpp @@ -107,6 +107,13 @@ std::int64_t localOffsetSeconds(std::uint64_t utcTick) { return localSeconds - static_cast(seconds); } +constexpr const char* WEEKDAY_NAMES[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; +constexpr const char* MONTH_NAMES[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + +int localOffsetMinutes(const RtcTick& utc) { + return static_cast(localOffsetSeconds(utc.tick) / 60); +} + int addTicks(RtcTick* dst, const RtcTick* src, std::int64_t count, std::int64_t unit) { if (!dst || !src) return SCE_RTC_ERROR_INVALID_POINTER; if (src->tick > MAX_TICK) return SCE_RTC_ERROR_INVALID_VALUE; @@ -286,6 +293,28 @@ int APS5_VABI sceRtcFormatRFC3339(char* date_time, const RtcTick* utc, int time_ return 0; } +int APS5_VABI sceRtcFormatRFC3339LocalTime(char* date_time, const RtcTick* utc) { + if (!date_time || !utc) return SCE_RTC_ERROR_INVALID_POINTER; + return sceRtcFormatRFC3339(date_time, utc, localOffsetMinutes(*utc)); +} + +int APS5_VABI sceRtcFormatRFC2822(char* date_time, const RtcTick* utc, int time_zone_minutes) { + if (!date_time || !utc) return SCE_RTC_ERROR_INVALID_POINTER; + if (time_zone_minutes < -1439 || time_zone_minutes > 1439) return SCE_RTC_ERROR_INVALID_VALUE; + RtcTick local{}; + if (const int result = addTicks(&local, utc, time_zone_minutes, TICKS_PER_MINUTE); result != 0) return result; + const RtcDateTime time = fromTick(local.tick); + const int offset = time_zone_minutes < 0 ? -time_zone_minutes : time_zone_minutes; + std::snprintf(date_time, 32, "%s, %02u %s %04u %02u:%02u:%02u %c%02d%02d", WEEKDAY_NAMES[(local.tick / TICKS_PER_DAY + 1) % 7], time.day, + MONTH_NAMES[time.month - 1], time.year, time.hour, time.minute, time.second, time_zone_minutes < 0 ? '-' : '+', offset / 60, offset % 60); + return 0; +} + +int APS5_VABI sceRtcFormatRFC2822LocalTime(char* date_time, const RtcTick* utc) { + if (!date_time || !utc) return SCE_RTC_ERROR_INVALID_POINTER; + return sceRtcFormatRFC2822(date_time, utc, localOffsetMinutes(*utc)); +} + int APS5_VABI sceRtcParseRFC3339(RtcTick* utc, const char* date_time) { if (!utc || !date_time) return SCE_RTC_ERROR_INVALID_POINTER; const char* cursor = date_time; diff --git a/core/libs/tests/GuestRtc.cpp b/core/libs/tests/GuestRtc.cpp index 2d843ebfe..8f8bdcf08 100644 --- a/core/libs/tests/GuestRtc.cpp +++ b/core/libs/tests/GuestRtc.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -30,10 +31,23 @@ int APS5_VABI sceRtcTickAddSeconds(RtcTick*, const RtcTick*, std::int64_t); int APS5_VABI sceRtcTickAddDays(RtcTick*, const RtcTick*, std::int32_t); int APS5_VABI sceRtcTickAddMonths(RtcTick*, const RtcTick*, std::int32_t); int APS5_VABI sceRtcTickAddYears(RtcTick*, const RtcTick*, std::int16_t); +int APS5_VABI sceRtcFormatRFC3339LocalTime(char*, const RtcTick*); +int APS5_VABI sceRtcFormatRFC2822(char*, const RtcTick*, int); +int APS5_VABI sceRtcFormatRFC2822LocalTime(char*, const RtcTick*); } static void Require(bool value) { if (!value) std::abort(); } +static void SetTimeZone(const char* zone) { +#ifdef _WIN32 + _putenv_s("TZ", zone); + _tzset(); +#else + setenv("TZ", zone, 1); + tzset(); +#endif +} + static bool Equal(const RtcDateTime& left, const RtcDateTime& right) { return left.year == right.year && left.month == right.month && left.day == right.day && left.hour == right.hour && left.minute == right.minute && left.second == right.second && left.microsecond == right.microsecond; @@ -224,4 +238,50 @@ int main() { RtcTick back{}; Require(sceRtcConvertUtcToLocalTime(&now, &local) == 0); Require(sceRtcConvertLocalTimeToUtc(&local, &back) == 0 && back.tick == now.tick); + + char rfc2822[32]; + tick.tick = leapDayTick; + Require(sceRtcFormatRFC2822(rfc2822, &tick, 0) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 12:34:56 +0000") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, 90) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 14:04:56 +0130") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, -300) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 07:34:56 -0500") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, -30) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 12:04:56 -0030") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, 65) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 13:39:56 +0105") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, 1439) == 0 && std::strcmp(rfc2822, "Fri, 01 Mar 2024 12:33:56 +2359") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, -1439) == 0 && std::strcmp(rfc2822, "Wed, 28 Feb 2024 12:35:56 -2359") == 0); + const char* week[] = {"Sun, 03 Mar", "Mon, 04 Mar", "Tue, 05 Mar", "Wed, 06 Mar", "Thu, 07 Mar", "Fri, 08 Mar", "Sat, 09 Mar"}; + for (int day = 0; day < 7; ++day) { + const RtcDateTime date{2024, 3, static_cast(3 + day), 0, 0, 0, 0}; + Require(sceRtcGetTick(&date, &tick) == 0 && sceRtcFormatRFC2822(rfc2822, &tick, 0) == 0); + Require(std::strncmp(rfc2822, week[day], std::strlen(week[day])) == 0); + } + tick.tick = 0; + Require(sceRtcFormatRFC2822(rfc2822, &tick, 0) == 0 && std::strcmp(rfc2822, "Mon, 01 Jan 0001 00:00:00 +0000") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, -1) == invalidValue); + tick.tick = maxTick; + Require(sceRtcFormatRFC2822(rfc2822, &tick, 0) == 0 && std::strcmp(rfc2822, "Fri, 31 Dec 9999 23:59:59 +0000") == 0); + Require(sceRtcFormatRFC2822(rfc2822, &tick, 1) == invalidValue); + tick.tick = leapDayTick; + for (int offset : {1440, -1440, std::numeric_limits::min(), std::numeric_limits::max()}) { + std::memset(rfc2822, 'x', sizeof(rfc2822)); + char original[sizeof(rfc2822)]; + std::memcpy(original, rfc2822, sizeof(rfc2822)); + Require(sceRtcFormatRFC2822(rfc2822, &tick, offset) == invalidValue); + Require(std::memcmp(rfc2822, original, sizeof(rfc2822)) == 0); + } + Require(sceRtcFormatRFC2822(nullptr, &tick, 0) == invalidPointer); + Require(sceRtcFormatRFC2822(rfc2822, nullptr, 0) == invalidPointer); + + SetTimeZone("XXX-5:30"); + Require(sceRtcFormatRFC2822LocalTime(rfc2822, &tick) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 18:04:56 +0530") == 0); + Require(sceRtcFormatRFC3339LocalTime(text, &tick) == 0 && std::strcmp(text, "2024-02-29T18:04:56.78+05:30") == 0); + SetTimeZone("XXX+3"); + Require(sceRtcFormatRFC2822LocalTime(rfc2822, &tick) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 09:34:56 -0300") == 0); + Require(sceRtcFormatRFC3339LocalTime(text, &tick) == 0 && std::strcmp(text, "2024-02-29T09:34:56.78-03:00") == 0); + SetTimeZone("UTC0"); + Require(sceRtcFormatRFC2822LocalTime(rfc2822, &tick) == 0 && std::strcmp(rfc2822, "Thu, 29 Feb 2024 12:34:56 +0000") == 0); + Require(sceRtcFormatRFC3339LocalTime(text, &tick) == 0 && std::strcmp(text, "2024-02-29T12:34:56.78Z") == 0); + Require(sceRtcFormatRFC2822LocalTime(nullptr, &tick) == invalidPointer); + Require(sceRtcFormatRFC2822LocalTime(rfc2822, nullptr) == invalidPointer); + Require(sceRtcFormatRFC3339LocalTime(nullptr, &tick) == invalidPointer); + Require(sceRtcFormatRFC3339LocalTime(text, nullptr) == invalidPointer); } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index cd0f433c1..cb62288f1 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -118,6 +118,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceSystemServiceReenableMediaPlay](../../core/libs/prx/libSceSystemService/Export.cpp) (libSceSystemService) - unknown signature - [sceSystemServiceParamGetString](../../core/libs/prx/libSceSystemService/Export.cpp) (libSceSystemService) - the system name (parameter 6) is the fixed `PS5`, not the console's name; other parameters and buffers of 1 to 64 bytes throw - [sceVoiceSetMuteFlag](../../core/libs/prx/libSceVoice/Export.cpp) (libSceVoice) - unknown signature +- [sceRtcFormatRFC2822, sceRtcFormatRFC2822LocalTime, sceRtcFormatRFC3339LocalTime](../../core/libs/prx/libSceRtc/Export.cpp) (libSceRtc) - only shadPS4 (PS4) has bodies. A null tick returns `INVALID_POINTER` like the existing `sceRtcFormatRFC3339`, where shadPS4 formats the current time instead; offsets outside ±1439 minutes return `INVALID_VALUE` like `sceRtcFormatRFC3339`; the local-time variants use the host's offset at the given instant (shadPS4 uses `sceKernelGettimezone`, the current offset) - [snwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follows C11 K.3.9.1.3 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`. A runtime-constraint violation only returns a negative value: `set_constraint_handler_s` is not exported and the console's default handler is unknown. An invalid multibyte `%s` argument is copied byte by byte instead of being reported as an encoding error, as in `vswprintf` - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) - the added `sceUltQueuePop`, `sceUltQueueTryPush`, `sceUltQueueDestroy` and `sceUltQueueDataResourcePoolDestroy` signatures are inferred from the existing push/pop and object APIs. Queue destruction is assumed to reject blocked callers with `ULT_ERROR_BUSY` and otherwise discard queued data; pool exhaustion returns `ULT_ERROR_AGAIN`. These rules, alignment checks and shared slot limits have not been confirmed on PS5 hardware or a title. Non-null queue and data-pool option parameters throw because their layouts are unknown. - [_sceUlobjmgrRegisterObject](../../core/libs/prx/ulobjmgr/Export.cpp) (ulobjmgr) - parameters taken from shadPS4 (PS4): a nonzero 64-bit object, a nonzero 32-bit kind and a 32-bit id output; the meaning of the first two and the PS5 signature are unverified. The id bound of `_sceUlobjmgrUnregisterObject` (below 0x4000) and the raw `EINVAL` (22) return also come from shadPS4 From ab98cd7f4a37378ac6da46c0863e097fe903472a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 07:32:51 +0200 Subject: [PATCH 35/42] feat(libkernel): sceKernelReadv, Writev, Preadv and Pwritev Co-Authored-By: Claude --- core/libs/prx/libkernel/CMakeLists.txt | 4 + core/libs/prx/libkernel/File/src/Stdio.cpp | 75 ++++++++++++++ core/libs/tests/GuestFileVector.cpp | 111 +++++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 4 files changed, 191 insertions(+) create mode 100644 core/libs/tests/GuestFileVector.cpp diff --git a/core/libs/prx/libkernel/CMakeLists.txt b/core/libs/prx/libkernel/CMakeLists.txt index 43949deb4..4af7886fc 100644 --- a/core/libs/prx/libkernel/CMakeLists.txt +++ b/core/libs/prx/libkernel/CMakeLists.txt @@ -355,6 +355,10 @@ if(BUILD_TESTING) target_include_directories(guest_directory_entry_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_directory_entry_tests PRIVATE libkernel libc) add_test(NAME guest_directory_entries COMMAND guest_directory_entry_tests) + add_test_executable(guest_file_vector_tests ${LIBS_INCLUDE_DIR}/tests/GuestFileVector.cpp) + target_include_directories(guest_file_vector_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_file_vector_tests PRIVATE libkernel libc) + add_test(NAME guest_file_vector COMMAND guest_file_vector_tests) else() add_test_executable(guest_directory_close_tests ${LIBS_INCLUDE_DIR}/tests/GuestDirectoryClose.cpp) target_include_directories(guest_directory_close_tests PRIVATE ${LIBS_INCLUDE_DIR}) diff --git a/core/libs/prx/libkernel/File/src/Stdio.cpp b/core/libs/prx/libkernel/File/src/Stdio.cpp index 5785a3c9b..7defbc421 100644 --- a/core/libs/prx/libkernel/File/src/Stdio.cpp +++ b/core/libs/prx/libkernel/File/src/Stdio.cpp @@ -17,6 +17,14 @@ #include #include #include + +struct KernelIovec { + void* base; + std::size_t length; +}; + +static constexpr int KERNEL_IOV_MAX = 1024; + #ifdef _WIN32 #include #include @@ -119,6 +127,8 @@ static std::int64_t NativePwrite(int descriptor, const void* buf, std::size_t nb #include #include #include +#include +#include #include static int NativeRmdir(const std::filesystem::path& path) { return ::rmdir(path.c_str()); @@ -156,6 +166,12 @@ static std::int64_t NativePread(int descriptor, void* buf, std::size_t nbytes, s static std::int64_t NativePwrite(int descriptor, const void* buf, std::size_t nbytes, std::int64_t offset) { return static_cast(::pwrite(descriptor, buf, nbytes, static_cast(offset))); } +static_assert(sizeof(KernelIovec) == sizeof(struct iovec)); +static_assert(offsetof(KernelIovec, base) == offsetof(struct iovec, iov_base)); +static_assert(offsetof(KernelIovec, length) == offsetof(struct iovec, iov_len)); +static const struct iovec* NativeIovecs(const KernelIovec* iov) { + return reinterpret_cast(iov); +} #endif static constexpr int GUEST_ENOENT = 2; @@ -471,6 +487,22 @@ int64_t APS5_VABI sceKernelPwrite(int d, const void* buf, size_t nbytes, int64_t return pwrite_nid_disambig1_nid_postfix(d, buf, nbytes, offset); } +int64_t APS5_VABI sceKernelReadv(int, const KernelIovec*, int) { + throw std::runtime_error(std::string(__func__) + ": not implemented on Windows"); +} + +int64_t APS5_VABI sceKernelWritev(int, const KernelIovec*, int) { + throw std::runtime_error(std::string(__func__) + ": not implemented on Windows"); +} + +int64_t APS5_VABI sceKernelPreadv(int, const KernelIovec*, int, int64_t) { + throw std::runtime_error(std::string(__func__) + ": not implemented on Windows"); +} + +int64_t APS5_VABI sceKernelPwritev(int, const KernelIovec*, int, int64_t) { + throw std::runtime_error(std::string(__func__) + ": not implemented on Windows"); +} + #else int64_t APS5_VABI sceKernelPread(int d, void* buf, size_t nbytes, int64_t offset) { @@ -489,6 +521,49 @@ int64_t APS5_VABI sceKernelPwrite(int d, const void* buf, size_t nbytes, int64_t return result < 0 ? SceErrorFromErrno(errno) : result; } +static int CheckIovecs(const KernelIovec* iov, int iovcnt) { + if (iovcnt < 0 || iovcnt > KERNEL_IOV_MAX) return SceErrorFromErrno(GUEST_EINVAL); + if (iov == nullptr && iovcnt != 0) return SceErrorFromErrno(GUEST_EFAULT); + return 0; +} + +static bool OpenIovecs(const KernelIovec* iov, int iovcnt, std::deque& destinations) { + for (int i = 0; i < iovcnt; ++i) { + if (!destinations.emplace_back(iov[i].base, iov[i].length).Open()) return false; + } + return true; +} + +int64_t APS5_VABI sceKernelReadv(int d, const KernelIovec* iov, int iovcnt) { + if (const int error = CheckIovecs(iov, iovcnt)) return error; + std::deque destinations; + if (!OpenIovecs(iov, iovcnt, destinations)) return SceErrorFromErrno(GUEST_EFAULT); + const auto result = static_cast(::readv(d, NativeIovecs(iov), iovcnt)); + return result < 0 ? SceErrorFromErrno(errno) : result; +} + +int64_t APS5_VABI sceKernelWritev(int d, const KernelIovec* iov, int iovcnt) { + if (const int error = CheckIovecs(iov, iovcnt)) return error; + const auto result = static_cast(::writev(d, NativeIovecs(iov), iovcnt)); + return result < 0 ? SceErrorFromErrno(errno) : result; +} + +int64_t APS5_VABI sceKernelPreadv(int d, const KernelIovec* iov, int iovcnt, int64_t offset) { + if (const int error = CheckIovecs(iov, iovcnt)) return error; + if (offset < 0) return SceErrorFromErrno(GUEST_EINVAL); + std::deque destinations; + if (!OpenIovecs(iov, iovcnt, destinations)) return SceErrorFromErrno(GUEST_EFAULT); + const auto result = static_cast(::preadv(d, NativeIovecs(iov), iovcnt, static_cast(offset))); + return result < 0 ? SceErrorFromErrno(errno) : result; +} + +int64_t APS5_VABI sceKernelPwritev(int d, const KernelIovec* iov, int iovcnt, int64_t offset) { + if (const int error = CheckIovecs(iov, iovcnt)) return error; + if (offset < 0) return SceErrorFromErrno(GUEST_EINVAL); + const auto result = static_cast(::pwritev(d, NativeIovecs(iov), iovcnt, static_cast(offset))); + return result < 0 ? SceErrorFromErrno(errno) : result; +} + #endif int APS5_VABI sceKernelRename(const char* from, const char* to) { diff --git a/core/libs/tests/GuestFileVector.cpp b/core/libs/tests/GuestFileVector.cpp new file mode 100644 index 000000000..a3cb50f35 --- /dev/null +++ b/core/libs/tests/GuestFileVector.cpp @@ -0,0 +1,111 @@ +#include "prx/libc/include/general/VabiMacros.hpp" +#include "prx/libkernel/File/include/FileFlags.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct GuestIovec { + void* base; + std::size_t length; +}; + +extern "C" { +int APS5_VABI sceKernelOpen(const char*, int, std::uint16_t); +int APS5_VABI sceKernelClose(int); +std::int64_t APS5_VABI sceKernelRead(int, void*, std::size_t); +int APS5_VABI sceKernelLseek(int, std::int64_t, int); +std::int64_t APS5_VABI sceKernelReadv(int, const GuestIovec*, int); +std::int64_t APS5_VABI sceKernelWritev(int, const GuestIovec*, int); +std::int64_t APS5_VABI sceKernelPreadv(int, const GuestIovec*, int, std::int64_t); +std::int64_t APS5_VABI sceKernelPwritev(int, const GuestIovec*, int, std::int64_t); +} + +static void Check(bool value, int line) { + if (!value) { + std::fprintf(stderr, "File vector check failed at line %d\n", line); + std::abort(); + } +} +#define Require(value) Check((value), __LINE__) + +static constexpr std::int64_t ErrorEbadf = static_cast(0x80020009u); +static constexpr std::int64_t ErrorEfault = static_cast(0x8002000Eu); +static constexpr std::int64_t ErrorEinval = static_cast(0x80020016u); + +static std::string Contents(const std::filesystem::path& path) { + std::ifstream stream(path, std::ios::binary); + return std::string(std::istreambuf_iterator(stream), std::istreambuf_iterator()); +} + +int main() { + const auto root = std::filesystem::path("anyps5-file-vector-test-" + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + Require(std::filesystem::create_directory(root)); + const auto path = root / "data.bin"; + { std::ofstream stream(path, std::ios::binary); stream << "0123456789"; } + + const int file = sceKernelOpen(path.string().c_str(), SCE_KERNEL_O_RDWR, 0); + Require(file >= 0); + + char first[3] = {}; + char second[4] = {}; + GuestIovec reads[2] = {{first, sizeof(first)}, {second, sizeof(second)}}; + Require(sceKernelReadv(file, reads, 2) == 7); + Require(std::memcmp(first, "012", 3) == 0 && std::memcmp(second, "3456", 4) == 0); + Require(sceKernelLseek(file, 0, 1) == 7); + Require(sceKernelReadv(file, reads, 2) == 3); + Require(std::memcmp(first, "789", 3) == 0); + Require(sceKernelReadv(file, reads, 2) == 0); + + Require(sceKernelPreadv(file, reads, 2, 1) == 7); + Require(std::memcmp(first, "123", 3) == 0 && std::memcmp(second, "4567", 4) == 0); + Require(sceKernelLseek(file, 0, 1) == 10); + Require(sceKernelPreadv(file, reads, 2, 8) == 2); + Require(std::memcmp(first, "89", 2) == 0); + + char ab[] = "AB"; + char cde[] = "CDE"; + GuestIovec writes[2] = {{ab, 2}, {cde, 3}}; + Require(sceKernelPwritev(file, writes, 2, 2) == 5); + Require(sceKernelLseek(file, 0, 1) == 10); + Require(Contents(path) == "01ABCDE789"); + Require(sceKernelLseek(file, 8, 0) == 8); + Require(sceKernelWritev(file, writes, 2) == 5); + Require(sceKernelLseek(file, 0, 1) == 13); + Require(Contents(path) == "01ABCDE7ABCDE"); + + GuestIovec empty[1] = {{nullptr, 0}}; + Require(sceKernelReadv(file, empty, 1) == 0); + Require(sceKernelReadv(file, reads, 0) == 0); + Require(sceKernelWritev(file, nullptr, 0) == 0); + + Require(sceKernelReadv(file, reads, -1) == ErrorEinval); + Require(sceKernelWritev(file, writes, -1) == ErrorEinval); + Require(sceKernelPreadv(file, reads, -1, 0) == ErrorEinval); + Require(sceKernelPwritev(file, writes, -1, 0) == ErrorEinval); + Require(sceKernelReadv(file, reads, 1025) == ErrorEinval); + Require(sceKernelWritev(file, writes, 1025) == ErrorEinval); + Require(sceKernelReadv(file, nullptr, 1) == ErrorEfault); + Require(sceKernelWritev(file, nullptr, 1) == ErrorEfault); + Require(sceKernelPreadv(file, nullptr, 1, 0) == ErrorEfault); + Require(sceKernelPwritev(file, nullptr, 1, 0) == ErrorEfault); + Require(sceKernelPreadv(file, reads, 2, -1) == ErrorEinval); + Require(sceKernelPwritev(file, writes, 2, -1) == ErrorEinval); + Require(Contents(path) == "01ABCDE7ABCDE"); + + Require(sceKernelClose(file) == 0); + Require(sceKernelReadv(file, reads, 2) == ErrorEbadf); + Require(sceKernelWritev(file, writes, 2) == ErrorEbadf); + Require(sceKernelPreadv(file, reads, 2, 0) == ErrorEbadf); + Require(sceKernelPwritev(file, writes, 2, 0) == ErrorEbadf); + + std::filesystem::remove_all(root); + return 0; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index cd0f433c1..47ca593d1 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -120,6 +120,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceVoiceSetMuteFlag](../../core/libs/prx/libSceVoice/Export.cpp) (libSceVoice) - unknown signature - [snwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follows C11 K.3.9.1.3 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`. A runtime-constraint violation only returns a negative value: `set_constraint_handler_s` is not exported and the console's default handler is unknown. An invalid multibyte `%s` argument is copied byte by byte instead of being reported as an encoding error, as in `vswprintf` - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) - the added `sceUltQueuePop`, `sceUltQueueTryPush`, `sceUltQueueDestroy` and `sceUltQueueDataResourcePoolDestroy` signatures are inferred from the existing push/pop and object APIs. Queue destruction is assumed to reject blocked callers with `ULT_ERROR_BUSY` and otherwise discard queued data; pool exhaustion returns `ULT_ERROR_AGAIN`. These rules, alignment checks and shared slot limits have not been confirmed on PS5 hardware or a title. Non-null queue and data-pool option parameters throw because their layouts are unknown. +- [sceKernelReadv / sceKernelWritev / sceKernelPreadv / sceKernelPwritev](../../core/libs/prx/libkernel/File/src/Stdio.cpp) (libkernel) are implemented on Linux only; on Windows they throw - [_sceUlobjmgrRegisterObject](../../core/libs/prx/ulobjmgr/Export.cpp) (ulobjmgr) - parameters taken from shadPS4 (PS4): a nonzero 64-bit object, a nonzero 32-bit kind and a 32-bit id output; the meaning of the first two and the PS5 signature are unverified. The id bound of `_sceUlobjmgrUnregisterObject` (below 0x4000) and the raw `EINVAL` (22) return also come from shadPS4 - [sceShareGetCurrentStatus](../../core/libs/prx/libSceShare/Export.cpp) (libSceShare) - validation (feature flag non-zero, status non-null) and the all-zero 16-byte status taken from the [KytyPS5](https://github.com/KytyPS5/KytyPS5) reimplementation, not confirmed on a PS5 title; the meaning of the recording status values is unknown - [sceAgcDcbSetZPassPredicationEnableGetSize, sceAgcDcbSetPredicationDisableGetSize, sceAgcDcbSetBoolPredicationEnableGetSize](../../core/libs/prx/libSceAgc/DcbState/src/Predication.cpp) (libSceAgc) - the builders are inline in the SDK and not exported; the size is assumed to be that of the SET_PREDICATION packet `sceAgcDcbSetPredication` writes (16 bytes) From a2e0be6e76d74aed85c55d69e507c3e76564c975 Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:28:50 +0200 Subject: [PATCH 36/42] docs: record how EXEC written as a value is read on narrow subgroups On a host subgroup narrower than 32 lanes, threadBit reads an EXEC written with s_mov_b32 or s_mov_b64 at bit LaneId & 31 of EXEC_LO, and LaneId is the subgroup invocation id. Every lane at or above the host subgroup size therefore reads the bit of a lower lane, in wave32 and wave64 alike. An EXEC produced by a compare stays consistent because its ballot is subgroup-local as well. Found while investigating the llvmpipe failure of #751. --- docs/dev/TechnicalDebt.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 4e605cf32..05cb0acde 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -134,6 +134,7 @@ Throughout the project, every function at every stage either **does exactly what - [MIMG `tfe` and `lwe`](../../core/shader/recompiler/RdnaDecoder/src/RdnaImageOpDecoder.cpp) never write the status VGPR after the data. On hardware it is written only when a texel fetch hits an unmapped page of a partially resident texture, or, for `lwe` on sample/gather, when the LOD is below the T# `MIN_LOD_WARN`; texture memory is always resident here, and `lwe` on sample, gather and `image_get_lod` throws. - [Image atomics](../../core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp) on 32_SINT and 32_FLOAT surfaces act on the raw dword through an R32_UINT storage view; their float results are assumed to match those measured on 32_UINT surfaces. Other formats throw. - The shader recompiler [ignores `s_setreg_b32`](../../core/shader/recompiler/Translation/src/ScalarInstructions.cpp): writes to MODE (float rounding and denormal controls) and the other hardware registers have no effect, and `s_getreg_b32` reads of the MODE round fields report round to nearest even even after `s_setreg_b32` wrote another mode. The initial round mode from the shader's program registers is not read either. +- On a host subgroup narrower than 32 lanes, [`threadBit`](../../core/shader/recompiler/Translation/src/TranslationContext/ExecMask.cpp) reads an EXEC written as a value (`s_mov_b32`/`s_mov_b64`) at bit (subgroup invocation id) of EXEC_LO, so lanes at or above the subgroup size read a lower lane's bit. - [Shader recompilation](../../core/shader/recompiler/Recompiler.cpp) currently occurs right before it was transferred to Vulkan with caching, but should be moved to the [relinker](../../core/relinker/main.cpp) stage. For this purpose, [shader/recompiler](../../core/shader/recompiler) was written completely independently from [libs/prx](../../core/libs/prx). - [v_fma_f64](../../core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterFloat64.cpp) is fused exactly only for normal inputs: with a subnormal input it is a separate multiply and add, which rounds twice. - [COND_EXEC](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp) reads its condition after the earlier packets of its queue complete. Without PFP_SYNC_ME the console's graphics PFP reads it ahead of the ME, so a title that races the read sees a later value here. From 52869f0112d2ccab6fab58eff42d6e403b095e75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 01:28:28 +0200 Subject: [PATCH 37/42] feat(ngs2): custom submixer rack with UserFx2 modules Co-Authored-By: Claude --- .../libs/prx/libSceNgs2.native/CMakeLists.txt | 3 +- .../libSceNgs2.native/include/Ngs2Types.hpp | 121 +++++++++ .../libs/prx/libSceNgs2.native/src/Custom.cpp | 109 +++++++++ .../libSceNgs2.native/src/Ngs2Internal.hpp | 23 ++ core/libs/prx/libSceNgs2.native/src/Rack.cpp | 7 + .../libs/prx/libSceNgs2.native/src/Render.cpp | 1 + core/libs/prx/libSceNgs2.native/src/Voice.cpp | 10 +- .../libSceNgs2.native/tests/Ngs2Custom.cpp | 231 ++++++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 9 files changed, 499 insertions(+), 7 deletions(-) create mode 100644 core/libs/prx/libSceNgs2.native/src/Custom.cpp create mode 100644 core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp diff --git a/core/libs/prx/libSceNgs2.native/CMakeLists.txt b/core/libs/prx/libSceNgs2.native/CMakeLists.txt index 986014221..a2d50f9b8 100644 --- a/core/libs/prx/libSceNgs2.native/CMakeLists.txt +++ b/core/libs/prx/libSceNgs2.native/CMakeLists.txt @@ -1,5 +1,6 @@ add_library(libSceNgs2.native SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/src/Atrac9.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/Custom.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Rack.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Render.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/System.cpp @@ -25,7 +26,7 @@ if(MINGW) endif() if(BUILD_TESTING) - foreach(ngs2Test IN ITEMS Render Atrac9 Filter) + foreach(ngs2Test IN ITEMS Render Atrac9 Filter Custom) string(TOLOWER ${ngs2Test} testName) add_test_executable(ngs2_${testName}_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/Ngs2${ngs2Test}.cpp) target_include_directories(ngs2_${testName}_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/LibAtrac9/C/src) diff --git a/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp b/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp index 6c99f3f42..e7d5fd04c 100644 --- a/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp +++ b/core/libs/prx/libSceNgs2.native/include/Ngs2Types.hpp @@ -18,6 +18,7 @@ static constexpr int SCE_NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT = static_cast(0 static constexpr std::uint32_t SCE_NGS2_RACK_ID_SAMPLER = 0x1000; static constexpr std::uint32_t SCE_NGS2_RACK_ID_SUBMIXER = 0x2000; static constexpr std::uint32_t SCE_NGS2_RACK_ID_MASTERING = 0x3000; +static constexpr std::uint32_t SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER = 0x4002; static constexpr std::uint32_t SCE_NGS2_WAVEFORM_TYPE_PCM_I16L = 0x12; static constexpr std::uint32_t SCE_NGS2_WAVEFORM_TYPE_PCM_F32L = 0x18; @@ -50,6 +51,12 @@ static constexpr std::uint32_t SCE_NGS2_SAMPLER_VOICE_PARAM_FILTER = 0x1000000a; static constexpr std::uint32_t SCE_NGS2_SUBMIXER_VOICE_PARAM_SETUP = 0x20000000; static constexpr std::uint32_t SCE_NGS2_MASTERING_VOICE_PARAM_SETUP = 0x30000000; static constexpr std::uint32_t SCE_NGS2_MASTERING_VOICE_PARAM_OUTPUT = 0x30000005; +static constexpr std::uint32_t SCE_NGS2_CUSTOM_SUBMIXER_VOICE_PARAM_SETUP = 0x40020000; +static constexpr std::uint32_t SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 = 0x40001f00; + +static constexpr std::uint32_t SCE_NGS2_CUSTOM_MAX_MODULES = 24; +static constexpr std::uint32_t SCE_NGS2_CUSTOM_MAX_PORTS = 16; +static constexpr std::uint32_t SCE_NGS2_CUSTOM_MODULE_ID_USER_FX2 = 0x1f; static constexpr std::uint32_t SCE_NGS2_WAVEFORM_BLOCKS_FLAG_CONTINUE = 1; static constexpr std::uint32_t SCE_NGS2_WAVEFORM_BLOCKS_FLAG_RESET = 4; @@ -149,6 +156,104 @@ struct Ngs2MasteringRackOption { std::uint32_t num_peak_meter_blocks; }; +struct Ngs2CustomModuleOption { + std::uint32_t size; +}; + +struct Ngs2UserFx2SetupContext { + void* common; + void* param; + void* work; + std::uintptr_t user_data; + std::uint32_t max_voices; + std::uint32_t voice_index; + std::uint64_t reserved[4]; +}; +static_assert(sizeof(Ngs2UserFx2SetupContext) == 72); + +using Ngs2UserFx2CleanupContext = Ngs2UserFx2SetupContext; + +struct Ngs2UserFx2ControlContext { + const void* data; + std::size_t data_size; + void* common; + void* param; + std::uintptr_t user_data; + std::uint64_t reserved[4]; +}; +static_assert(sizeof(Ngs2UserFx2ControlContext) == 72); + +struct Ngs2UserFx2ProcessContext { + float** channel_data; + void* common; + const void* param; + void* work; + void* state; + std::uintptr_t user_data; + std::uint32_t flags; + std::uint32_t num_input_channels; + std::uint32_t num_output_channels; + std::uint32_t num_grain_samples; + std::uint32_t sample_rate; + std::uint32_t reserved; + std::uint64_t reserved2[4]; +}; +static_assert(sizeof(Ngs2UserFx2ProcessContext) == 104); + +using Ngs2UserFx2SetupHandler = std::int32_t (APS5_VABI *)(Ngs2UserFx2SetupContext*); +using Ngs2UserFx2CleanupHandler = std::int32_t (APS5_VABI *)(Ngs2UserFx2CleanupContext*); +using Ngs2UserFx2ControlHandler = std::int32_t (APS5_VABI *)(Ngs2UserFx2ControlContext*); +using Ngs2UserFx2ProcessHandler = std::int32_t (APS5_VABI *)(Ngs2UserFx2ProcessContext*); + +struct Ngs2CustomUserFx2ModuleOption { + Ngs2CustomModuleOption custom_module_option; + Ngs2UserFx2SetupHandler setup_handler; + Ngs2UserFx2CleanupHandler cleanup_handler; + Ngs2UserFx2ControlHandler control_handler; + Ngs2UserFx2ProcessHandler process_handler; + std::size_t common_size; + std::size_t param_size; + std::size_t work_size; + std::uintptr_t user_data; +}; +static_assert(sizeof(Ngs2CustomUserFx2ModuleOption) == 72); + +struct Ngs2CustomRackModuleInfo { + const Ngs2CustomModuleOption* option; + std::uint32_t module_id; + std::uint32_t source_buffer_id; + std::uint32_t extra_buffer_id; + std::uint32_t dest_buffer_id; + std::uint32_t state_offset; + std::uint32_t state_size; + std::uint32_t reserved; + std::uint32_t reserved2; +}; +static_assert(sizeof(Ngs2CustomRackModuleInfo) == 40); + +struct Ngs2CustomRackPortInfo { + std::uint32_t source_buffer_id; + std::uint32_t reserved; +}; + +struct Ngs2CustomRackOption { + Ngs2RackOption rack_option; + std::uint32_t state_size; + std::uint32_t num_buffers; + std::uint32_t num_modules; + std::uint32_t reserved; + Ngs2CustomRackModuleInfo module[SCE_NGS2_CUSTOM_MAX_MODULES]; + Ngs2CustomRackPortInfo port[SCE_NGS2_CUSTOM_MAX_PORTS]; +}; +static_assert(sizeof(Ngs2CustomRackOption) == 1280); + +struct Ngs2CustomSubmixerRackOption { + Ngs2CustomRackOption custom_rack_option; + std::uint32_t max_channels; + std::uint32_t max_inputs; +}; +static_assert(sizeof(Ngs2CustomSubmixerRackOption) == 1288); + struct Ngs2VoiceParamHeader { std::uint16_t size; std::int16_t next; @@ -275,6 +380,22 @@ struct Ngs2SubmixerVoiceSetupParam { }; static_assert(sizeof(Ngs2SubmixerVoiceSetupParam) == 16); +struct Ngs2CustomSubmixerVoiceSetupParam { + Ngs2VoiceParamHeader header; + std::uint32_t num_input_channels; + std::uint32_t num_output_channels; + std::uint32_t flags; + std::uint32_t reserved; +}; +static_assert(sizeof(Ngs2CustomSubmixerVoiceSetupParam) == 24); + +struct Ngs2CustomVoiceUserFx2Param { + Ngs2VoiceParamHeader header; + const void* data; + std::size_t data_size; +}; +static_assert(sizeof(Ngs2CustomVoiceUserFx2Param) == 24); + struct Ngs2MasteringVoiceSetupParam { Ngs2VoiceParamHeader header; std::uint32_t num_io_channels; diff --git a/core/libs/prx/libSceNgs2.native/src/Custom.cpp b/core/libs/prx/libSceNgs2.native/src/Custom.cpp new file mode 100644 index 000000000..2ba302fb2 --- /dev/null +++ b/core/libs/prx/libSceNgs2.native/src/Custom.cpp @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include + +#include "prx/libc/include/General.hpp" +#include "Ngs2Internal.hpp" + +static constexpr std::uint32_t USER_FX2_FLAG_PARAM_CHANGED = 2; + +void Ngs2CheckCustomRack(const Ngs2CustomRackOption& option) { + if (option.num_buffers != 1) throw std::runtime_error("NGS2: custom racks with " + std::to_string(option.num_buffers) + " buffers are not implemented"); + if (option.num_modules > SCE_NGS2_CUSTOM_MAX_MODULES || option.rack_option.max_ports > SCE_NGS2_CUSTOM_MAX_PORTS) APS5_INVALID_ARG_EX; + for (std::uint32_t m = 0; m < option.num_modules; m++) { + const auto& info = option.module[m]; + if (info.module_id != SCE_NGS2_CUSTOM_MODULE_ID_USER_FX2) throw std::runtime_error("NGS2: custom module id " + Ngs2Hex(info.module_id) + " is not implemented"); + if (info.option == nullptr || info.option->size != sizeof(Ngs2CustomUserFx2ModuleOption)) APS5_INVALID_ARG_EX; + if (info.source_buffer_id != 0 || info.dest_buffer_id != 0) APS5_INVALID_ARG_EX; + if (reinterpret_cast(info.option)->process_handler == nullptr) APS5_INVALID_ARG_EX; + } + for (std::uint32_t p = 0; p < option.rack_option.max_ports; p++) { + if (option.port[p].source_buffer_id != 0) APS5_INVALID_ARG_EX; + } +} + +static Ngs2UserFx2SetupContext UserFxContext(Ngs2Rack& rack, std::size_t module, std::uint32_t voiceIndex) { + auto& fx = rack.voices[voiceIndex].userFx[module]; + return {rack.userFxCommon[module].data(), fx.param.data(), fx.work.data(), rack.userFx[module].user_data, + static_cast(rack.voices.size()), voiceIndex, {}}; +} + +void Ngs2SetupUserFx(Ngs2Rack& rack, const Ngs2CustomRackOption& option) { + rack.userFx.resize(option.num_modules); + rack.userFxCommon.resize(option.num_modules); + for (auto& voice : rack.voices) voice.userFx.resize(option.num_modules); + for (std::uint32_t m = 0; m < option.num_modules; m++) { + const auto& module = *reinterpret_cast(option.module[m].option); + rack.userFx[m] = module; + rack.userFxCommon[m].resize(module.common_size); + for (std::uint32_t i = 0; i < rack.voices.size(); i++) { + auto& fx = rack.voices[i].userFx[m]; + fx.param.resize(module.param_size); + fx.work.resize(module.work_size); + fx.state.resize(option.module[m].state_size); + if (module.setup_handler == nullptr) continue; + auto context = UserFxContext(rack, m, i); + const int result = module.setup_handler(&context); + if (result != SCE_NGS2_OK) throw std::runtime_error("NGS2: the UserFx2 setup handler failed with " + std::to_string(result)); + } + } +} + +void Ngs2CleanupUserFx(Ngs2Rack& rack) { + for (std::uint32_t i = 0; i < rack.voices.size(); i++) { + for (std::size_t m = 0; m < rack.userFx.size(); m++) { + if (rack.userFx[m].cleanup_handler == nullptr) continue; + auto context = UserFxContext(rack, m, i); + const int result = rack.userFx[m].cleanup_handler(&context); + if (result != SCE_NGS2_OK) throw std::runtime_error("NGS2: the UserFx2 cleanup handler failed with " + std::to_string(result)); + } + } +} + +static void SetupCustomSubmixer(Ngs2Voice& voice, const Ngs2CustomSubmixerVoiceSetupParam& setup) { + if (setup.flags != 0) throw std::runtime_error("NGS2: custom submixer setup flags are not implemented"); + if (setup.num_input_channels != setup.num_output_channels) throw std::runtime_error("NGS2: custom submixer channel conversion is not implemented"); + if (setup.num_input_channels == 0 || setup.num_input_channels > voice.rack->maxChannels) APS5_INVALID_ARG_EX; + voice.channels = setup.num_input_channels; +} + +static void SetUserFxParam(Ngs2Voice& voice, std::uint32_t index, const Ngs2CustomVoiceUserFx2Param& param) { + if (index >= voice.userFx.size()) APS5_INVALID_ARG_EX; + const auto& module = voice.rack->userFx[index]; + if (module.control_handler != nullptr) throw std::runtime_error("NGS2: the UserFx2 control handler is not implemented"); + auto& fx = voice.userFx[index]; + if (param.data_size != fx.param.size() || (param.data == nullptr && param.data_size != 0)) APS5_INVALID_ARG_EX; + if (param.data_size != 0) std::memcpy(fx.param.data(), param.data, param.data_size); + fx.flags |= USER_FX2_FLAG_PARAM_CHANGED; +} + +void Ngs2ApplyCustomParam(Ngs2Voice& voice, const Ngs2VoiceParamHeader& param) { + if (voice.rack->rackId != SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER) throw std::invalid_argument("NGS2: voice param " + Ngs2Hex(param.id) + " belongs to another rack"); + if (param.id == SCE_NGS2_CUSTOM_SUBMIXER_VOICE_PARAM_SETUP) { + SetupCustomSubmixer(voice, ParamAs(param)); + return; + } + if ((param.id & ~0x1fu) == SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2) { + SetUserFxParam(voice, param.id & 0x1f, ParamAs(param)); + return; + } + throw std::runtime_error("NGS2: voice param " + Ngs2Hex(param.id) + " is not implemented"); +} + +void Ngs2ProcessUserFx(Ngs2Voice& voice, std::uint32_t grain, std::uint32_t sampleRate) { + if (voice.userFx.empty()) return; + std::vector channels(voice.channels); + for (std::uint32_t c = 0; c < voice.channels; c++) channels[c] = voice.samples.data() + static_cast(c) * grain; + for (std::size_t m = 0; m < voice.userFx.size(); m++) { + auto& fx = voice.userFx[m]; + const auto& module = voice.rack->userFx[m]; + Ngs2UserFx2ProcessContext context{channels.data(), voice.rack->userFxCommon[m].data(), fx.param.data(), fx.work.data(), fx.state.data(), + module.user_data, fx.flags, voice.channels, voice.channels, grain, sampleRate, 0, {}}; + const int result = module.process_handler(&context); + if (result != SCE_NGS2_OK) throw std::runtime_error("NGS2: the UserFx2 process handler failed with " + std::to_string(result)); + fx.flags = 0; + } +} diff --git a/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp b/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp index 615380f59..022be9971 100644 --- a/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp +++ b/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -71,6 +72,13 @@ struct Ngs2Port { std::int32_t matrix = -1; }; +struct Ngs2UserFx2 { + std::vector param; + std::vector work; + std::vector state; + std::uint32_t flags = 0; +}; + struct Ngs2Voice { Ngs2Rack* rack = nullptr; Ngs2PlayState state = Ngs2PlayState::Empty; @@ -93,6 +101,7 @@ struct Ngs2Voice { std::vector> matrices; std::vector filters; std::uint32_t outputId = 0; + std::vector userFx; std::vector samples; bool rendering = false; bool rendered = false; @@ -111,6 +120,8 @@ struct Ngs2Rack { Ngs2ContextBufferInfo bufferInfo{}; Ngs2BufferAllocator allocator{}; std::vector voices; + std::vector userFx; + std::vector> userFxCommon; }; struct Ngs2System { @@ -125,6 +136,13 @@ struct Ngs2System { std::string Ngs2Hex(std::uint32_t value); std::recursive_mutex& Ngs2Mutex(); Ngs2System* Ngs2FindSystem(Ngs2Handle handle); + +template +const TParam& ParamAs(const Ngs2VoiceParamHeader& param) { + if (param.size < sizeof(TParam)) throw std::invalid_argument("NGS2: voice param " + Ngs2Hex(param.id) + " is too small"); + return reinterpret_cast(param); +} + Ngs2Rack* Ngs2FindRack(Ngs2Handle handle); Ngs2Voice* Ngs2FindVoice(Ngs2Handle handle); void* Ngs2Place(const Ngs2ContextBufferInfo* bufferInfo, std::size_t size, std::size_t alignment); @@ -134,6 +152,11 @@ void Ngs2SetupAtrac9(Ngs2Voice& voice, const Ngs2WaveformFormat& format); std::size_t Ngs2Atrac9BlockBytes(const Ngs2Voice& voice, const Ngs2WaveformBlock& block); void Ngs2RestartAtrac9(Ngs2Voice& voice); const float* Ngs2Atrac9Frame(Ngs2Voice& voice, Ngs2Block& block, std::uint32_t frame); +void Ngs2CheckCustomRack(const Ngs2CustomRackOption& option); +void Ngs2SetupUserFx(Ngs2Rack& rack, const Ngs2CustomRackOption& option); +void Ngs2CleanupUserFx(Ngs2Rack& rack); +void Ngs2ApplyCustomParam(Ngs2Voice& voice, const Ngs2VoiceParamHeader& param); +void Ngs2ProcessUserFx(Ngs2Voice& voice, std::uint32_t grain, std::uint32_t sampleRate); void Ngs2RenderSystem(Ngs2System& system, const Ngs2RenderBufferInfo* bufferInfo, std::uint32_t numBufferInfo); #endif diff --git a/core/libs/prx/libSceNgs2.native/src/Rack.cpp b/core/libs/prx/libSceNgs2.native/src/Rack.cpp index b98f15b96..1c0ce54f9 100644 --- a/core/libs/prx/libSceNgs2.native/src/Rack.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Rack.cpp @@ -16,6 +16,7 @@ union RackOptions { Ngs2SamplerRackOption sampler; Ngs2SubmixerRackOption submixer; Ngs2MasteringRackOption mastering; + Ngs2CustomSubmixerRackOption customSubmixer; }; static std::size_t RackOptionSize(std::uint32_t rackId) { @@ -23,11 +24,13 @@ static std::size_t RackOptionSize(std::uint32_t rackId) { case SCE_NGS2_RACK_ID_SAMPLER: return sizeof(Ngs2SamplerRackOption); case SCE_NGS2_RACK_ID_SUBMIXER: return sizeof(Ngs2SubmixerRackOption); case SCE_NGS2_RACK_ID_MASTERING: return sizeof(Ngs2MasteringRackOption); + case SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER: return sizeof(Ngs2CustomSubmixerRackOption); default: throw std::runtime_error("NGS2: rack id " + Ngs2Hex(rackId) + " is not implemented"); } } static RackOptions DefaultRackOption(std::uint32_t rackId) { + if (rackId == SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER) throw std::runtime_error("NGS2: default custom rack options are not implemented"); RackOptions options{}; auto& common = options.common; common.size = RackOptionSize(rackId); @@ -69,6 +72,7 @@ static RackOptions DefaultRackOption(std::uint32_t rackId) { static std::uint32_t RackMaxChannels(std::uint32_t rackId, const RackOptions& options) { if (rackId == SCE_NGS2_RACK_ID_SUBMIXER) return options.submixer.max_channels; if (rackId == SCE_NGS2_RACK_ID_MASTERING) return options.mastering.max_channels; + if (rackId == SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER) return options.customSubmixer.max_channels; return NGS2_MAX_CHANNELS; } @@ -82,6 +86,7 @@ static RackOptions CheckedRackOption(std::uint32_t rackId, const Ngs2RackOption* if (options.common.max_voices == 0 || maxChannels == 0 || maxChannels > NGS2_MAX_CHANNELS) { throw std::invalid_argument("NGS2: invalid rack voice or channel count"); } + if (rackId == SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER) Ngs2CheckCustomRack(options.customSubmixer.custom_rack_option); return options; } @@ -102,12 +107,14 @@ static int CreateRack(Ngs2Handle systemHandle, std::uint32_t rackId, const RackO voice.ports.resize(options.common.max_ports); voice.matrices.resize(options.common.max_matrices); } + if (rackId == SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER) Ngs2SetupUserFx(*rack, options.customSubmixer.custom_rack_option); system->racks.push_back(rack); *handle = reinterpret_cast(rack); return SCE_NGS2_OK; } int Ngs2DestroyRack(Ngs2Rack& rack, Ngs2ContextBufferInfo* outBufferInfo) { + Ngs2CleanupUserFx(rack); auto& racks = rack.system->racks; std::erase(racks, &rack); for (auto* other : racks) { diff --git a/core/libs/prx/libSceNgs2.native/src/Render.cpp b/core/libs/prx/libSceNgs2.native/src/Render.cpp index ba5b520b3..4d0f5e394 100644 --- a/core/libs/prx/libSceNgs2.native/src/Render.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Render.cpp @@ -176,6 +176,7 @@ static void RenderVoice(Ngs2Voice& voice, const std::vector& voices, if (voice.state == Ngs2PlayState::Playing && voice.channels != 0) { if (voice.rack->rackId == SCE_NGS2_RACK_ID_SAMPLER) RenderSampler(voice, grain, systemRate); else MixInputs(voice, voices, grain, systemRate); + if (voice.hasSamples) Ngs2ProcessUserFx(voice, grain, systemRate); } voice.rendering = false; voice.rendered = true; diff --git a/core/libs/prx/libSceNgs2.native/src/Voice.cpp b/core/libs/prx/libSceNgs2.native/src/Voice.cpp index b92ece2f4..9afecf10c 100644 --- a/core/libs/prx/libSceNgs2.native/src/Voice.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Voice.cpp @@ -69,12 +69,6 @@ const std::uint8_t* Ngs2Voice::WaveformData() const { return block.data + (static_cast(block.info.num_skip_samples) + block.cursor) * channels * sizeof(std::int16_t); } -template -static const TParam& ParamAs(const Ngs2VoiceParamHeader& param) { - if (param.size < sizeof(TParam)) throw std::invalid_argument("NGS2: voice param " + Ngs2Hex(param.id) + " is too small"); - return reinterpret_cast(param); -} - static Ngs2Port& PortAt(Ngs2Voice& voice, std::uint32_t port) { if (port >= voice.ports.size()) throw std::invalid_argument("NGS2: voice port " + std::to_string(port) + " is out of range"); return voice.ports[port]; @@ -246,6 +240,10 @@ static void ApplyParam(Ngs2Voice& voice, const Ngs2VoiceParamHeader& param) { ApplyCommonParam(voice, param); return; } + if (rackId == (SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 >> 16) || rackId == SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER) { + Ngs2ApplyCustomParam(voice, param); + return; + } if (rackId != voice.rack->rackId) throw std::invalid_argument("NGS2: voice param " + Ngs2Hex(param.id) + " belongs to another rack"); switch (rackId) { case SCE_NGS2_RACK_ID_SAMPLER: ApplySamplerParam(voice, param); return; diff --git a/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp b/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp new file mode 100644 index 000000000..198b42fe2 --- /dev/null +++ b/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp @@ -0,0 +1,231 @@ +#include "Ngs2Test.hpp" + +#include +#include +#include +#include + +struct Calls { + std::vector setupVoices; + std::vector cleanupVoices; + std::vector processFlags; + std::vector order; + int processResult = SCE_NGS2_OK; +}; +static Calls calls; + +static std::int32_t APS5_VABI Setup(Ngs2UserFx2SetupContext* context) { + Require(context->common != nullptr && context->param != nullptr && context->work != nullptr); + Require(context->user_data == 0x77 && context->max_voices == 2); + std::memset(context->work, 0x5a, 8); + *static_cast(context->param) = 1.0f; + *static_cast(context->common) = 0.25f; + calls.setupVoices.push_back(context->voice_index); + return SCE_NGS2_OK; +} + +static std::int32_t APS5_VABI Cleanup(Ngs2UserFx2CleanupContext* context) { + Require(context->user_data == 0x77 && context->max_voices == 2 && static_cast(context->work)[7] == 0x5a); + calls.cleanupVoices.push_back(context->voice_index); + return SCE_NGS2_OK; +} + +static std::int32_t APS5_VABI Gain(Ngs2UserFx2ProcessContext* context) { + Require(context->user_data == 0x77 && context->num_input_channels == 2 && context->num_output_channels == 2); + Require(context->num_grain_samples == Grain && context->sample_rate == 48000 && context->state != nullptr); + Require(static_cast(context->work)[0] == 0x5a); + const float gain = *static_cast(context->param); + for (std::uint32_t c = 0; c < 2; c++) { + for (std::uint32_t i = 0; i < Grain; i++) context->channel_data[c][i] *= gain; + } + *static_cast(context->common) = 0.125f; + calls.processFlags.push_back(context->flags); + calls.order.push_back(0); + return calls.processResult; +} + +static std::int32_t APS5_VABI Offset(Ngs2UserFx2ProcessContext* context) { + const float offset = *static_cast(context->common); + for (std::uint32_t i = 0; i < Grain; i++) context->channel_data[1][i] += offset; + calls.order.push_back(1); + return SCE_NGS2_OK; +} + +static std::int32_t APS5_VABI ControlHandler(Ngs2UserFx2ControlContext*) { + return SCE_NGS2_OK; +} + +static Ngs2CustomUserFx2ModuleOption Module(Ngs2UserFx2ProcessHandler process) { + return {{sizeof(Ngs2CustomUserFx2ModuleOption)}, Setup, Cleanup, nullptr, process, sizeof(float), sizeof(float), 8, 0x77}; +} + +static Ngs2CustomSubmixerRackOption RackOption(const Ngs2CustomUserFx2ModuleOption* modules, std::uint32_t count) { + Ngs2CustomSubmixerRackOption option{}; + auto& common = option.custom_rack_option.rack_option; + common.size = sizeof(option); + common.max_grain_samples = 512; + common.max_voices = 2; + common.max_matrices = 1; + common.max_ports = 1; + option.custom_rack_option.num_buffers = 1; + option.custom_rack_option.num_modules = count; + for (std::uint32_t m = 0; m < count; m++) { + option.custom_rack_option.module[m].option = &modules[m].custom_module_option; + option.custom_rack_option.module[m].module_id = SCE_NGS2_CUSTOM_MODULE_ID_USER_FX2; + option.custom_rack_option.module[m].state_size = 16; + } + option.max_channels = 2; + option.max_inputs = 1; + return option; +} + +template +static bool CreateThrows(const Ngs2CustomSubmixerRackOption& option) { + Ngs2ContextBufferInfo query{}; + try { + sceNgs2RackQueryBufferSize(SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER, &option.custom_rack_option.rack_option, &query); + } catch (const TException&) { + return true; + } + return false; +} + +template +static bool ControlThrows(uintptr_t voice, std::uint32_t id, TParam param) { + param.header = {static_cast(sizeof(TParam)), 0, id}; + try { + sceNgs2VoiceControl(voice, ¶m.header); + } catch (const TException&) { + return true; + } + return false; +} + +static uintptr_t CustomRack(uintptr_t system, const Ngs2CustomSubmixerRackOption& option) { + Ngs2ContextBufferInfo query{}; + Require(sceNgs2RackQueryBufferSize(SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER, &option.custom_rack_option.rack_option, &query) == SCE_NGS2_OK); + const auto info = Buffer(query); + uintptr_t rack = 0; + Require(sceNgs2RackCreate(system, SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER, &option.custom_rack_option.rack_option, &info, &rack) == SCE_NGS2_OK); + return rack; +} + +static uintptr_t Sampler(uintptr_t system, const std::vector& pcm) { + const auto voice = Voice(CreateRack(system, SCE_NGS2_RACK_ID_SAMPLER)); + Control(voice, SCE_NGS2_SAMPLER_VOICE_PARAM_SETUP, Ngs2SamplerVoiceSetupParam{{}, {SCE_NGS2_WAVEFORM_TYPE_PCM_I16L, 2, 48000, 0, 0, 0}}); + const Ngs2WaveformBlock block{0, pcm.size() * sizeof(std::int16_t), 0, 0, static_cast(pcm.size() / 2), 0, 0}; + Control(voice, SCE_NGS2_SAMPLER_VOICE_PARAM_ADD_WAVEFORM_BLOCKS, Ngs2SamplerVoiceWaveformBlocksParam{{}, pcm.data(), 0, 1, &block}); + return voice; +} + +static std::vector Render(uintptr_t system) { + std::vector out(Grain * 2, -1.0f); + const Ngs2RenderBufferInfo info{out.data(), out.size() * sizeof(float), SCE_NGS2_WAVEFORM_TYPE_PCM_F32L, 2}; + Require(sceNgs2SystemRender(system, &info, 1) == SCE_NGS2_OK); + return out; +} + +static void TestUserFxChain() { + calls = {}; + const auto system = CreateSystem(); + const auto master = Mastering(system, 2); + const Ngs2CustomUserFx2ModuleOption modules[2] = {Module(Gain), Module(Offset)}; + const auto rack = CustomRack(system, RackOption(modules, 2)); + Require(calls.setupVoices == (std::vector{0, 1, 0, 1})); + + const auto custom = Voice(rack); + Control(custom, SCE_NGS2_CUSTOM_SUBMIXER_VOICE_PARAM_SETUP, Ngs2CustomSubmixerVoiceSetupParam{{}, 2, 2, 0, 0}); + Patch(custom, master); + Event(custom, SCE_NGS2_VOICE_EVENT_PLAY); + + std::vector pcm(Grain * 2 * 8, 16384); + const auto sampler = Sampler(system, pcm); + Patch(sampler, custom); + Event(sampler, SCE_NGS2_VOICE_EVENT_PLAY); + + auto out = Render(system); + for (std::uint32_t i = 0; i < Grain; i++) Require(out[i * 2] == 0.5f && out[i * 2 + 1] == 0.75f); + Require(calls.processFlags == (std::vector{0}) && calls.order == (std::vector{0, 1})); + + const float gain = 0.5f; + Control(custom, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 0, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain)}); + out = Render(system); + for (std::uint32_t i = 0; i < Grain; i++) Require(out[i * 2] == 0.25f && out[i * 2 + 1] == 0.5f); + Require(calls.processFlags == (std::vector{0, 2})); + out = Render(system); + Require(calls.processFlags == (std::vector{0, 2, 0})); + + Require(ControlThrows(custom, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 0, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain) - 1})); + Require(ControlThrows(custom, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 2, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain)})); + Require(ControlThrows(custom, SCE_NGS2_CUSTOM_SUBMIXER_VOICE_PARAM_SETUP, Ngs2CustomSubmixerVoiceSetupParam{{}, 2, 1, 0, 0})); + Require(ControlThrows(custom, SCE_NGS2_CUSTOM_SUBMIXER_VOICE_PARAM_SETUP, Ngs2CustomSubmixerVoiceSetupParam{{}, 2, 2, 1, 0})); + Require(ControlThrows(custom, SCE_NGS2_CUSTOM_SUBMIXER_VOICE_PARAM_SETUP, Ngs2CustomSubmixerVoiceSetupParam{{}, 3, 3, 0, 0})); + Require(ControlThrows(sampler, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 0, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain)})); + + calls.processResult = -1; + bool failed = false; + try { + Render(system); + } catch (const std::runtime_error&) { + failed = true; + } + Require(failed); + calls.processResult = SCE_NGS2_OK; + + Require(sceNgs2RackDestroy(rack, nullptr) == SCE_NGS2_OK); + Require(calls.cleanupVoices == (std::vector{0, 0, 1, 1})); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +static void TestRackOptions() { + calls = {}; + const auto system = CreateSystem(); + const Ngs2CustomUserFx2ModuleOption modules[1] = {Module(Gain)}; + const auto good = RackOption(modules, 1); + Ngs2ContextBufferInfo query{}; + Require(sceNgs2RackQueryBufferSize(SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER, &good.custom_rack_option.rack_option, &query) == SCE_NGS2_OK); + + auto option = good; + option.custom_rack_option.num_buffers = 2; + Require(CreateThrows(option)); + option = good; + option.custom_rack_option.module[0].module_id = 0x10; + Require(CreateThrows(option)); + option = good; + option.custom_rack_option.module[0].dest_buffer_id = 1; + Require(CreateThrows(option)); + option = good; + option.custom_rack_option.port[0].source_buffer_id = 1; + Require(CreateThrows(option)); + option = good; + option.custom_rack_option.num_modules = SCE_NGS2_CUSTOM_MAX_MODULES + 1; + Require(CreateThrows(option)); + auto noProcess = Module(nullptr); + option = RackOption(&noProcess, 1); + Require(CreateThrows(option)); + auto badSize = Module(Gain); + badSize.custom_module_option.size = 8; + option = RackOption(&badSize, 1); + Require(CreateThrows(option)); + bool failed = false; + try { + sceNgs2RackQueryBufferSize(SCE_NGS2_RACK_ID_CUSTOM_SUBMIXER, nullptr, &query); + } catch (const std::runtime_error&) { + failed = true; + } + Require(failed && calls.setupVoices.empty()); + + auto withControl = Module(Gain); + withControl.control_handler = ControlHandler; + const auto voice = Voice(CustomRack(system, RackOption(&withControl, 1))); + const float gain = 0.5f; + Require(ControlThrows(voice, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 0, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain)})); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); + Require(calls.cleanupVoices == (std::vector{0, 1})); +} + +int main() { + TestUserFxChain(); + TestRackOptions(); + return 0; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 4e605cf32..2cf3d0b50 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -103,6 +103,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceAjmDecMp3ParseFrame](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native) - signature, result layout and rate tables taken from the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation of the PS4 library, not confirmed on a PS5 title: the layer field is not checked and MPEG-2.5 stops at 64 kbps; the original file length (`parse_ofl`) layout (Xing/Info + LAME tag, VBRI, Fraunhofer `0xB4` block with its CRC, encoder delay = samples per frame + LAME delay + 529) also comes from shadPS4 only, and the Fraunhofer block has no other public description - [sceAjmBatchJobGetCodecInfo, sceAjmBatchJobGetGaplessDecode](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native) - the `RUN_GET_CODEC_INFO` flag (0x800), the ATRAC9 codec info layout and its next frame size are taken from the [shadPS4](https://github.com/shadps4-emu/shadPS4) and [RPCSX](https://github.com/RPCSX/rpcsx) reimplementations, not confirmed on a PS5 title; a run job without buffers returns result 0, as in shadPS4. The gapless sideband reports the total and skip counts the title set and does not count them down: RPCSX does the same, shadPS4 counts them down and BryKytyPS5 returns its current counts - [AJM Opus decoder](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native, codec 24) - the initialize parameter layout (`u32 channels, u32 sample rate, u32`, seen as `2, 48000, 0`) and the little-endian `u16` byte count before each packet come from one title (The Smurfs Dreams); only 48000 Hz and a zero third word are accepted +- [NGS2 custom submixer rack](../../core/libs/prx/libSceNgs2.native/src/Custom.cpp) (libSceNgs2.native, rack 0x4002) - structure layouts from [shadPS4](https://github.com/shadps4-emu/shadPS4)'s `ngs2_custom.h`; module id 0x1f for UserFx2, the voice parameter id `0x40001f00 | module index`, the process flag 2 after a parameter change and the call order (setup per voice at rack creation, process after the inputs are mixed, cleanup at destruction) come only from [KytyPS5](https://github.com/KytyPS5/KytyPS5). Only UserFx2 modules on a single buffer are accepted: other module ids, more buffers, a module control handler, different input and output channel counts, setup flags and default rack options throw. Each module's state is a separate buffer, not the `state_offset` slice of the voice state, and `sceNgs2VoiceGetState` still throws for this rack - [sceHttpParseResponseHeader](../../core/libs/prx/libSceHttp/Export.cpp) (libSceHttp) - signature follows [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Net/Http.cs); parsing and error codes follow [shadPS4's reverse-engineered PS4 library](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp), not confirmed on a PS5 title or hardware. Folded values retain their line breaks and whitespace; an empty first line starts the value scan after its line feed. A consumed byte count above `INT_MAX` throws instead of wrapping. - [sceHttpParseStatusLine](../../core/libs/prx/libSceHttp/src/Parse.cpp) (libSceHttp) - behaviour and error codes follow the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation of the PS4 library, not confirmed on a PS5 title; unlike it, no byte past `lineLen` is read - [sceHttpUriUnescape](../../core/libs/prx/libSceHttp/src/Uri.cpp) (libSceHttp) - signature follows [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Net/Http.cs); percent decoding, invalid sequences and error codes follow [shadPS4](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp), not confirmed on a PS5 title or hardware. Size includes the final NUL; malformed escapes and `+` remain unchanged, and decoding runs once. From 5a031f3ef6d7f9233e14b74d3b947a228202b469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 07:17:23 +0200 Subject: [PATCH 38/42] fix(ngs2): start UserFx2 process flags at 1 on the first call --- core/libs/prx/libSceNgs2.native/src/Custom.cpp | 2 ++ core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp | 6 +++--- docs/dev/TechnicalDebt.md | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceNgs2.native/src/Custom.cpp b/core/libs/prx/libSceNgs2.native/src/Custom.cpp index 2ba302fb2..d97ae633c 100644 --- a/core/libs/prx/libSceNgs2.native/src/Custom.cpp +++ b/core/libs/prx/libSceNgs2.native/src/Custom.cpp @@ -8,6 +8,7 @@ #include "prx/libc/include/General.hpp" #include "Ngs2Internal.hpp" +static constexpr std::uint32_t USER_FX2_FLAG_FIRST_PROCESS = 1; static constexpr std::uint32_t USER_FX2_FLAG_PARAM_CHANGED = 2; void Ngs2CheckCustomRack(const Ngs2CustomRackOption& option) { @@ -44,6 +45,7 @@ void Ngs2SetupUserFx(Ngs2Rack& rack, const Ngs2CustomRackOption& option) { fx.param.resize(module.param_size); fx.work.resize(module.work_size); fx.state.resize(option.module[m].state_size); + fx.flags = USER_FX2_FLAG_FIRST_PROCESS; if (module.setup_handler == nullptr) continue; auto context = UserFxContext(rack, m, i); const int result = module.setup_handler(&context); diff --git a/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp b/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp index 198b42fe2..b5872f457 100644 --- a/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp +++ b/core/libs/prx/libSceNgs2.native/tests/Ngs2Custom.cpp @@ -145,15 +145,15 @@ static void TestUserFxChain() { auto out = Render(system); for (std::uint32_t i = 0; i < Grain; i++) Require(out[i * 2] == 0.5f && out[i * 2 + 1] == 0.75f); - Require(calls.processFlags == (std::vector{0}) && calls.order == (std::vector{0, 1})); + Require(calls.processFlags == (std::vector{1}) && calls.order == (std::vector{0, 1})); const float gain = 0.5f; Control(custom, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 0, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain)}); out = Render(system); for (std::uint32_t i = 0; i < Grain; i++) Require(out[i * 2] == 0.25f && out[i * 2 + 1] == 0.5f); - Require(calls.processFlags == (std::vector{0, 2})); + Require(calls.processFlags == (std::vector{1, 2})); out = Render(system); - Require(calls.processFlags == (std::vector{0, 2, 0})); + Require(calls.processFlags == (std::vector{1, 2, 0})); Require(ControlThrows(custom, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 0, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain) - 1})); Require(ControlThrows(custom, SCE_NGS2_CUSTOM_VOICE_PARAM_USER_FX2 | 2, Ngs2CustomVoiceUserFx2Param{{}, &gain, sizeof(gain)})); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 2cf3d0b50..4b4d773ca 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -103,7 +103,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceAjmDecMp3ParseFrame](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native) - signature, result layout and rate tables taken from the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation of the PS4 library, not confirmed on a PS5 title: the layer field is not checked and MPEG-2.5 stops at 64 kbps; the original file length (`parse_ofl`) layout (Xing/Info + LAME tag, VBRI, Fraunhofer `0xB4` block with its CRC, encoder delay = samples per frame + LAME delay + 529) also comes from shadPS4 only, and the Fraunhofer block has no other public description - [sceAjmBatchJobGetCodecInfo, sceAjmBatchJobGetGaplessDecode](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native) - the `RUN_GET_CODEC_INFO` flag (0x800), the ATRAC9 codec info layout and its next frame size are taken from the [shadPS4](https://github.com/shadps4-emu/shadPS4) and [RPCSX](https://github.com/RPCSX/rpcsx) reimplementations, not confirmed on a PS5 title; a run job without buffers returns result 0, as in shadPS4. The gapless sideband reports the total and skip counts the title set and does not count them down: RPCSX does the same, shadPS4 counts them down and BryKytyPS5 returns its current counts - [AJM Opus decoder](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native, codec 24) - the initialize parameter layout (`u32 channels, u32 sample rate, u32`, seen as `2, 48000, 0`) and the little-endian `u16` byte count before each packet come from one title (The Smurfs Dreams); only 48000 Hz and a zero third word are accepted -- [NGS2 custom submixer rack](../../core/libs/prx/libSceNgs2.native/src/Custom.cpp) (libSceNgs2.native, rack 0x4002) - structure layouts from [shadPS4](https://github.com/shadps4-emu/shadPS4)'s `ngs2_custom.h`; module id 0x1f for UserFx2, the voice parameter id `0x40001f00 | module index`, the process flag 2 after a parameter change and the call order (setup per voice at rack creation, process after the inputs are mixed, cleanup at destruction) come only from [KytyPS5](https://github.com/KytyPS5/KytyPS5). Only UserFx2 modules on a single buffer are accepted: other module ids, more buffers, a module control handler, different input and output channel counts, setup flags and default rack options throw. Each module's state is a separate buffer, not the `state_offset` slice of the voice state, and `sceNgs2VoiceGetState` still throws for this rack +- [NGS2 custom submixer rack](../../core/libs/prx/libSceNgs2.native/src/Custom.cpp) (libSceNgs2.native, rack 0x4002) - structure layouts from [shadPS4](https://github.com/shadps4-emu/shadPS4)'s `ngs2_custom.h`; module id 0x1f for UserFx2, the voice parameter id `0x40001f00 | module index`, the process flags (1 on the first process call after setup, 2 after a parameter change, 0 otherwise) and the call order (setup per voice at rack creation, process after the inputs are mixed, cleanup at destruction) come only from [KytyPS5](https://github.com/KytyPS5/KytyPS5). Only UserFx2 modules on a single buffer are accepted: other module ids, more buffers, a module control handler, different input and output channel counts, setup flags and default rack options throw. Each module's state is a separate buffer, not the `state_offset` slice of the voice state, and `sceNgs2VoiceGetState` still throws for this rack. As in KytyPS5, process runs only on grains where an input produced samples, so an effect tail stops with the input and a pending flag 2 waits for the next audible grain - [sceHttpParseResponseHeader](../../core/libs/prx/libSceHttp/Export.cpp) (libSceHttp) - signature follows [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Net/Http.cs); parsing and error codes follow [shadPS4's reverse-engineered PS4 library](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp), not confirmed on a PS5 title or hardware. Folded values retain their line breaks and whitespace; an empty first line starts the value scan after its line feed. A consumed byte count above `INT_MAX` throws instead of wrapping. - [sceHttpParseStatusLine](../../core/libs/prx/libSceHttp/src/Parse.cpp) (libSceHttp) - behaviour and error codes follow the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation of the PS4 library, not confirmed on a PS5 title; unlike it, no byte past `lineLen` is read - [sceHttpUriUnescape](../../core/libs/prx/libSceHttp/src/Uri.cpp) (libSceHttp) - signature follows [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Net/Http.cs); percent decoding, invalid sequences and error codes follow [shadPS4](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp), not confirmed on a PS5 title or hardware. Size includes the final NUL; malformed escapes and `+` remain unchanged, and decoding runs once. From 6d2713cbdd0f93a3e13fcdfcc24599e1c839876b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 07:44:18 +0200 Subject: [PATCH 39/42] feat(libkernel): implement sceKernelGetDirectMemoryType Co-Authored-By: Claude --- .../prx/libkernel/DirectMemory/Export.cpp | 12 +++++++ core/libs/tests/GuestMemory.cpp | 34 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/core/libs/prx/libkernel/DirectMemory/Export.cpp b/core/libs/prx/libkernel/DirectMemory/Export.cpp index 373de6c2a..2ab677f2e 100644 --- a/core/libs/prx/libkernel/DirectMemory/Export.cpp +++ b/core/libs/prx/libkernel/DirectMemory/Export.cpp @@ -148,6 +148,18 @@ int APS5_VABI sceKernelDirectMemoryQuery(int64_t offset, int flags, void* info, return 0; } +int APS5_VABI sceKernelGetDirectMemoryType(int64_t offset, int* memory_type, int64_t* start, int64_t* end) { + if (!memory_type || !start || !end) return SCE_KERNEL_ERROR_EINVAL; + int64_t blockStart = 0; + int64_t blockEnd = 0; + int blockType = 0; + if (!DirectMemoryFind(offset, false, &blockStart, &blockEnd, &blockType)) return SCE_KERNEL_ERROR_ENOENT; + *memory_type = blockType; + *start = blockStart; + *end = blockEnd; + return 0; +} + size_t APS5_VABI sceKernelGetDirectMemorySize(void) { return DIRECT_MEMORY_SIZE; } diff --git a/core/libs/tests/GuestMemory.cpp b/core/libs/tests/GuestMemory.cpp index 58358ae15..1aa3007c9 100644 --- a/core/libs/tests/GuestMemory.cpp +++ b/core/libs/tests/GuestMemory.cpp @@ -59,6 +59,7 @@ int APS5_VABI sceKernelAioSubmitReadCommands(KernelAioRwRequest*, std::int32_t, int APS5_VABI sceKernelAioWaitRequest(std::int32_t, std::int32_t*, std::uint32_t*); int APS5_VABI sceKernelAioDeleteRequest(std::int32_t, std::int32_t*); int APS5_VABI sceKernelMlock_nid_postfix(void*, std::uint64_t); +int APS5_VABI sceKernelGetDirectMemoryType(std::int64_t, int*, std::int64_t*, std::int64_t*); } static void Require(bool condition, std::source_location location = std::source_location::current()) { @@ -191,6 +192,38 @@ static void CheckReleaseDirectMemoryClearsMappings() { Require(sceKernelMunmap(mapped, page * 2) == 0); } +static void CheckGetDirectMemoryType() { + constexpr std::size_t page = 0x4000; + std::int64_t first = 0; + Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, page * 2, 0, 3, &first) == 0); + std::int64_t second = 0; + Require(sceKernelAllocateDirectMemory(first + page * 2, first + page * 3, page, 0, 1, &second) == 0 && second == first + page * 2); + int type = -1; + std::int64_t start = -1; + std::int64_t end = -1; + Require(sceKernelGetDirectMemoryType(first, &type, &start, &end) == 0); + Require(type == 3 && start == first && end == first + page * 2); + type = -1; + Require(sceKernelGetDirectMemoryType(first + page * 2 - 1, &type, &start, &end) == 0); + Require(type == 3 && start == first && end == first + page * 2); + Require(sceKernelGetDirectMemoryType(first + page * 2, &type, &start, &end) == 0); + Require(type == 1 && start == second && end == second + page); + Require(sceKernelGetDirectMemoryType(first, nullptr, &start, &end) == SCE_KERNEL_ERROR_EINVAL); + Require(sceKernelGetDirectMemoryType(first, &type, nullptr, &end) == SCE_KERNEL_ERROR_EINVAL); + Require(sceKernelGetDirectMemoryType(first, &type, &start, nullptr) == SCE_KERNEL_ERROR_EINVAL); + Require(sceKernelReleaseDirectMemory(first, page) == 0); + type = -1; + start = -1; + end = -1; + Require(sceKernelGetDirectMemoryType(first, &type, &start, &end) == SCE_KERNEL_ERROR_ENOENT); + Require(type == -1 && start == -1 && end == -1); + Require(sceKernelGetDirectMemoryType(-1, &type, &start, &end) == SCE_KERNEL_ERROR_ENOENT); + Require(sceKernelGetDirectMemoryType(first + page, &type, &start, &end) == 0); + Require(type == 3 && start == first + page && end == first + page * 2); + Require(sceKernelReleaseDirectMemory(first + page, page * 2) == 0); + Require(sceKernelGetDirectMemoryType(second, &type, &start, &end) == SCE_KERNEL_ERROR_ENOENT); +} + static void CheckFixedVirtualReservation() { constexpr std::size_t page = 0x4000; void* probe = nullptr; @@ -727,6 +760,7 @@ int main() { CheckFixedVirtualReservation(); CheckMlock(); CheckSharedDirectMemoryLifecycle(); + CheckGetDirectMemoryType(); CheckHeapAfterMappingReuse(); #ifdef _WIN32 CheckNoOverwriteRejectsHostOccupiedMapping(); From 6dbdd927eed09f0b7e12f483c3ac157dd4512c70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 08:01:34 +0200 Subject: [PATCH 40/42] feat(ngs2): system sample rate, user data and lock Co-Authored-By: Claude --- .../libSceNgs2.native/src/Ngs2Internal.hpp | 1 + .../libs/prx/libSceNgs2.native/src/System.cpp | 49 +++++++++++++ .../libSceNgs2.native/tests/Ngs2Filter.cpp | 18 +++++ .../libSceNgs2.native/tests/Ngs2Render.cpp | 72 +++++++++++++++++++ .../prx/libSceNgs2.native/tests/Ngs2Test.hpp | 7 +- docs/dev/TechnicalDebt.md | 1 + 6 files changed, 147 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp b/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp index 615380f59..dd2dd3cc7 100644 --- a/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp +++ b/core/libs/prx/libSceNgs2.native/src/Ngs2Internal.hpp @@ -119,6 +119,7 @@ struct Ngs2System { Ngs2BufferAllocator allocator{}; std::uint32_t uid = 0; std::int64_t renderCount = 0; + std::uintptr_t userData = 0; std::vector racks; }; diff --git a/core/libs/prx/libSceNgs2.native/src/System.cpp b/core/libs/prx/libSceNgs2.native/src/System.cpp index 1bb850606..468dcc39a 100644 --- a/core/libs/prx/libSceNgs2.native/src/System.cpp +++ b/core/libs/prx/libSceNgs2.native/src/System.cpp @@ -188,6 +188,55 @@ int APS5_VABI sceNgs2SystemSetGrainSamples(uintptr_t system_handle, uint32_t num return SCE_NGS2_OK; } +int APS5_VABI sceNgs2SystemSetSampleRate(uintptr_t system_handle, uint32_t sample_rate) { + std::lock_guard lock(Ngs2Mutex()); + auto* system = Ngs2FindSystem(system_handle); + if (system == nullptr) return SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE; + if (sample_rate == 0) APS5_INVALID_ARG_EX; + for (const auto* rack : system->racks) { + for (const auto& voice : rack->voices) { + for (const auto& filter : voice.filters) { + if (filter.enabled && sample_rate != system->option.sample_rate) { + throw std::runtime_error("NGS2: changing the sample rate under an enabled sampler filter is not implemented"); + } + } + } + } + system->option.sample_rate = sample_rate; + return SCE_NGS2_OK; +} + +int APS5_VABI sceNgs2SystemSetUserData(uintptr_t system_handle, uintptr_t user_data) { + std::lock_guard lock(Ngs2Mutex()); + auto* system = Ngs2FindSystem(system_handle); + if (system == nullptr) return SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE; + system->userData = user_data; + return SCE_NGS2_OK; +} + +int APS5_VABI sceNgs2SystemGetUserData(uintptr_t system_handle, uintptr_t* user_data) { + std::lock_guard lock(Ngs2Mutex()); + const auto* system = Ngs2FindSystem(system_handle); + if (system == nullptr) return SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE; + if (user_data == nullptr) APS5_INVALID_ARG_EX; + *user_data = system->userData; + return SCE_NGS2_OK; +} + +int APS5_VABI sceNgs2SystemLock(uintptr_t system_handle) { + Ngs2Mutex().lock(); + if (Ngs2FindSystem(system_handle) != nullptr) return SCE_NGS2_OK; + Ngs2Mutex().unlock(); + return SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE; +} + +int APS5_VABI sceNgs2SystemUnlock(uintptr_t system_handle) { + std::lock_guard lock(Ngs2Mutex()); + if (Ngs2FindSystem(system_handle) == nullptr) return SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE; + Ngs2Mutex().unlock(); + return SCE_NGS2_OK; +} + int APS5_VABI sceNgs2SystemRender(uintptr_t system_handle, const Ngs2RenderBufferInfo* buffer_info, uint32_t num_buffer_info) { std::lock_guard lock(Ngs2Mutex()); auto* system = Ngs2FindSystem(system_handle); diff --git a/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp b/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp index 0c7f193c4..cf47e314b 100644 --- a/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp +++ b/core/libs/prx/libSceNgs2.native/tests/Ngs2Filter.cpp @@ -173,10 +173,28 @@ static void TestRejectedParams() { Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); } +static void TestRateChangeUnderFilter() { + const auto system = CreateSystem(); + const auto sampler = Sampler(system, std::vector(Grain, 0), 1, 48000); + SetFilter(sampler, Filter(0, 1, 1, 0, 1000.0f, 1.0f, 1.0f)); + Require(sceNgs2SystemSetSampleRate(system, 48000) == SCE_NGS2_OK); + bool rejected = false; + try { + sceNgs2SystemSetSampleRate(system, 96000); + } catch (const std::runtime_error&) { + rejected = true; + } + Require(rejected); + SetFilter(sampler, Filter(0, 1, 0, 0, 0.0f, 1.0f, 1.0f)); + Require(sceNgs2SystemSetSampleRate(system, 96000) == SCE_NGS2_OK); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + int main() { TestLowPassAndTail(); TestBypassMaskAndGain(); TestSystemRateAndZeroCutoff(); TestRejectedParams(); + TestRateChangeUnderFilter(); return 0; } diff --git a/core/libs/prx/libSceNgs2.native/tests/Ngs2Render.cpp b/core/libs/prx/libSceNgs2.native/tests/Ngs2Render.cpp index ea0f7c9eb..5250c7eee 100644 --- a/core/libs/prx/libSceNgs2.native/tests/Ngs2Render.cpp +++ b/core/libs/prx/libSceNgs2.native/tests/Ngs2Render.cpp @@ -1,7 +1,11 @@ #include "Ngs2Test.hpp" +#include +#include #include #include +#include +#include #include static uintptr_t Sampler(uintptr_t system, const std::vector& pcm, std::uint32_t repeats) { @@ -152,6 +156,71 @@ static std::int32_t APS5_VABI Release(Ngs2ContextBufferInfo* info) { return SCE_NGS2_OK; } +static void TestSampleRate() { + const auto system = CreateSystem(); + Require(sceNgs2SystemSetSampleRate(0x1234, 96000) == SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE); + bool threw = false; + try { + sceNgs2SystemSetSampleRate(system, 0); + } catch (const std::invalid_argument&) { + threw = true; + } + Require(threw); + Require(sceNgs2SystemSetSampleRate(system, 96000) == SCE_NGS2_OK); + Ngs2SystemInfo info{}; + Require(sceNgs2SystemGetInfo(system, &info, sizeof(info)) == SCE_NGS2_OK && info.sample_rate == 96000); + + const auto master = Mastering(system, 1); + const std::vector pcm{0, 1000, 2000, 3000}; + const auto sampler = Sampler(system, pcm, 1); + Patch(sampler, master); + Event(sampler, SCE_NGS2_VOICE_EVENT_PLAY); + const std::int16_t expected[Grain] = {0, 500, 1000, 1500, 2000, 2500, 3000, 1500}; + const auto out = RenderI16(system); + for (std::uint32_t i = 0; i < Grain; i++) Require(out[i] == expected[i]); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +static void TestUserData() { + uintptr_t value = 1; + Require(sceNgs2SystemSetUserData(0x1234, 5) == SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE); + Require(sceNgs2SystemGetUserData(0x1234, &value) == SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE && value == 1); + const auto system = CreateSystem(); + Require(sceNgs2SystemGetUserData(system, &value) == SCE_NGS2_OK && value == 0); + Require(sceNgs2SystemSetUserData(system, 0xfedcba9876543210) == SCE_NGS2_OK); + Require(sceNgs2SystemGetUserData(system, &value) == SCE_NGS2_OK && value == 0xfedcba9876543210); + bool threw = false; + try { + sceNgs2SystemGetUserData(system, nullptr); + } catch (const std::invalid_argument&) { + threw = true; + } + Require(threw); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + +static void TestLock() { + const auto system = CreateSystem(); + Require(sceNgs2SystemLock(0x1234) == SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE); + Require(sceNgs2SystemUnlock(0x1234) == SCE_NGS2_ERROR_INVALID_SYSTEM_HANDLE); + Ngs2SystemInfo info{}; + std::thread free([&] { Require(sceNgs2SystemGetInfo(system, &info, sizeof(info)) == SCE_NGS2_OK); }); + free.join(); + + Require(sceNgs2SystemLock(system) == SCE_NGS2_OK); + std::atomic done = false; + std::thread blocked([&] { + Require(sceNgs2SystemGetInfo(system, &info, sizeof(info)) == SCE_NGS2_OK); + done = true; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + Require(!done); + Require(sceNgs2SystemUnlock(system) == SCE_NGS2_OK); + blocked.join(); + Require(done); + Require(sceNgs2SystemDestroy(system, nullptr) == SCE_NGS2_OK); +} + static void TestAllocator() { const Ngs2BufferAllocator allocator{Allocate, Release, 9}; uintptr_t system = 0; @@ -171,6 +240,9 @@ int main() { TestPcmBlockEnd(); TestPitchAndRepeat(); TestSubmixerMatrix(); + TestSampleRate(); + TestUserData(); + TestLock(); TestAllocator(); return 0; } diff --git a/core/libs/prx/libSceNgs2.native/tests/Ngs2Test.hpp b/core/libs/prx/libSceNgs2.native/tests/Ngs2Test.hpp index 223618449..0b1429a67 100644 --- a/core/libs/prx/libSceNgs2.native/tests/Ngs2Test.hpp +++ b/core/libs/prx/libSceNgs2.native/tests/Ngs2Test.hpp @@ -18,6 +18,11 @@ int APS5_VABI sceNgs2SystemCreateWithAllocator(const Ngs2SystemOption*, const Ng int APS5_VABI sceNgs2SystemDestroy(uintptr_t, Ngs2ContextBufferInfo*); int APS5_VABI sceNgs2SystemGetInfo(uintptr_t, Ngs2SystemInfo*, size_t); int APS5_VABI sceNgs2SystemSetGrainSamples(uintptr_t, uint32_t); +int APS5_VABI sceNgs2SystemSetSampleRate(uintptr_t, uint32_t); +int APS5_VABI sceNgs2SystemSetUserData(uintptr_t, uintptr_t); +int APS5_VABI sceNgs2SystemGetUserData(uintptr_t, uintptr_t*); +int APS5_VABI sceNgs2SystemLock(uintptr_t); +int APS5_VABI sceNgs2SystemUnlock(uintptr_t); int APS5_VABI sceNgs2SystemRender(uintptr_t, const Ngs2RenderBufferInfo*, uint32_t); int APS5_VABI sceNgs2RackQueryBufferSize(uint32_t, const Ngs2RackOption*, Ngs2ContextBufferInfo*); int APS5_VABI sceNgs2RackCreate(uintptr_t, uint32_t, const Ngs2RackOption*, const Ngs2ContextBufferInfo*, uintptr_t*); @@ -40,7 +45,7 @@ inline void Check(bool value, int line) { inline constexpr std::uint32_t Grain = 8; -inline std::vector buffers[16]; +inline std::vector buffers[32]; inline std::size_t usedBuffers = 0; inline Ngs2ContextBufferInfo Buffer(const Ngs2ContextBufferInfo& query) { diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 4e605cf32..9ff11e7d2 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -118,6 +118,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceSystemServiceDisableMediaPlay](../../core/libs/prx/libSceSystemService/Export.cpp) (libSceSystemService) - unknown signature - [sceSystemServiceReenableMediaPlay](../../core/libs/prx/libSceSystemService/Export.cpp) (libSceSystemService) - unknown signature - [sceSystemServiceParamGetString](../../core/libs/prx/libSceSystemService/Export.cpp) (libSceSystemService) - the system name (parameter 6) is the fixed `PS5`, not the console's name; other parameters and buffers of 1 to 64 bytes throw +- [sceNgs2SystemSetSampleRate, sceNgs2SystemSetUserData, sceNgs2SystemGetUserData, sceNgs2SystemLock, sceNgs2SystemUnlock](../../core/libs/prx/libSceNgs2.native/src/System.cpp) (libSceNgs2.native) - shadPS4 only checks the system handle (`INVALID_SYSTEM_HANDLE`) and SharpProspero names what each call does; neither gives the other limits. A sample rate of 0 and a null user data pointer throw, any other rate is accepted, and changing the rate while a sampler filter is enabled throws because the filter coefficients were computed for the old rate. Lock and unlock take the same lock as `sceNgs2RackLock` - [sceVoiceSetMuteFlag](../../core/libs/prx/libSceVoice/Export.cpp) (libSceVoice) - unknown signature - [snwprintf_s](../../core/libs/prx/libc/src/FormattingWide.cpp) (libc) - follows C11 K.3.9.1.3 with `RSIZE_MAX` assumed to be `SIZE_MAX >> 1`. A runtime-constraint violation only returns a negative value: `set_constraint_handler_s` is not exported and the console's default handler is unknown. An invalid multibyte `%s` argument is copied byte by byte instead of being reported as an encoding error, as in `vswprintf` - [libSceUlt queues](../../core/libs/prx/libSceUlt/Export.cpp) - the added `sceUltQueuePop`, `sceUltQueueTryPush`, `sceUltQueueDestroy` and `sceUltQueueDataResourcePoolDestroy` signatures are inferred from the existing push/pop and object APIs. Queue destruction is assumed to reject blocked callers with `ULT_ERROR_BUSY` and otherwise discard queued data; pool exhaustion returns `ULT_ERROR_AGAIN`. These rules, alignment checks and shared slot limits have not been confirmed on PS5 hardware or a title. Non-null queue and data-pool option parameters throw because their layouts are unknown. From bc7fdff9e5eac79aa5f1680b549acd0b015172fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 08:06:17 +0200 Subject: [PATCH 41/42] feat(libSceHttp): add sceHttpSetResponseHeaderMaxSize, sceHttpRedirectCacheFlush, sceHttpsUnloadCert Co-Authored-By: Claude --- core/libs/prx/libSceHttp/Export.cpp | 16 ++++++++++++++++ core/libs/tests/GuestHttp.cpp | 6 ++++++ docs/dev/TechnicalDebt.md | 2 ++ 3 files changed, 24 insertions(+) diff --git a/core/libs/prx/libSceHttp/Export.cpp b/core/libs/prx/libSceHttp/Export.cpp index fa00ad2d7..1d10d5348 100644 --- a/core/libs/prx/libSceHttp/Export.cpp +++ b/core/libs/prx/libSceHttp/Export.cpp @@ -172,6 +172,12 @@ int APS5_VABI sceHttpSetRecvTimeOut(int id, uint32_t usec) { return 0; } +int APS5_VABI sceHttpSetResponseHeaderMaxSize(int id, uint64_t header_size) { + (void)id; + (void)header_size; + return 0; +} + int APS5_VABI sceHttpSetRequestContentLength(int request_id, uint64_t content_length) { (void)request_id; (void)content_length; @@ -242,6 +248,11 @@ int APS5_VABI sceHttpReadData(int request_id, void* data, size_t size) { return ERROR_NETWORK; } +int APS5_VABI sceHttpRedirectCacheFlush(int http_ctx_id) { + (void)http_ctx_id; + return 0; +} + int APS5_VABI sceHttpSetChunkedTransferEnabled(int id, int enable) { (void)id; (void)enable; @@ -345,6 +356,11 @@ int APS5_VABI sceHttpsLoadCert(int http_ctx_id, int num, void* ca_list, void* ce return 0; } +int APS5_VABI sceHttpsUnloadCert(int http_ctx_id) { + (void)http_ctx_id; + return 0; +} + int APS5_VABI sceHttpGetLastErrno(int request_id, int* errno_out) { (void)request_id; if (errno_out == nullptr) { diff --git a/core/libs/tests/GuestHttp.cpp b/core/libs/tests/GuestHttp.cpp index 1a5d01074..ae625c507 100644 --- a/core/libs/tests/GuestHttp.cpp +++ b/core/libs/tests/GuestHttp.cpp @@ -18,6 +18,9 @@ int APS5_VABI sceHttpCreateRequest2(int, const char*, const char*, std::uint64_t int APS5_VABI sceHttpsEnableOption(int, std::uint32_t); int APS5_VABI sceHttpsLoadCert(int, int, void*, void*, void*); int APS5_VABI sceHttpGetLastErrno(int, int*); +int APS5_VABI sceHttpSetResponseHeaderMaxSize(int, std::uint64_t); +int APS5_VABI sceHttpRedirectCacheFlush(int); +int APS5_VABI sceHttpsUnloadCert(int); int APS5_VABI sceHttpParseStatusLine(const char*, std::size_t, std::int32_t*, std::int32_t*, std::int32_t*, const char**, std::size_t*); } @@ -137,6 +140,9 @@ int main() { Require(sceHttpSetInflateGZIPEnabled(1, -1) == invalidValue); Require(sceHttpsEnableOption(1, 0) == 0); Require(sceHttpsLoadCert(1, 0, nullptr, nullptr, nullptr) == 0); + Require(sceHttpsUnloadCert(1) == 0); + Require(sceHttpSetResponseHeaderMaxSize(1, 8192) == 0); + Require(sceHttpRedirectCacheFlush(1) == 0); int httpErrno = -1; Require(sceHttpGetLastErrno(1, &httpErrno) == 0); Require(httpErrno == 0); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 4e605cf32..9c35efd56 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -26,6 +26,7 @@ Throughout the project, every function at every stage either **does exactly what - [libSceNpTrophy2](../../core/libs/prx/libSceNpTrophy2/src/GameInfo.cpp): `sceNpTrophy2RegisterUnlockCallback` accepts a callback that is never called, as no trophy is ever unlocked, and `sceNpTrophy2UnregisterUnlockCallback` only returns success. - [sceAvPlayerSetTrickSpeed](../../core/libs/prx/libSceAvPlayer/src/Source.cpp) (libSceAvPlayer) with a negative speed runs the clock backwards but delivers no frames; when a forward speed is set again, playback resumes from the rewound time. - [ulobjmgr](../../core/libs/prx/ulobjmgr/Export.cpp) registers no object: `_sceUlobjmgrRegisterObject` always hands out id 0 and `_sceUlobjmgrUnregisterObject` releases nothing, as shadPS4 does +- [libSceHttp](../../core/libs/prx/libSceHttp/Export.cpp) - no request reaches the network, so `sceHttpSetResponseHeaderMaxSize` has no response header to limit and `sceHttpRedirectCacheFlush` no redirect to forget; `sceHttpsUnloadCert` returns success like `sceHttpsLoadCert`, which keeps no certificate ### Unknown function info @@ -106,6 +107,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceHttpParseResponseHeader](../../core/libs/prx/libSceHttp/Export.cpp) (libSceHttp) - signature follows [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Net/Http.cs); parsing and error codes follow [shadPS4's reverse-engineered PS4 library](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp), not confirmed on a PS5 title or hardware. Folded values retain their line breaks and whitespace; an empty first line starts the value scan after its line feed. A consumed byte count above `INT_MAX` throws instead of wrapping. - [sceHttpParseStatusLine](../../core/libs/prx/libSceHttp/src/Parse.cpp) (libSceHttp) - behaviour and error codes follow the [shadPS4](https://github.com/shadps4-emu/shadPS4) reimplementation of the PS4 library, not confirmed on a PS5 title; unlike it, no byte past `lineLen` is read - [sceHttpUriUnescape](../../core/libs/prx/libSceHttp/src/Uri.cpp) (libSceHttp) - signature follows [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/main/src/SharpProspero/Interop/Net/Http.cs); percent decoding, invalid sequences and error codes follow [shadPS4](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp), not confirmed on a PS5 title or hardware. Size includes the final NUL; malformed escapes and `+` remain unchanged, and decoding runs once. +- [sceHttpSetResponseHeaderMaxSize, sceHttpRedirectCacheFlush, sceHttpsUnloadCert](../../core/libs/prx/libSceHttp/Export.cpp) (libSceHttp) - signatures follow [shadPS4](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/network/http.cpp) (PS4); no PS5 reference has them - [sceHttp2GetMemoryPoolStats](../../core/libs/prx/libSceHttp2/Export.cpp) (libSceHttp2) - unknown signature - [sceNetGetMemoryPoolStats](../../core/libs/prx/libSceNet/Export.cpp) (libSceNet) - unknown signature - [sceHttpSetRequestStatusCallback](../../core/libs/prx/libSceHttp/Export.cpp) (libSceHttp) - no reference implements it (shadPS4 only logs and returns 0); when the callback runs and what status it gets is unknown From 0f2699eef4c406573d5f35625d53c83634d0de9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Franch?= Date: Tue, 6 Oct 2026 08:11:07 +0200 Subject: [PATCH 42/42] feat(libkernel): Aio batch submit, wait, cancel and delete Co-Authored-By: Claude --- core/libs/prx/libkernel/Aio/src/Aio.cpp | 142 +++++++++++++++++++++--- core/libs/tests/GuestAio.cpp | 92 +++++++++++++++ docs/dev/TechnicalDebt.md | 1 + 3 files changed, 220 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libkernel/Aio/src/Aio.cpp b/core/libs/prx/libkernel/Aio/src/Aio.cpp index b592c1643..4811010a6 100644 --- a/core/libs/prx/libkernel/Aio/src/Aio.cpp +++ b/core/libs/prx/libkernel/Aio/src/Aio.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "SceTypes.hpp" #include "prx/libc/include/General.hpp" @@ -26,6 +27,10 @@ constexpr std::int32_t AioProcessing = 2; constexpr std::int32_t AioCompleted = 3; constexpr std::int32_t AioAborted = 4; constexpr std::int32_t AioMaxQueues = 512; +constexpr std::int32_t AioRequestNumMax = 128; +constexpr std::int32_t AioIdNumMax = 128; +constexpr std::uint32_t AioWaitAnd = 1; +constexpr std::uint32_t AioWaitOr = 2; std::mutex g_mutex; std::array g_states{}; @@ -100,35 +105,67 @@ std::int64_t NativePwrite(std::int32_t fd, const void* buf, std::size_t nbyte, s #endif } -int SubmitCommands(KernelAioRwRequest* req, std::int32_t size, bool write, std::int32_t* id) { +bool RunRequest(KernelAioRwRequest& req, bool write) { + const std::int64_t done = write + ? NativePwrite(req.fd, req.buf, req.nbyte, req.offset) + : NativePread(req.fd, req.buf, req.nbyte, req.offset); + if (done < 0) { + const int error = errno; + req.result->return_value = static_cast(SCE_KERNEL_ERROR_EIO); + if (error == EBADF) req.result->return_value = static_cast(SCE_KERNEL_ERROR_EBADF); + if (error == EFAULT) req.result->return_value = static_cast(SCE_KERNEL_ERROR_EFAULT); + req.result->state = AioAborted; + return false; + } + req.result->return_value = done; + req.result->state = AioCompleted; + return true; +} + +int ValidateRequests(KernelAioRwRequest* req, std::int32_t size, const void* id) { if (req == nullptr || id == nullptr) return SCE_KERNEL_ERROR_EFAULT; if (size <= 0) return SCE_KERNEL_ERROR_EINVAL; for (std::int32_t i = 0; i < size; ++i) { if (req[i].result == nullptr) return SCE_KERNEL_ERROR_EFAULT; } + return 0; +} + +int SubmitCommands(KernelAioRwRequest* req, std::int32_t size, bool write, std::int32_t* id) { + const int error = ValidateRequests(req, size, id); + if (error != 0) return error; const std::int32_t queue = AllocateId(); bool aborted = false; for (std::int32_t i = 0; i < size; ++i) { - const std::int64_t done = write - ? NativePwrite(req[i].fd, req[i].buf, req[i].nbyte, req[i].offset) - : NativePread(req[i].fd, req[i].buf, req[i].nbyte, req[i].offset); - if (done < 0) { - const int error = errno; - req[i].result->return_value = static_cast(SCE_KERNEL_ERROR_EIO); - if (error == EBADF) req[i].result->return_value = static_cast(SCE_KERNEL_ERROR_EBADF); - if (error == EFAULT) req[i].result->return_value = static_cast(SCE_KERNEL_ERROR_EFAULT); - req[i].result->state = AioAborted; - aborted = true; - } else { - req[i].result->return_value = done; - req[i].result->state = AioCompleted; - } + if (!RunRequest(req[i], write)) aborted = true; } SetState(queue, aborted ? AioAborted : AioCompleted); *id = queue; return 0; } +int SubmitCommandsMultiple(KernelAioRwRequest* req, std::int32_t size, bool write, std::int32_t* id, const char* name) { + const int error = ValidateRequests(req, size, id); + if (error != 0) return error; + if (size > AioRequestNumMax) throw std::runtime_error(std::string(name) + ": more than 128 requests per batch is not modelled"); + for (std::int32_t i = 0; i < size; ++i) { + const std::int32_t queue = AllocateId(); + SetState(queue, RunRequest(req[i], write) ? AioCompleted : AioAborted); + id[i] = queue; + } + return 0; +} + +int ValidateIds(const std::int32_t* id, std::int32_t num, const void* out, const char* name) { + if (id == nullptr || out == nullptr) return SCE_KERNEL_ERROR_EFAULT; + if (num < 0) return SCE_KERNEL_ERROR_EINVAL; + if (num > AioIdNumMax) throw std::runtime_error(std::string(name) + ": more than 128 ids per batch is not modelled"); + for (std::int32_t i = 0; i < num; ++i) { + if (!ValidId(id[i])) return SCE_KERNEL_ERROR_EINVAL; + } + return 0; +} + } extern "C" { @@ -141,6 +178,46 @@ int APS5_VABI sceKernelAioDeleteRequest(int32_t id, int32_t* ret) { return 0; } +int APS5_VABI sceKernelAioDeleteRequests(int32_t* id, int32_t num, int32_t* ret) { + const int error = ValidateIds(id, num, ret, "sceKernelAioDeleteRequests"); + if (error != 0) return error; + for (int32_t i = 0; i < num; ++i) { + SetState(id[i], AioAborted); + ret[i] = 0; + } + return 0; +} + +int APS5_VABI sceKernelAioCancelRequest(int32_t id, int32_t* state) { + if (state == nullptr) return SCE_KERNEL_ERROR_EFAULT; + if (id == 0) { + *state = AioProcessing; + return 0; + } + if (!ValidId(id)) return SCE_KERNEL_ERROR_EINVAL; + SetState(id, AioAborted); + *state = AioAborted; + return 0; +} + +int APS5_VABI sceKernelAioCancelRequests(int32_t* id, int32_t num, int32_t* state) { + if (id == nullptr || state == nullptr) return SCE_KERNEL_ERROR_EFAULT; + if (num < 0) return SCE_KERNEL_ERROR_EINVAL; + if (num > AioIdNumMax) throw std::runtime_error("sceKernelAioCancelRequests: more than 128 ids per batch is not modelled"); + for (int32_t i = 0; i < num; ++i) { + if (id[i] != 0 && !ValidId(id[i])) return SCE_KERNEL_ERROR_EINVAL; + } + for (int32_t i = 0; i < num; ++i) { + if (id[i] == 0) { + state[i] = AioProcessing; + continue; + } + SetState(id[i], AioAborted); + state[i] = AioAborted; + } + return 0; +} + int APS5_VABI sceKernelAioInitializeImpl(void* param, int32_t size) { (void)param; (void)size; @@ -161,6 +238,16 @@ int APS5_VABI sceKernelAioSubmitWriteCommands(KernelAioRwRequest* req, int32_t s return SubmitCommands(req, size, true, id); } +int APS5_VABI sceKernelAioSubmitReadCommandsMultiple(KernelAioRwRequest* req, int32_t size, int32_t prio, int32_t* id) { + (void)prio; + return SubmitCommandsMultiple(req, size, false, id, "sceKernelAioSubmitReadCommandsMultiple"); +} + +int APS5_VABI sceKernelAioSubmitWriteCommandsMultiple(KernelAioRwRequest* req, int32_t size, int32_t prio, int32_t* id) { + (void)prio; + return SubmitCommandsMultiple(req, size, true, id, "sceKernelAioSubmitWriteCommandsMultiple"); +} + int APS5_VABI sceKernelAioPollRequest(int32_t id, int32_t* state) { if (state == nullptr) return SCE_KERNEL_ERROR_EFAULT; if (!ValidId(id)) return SCE_KERNEL_ERROR_EINVAL; @@ -169,6 +256,31 @@ int APS5_VABI sceKernelAioPollRequest(int32_t id, int32_t* state) { return 0; } +int APS5_VABI sceKernelAioWaitRequests(int32_t* id, int32_t num, int32_t* state, uint32_t mode, uint32_t* usec) { + const int error = ValidateIds(id, num, state, "sceKernelAioWaitRequests"); + if (error != 0) return error; + if (mode != AioWaitAnd && mode != AioWaitOr) throw std::runtime_error("sceKernelAioWaitRequests: unsupported wait mode"); + const auto start = std::chrono::steady_clock::now(); + for (;;) { + bool allDone = true; + bool anyCompleted = false; + { + std::lock_guard lock(g_mutex); + for (int32_t i = 0; i < num; ++i) { + state[i] = g_states[id[i]]; + if (state[i] == AioProcessing) allDone = false; + if (state[i] == AioCompleted) anyCompleted = true; + } + } + if (allDone || (mode == AioWaitOr && anyCompleted)) return 0; + if (usec != nullptr && *usec != 0) { + const auto elapsed = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); + if (elapsed > static_cast(*usec)) return SCE_KERNEL_ERROR_ETIMEDOUT; + } + std::this_thread::sleep_for(std::chrono::microseconds(10)); + } +} + int APS5_VABI sceKernelAioWaitRequest(int32_t id, int32_t* state, uint32_t* usec) { if (state == nullptr) return SCE_KERNEL_ERROR_EFAULT; if (!ValidId(id)) return SCE_KERNEL_ERROR_EINVAL; diff --git a/core/libs/tests/GuestAio.cpp b/core/libs/tests/GuestAio.cpp index 36cad273a..7193da905 100644 --- a/core/libs/tests/GuestAio.cpp +++ b/core/libs/tests/GuestAio.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include extern "C" { int APS5_VABI sceKernelOpen(const char* path, int flags, std::uint16_t mode); @@ -20,6 +21,12 @@ int APS5_VABI sceKernelAioSubmitReadCommands(KernelAioRwRequest* req, std::int32 int APS5_VABI sceKernelAioSubmitWriteCommands(KernelAioRwRequest* req, std::int32_t size, std::int32_t prio, std::int32_t* id); int APS5_VABI sceKernelAioPollRequest(std::int32_t id, std::int32_t* state); int APS5_VABI sceKernelAioWaitRequest(std::int32_t id, std::int32_t* state, std::uint32_t* usec); +int APS5_VABI sceKernelAioSubmitReadCommandsMultiple(KernelAioRwRequest* req, std::int32_t size, std::int32_t prio, std::int32_t* id); +int APS5_VABI sceKernelAioSubmitWriteCommandsMultiple(KernelAioRwRequest* req, std::int32_t size, std::int32_t prio, std::int32_t* id); +int APS5_VABI sceKernelAioWaitRequests(std::int32_t* id, std::int32_t num, std::int32_t* state, std::uint32_t mode, std::uint32_t* usec); +int APS5_VABI sceKernelAioCancelRequest(std::int32_t id, std::int32_t* state); +int APS5_VABI sceKernelAioCancelRequests(std::int32_t* id, std::int32_t num, std::int32_t* state); +int APS5_VABI sceKernelAioDeleteRequests(std::int32_t* id, std::int32_t num, std::int32_t* ret); } static void Require(bool value, int line) { if (!value) { @@ -86,5 +93,90 @@ int main() { Check(sceKernelAioPollRequest(id, nullptr) == SCE_KERNEL_ERROR_EFAULT); Check(sceKernelAioPollRequest(0, &polled) == SCE_KERNEL_ERROR_EINVAL); Check(sceKernelAioDeleteRequest(id, nullptr) == SCE_KERNEL_ERROR_EFAULT); + const int batchFd = sceKernelOpen(file.string().c_str(), SCE_KERNEL_O_RDWR, 0); + Check(batchFd >= 0); + std::array patch = {'W', 'X', 'Y', 'Z'}; + KernelAioResult patchResult{-1, 0}; + KernelAioResult badResult{-1, 0}; + KernelAioRwRequest writeBatch[2] = { + {8, patch.size(), patch.data(), &patchResult, batchFd}, + {0, patch.size(), patch.data(), &badResult, -1}, + }; + std::int32_t writeIds[2] = {0, 0}; + Check(sceKernelAioSubmitWriteCommandsMultiple(writeBatch, 2, 0, writeIds) == 0); + Check(writeIds[0] > 0 && writeIds[1] > 0 && writeIds[0] != writeIds[1]); + Check(patchResult.state == 3 && patchResult.return_value == 4); + Check(badResult.state == 4 && badResult.return_value == SCE_KERNEL_ERROR_EBADF); + std::int32_t writeStates[2] = {0, 0}; + Check(sceKernelAioWaitRequests(writeIds, 2, writeStates, 1, nullptr) == 0); + Check(writeStates[0] == 3 && writeStates[1] == 4); + std::array readBack{}; + std::array tail{}; + KernelAioResult readBackResult{-1, 0}; + KernelAioResult tailResult{-1, 0}; + KernelAioRwRequest readBatch[2] = { + {8, readBack.size(), readBack.data(), &readBackResult, batchFd}, + {60, tail.size(), tail.data(), &tailResult, batchFd}, + }; + std::int32_t readIds[2] = {0, 0}; + Check(sceKernelAioSubmitReadCommandsMultiple(readBatch, 2, 0, readIds) == 0); + Check(readIds[0] > 0 && readIds[1] > 0 && readIds[0] != readIds[1]); + Check(readBackResult.state == 3 && readBackResult.return_value == 4); + Check(std::memcmp(readBack.data(), "WXYZ", 4) == 0); + Check(tailResult.state == 3 && tailResult.return_value == 4); + Check(std::memcmp(tail.data(), seed.data() + 60, 4) == 0); + std::int32_t readStates[2] = {0, 0}; + std::uint32_t timeout = 1000; + Check(sceKernelAioWaitRequests(readIds, 2, readStates, 2, &timeout) == 0); + Check(readStates[0] == 3 && readStates[1] == 3); + std::int32_t cancelled = 0; + Check(sceKernelAioCancelRequest(readIds[0], &cancelled) == 0); + Check(cancelled == 4); + Check(sceKernelAioPollRequest(readIds[0], &polled) == 0); + Check(polled == 4); + Check(sceKernelAioCancelRequest(0, &cancelled) == 0); + Check(cancelled == 2); + std::int32_t cancelIds[2] = {0, readIds[1]}; + std::int32_t cancelStates[2] = {0, 0}; + Check(sceKernelAioCancelRequests(cancelIds, 2, cancelStates) == 0); + Check(cancelStates[0] == 2 && cancelStates[1] == 4); + Check(sceKernelAioPollRequest(readIds[1], &polled) == 0); + Check(polled == 4); + std::int32_t deletedRets[2] = {-1, -1}; + Check(sceKernelAioDeleteRequests(writeIds, 2, deletedRets) == 0); + Check(deletedRets[0] == 0 && deletedRets[1] == 0); + Check(sceKernelAioPollRequest(writeIds[0], &polled) == 0); + Check(polled == 4); + Check(sceKernelAioDeleteRequests(writeIds, 0, deletedRets) == 0); + Check(sceKernelClose(batchFd) == 0); + std::int32_t badIds[2] = {readIds[0], 9999}; + std::int32_t untouched[2] = {7, 7}; + Check(sceKernelAioSubmitReadCommandsMultiple(nullptr, 1, 0, readIds) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioSubmitReadCommandsMultiple(readBatch, 1, 0, nullptr) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioSubmitWriteCommandsMultiple(writeBatch, 0, 0, writeIds) == SCE_KERNEL_ERROR_EINVAL); + KernelAioRwRequest noResult{0, 1, readBack.data(), nullptr, batchFd}; + Check(sceKernelAioSubmitWriteCommandsMultiple(&noResult, 1, 0, writeIds) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioWaitRequests(readIds, 2, nullptr, 1, nullptr) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioWaitRequests(nullptr, 2, readStates, 1, nullptr) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioWaitRequests(readIds, -1, readStates, 1, nullptr) == SCE_KERNEL_ERROR_EINVAL); + Check(sceKernelAioWaitRequests(badIds, 2, untouched, 1, nullptr) == SCE_KERNEL_ERROR_EINVAL); + Check(untouched[0] == 7 && untouched[1] == 7); + bool threw = false; + try { sceKernelAioWaitRequests(readIds, 2, readStates, 3, nullptr); } catch (const std::runtime_error&) { threw = true; } + Check(threw); + threw = false; + std::array manyIds{}; + std::array manyStates{}; + manyIds.fill(readIds[0]); + try { sceKernelAioDeleteRequests(manyIds.data(), 129, manyStates.data()); } catch (const std::runtime_error&) { threw = true; } + Check(threw); + Check(sceKernelAioCancelRequest(9999, &cancelled) == SCE_KERNEL_ERROR_EINVAL); + Check(sceKernelAioCancelRequest(readIds[0], nullptr) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioCancelRequests(badIds, 2, untouched) == SCE_KERNEL_ERROR_EINVAL); + Check(untouched[0] == 7 && untouched[1] == 7); + Check(sceKernelAioCancelRequests(cancelIds, 2, nullptr) == SCE_KERNEL_ERROR_EFAULT); + Check(sceKernelAioDeleteRequests(badIds, 2, untouched) == SCE_KERNEL_ERROR_EINVAL); + Check(untouched[0] == 7 && untouched[1] == 7); + Check(sceKernelAioDeleteRequests(writeIds, 2, nullptr) == SCE_KERNEL_ERROR_EFAULT); Check(std::filesystem::remove_all(root) > 0); } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 4e605cf32..63b571c21 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -65,6 +65,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKernelInternalMemoryGetModuleSegmentInfo](../../core/libs/prx/libkernel/Module/src/Module.cpp) (libkernel) - unknown signature - [sceKernelSyncOnAddressWait](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - the only known caller passes a null timeout and a name string as the fourth argument; the timeout is assumed to point to microseconds like the other kernel waits, and the name is ignored - [sceKernelSyncOnAddressWait8 / sceKernelSyncOnAddressWait16 / sceKernelSyncOnAddressWait32 / sceKernelSyncOnAddressWait64](../../core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp) (libkernel) - libc's `__std_atomic_wait_direct_8/16/32/64` pass a microsecond timeout or null and ignore the result; the by-value comparand, return values and the 2- and 8-byte alignment of Wait16 and Wait64 are assumed +- [sceKernelAioSubmitReadCommandsMultiple / sceKernelAioSubmitWriteCommandsMultiple / sceKernelAioWaitRequests / sceKernelAioCancelRequest / sceKernelAioCancelRequests / sceKernelAioDeleteRequests](../../core/libs/prx/libkernel/Aio/src/Aio.cpp) (libkernel) - behaviour from shadPS4 (one id per request for the Multiple submits, cancel turns any request aborted and id 0 reports processing, wait mode 2 returns once one request completed); the 128 requests or ids per batch limit is from SharpProspero, with an unknown error, so larger batches throw; wait modes other than 1 (and) and 2 (or) throw; null pointers, negative counts and invalid ids return the codes the single-request siblings use, checked before any state is written - [sceKernelGetAvailableCpumask](../../core/libs/prx/libkernel/Pthread/src/Thread.cpp) (libkernel) - returns the default thread affinity, 0x1FFF (CPUs 0 to 12), as KytyPS5 does. Titles pin threads within it (PPSA02664 passes 0x1FFB, Hades II PPSA36082 0x3 and 0x3F); whether CPU 13 is available to a title is not confirmed - [sceKernelMapNamedFlexibleMemoryInternal](../../core/libs/prx/libkernel/DirectMemory/Export.cpp) (libkernel) - flag 0x8000 unknown; only the sceKernelMapNamedFlexibleMemory flags are accepted - [Guest arena](../../core/libs/prx/libc/src/GuestArena.cpp) (libc) - the application map area is assumed to end at 0xFC_0000_0000, as `SCE_KERNEL_APP_MAP_AREA_END_ADDR` does on the PS4. On Windows, host allocations made in the arena before libc loads stay, and a fixed guest mapping over one throws