From 7e1a34d691ead04ecb2078b316c1061000c34a32 Mon Sep 17 00:00:00 2001 From: Mihai Date: Mon, 23 Nov 2026 15:32:34 +0200 Subject: [PATCH 01/18] feat(libc): implement libc++ streambuf defaults # Conflicts: # core/libs/prx/libc/CMakeLists.txt --- core/libs/prx/libc/CMakeLists.txt | 1 + core/libs/prx/libc/include/Api.hpp | 6 ++++ core/libs/prx/libc/src/LibcxxStreambuf.cpp | 31 +++++++++++++++++++ core/libs/tests/GuestLibcStaticImports.cpp | 28 +++++++++++++++++ .../feat-libc-libcxx-streambuf-defaults.md | 5 +++ 5 files changed, 71 insertions(+) create mode 100644 core/libs/prx/libc/src/LibcxxStreambuf.cpp create mode 100644 docs/dev/debt/changes/feat-libc-libcxx-streambuf-defaults.md diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index 0855a0e16de2..41c34d87872c 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -283,6 +283,7 @@ target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/Queue.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStringErase.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxPlainMutex.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStreambuf.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/NumericLimits.cpp ) diff --git a/core/libs/prx/libc/include/Api.hpp b/core/libs/prx/libc/include/Api.hpp index 53dd1296be4c..14e09c30d34c 100644 --- a/core/libs/prx/libc/include/Api.hpp +++ b/core/libs/prx/libc/include/Api.hpp @@ -1309,6 +1309,12 @@ void APS5_VABI clearerr_unlocked_nid_postfix(FileStream* stream); int APS5_VABI fileno_unlocked_nid_postfix(FileStream* stream); int APS5_VABI setvbuf_nid_postfix(FileStream* stream, char* buffer, int mode, std::size_t size); void APS5_VABI setbuf_nid_postfix(FileStream* stream, char* buffer); +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE4syncEv_nid_postfix(void* stream); +void* APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6setbufEPcl_nid_postfix(void* stream, char* buffer, std::int64_t count); +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE8overflowEi_nid_postfix(void* stream, int character); +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9pbackfailEi_nid_postfix(void* stream, int character); +std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9showmanycEv_nid_postfix(void* stream); +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9underflowEv_nid_postfix(void* stream); const char* APS5_VABI setlocale_nid_postfix(int, const char* locale); int APS5_VABI _new_setup_nid_postfix(const void* table); int CrtNewSetup_nid_no_patch(const void* table); diff --git a/core/libs/prx/libc/src/LibcxxStreambuf.cpp b/core/libs/prx/libc/src/LibcxxStreambuf.cpp new file mode 100644 index 000000000000..0cc638c9c57d --- /dev/null +++ b/core/libs/prx/libc/src/LibcxxStreambuf.cpp @@ -0,0 +1,31 @@ +#include "prx/libc/include/Api.hpp" + +#include + +extern "C" { + +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE4syncEv_nid_postfix(void*) { + return 0; +} + +void* APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6setbufEPcl_nid_postfix(void* stream, char*, std::int64_t) { + return stream; +} + +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE8overflowEi_nid_postfix(void*, int) { + return std::char_traits::eof(); +} + +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9pbackfailEi_nid_postfix(void*, int) { + return std::char_traits::eof(); +} + +std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9showmanycEv_nid_postfix(void*) { + return 0; +} + +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9underflowEv_nid_postfix(void*) { + return std::char_traits::eof(); +} + +} diff --git a/core/libs/tests/GuestLibcStaticImports.cpp b/core/libs/tests/GuestLibcStaticImports.cpp index 7246af6c8249..8bb4fcaf6ae5 100644 --- a/core/libs/tests/GuestLibcStaticImports.cpp +++ b/core/libs/tests/GuestLibcStaticImports.cpp @@ -169,6 +169,33 @@ void TestMtxTrylock() { _Mtx_destroy_nid_postfix(&recMutex); } +void TestLibcxxStreambufDefaults() { + constexpr auto Sync = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE4syncEv_nid_postfix; + constexpr auto SetBuffer = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6setbufEPcl_nid_postfix; + constexpr auto Overflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE8overflowEi_nid_postfix; + constexpr auto PutbackFailure = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9pbackfailEi_nid_postfix; + constexpr auto Available = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9showmanycEv_nid_postfix; + constexpr auto Underflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9underflowEv_nid_postfix; + + std::array stream{0x12, 0x34, 0x56, 0x78}; + std::array buffer{'k', 'e', 'e', 'p'}; + const auto originalStream = stream; + const auto originalBuffer = buffer; + + Require(Sync(stream.data()) == 0); + Require(Available(stream.data()) == 0); + Require(SetBuffer(stream.data(), buffer.data(), buffer.size()) == stream.data()); + Require(SetBuffer(stream.data(), nullptr, std::numeric_limits::max()) == stream.data()); + Require(Underflow(stream.data()) == -1); + for (const int character : {-1, 0, 0x41, 0xff}) { + Require(Overflow(stream.data(), character) == -1); + Require(PutbackFailure(stream.data(), character) == -1); + } + + Require(stream == originalStream); + Require(buffer == originalBuffer); +} + void TestThrdSleep() { timespec before{}; Require(clock_gettime(CLOCK_REALTIME, &before) == 0); @@ -236,5 +263,6 @@ int main() { TestLibcxxErrorCategory(); TestMtxTrylock(); TestThrdSleep(); + TestLibcxxStreambufDefaults(); return 0; } diff --git a/docs/dev/debt/changes/feat-libc-libcxx-streambuf-defaults.md b/docs/dev/debt/changes/feat-libc-libcxx-streambuf-defaults.md new file mode 100644 index 000000000000..6afc3487f3b4 --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-libcxx-streambuf-defaults.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ narrow stream-buffer defaults](../../../core/libs/prx/libc/src/LibcxxStreambuf.cpp) (libc) implements the base `sync`, `setbuf`, `overflow`, `pbackfail`, `showmanyc`, and `underflow` methods imported by the Azahar core (#5927). Their results and lack of object mutation match [LLVM libc++ 18.1.8](https://github.com/llvm/llvm-project/blob/3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff/libcxx/include/streambuf) and the [PS5 Payload SDK v0.42](https://github.com/ps5-payload-dev/sdk/releases/tag/v0.42) object. Physical firmware export provenance and full title execution are unverified. From a272dbf98a2d49e373384d593f4c6c77cd5c4c6f Mon Sep 17 00:00:00 2001 From: Mihai Date: Tue, 1 Dec 2026 21:16:45 +0200 Subject: [PATCH 02/18] feat(libc): implement libc++ base streambuf seek defaults # Conflicts: # core/libs/prx/libc/libc.hpp --- core/libs/prx/libc/CMakeLists.txt | 1 + .../prx/libc/include/LibcxxStreamPosition.hpp | 22 +++++++++++++ core/libs/prx/libc/libc.hpp | 1 + .../prx/libc/src/LibcxxStreamPosition.cpp | 15 +++++++++ .../cmake/guest_libcxx_stream_position.cmake | 12 +++++++ core/libs/tests/GuestLibcxxStreamPosition.cpp | 32 +++++++++++++++++++ .../debt/changes/feat-libc-streambuf-seek.md | 5 +++ 7 files changed, 88 insertions(+) create mode 100644 core/libs/prx/libc/include/LibcxxStreamPosition.hpp create mode 100644 core/libs/prx/libc/src/LibcxxStreamPosition.cpp create mode 100644 core/libs/prx/libc/tests/cmake/guest_libcxx_stream_position.cmake create mode 100644 core/libs/tests/GuestLibcxxStreamPosition.cpp create mode 100644 docs/dev/debt/changes/feat-libc-streambuf-seek.md diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index 41c34d87872c..e4deaff976b7 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -186,6 +186,7 @@ target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/CLocaleHelpers.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/StringExtensions.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStringSearch.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStreamPosition.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/GetSubOpt.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxToStringFloat.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStringbufSet.cpp diff --git a/core/libs/prx/libc/include/LibcxxStreamPosition.hpp b/core/libs/prx/libc/include/LibcxxStreamPosition.hpp new file mode 100644 index 000000000000..f1fa16542ab2 --- /dev/null +++ b/core/libs/prx/libc/include/LibcxxStreamPosition.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include "general/VabiMacros.hpp" +#include +#include + +struct LibcxxStreamPosition { + std::uint8_t state[128]; + std::int64_t offset; +}; + +static_assert(sizeof(LibcxxStreamPosition) == 136); +static_assert(offsetof(LibcxxStreamPosition, offset) == 128); + +extern "C" { + +LibcxxStreamPosition APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekoffExNS_8ios_base7seekdirEj_nid_postfix( + void* self, std::int64_t offset, std::int32_t direction, std::uint32_t mode); +LibcxxStreamPosition APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekposENS_4fposI11__mbstate_tEEj_nid_postfix( + void* self, LibcxxStreamPosition position, std::uint32_t mode); + +} diff --git a/core/libs/prx/libc/libc.hpp b/core/libs/prx/libc/libc.hpp index cd6864cd6c72..d3c59443f2f6 100644 --- a/core/libs/prx/libc/libc.hpp +++ b/core/libs/prx/libc/libc.hpp @@ -9,5 +9,6 @@ #include "prx/libc/include/SonyCrt.hpp" #include "prx/libc/include/LibcxxStringSearch.hpp" #include "prx/libc/include/LibcxxStringbufSet.hpp" +#include "prx/libc/include/LibcxxStreamPosition.hpp" #include "prx/libc/include/WindowsFormatting.hpp" #include "prx/libc/include/LibcxxIosInit.hpp" diff --git a/core/libs/prx/libc/src/LibcxxStreamPosition.cpp b/core/libs/prx/libc/src/LibcxxStreamPosition.cpp new file mode 100644 index 000000000000..7c864671d88f --- /dev/null +++ b/core/libs/prx/libc/src/LibcxxStreamPosition.cpp @@ -0,0 +1,15 @@ +#include "prx/libc/include/LibcxxStreamPosition.hpp" + +extern "C" { + +LibcxxStreamPosition APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekoffExNS_8ios_base7seekdirEj_nid_postfix( + void*, std::int64_t, std::int32_t, std::uint32_t) { + return {{}, -1}; +} + +LibcxxStreamPosition APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekposENS_4fposI11__mbstate_tEEj_nid_postfix( + void*, LibcxxStreamPosition, std::uint32_t) { + return {{}, -1}; +} + +} diff --git a/core/libs/prx/libc/tests/cmake/guest_libcxx_stream_position.cmake b/core/libs/prx/libc/tests/cmake/guest_libcxx_stream_position.cmake new file mode 100644 index 000000000000..f54a310c45c1 --- /dev/null +++ b/core/libs/prx/libc/tests/cmake/guest_libcxx_stream_position.cmake @@ -0,0 +1,12 @@ +if(BUILD_TESTING) + add_test_executable(guest_libcxx_stream_position_tests ${LIBS_INCLUDE_DIR}/tests/GuestLibcxxStreamPosition.cpp) + target_include_directories(guest_libcxx_stream_position_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_libcxx_stream_position_tests PRIVATE libc) + configure_windows_unwind(guest_libcxx_stream_position_tests) + add_test(NAME guest_libcxx_stream_position COMMAND guest_libcxx_stream_position_tests) + set_tests_properties(guest_libcxx_stream_position PROPERTIES TIMEOUT 15) + if(WIN32) + set_tests_properties(guest_libcxx_stream_position PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/tests/GuestLibcxxStreamPosition.cpp b/core/libs/tests/GuestLibcxxStreamPosition.cpp new file mode 100644 index 000000000000..52ed46c21064 --- /dev/null +++ b/core/libs/tests/GuestLibcxxStreamPosition.cpp @@ -0,0 +1,32 @@ +#include "prx/libc/include/LibcxxStreamPosition.hpp" +#include +#include +#include + +namespace { + +bool IsFailedPosition(const LibcxxStreamPosition& position) { + return position.offset == -1 && std::ranges::all_of(position.state, [](auto byte) { return byte == 0; }); +} + +} + +int main() { + std::array buffer{}; + buffer.fill(0x12345678); + const auto original = buffer; + LibcxxStreamPosition input{}; + std::ranges::fill(input.state, 0x7d); + input.offset = 345; + for (auto mode : {0u, 1u, 3u, 0xffffffffu}) { + for (auto direction : {0, 1, 2}) { + for (auto offset : {std::numeric_limits::min(), std::int64_t{0}, std::numeric_limits::max()}) { + if (!IsFailedPosition(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekoffExNS_8ios_base7seekdirEj_nid_postfix( + buffer.data(), offset, direction, mode))) return 1; + } + } + if (!IsFailedPosition(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekposENS_4fposI11__mbstate_tEEj_nid_postfix( + buffer.data(), input, mode))) return 1; + } + return buffer == original ? 0 : 1; +} diff --git a/docs/dev/debt/changes/feat-libc-streambuf-seek.md b/docs/dev/debt/changes/feat-libc-streambuf-seek.md new file mode 100644 index 000000000000..7c7683e1c5af --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-streambuf-seek.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ stream buffer seek defaults](../../../core/libs/prx/libc/src/LibcxxStreamPosition.cpp) (libc) - The firmware provider is unverified. RetroArch Azahar imports the two base `basic_streambuf` seek virtuals by name. Their failed position has 128 zero state bytes followed by a signed 64-bit offset of -1, as in the homebrew SDK. From 76cc6ac1e0bd5387663ea1945871e015eba24ae9 Mon Sep 17 00:00:00 2001 From: Mihai Date: Wed, 2 Dec 2026 16:39:45 +0200 Subject: [PATCH 03/18] feat(libc): implement libc++ base streambuf transfers # Conflicts: # core/libs/prx/libc/CMakeLists.txt # core/libs/prx/libc/libc.hpp --- core/libs/prx/libc/CMakeLists.txt | 1 + .../libc/include/LibcxxStreambufTransfer.hpp | 43 ++++++ core/libs/prx/libc/libc.hpp | 1 + .../prx/libc/src/LibcxxStreambufTransfer.cpp | 109 ++++++++++++++ .../guest_libcxx_streambuf_transfer.cmake | 12 ++ .../tests/GuestLibcxxStreambufTransfer.cpp | 133 ++++++++++++++++++ .../changes/feat-libc-streambuf-transfers.md | 5 + 7 files changed, 304 insertions(+) create mode 100644 core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp create mode 100644 core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp create mode 100644 core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_transfer.cmake create mode 100644 core/libs/tests/GuestLibcxxStreambufTransfer.cpp create mode 100644 docs/dev/debt/changes/feat-libc-streambuf-transfers.md diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index e4deaff976b7..d487c1030cd2 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -190,6 +190,7 @@ target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/GetSubOpt.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxToStringFloat.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStringbufSet.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStreambufTransfer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/VectorAlgorithms.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Math.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/MathGamma.cpp diff --git a/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp b/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp new file mode 100644 index 000000000000..99ff59fd4365 --- /dev/null +++ b/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include "general/VabiMacros.hpp" +#include +#include + +struct LibcxxStreambuf; + +struct LibcxxStreambufVtable { + std::uintptr_t beforeUnderflow[9]; + int (APS5_VABI* underflow)(LibcxxStreambuf*); + int (APS5_VABI* uflow)(LibcxxStreambuf*); + std::uintptr_t beforeOverflow[2]; + int (APS5_VABI* overflow)(LibcxxStreambuf*, int); +}; + +struct LibcxxStreambuf { + const LibcxxStreambufVtable* vtable; + void* locale; + char* getStart; + char* getCurrent; + char* getEnd; + char* putStart; + char* putCurrent; + char* putEnd; +}; + +static_assert(sizeof(LibcxxStreambuf) == 64); +static_assert(offsetof(LibcxxStreambuf, getCurrent) == 0x18); +static_assert(offsetof(LibcxxStreambuf, getEnd) == 0x20); +static_assert(offsetof(LibcxxStreambuf, putCurrent) == 0x30); +static_assert(offsetof(LibcxxStreambuf, putEnd) == 0x38); +static_assert(offsetof(LibcxxStreambufVtable, underflow) == 0x48); +static_assert(offsetof(LibcxxStreambufVtable, uflow) == 0x50); +static_assert(offsetof(LibcxxStreambufVtable, overflow) == 0x68); + +extern "C" { + +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(LibcxxStreambuf* self); +std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(LibcxxStreambuf* self, char* destination, std::int64_t count); +std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(LibcxxStreambuf* self, const char* source, std::int64_t count); + +} diff --git a/core/libs/prx/libc/libc.hpp b/core/libs/prx/libc/libc.hpp index d3c59443f2f6..9ad04e56b212 100644 --- a/core/libs/prx/libc/libc.hpp +++ b/core/libs/prx/libc/libc.hpp @@ -12,3 +12,4 @@ #include "prx/libc/include/LibcxxStreamPosition.hpp" #include "prx/libc/include/WindowsFormatting.hpp" #include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" diff --git a/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp b/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp new file mode 100644 index 000000000000..8039970a4fa4 --- /dev/null +++ b/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp @@ -0,0 +1,109 @@ +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestPtr.hpp" +#include +#include +#include +#include + +namespace { + +constexpr int GuestEof = -1; + +template +T ReadGuest(const T* address) { + T value{}; + if (!GuestPtr(address).CopyIn(value)) + throw std::invalid_argument("libc++ streambuf: unreadable guest data"); + return value; +} + +template +Method ReadVirtual(const LibcxxStreambuf& stream, Method LibcxxStreambufVtable::*slot) { + const auto method = ReadGuest(stream.vtable).*slot; + if (method == nullptr) + throw std::invalid_argument("libc++ streambuf: missing virtual function"); + return method; +} + +std::size_t BufferedBytes(const char* current, const char* end, std::int64_t count) { + const auto first = reinterpret_cast(current); + const auto last = reinterpret_cast(end); + return first < last ? std::min(last - first, static_cast(count)) : 0; +} + +void CopyBuffered(char* destination, const char* source, std::size_t bytes) { + if (!GuestReadable_nid_no_patch(source, bytes)) + throw std::invalid_argument("libc++ streambuf: unreadable source range"); + GuestArena::GuestArenaPrepareHostRead_nid_no_patch(source, bytes); + const GuestArena::HostWrite write(destination, bytes); + if (!write.Open() || !GuestWritable_nid_no_patch(destination, bytes)) + throw std::invalid_argument("libc++ streambuf: unwritable destination range"); + std::memmove(destination, source, bytes); +} + +void StoreCursor(char** slot, char* value) { + if (!GuestPtr(slot).CopyOut(value)) + throw std::invalid_argument("libc++ streambuf: unwritable cursor"); +} + +} + +extern "C" { + +int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(LibcxxStreambuf* self) { + const auto underflow = ReadVirtual(ReadGuest(self), &LibcxxStreambufVtable::underflow); + if (underflow(self) == GuestEof) + return GuestEof; + auto* const current = ReadGuest(&self->getCurrent); + const auto value = ReadGuest(current); + StoreCursor(&self->getCurrent, current + 1); + return static_cast(value); +} + +std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix( + LibcxxStreambuf* self, char* destination, std::int64_t count) { + std::int64_t transferred = 0; + while (transferred < count) { + const auto stream = ReadGuest(self); + const auto buffered = BufferedBytes(stream.getCurrent, stream.getEnd, count - transferred); + if (buffered != 0) { + const auto bytes = std::min(buffered, std::numeric_limits::max()); + CopyBuffered(destination + transferred, stream.getCurrent, bytes); + StoreCursor(&self->getCurrent, stream.getCurrent + bytes); + transferred += static_cast(bytes); + } else { + const auto uflow = ReadVirtual(stream, &LibcxxStreambufVtable::uflow); + const auto value = uflow(self); + if (value == GuestEof) + break; + if (!GuestPtr(destination + transferred).CopyOut(static_cast(value))) + throw std::invalid_argument("libc++ streambuf: unwritable destination byte"); + ++transferred; + } + } + return transferred; +} + +std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix( + LibcxxStreambuf* self, const char* source, std::int64_t count) { + std::int64_t transferred = 0; + while (transferred < count) { + const auto stream = ReadGuest(self); + const auto bytes = BufferedBytes(stream.putCurrent, stream.putEnd, count - transferred); + if (bytes != 0) { + CopyBuffered(stream.putCurrent, source + transferred, bytes); + StoreCursor(&self->putCurrent, stream.putCurrent + bytes); + transferred += static_cast(bytes); + } else { + const auto value = static_cast(ReadGuest(source + transferred)); + const auto overflow = ReadVirtual(stream, &LibcxxStreambufVtable::overflow); + if (overflow(self, value) == GuestEof) + break; + ++transferred; + } + } + return transferred; +} + +} diff --git a/core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_transfer.cmake b/core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_transfer.cmake new file mode 100644 index 000000000000..ae375f23de96 --- /dev/null +++ b/core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_transfer.cmake @@ -0,0 +1,12 @@ +if(BUILD_TESTING) + add_test_executable(guest_libcxx_streambuf_transfer_tests ${LIBS_INCLUDE_DIR}/tests/GuestLibcxxStreambufTransfer.cpp) + target_include_directories(guest_libcxx_streambuf_transfer_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_libcxx_streambuf_transfer_tests PRIVATE libc) + configure_windows_unwind(guest_libcxx_streambuf_transfer_tests) + add_test(NAME guest_libcxx_streambuf_transfer COMMAND guest_libcxx_streambuf_transfer_tests) + set_tests_properties(guest_libcxx_streambuf_transfer PROPERTIES TIMEOUT 15) + if(WIN32) + set_tests_properties(guest_libcxx_streambuf_transfer PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/tests/GuestLibcxxStreambufTransfer.cpp b/core/libs/tests/GuestLibcxxStreambufTransfer.cpp new file mode 100644 index 000000000000..9afa452c3f1f --- /dev/null +++ b/core/libs/tests/GuestLibcxxStreambufTransfer.cpp @@ -0,0 +1,133 @@ +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" +#include +#include + +namespace { + +struct Fixture { + LibcxxStreambuf stream{}; + std::array refillInput{static_cast(0xff), 'r'}; + std::array refillOutput{}; + std::array overflowValues{}; + std::size_t underflowCalls{}; + std::size_t uflowCalls{}; + std::size_t overflowCalls{}; +}; + +void Require(bool condition) { + if (!condition) + std::abort(); +} + +int APS5_VABI Underflow(LibcxxStreambuf* stream) { + auto& fixture = *reinterpret_cast(stream); + if (++fixture.underflowCalls != 1) + return -1; + stream->getStart = stream->getCurrent = fixture.refillInput.data(); + stream->getEnd = stream->getStart + fixture.refillInput.size(); + return 'x'; +} + +int APS5_VABI Uflow(LibcxxStreambuf* stream) { + auto& fixture = *reinterpret_cast(stream); + if (++fixture.uflowCalls != 1) + return -1; + stream->getStart = fixture.refillInput.data(); + stream->getCurrent = stream->getStart + 1; + stream->getEnd = stream->getStart + fixture.refillInput.size(); + return static_cast(fixture.refillInput.front()); +} + +int APS5_VABI Overflow(LibcxxStreambuf* stream, int value) { + auto& fixture = *reinterpret_cast(stream); + Require(fixture.overflowCalls < fixture.overflowValues.size()); + fixture.overflowValues[fixture.overflowCalls++] = value; + if (fixture.overflowCalls != 1) + return -1; + stream->putStart = stream->putCurrent = fixture.refillOutput.data(); + stream->putEnd = stream->putStart + fixture.refillOutput.size(); + return value; +} + +const LibcxxStreambufVtable Methods{ + .beforeUnderflow = {}, + .underflow = Underflow, + .uflow = Uflow, + .beforeOverflow = {}, + .overflow = Overflow, +}; + +void TestUflow() { + Fixture fixture{}; + fixture.stream.vtable = &Methods; + auto& stream = fixture.stream; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(&stream) == 0xff); + Require(stream.getCurrent == fixture.refillInput.data() + 1); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(&stream) == -1); + Require(stream.getCurrent == fixture.refillInput.data() + 1); + Require(fixture.underflowCalls == 2); +} + +void TestRead() { + Fixture fixture{}; + fixture.stream.vtable = &Methods; + std::array initial{'q', static_cast(0x80)}; + auto& stream = fixture.stream; + stream.getStart = stream.getCurrent = initial.data(); + stream.getEnd = stream.getStart + initial.size(); + std::array out{'.', '.', '.', '.', '.', '.'}; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(&stream, out.data(), 1) == 1); + Require(out[0] == 'q' && out[1] == '.' && fixture.uflowCalls == 0); + Require(stream.getCurrent == initial.data() + 1); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(&stream, out.data() + 1, out.size() - 1) == 3); + Require(out == std::array{'q', static_cast(0x80), static_cast(0xff), 'r', '.', '.'}); + Require(fixture.uflowCalls == 2 && fixture.underflowCalls == 0); + Require(stream.getCurrent == fixture.refillInput.data() + fixture.refillInput.size()); +} + +void TestWrite() { + Fixture fixture{}; + fixture.stream.vtable = &Methods; + std::array initial{}; + auto& stream = fixture.stream; + stream.putStart = stream.putCurrent = initial.data(); + stream.putEnd = stream.putStart + initial.size(); + const std::array input{'w', static_cast(0xff), 'a', 'b', static_cast(0xfe), 'z'}; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(&stream, input.data(), input.size()) == 4); + Require(initial[0] == 'w'); + Require(fixture.refillOutput == std::array{'a', 'b'}); + Require(fixture.overflowCalls == 2 && fixture.overflowValues == std::array{0xff, 0xfe}); + Require(stream.putCurrent == fixture.refillOutput.data() + fixture.refillOutput.size()); +} + +void TestOverlappingBuffers() { + Fixture fixture{}; + fixture.stream.vtable = &Methods; + auto& stream = fixture.stream; + std::array bytes{'a', 'b', 'c', 'd'}; + stream.getStart = stream.getCurrent = bytes.data(); + stream.getEnd = bytes.data() + bytes.size(); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(&stream, bytes.data() + 1, 2) == 2); + Require(bytes == std::array{'a', 'a', 'b', 'd'}); + Require(stream.getCurrent == bytes.data() + 2); + + bytes = {'a', 'b', 'c', 'd'}; + stream.putStart = stream.putCurrent = bytes.data() + 1; + stream.putEnd = bytes.data() + bytes.size(); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(&stream, bytes.data(), 2) == 2); + Require(bytes == std::array{'a', 'a', 'b', 'd'}); + Require(stream.putCurrent == bytes.data() + 3); +} + +} + +int main() { + TestUflow(); + TestRead(); + TestWrite(); + TestOverlappingBuffers(); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(nullptr, nullptr, 0) == 0); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(nullptr, nullptr, -1) == 0); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(nullptr, nullptr, 0) == 0); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(nullptr, nullptr, -1) == 0); +} diff --git a/docs/dev/debt/changes/feat-libc-streambuf-transfers.md b/docs/dev/debt/changes/feat-libc-streambuf-transfers.md new file mode 100644 index 000000000000..90e74540a0fe --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-streambuf-transfers.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ stream buffer transfers](../../../core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp) (libc) - The firmware provider is unverified. RetroArch Azahar imports the narrow base `uflow`, `xsgetn`, and `xsputn` virtuals by name. The object layout, virtual slots, and EOF behavior follow the PS5 Payload SDK v0.42. Full Azahar execution remains unverified. From be8fce5ffefcf199968f751528adee6bbb5bb392 Mon Sep 17 00:00:00 2001 From: Mihai Date: Wed, 2 Dec 2026 17:12:50 +0200 Subject: [PATCH 04/18] fix(libc): preserve streambuf characters and partial transfers --- .../prx/libc/src/LibcxxStreambufTransfer.cpp | 53 +++++++++------ core/libs/tests/GuardedBuffer.hpp | 8 +++ .../tests/GuestLibcxxStreambufTransfer.cpp | 66 +++++++++++++++++++ .../changes/feat-libc-streambuf-transfers.md | 2 +- 4 files changed, 107 insertions(+), 22 deletions(-) diff --git a/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp b/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp index 8039970a4fa4..1dc92dae3b08 100644 --- a/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp +++ b/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp @@ -32,19 +32,19 @@ std::size_t BufferedBytes(const char* current, const char* end, std::int64_t cou return first < last ? std::min(last - first, static_cast(count)) : 0; } -void CopyBuffered(char* destination, const char* source, std::size_t bytes) { +bool CopyBuffered(char* destination, const char* source, std::size_t bytes, char** cursor, char* next) { if (!GuestReadable_nid_no_patch(source, bytes)) - throw std::invalid_argument("libc++ streambuf: unreadable source range"); + return false; GuestArena::GuestArenaPrepareHostRead_nid_no_patch(source, bytes); const GuestArena::HostWrite write(destination, bytes); if (!write.Open() || !GuestWritable_nid_no_patch(destination, bytes)) - throw std::invalid_argument("libc++ streambuf: unwritable destination range"); + return false; + const GuestArena::HostWrite advance(cursor, sizeof(next)); + if (!advance.Open() || !GuestWritable_nid_no_patch(cursor, sizeof(next))) + return false; std::memmove(destination, source, bytes); -} - -void StoreCursor(char** slot, char* value) { - if (!GuestPtr(slot).CopyOut(value)) - throw std::invalid_argument("libc++ streambuf: unwritable cursor"); + std::memcpy(cursor, &next, sizeof(next)); + return true; } } @@ -53,12 +53,16 @@ extern "C" { int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(LibcxxStreambuf* self) { const auto underflow = ReadVirtual(ReadGuest(self), &LibcxxStreambufVtable::underflow); - if (underflow(self) == GuestEof) - return GuestEof; - auto* const current = ReadGuest(&self->getCurrent); - const auto value = ReadGuest(current); - StoreCursor(&self->getCurrent, current + 1); - return static_cast(value); + const auto result = underflow(self); + if (result == GuestEof) + return result; + const auto stream = ReadGuest(self); + unsigned char value{}; + if (BufferedBytes(stream.getCurrent, stream.getEnd, 1) == 0 || + !GuestPtr(stream.getCurrent).CopyIn(value) || + !GuestPtr(&self->getCurrent).CopyOut(stream.getCurrent + 1)) + return result; + return value; } std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix( @@ -69,16 +73,20 @@ std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnE const auto buffered = BufferedBytes(stream.getCurrent, stream.getEnd, count - transferred); if (buffered != 0) { const auto bytes = std::min(buffered, std::numeric_limits::max()); - CopyBuffered(destination + transferred, stream.getCurrent, bytes); - StoreCursor(&self->getCurrent, stream.getCurrent + bytes); + if (!CopyBuffered(destination + transferred, stream.getCurrent, bytes, + &self->getCurrent, stream.getCurrent + bytes)) + break; transferred += static_cast(bytes); } else { + auto* const output = reinterpret_cast(destination + transferred); + const GuestArena::HostWrite write(output, 1); + if (!write.Open() || !GuestWritable_nid_no_patch(output, 1)) + break; const auto uflow = ReadVirtual(stream, &LibcxxStreambufVtable::uflow); const auto value = uflow(self); if (value == GuestEof) break; - if (!GuestPtr(destination + transferred).CopyOut(static_cast(value))) - throw std::invalid_argument("libc++ streambuf: unwritable destination byte"); + *output = static_cast(value); ++transferred; } } @@ -92,11 +100,14 @@ std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnE const auto stream = ReadGuest(self); const auto bytes = BufferedBytes(stream.putCurrent, stream.putEnd, count - transferred); if (bytes != 0) { - CopyBuffered(stream.putCurrent, source + transferred, bytes); - StoreCursor(&self->putCurrent, stream.putCurrent + bytes); + if (!CopyBuffered(stream.putCurrent, source + transferred, bytes, + &self->putCurrent, stream.putCurrent + bytes)) + break; transferred += static_cast(bytes); } else { - const auto value = static_cast(ReadGuest(source + transferred)); + unsigned char value{}; + if (!GuestPtr(source + transferred).CopyIn(value)) + break; const auto overflow = ReadVirtual(stream, &LibcxxStreambufVtable::overflow); if (overflow(self, value) == GuestEof) break; diff --git a/core/libs/tests/GuardedBuffer.hpp b/core/libs/tests/GuardedBuffer.hpp index b7a71d5ccd87..2216e45371ca 100644 --- a/core/libs/tests/GuardedBuffer.hpp +++ b/core/libs/tests/GuardedBuffer.hpp @@ -53,6 +53,14 @@ class GuardedBuffer { Require(VirtualFree(allocation, 0, MEM_RELEASE) != 0); #else Require(munmap(allocation, page * 3) == 0); +#endif + } + void ReadOnly() { +#ifdef _WIN32 + DWORD previous; + Require(VirtualProtect(allocation + page, page, PAGE_READONLY, &previous) != 0); +#else + Require(mprotect(allocation + page, page, PROT_READ) == 0); #endif } GuardedBuffer(const GuardedBuffer&) = delete; diff --git a/core/libs/tests/GuestLibcxxStreambufTransfer.cpp b/core/libs/tests/GuestLibcxxStreambufTransfer.cpp index 9afa452c3f1f..22b35d166a8c 100644 --- a/core/libs/tests/GuestLibcxxStreambufTransfer.cpp +++ b/core/libs/tests/GuestLibcxxStreambufTransfer.cpp @@ -1,6 +1,8 @@ +#include "GuardedBuffer.hpp" #include "prx/libc/include/LibcxxStreambufTransfer.hpp" #include #include +#include namespace { @@ -119,6 +121,67 @@ void TestOverlappingBuffers() { Require(stream.putCurrent == bytes.data() + 3); } +int APS5_VABI UnderflowWithoutBuffer(LibcxxStreambuf*) { + return 0xfe; +} + +void TestUflowWithoutReadableBuffer() { + auto methods = Methods; + methods.underflow = UnderflowWithoutBuffer; + LibcxxStreambuf stream{}; + stream.vtable = &methods; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(&stream) == 0xfe); + Require(stream.getCurrent == nullptr); + + char sentinel = 'z'; + stream.getStart = stream.getCurrent = stream.getEnd = &sentinel; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(&stream) == 0xfe); + Require(stream.getCurrent == &sentinel); + + GuardedBuffer buffer; + auto* const unreadable = buffer.At(1) + 1; + stream.getCurrent = unreadable; + stream.getEnd = unreadable + 1; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(&stream) == 0xfe); + Require(stream.getCurrent == unreadable); +} + +void TestPartialTransferAtGuardPage() { + GuardedBuffer buffer; + auto* const byte = buffer.At(1); + Fixture fixture{}; + auto& stream = fixture.stream; + stream.vtable = &Methods; + char input = 'r'; + char output = '.'; + stream.getStart = stream.getCurrent = &input; + stream.getEnd = &input + 1; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(&stream, byte, 2) == 1); + Require(*byte == input && stream.getCurrent == stream.getEnd && fixture.uflowCalls == 0); + + stream.putStart = stream.putCurrent = &output; + stream.putEnd = &output + 1; + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(&stream, byte, 2) == 1); + Require(output == input && stream.putCurrent == stream.putEnd && fixture.overflowCalls == 0); +} + +void TestBufferedCopyRequiresWritableCursor() { + GuardedBuffer buffer; + auto* const stream = new (buffer.At(1)) LibcxxStreambuf{}; + char input = 'r'; + char output = '.'; + char destination = '.'; + stream->getStart = stream->getCurrent = &input; + stream->getEnd = &input + 1; + stream->putStart = stream->putCurrent = &output; + stream->putEnd = &output + 1; + buffer.ReadOnly(); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(stream, &destination, 1) == 0); + Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(stream, &input, 1) == 0); + Require(destination == '.' && output == '.'); + Require(stream->getCurrent == &input && stream->putCurrent == &output); +} + } int main() { @@ -126,6 +189,9 @@ int main() { TestRead(); TestWrite(); TestOverlappingBuffers(); + TestUflowWithoutReadableBuffer(); + TestPartialTransferAtGuardPage(); + TestBufferedCopyRequiresWritableCursor(); Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(nullptr, nullptr, 0) == 0); Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(nullptr, nullptr, -1) == 0); Require(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(nullptr, nullptr, 0) == 0); diff --git a/docs/dev/debt/changes/feat-libc-streambuf-transfers.md b/docs/dev/debt/changes/feat-libc-streambuf-transfers.md index 90e74540a0fe..dc1978f28b59 100644 --- a/docs/dev/debt/changes/feat-libc-streambuf-transfers.md +++ b/docs/dev/debt/changes/feat-libc-streambuf-transfers.md @@ -2,4 +2,4 @@ ## add Functional -- [libc++ stream buffer transfers](../../../core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp) (libc) - The firmware provider is unverified. RetroArch Azahar imports the narrow base `uflow`, `xsgetn`, and `xsputn` virtuals by name. The object layout, virtual slots, and EOF behavior follow the PS5 Payload SDK v0.42. Full Azahar execution remains unverified. +- [libc++ stream buffer transfers](../../../core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp) (libc) - The firmware provider is unverified. RetroArch Azahar imports the narrow base `uflow`, `xsgetn`, and `xsputn` virtuals by name. The object layout, virtual slots, and EOF behavior follow the PS5 Payload SDK v0.42. If a non-EOF underflow leaves no readable get byte, the returned character is preserved. Invalid transfer ranges stop the transfer at the completed byte count. Full Azahar execution remains unverified. From 13634ac6fbf72ee41a2c166cb11dd3863d77bd47 Mon Sep 17 00:00:00 2001 From: Mihai Date: Thu, 3 Dec 2026 15:37:55 +0200 Subject: [PATCH 05/18] fix(libc): prepare buffered stream reads before validation --- core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp b/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp index 1dc92dae3b08..2824642aa4c5 100644 --- a/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp +++ b/core/libs/prx/libc/src/LibcxxStreambufTransfer.cpp @@ -33,9 +33,9 @@ std::size_t BufferedBytes(const char* current, const char* end, std::int64_t cou } bool CopyBuffered(char* destination, const char* source, std::size_t bytes, char** cursor, char* next) { + GuestArena::GuestArenaPrepareHostRead_nid_no_patch(source, bytes); if (!GuestReadable_nid_no_patch(source, bytes)) return false; - GuestArena::GuestArenaPrepareHostRead_nid_no_patch(source, bytes); const GuestArena::HostWrite write(destination, bytes); if (!write.Open() || !GuestWritable_nid_no_patch(destination, bytes)) return false; From 4cf582c1675f30500eba20c680a8255199aee52c Mon Sep 17 00:00:00 2001 From: Mihai Date: Wed, 2 Dec 2026 17:20:07 +0200 Subject: [PATCH 06/18] feat(libc): expose libc++ base streambuf locale hook and RTTI --- core/libs/prx/libc/include/Api.hpp | 4 ++++ core/libs/prx/libc/src/LibcxxLocaleFacet.cpp | 2 ++ .../libc/src/exception/StandardExceptions.cpp | 2 -- core/libs/prx/libc/src/exception/TypeInfo.cpp | 5 +++++ core/libs/tests/GuestLibcStaticImports.cpp | 22 +++++++++++++++++++ .../changes/feat-libc-streambuf-metadata.md | 5 +++++ 6 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 docs/dev/debt/changes/feat-libc-streambuf-metadata.md diff --git a/core/libs/prx/libc/include/Api.hpp b/core/libs/prx/libc/include/Api.hpp index 14e09c30d34c..f47720f45641 100644 --- a/core/libs/prx/libc/include/Api.hpp +++ b/core/libs/prx/libc/include/Api.hpp @@ -116,6 +116,8 @@ struct SharedWeakCountRtti { struct ExceptionObject { const void* vtable; const char* message; }; +struct ClassTypeRecord { const void* vtable; const char* name; }; + struct TypeRecord { const void* const* vtable; const char* name; const TypeRecord* base; }; struct BaseTypeRecord { const TypeRecord* type; std::int64_t offsetFlags; }; @@ -2102,6 +2104,8 @@ extern const LibcException::MultipleTypeRecord<2> _ZTINSt3__17codecvtIcc11__mbst void APS5_VABI _ZNSt3__16locale5facetD2Ev_nid_postfix(GuestLocale::LibcxxFacet* self); void APS5_VABI _ZNSt3__16locale5facet16__on_zero_sharedEv_nid_postfix(GuestLocale::LibcxxFacet* self); extern const LibcException::TypeRecord _ZTINSt3__16locale5facetE_nid_postfix; +void APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5imbueERKNS_6localeE_nid_postfix(void* self, const void* locale); +extern const LibcException::ClassTypeRecord _ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix; std::int64_t APS5_VABI _ZNSt3__16locale2id5__getEv_nid_postfix(GuestLocale::LibcxxLocaleId* self); extern GuestLocale::LibcxxLocaleId _ZNSt3__15ctypeIcE2idE_nid_postfix; extern GuestLocale::LibcxxLocaleId _ZNSt3__17codecvtIcc11__mbstate_tE2idE_nid_postfix; diff --git a/core/libs/prx/libc/src/LibcxxLocaleFacet.cpp b/core/libs/prx/libc/src/LibcxxLocaleFacet.cpp index d8ce9fd25ed2..a5711fa9bdaf 100644 --- a/core/libs/prx/libc/src/LibcxxLocaleFacet.cpp +++ b/core/libs/prx/libc/src/LibcxxLocaleFacet.cpp @@ -37,6 +37,8 @@ const LibcException::TypeRecord SharedCountType { extern "C" { +void APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5imbueERKNS_6localeE_nid_postfix(void*, const void*) {} + void APS5_VABI _ZNSt3__16locale5facetD2Ev_nid_postfix(GuestLocale::LibcxxFacet* self) { if (self == nullptr) APS5_INVALID_ARG_EX; } diff --git a/core/libs/prx/libc/src/exception/StandardExceptions.cpp b/core/libs/prx/libc/src/exception/StandardExceptions.cpp index eebed27cdb0a..840b964ee5dd 100644 --- a/core/libs/prx/libc/src/exception/StandardExceptions.cpp +++ b/core/libs/prx/libc/src/exception/StandardExceptions.cpp @@ -12,8 +12,6 @@ #include namespace LibcException { -struct ClassTypeRecord { const void* const* vtable; const char* name; }; - struct FutureErrorVtable { std::ptrdiff_t offset; const TypeRecord* type; diff --git a/core/libs/prx/libc/src/exception/TypeInfo.cpp b/core/libs/prx/libc/src/exception/TypeInfo.cpp index 856c5baf7c22..ebdce08656ef 100644 --- a/core/libs/prx/libc/src/exception/TypeInfo.cpp +++ b/core/libs/prx/libc/src/exception/TypeInfo.cpp @@ -174,12 +174,17 @@ constinit const ClassTypeRecord SharedCountType { }; } +static_assert(sizeof(LibcException::ClassTypeRecord) == 2 * sizeof(void*)); + extern "C" { constinit const LibcException::SharedWeakCountRtti _ZTINSt3__119__shared_weak_countE_nid_postfix { &_ZTVN10__cxxabiv121__vmi_class_type_infoE_nid_postfix.destroy, "NSt3__119__shared_weak_countE", 0, 1, &SharedCountType, 0, }; +constinit const LibcException::ClassTypeRecord _ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix { + &_ZTVN10__cxxabiv117__class_type_infoE_nid_postfix.destroy, "NSt3__115basic_streambufIcNS_11char_traitsIcEEEE", +}; FundamentalTypeRecord _ZTIv_nid_postfix {reinterpret_cast(&_ZTVN10__cxxabiv123__fundamental_type_infoE_nid_postfix.destroy), "v"}; FundamentalTypeRecord _ZTIw_nid_postfix {reinterpret_cast(&_ZTVN10__cxxabiv123__fundamental_type_infoE_nid_postfix.destroy), "w"}; FundamentalTypeRecord _ZTIb_nid_postfix {reinterpret_cast(&_ZTVN10__cxxabiv123__fundamental_type_infoE_nid_postfix.destroy), "b"}; diff --git a/core/libs/tests/GuestLibcStaticImports.cpp b/core/libs/tests/GuestLibcStaticImports.cpp index 8bb4fcaf6ae5..37e79821b2ce 100644 --- a/core/libs/tests/GuestLibcStaticImports.cpp +++ b/core/libs/tests/GuestLibcStaticImports.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -257,7 +258,28 @@ static void TestLibcxxRegexDot() { } } +void TestLibcxxStreambufMetadata() { + std::array buffer{}; + buffer.fill(0x1020304050607080); + const auto original = buffer; + std::uint64_t locale = 0x1122334455667788; + _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5imbueERKNS_6localeE_nid_postfix(buffer.data(), &locale); + Require(buffer == original && locale == 0x1122334455667788); + + const auto& type = _ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix; + Require(std::strcmp(type.name, "NSt3__115basic_streambufIcNS_11char_traitsIcEEEE") == 0); + const auto addressPoint = reinterpret_cast(type.vtable); + Require(addressPoint >= sizeof(void*)); + const void* metatype = nullptr; + std::memcpy(&metatype, reinterpret_cast(addressPoint - sizeof(metatype)), sizeof(metatype)); + Require(metatype != nullptr); + LibcException::ClassTypeRecord metatypeRecord{}; + std::memcpy(&metatypeRecord, metatype, sizeof(metatypeRecord)); + Require(std::strcmp(metatypeRecord.name, "N10__cxxabiv117__class_type_infoE") == 0); +} + int main() { + TestLibcxxStreambufMetadata(); TestLibcxxRegexDot(); TestNearbyintf(); TestLibcxxErrorCategory(); diff --git a/docs/dev/debt/changes/feat-libc-streambuf-metadata.md b/docs/dev/debt/changes/feat-libc-streambuf-metadata.md new file mode 100644 index 000000000000..c7b475a17c6f --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-streambuf-metadata.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ stream buffer locale hook and RTTI](../../../core/libs/prx/libc/src/LibcxxLocaleFacet.cpp) (libc) - RetroArch Azahar imports the narrow base `basic_streambuf` locale hook and class type-info record by name. PS5 Payload SDK v0.42 leaves the base `imbue` hook empty and uses a two-pointer Itanium class RTTI record. The firmware provider and full title execution are unverified. From cb78535da8590de3245aea539da7a414f3f9d038 Mon Sep 17 00:00:00 2001 From: cmsierrave-coder <317402244+cmsierrave-coder@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:49:44 -0500 Subject: [PATCH 07/18] feat(libc): implement the libc++ streambuf base destructor --- core/libs/prx/libc/CMakeLists.txt | 1 + .../libc/include/LibcxxStreambufTransfer.hpp | 26 ++++-- .../prx/libc/src/LibcxxStreambufLifecycle.cpp | 48 +++++++++++ .../guest_libcxx_streambuf_lifecycle.cmake | 12 +++ .../tests/GuestLibcxxStreambufLifecycle.cpp | 81 +++++++++++++++++++ .../tests/GuestLibcxxStreambufTransfer.cpp | 22 ++--- .../feat-libc-streambuf-destruction.md | 5 ++ 7 files changed, 180 insertions(+), 15 deletions(-) create mode 100644 core/libs/prx/libc/src/LibcxxStreambufLifecycle.cpp create mode 100644 core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_lifecycle.cmake create mode 100644 core/libs/tests/GuestLibcxxStreambufLifecycle.cpp create mode 100644 docs/dev/debt/changes/feat-libc-streambuf-destruction.md diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index d487c1030cd2..52ad1c82a4fc 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -191,6 +191,7 @@ target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxToStringFloat.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStringbufSet.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStreambufTransfer.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxStreambufLifecycle.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/VectorAlgorithms.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Math.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/MathGamma.cpp diff --git a/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp b/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp index 99ff59fd4365..6c31f317d644 100644 --- a/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp +++ b/core/libs/prx/libc/include/LibcxxStreambufTransfer.hpp @@ -1,22 +1,33 @@ #pragma once #include "general/VabiMacros.hpp" +#include "prx/libc/include/GuestLocale.hpp" +#include "prx/libc/include/LibcxxStreamPosition.hpp" #include #include struct LibcxxStreambuf; struct LibcxxStreambufVtable { - std::uintptr_t beforeUnderflow[9]; - int (APS5_VABI* underflow)(LibcxxStreambuf*); + void (APS5_VABI* destroy)(LibcxxStreambuf*); + void (APS5_VABI* deleteObject)(LibcxxStreambuf*); + void (APS5_VABI* imbue)(void*, const void*); + void* (APS5_VABI* setbuf)(void*, char*, std::int64_t); + LibcxxStreamPosition (APS5_VABI* seekoff)(void*, std::int64_t, std::int32_t, std::uint32_t); + LibcxxStreamPosition (APS5_VABI* seekpos)(void*, LibcxxStreamPosition, std::uint32_t); + int (APS5_VABI* sync)(void*); + std::int64_t (APS5_VABI* showmanyc)(void*); + std::int64_t (APS5_VABI* xsgetn)(LibcxxStreambuf*, char*, std::int64_t); + int (APS5_VABI* underflow)(void*); int (APS5_VABI* uflow)(LibcxxStreambuf*); - std::uintptr_t beforeOverflow[2]; - int (APS5_VABI* overflow)(LibcxxStreambuf*, int); + int (APS5_VABI* pbackfail)(void*, int); + std::int64_t (APS5_VABI* xsputn)(LibcxxStreambuf*, const char*, std::int64_t); + int (APS5_VABI* overflow)(void*, int); }; struct LibcxxStreambuf { const LibcxxStreambufVtable* vtable; - void* locale; + GuestLocale::LibcxxLocale locale; char* getStart; char* getCurrent; char* getEnd; @@ -26,8 +37,12 @@ struct LibcxxStreambuf { }; static_assert(sizeof(LibcxxStreambuf) == 64); +static_assert(offsetof(LibcxxStreambuf, vtable) == 0x00); +static_assert(offsetof(LibcxxStreambuf, locale) == 0x08); +static_assert(offsetof(LibcxxStreambuf, getStart) == 0x10); static_assert(offsetof(LibcxxStreambuf, getCurrent) == 0x18); static_assert(offsetof(LibcxxStreambuf, getEnd) == 0x20); +static_assert(offsetof(LibcxxStreambuf, putStart) == 0x28); static_assert(offsetof(LibcxxStreambuf, putCurrent) == 0x30); static_assert(offsetof(LibcxxStreambuf, putEnd) == 0x38); static_assert(offsetof(LibcxxStreambufVtable, underflow) == 0x48); @@ -36,6 +51,7 @@ static_assert(offsetof(LibcxxStreambufVtable, overflow) == 0x68); extern "C" { +void APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix(LibcxxStreambuf* self); int APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix(LibcxxStreambuf* self); std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix(LibcxxStreambuf* self, char* destination, std::int64_t count); std::int64_t APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix(LibcxxStreambuf* self, const char* source, std::int64_t count); diff --git a/core/libs/prx/libc/src/LibcxxStreambufLifecycle.cpp b/core/libs/prx/libc/src/LibcxxStreambufLifecycle.cpp new file mode 100644 index 000000000000..6a7613b1ad27 --- /dev/null +++ b/core/libs/prx/libc/src/LibcxxStreambufLifecycle.cpp @@ -0,0 +1,48 @@ +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/General.hpp" +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" + +namespace { + +struct StreambufVtable { + std::ptrdiff_t offsetToTop; + const LibcException::ClassTypeRecord* type; + LibcxxStreambufVtable methods; +}; + +static_assert(offsetof(StreambufVtable, methods) == 0x10); +static_assert(sizeof(StreambufVtable) == 0x80); + +void APS5_VABI DeleteStreambuf(LibcxxStreambuf* self) { + _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix(self); + _ZdlPv_nid_postfix(self); +} + +constinit const StreambufVtable BaseVtable{ + 0, + &_ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix, + { + .destroy = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix, + .deleteObject = DeleteStreambuf, + .imbue = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5imbueERKNS_6localeE_nid_postfix, + .setbuf = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6setbufEPcl_nid_postfix, + .seekoff = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekoffExNS_8ios_base7seekdirEj_nid_postfix, + .seekpos = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekposENS_4fposI11__mbstate_tEEj_nid_postfix, + .sync = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE4syncEv_nid_postfix, + .showmanyc = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9showmanycEv_nid_postfix, + .xsgetn = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix, + .underflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9underflowEv_nid_postfix, + .uflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix, + .pbackfail = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9pbackfailEi_nid_postfix, + .xsputn = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl_nid_postfix, + .overflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE8overflowEi_nid_postfix, + }, +}; + +} + +extern "C" void APS5_VABI _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix(LibcxxStreambuf* self) { + if (self == nullptr) APS5_INVALID_ARG_EX; + self->vtable = &BaseVtable.methods; + _ZNSt3__16localeD1Ev_nid_postfix(&self->locale); +} diff --git a/core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_lifecycle.cmake b/core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_lifecycle.cmake new file mode 100644 index 000000000000..32d09031bbe3 --- /dev/null +++ b/core/libs/prx/libc/tests/cmake/guest_libcxx_streambuf_lifecycle.cmake @@ -0,0 +1,12 @@ +if(BUILD_TESTING) + add_test_executable(guest_libcxx_streambuf_lifecycle_tests ${LIBS_INCLUDE_DIR}/tests/GuestLibcxxStreambufLifecycle.cpp) + target_include_directories(guest_libcxx_streambuf_lifecycle_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_libcxx_streambuf_lifecycle_tests PRIVATE libc) + configure_windows_unwind(guest_libcxx_streambuf_lifecycle_tests) + add_test(NAME guest_libcxx_streambuf_lifecycle COMMAND guest_libcxx_streambuf_lifecycle_tests) + set_tests_properties(guest_libcxx_streambuf_lifecycle PROPERTIES TIMEOUT 15) + if(WIN32) + set_tests_properties(guest_libcxx_streambuf_lifecycle PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp b/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp new file mode 100644 index 000000000000..93b91856cddc --- /dev/null +++ b/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp @@ -0,0 +1,81 @@ +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" +#include +#include +#include +#include + +namespace { + +void Require(bool condition, std::source_location location = std::source_location::current()) { + if (!condition) { + std::fprintf(stderr, "Streambuf lifecycle check failed at line %u\n", location.line()); + std::abort(); + } +} + +struct Fixture { + std::uint64_t before = 0x0123456789abcdef; + LibcxxStreambuf stream{}; + std::uint64_t after = 0xfedcba9876543210; +}; + +struct TestFacet { + GuestLocale::LibcxxFacet base; + const LibcxxStreambuf* stream; + const LibcxxStreambufVtable* observedVtable = nullptr; + unsigned releases = 0; +}; + +void APS5_VABI OnZeroShared(GuestLocale::LibcxxFacet* base) { + auto& facet = *reinterpret_cast(base); + ++facet.releases; + facet.observedVtable = facet.stream->vtable; +} + +void TestDestruction() { + Fixture fixture; + auto& stream = fixture.stream; + const LibcxxStreambufVtable derivedVtable{}; + stream.vtable = &derivedVtable; + char buffer[] = "abcdef"; + stream.getStart = buffer; + stream.getCurrent = buffer + 1; + stream.getEnd = buffer + 2; + stream.putStart = buffer + 3; + stream.putCurrent = buffer + 4; + stream.putEnd = buffer + 5; + + const GuestLocale::LibcxxFacetVtable methods{nullptr, nullptr, OnZeroShared}; + TestFacet facet{{&methods, -1}, &stream}; + GuestLocale::LibcxxLocaleId id{}; + _ZNSt3__16locale14__install_ctorERKS0_PNS0_5facetEl_nid_postfix( + &stream.locale, _ZNSt3__16locale7classicEv_nid_postfix(), &facet.base, + _ZNSt3__16locale2id5__getEv_nid_postfix(&id)); + Require(facet.base.sharedOwners == 0 && facet.releases == 0); + + _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix(&stream); + + Require(facet.base.sharedOwners == -1 && facet.releases == 1); + Require(stream.vtable && stream.vtable != &derivedVtable); + Require(facet.observedVtable == stream.vtable); + Require(stream.vtable->destroy == _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix); + Require(stream.vtable->deleteObject != nullptr); + struct { + std::ptrdiff_t offsetToTop; + const LibcException::ClassTypeRecord* type; + } metadata{}; + const auto addressPoint = reinterpret_cast(stream.vtable); + std::memcpy(&metadata, reinterpret_cast(addressPoint - sizeof(metadata)), sizeof(metadata)); + Require(metadata.offsetToTop == 0); + Require(metadata.type == &_ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix); + Require(stream.getStart == buffer && stream.getCurrent == buffer + 1 && stream.getEnd == buffer + 2); + Require(stream.putStart == buffer + 3 && stream.putCurrent == buffer + 4 && stream.putEnd == buffer + 5); + Require(fixture.before == 0x0123456789abcdef && fixture.after == 0xfedcba9876543210); +} + +} + +int main() { + TestDestruction(); +} diff --git a/core/libs/tests/GuestLibcxxStreambufTransfer.cpp b/core/libs/tests/GuestLibcxxStreambufTransfer.cpp index 22b35d166a8c..a87cb455e285 100644 --- a/core/libs/tests/GuestLibcxxStreambufTransfer.cpp +++ b/core/libs/tests/GuestLibcxxStreambufTransfer.cpp @@ -21,7 +21,8 @@ void Require(bool condition) { std::abort(); } -int APS5_VABI Underflow(LibcxxStreambuf* stream) { +int APS5_VABI Underflow(void* self) { + auto* const stream = static_cast(self); auto& fixture = *reinterpret_cast(stream); if (++fixture.underflowCalls != 1) return -1; @@ -40,7 +41,8 @@ int APS5_VABI Uflow(LibcxxStreambuf* stream) { return static_cast(fixture.refillInput.front()); } -int APS5_VABI Overflow(LibcxxStreambuf* stream, int value) { +int APS5_VABI Overflow(void* self, int value) { + auto* const stream = static_cast(self); auto& fixture = *reinterpret_cast(stream); Require(fixture.overflowCalls < fixture.overflowValues.size()); fixture.overflowValues[fixture.overflowCalls++] = value; @@ -51,13 +53,13 @@ int APS5_VABI Overflow(LibcxxStreambuf* stream, int value) { return value; } -const LibcxxStreambufVtable Methods{ - .beforeUnderflow = {}, - .underflow = Underflow, - .uflow = Uflow, - .beforeOverflow = {}, - .overflow = Overflow, -}; +const LibcxxStreambufVtable Methods = [] { + LibcxxStreambufVtable methods{}; + methods.underflow = Underflow; + methods.uflow = Uflow; + methods.overflow = Overflow; + return methods; +}(); void TestUflow() { Fixture fixture{}; @@ -121,7 +123,7 @@ void TestOverlappingBuffers() { Require(stream.putCurrent == bytes.data() + 3); } -int APS5_VABI UnderflowWithoutBuffer(LibcxxStreambuf*) { +int APS5_VABI UnderflowWithoutBuffer(void*) { return 0xfe; } diff --git a/docs/dev/debt/changes/feat-libc-streambuf-destruction.md b/docs/dev/debt/changes/feat-libc-streambuf-destruction.md new file mode 100644 index 000000000000..9bf8fd1f6c6c --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-streambuf-destruction.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ narrow stream buffer destructor](../../../core/libs/prx/libc/src/LibcxxStreambufLifecycle.cpp) (libc) restores the base vtable and releases the embedded locale without deallocating the stream. The object layout, address point and destructor calls follow the [PS5 Payload SDK v0.42](https://github.com/ps5-payload-dev/sdk/releases/tag/v0.42) archive. The firmware provider, layout and behavior on retail hardware, and RetroArch startup remain unverified. From d4135faba666ba892251ec648899d2496d9705f2 Mon Sep 17 00:00:00 2001 From: cmsierrave-coder <317402244+cmsierrave-coder@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:01:13 -0500 Subject: [PATCH 08/18] test(libc): exercise the streambuf destructor through its vtable --- core/libs/tests/GuestLibcxxStreambufLifecycle.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp b/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp index 93b91856cddc..9bc168af02f3 100644 --- a/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp +++ b/core/libs/tests/GuestLibcxxStreambufLifecycle.cpp @@ -33,7 +33,7 @@ void APS5_VABI OnZeroShared(GuestLocale::LibcxxFacet* base) { facet.observedVtable = facet.stream->vtable; } -void TestDestruction() { +const LibcxxStreambufVtable* TestDestruction(void (APS5_VABI* destroy)(LibcxxStreambuf*)) { Fixture fixture; auto& stream = fixture.stream; const LibcxxStreambufVtable derivedVtable{}; @@ -54,12 +54,12 @@ void TestDestruction() { _ZNSt3__16locale2id5__getEv_nid_postfix(&id)); Require(facet.base.sharedOwners == 0 && facet.releases == 0); - _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix(&stream); + destroy(&stream); Require(facet.base.sharedOwners == -1 && facet.releases == 1); Require(stream.vtable && stream.vtable != &derivedVtable); Require(facet.observedVtable == stream.vtable); - Require(stream.vtable->destroy == _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix); + Require(stream.vtable->destroy != nullptr); Require(stream.vtable->deleteObject != nullptr); struct { std::ptrdiff_t offsetToTop; @@ -68,14 +68,17 @@ void TestDestruction() { const auto addressPoint = reinterpret_cast(stream.vtable); std::memcpy(&metadata, reinterpret_cast(addressPoint - sizeof(metadata)), sizeof(metadata)); Require(metadata.offsetToTop == 0); - Require(metadata.type == &_ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix); + Require(metadata.type != nullptr); + Require(std::strcmp(metadata.type->name, "NSt3__115basic_streambufIcNS_11char_traitsIcEEEE") == 0); Require(stream.getStart == buffer && stream.getCurrent == buffer + 1 && stream.getEnd == buffer + 2); Require(stream.putStart == buffer + 3 && stream.putCurrent == buffer + 4 && stream.putEnd == buffer + 5); Require(fixture.before == 0x0123456789abcdef && fixture.after == 0xfedcba9876543210); + return stream.vtable; } } int main() { - TestDestruction(); + const auto* methods = TestDestruction(_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix); + TestDestruction(methods->destroy); } From c7b443047d5e22c4187e6bb9e9b524554032f2ca Mon Sep 17 00:00:00 2001 From: Kian Date: Fri, 27 Nov 2026 04:08:38 +1000 Subject: [PATCH 09/18] feat(libc): implement libc++ ios_base::failure and iostream_category Add the std::__1 iostream_category and the ios_base::failure const char* and string constructors, D1, D2, RTTI and vtable. failure is a system_error with its own vtable and typeinfo, so what() is msg + ": " + message() for a nonzero code. iostream_category is named "iostream" and reports "unspecified iostream_category error" for io_errc::stream (1) and from the ELAST cutoff on, strerror text otherwise, as LLVM libc++ 17 ios.cpp does. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libc/include/Api.hpp | 7 + .../libc/src/exception/StandardExceptions.cpp | 50 ++++++ core/libs/tests/GuestLibcxxSystemError.cpp | 158 ++++++++++++++++++ .../changes/feat-libc-libcxx-ios-failure.md | 5 + 4 files changed, 220 insertions(+) create mode 100644 docs/dev/debt/changes/feat-libc-libcxx-ios-failure.md diff --git a/core/libs/prx/libc/include/Api.hpp b/core/libs/prx/libc/include/Api.hpp index 53dd1296be4c..440b2e6e2512 100644 --- a/core/libs/prx/libc/include/Api.hpp +++ b/core/libs/prx/libc/include/Api.hpp @@ -1869,6 +1869,13 @@ void APS5_VABI _ZNSt3__112system_errorC1ENS_10error_codeERKNS_12basic_stringIcNS void APS5_VABI _ZNSt3__112system_errorD1Ev_nid_postfix(LibcException::LibcxxSystemErrorObject* self) noexcept; void APS5_VABI _ZNSt3__112system_errorD2Ev_nid_postfix(LibcException::LibcxxSystemErrorObject* self) noexcept; [[noreturn]] void APS5_VABI _ZNSt3__120__throw_system_errorEiPKc_nid_postfix(int value, const char* what); +const LibcException::CategoryObject* APS5_VABI _ZNSt3__117iostream_categoryEv_nid_postfix() noexcept; +extern const LibcException::TypeRecord _ZTINSt3__18ios_base7failureE_nid_postfix; +extern const LibcException::ExceptionVtable _ZTVNSt3__18ios_base7failureE_nid_postfix; +void APS5_VABI _ZNSt3__18ios_base7failureC1EPKcRKNS_10error_codeE_nid_postfix(LibcException::LibcxxSystemErrorObject* self, const char* what, const LibcException::LibcxxErrorCode* code); +void APS5_VABI _ZNSt3__18ios_base7failureC1ERKNS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEERKNS_10error_codeE_nid_postfix(LibcException::LibcxxSystemErrorObject* self, const void* what, const LibcException::LibcxxErrorCode* code); +void APS5_VABI _ZNSt3__18ios_base7failureD1Ev_nid_postfix(LibcException::LibcxxSystemErrorObject* self) noexcept; +void APS5_VABI _ZNSt3__18ios_base7failureD2Ev_nid_postfix(LibcException::LibcxxSystemErrorObject* self) noexcept; void APS5_VABI _ZNSt11range_errorD1Ev_nid_postfix(LibcException::ExceptionObject* self); void APS5_VABI _ZNSt11range_errorD2Ev_nid_postfix(LibcException::ExceptionObject* self); void APS5_VABI _ZNSt11range_errorD0Ev_nid_postfix(LibcException::ExceptionObject* self); diff --git a/core/libs/prx/libc/src/exception/StandardExceptions.cpp b/core/libs/prx/libc/src/exception/StandardExceptions.cpp index eebed27cdb0a..80b6cbf4d3a9 100644 --- a/core/libs/prx/libc/src/exception/StandardExceptions.cpp +++ b/core/libs/prx/libc/src/exception/StandardExceptions.cpp @@ -887,6 +887,56 @@ void APS5_VABI _ZNSt3__112system_errorC1ENS_10error_codeERKNS_12basic_stringIcNS } } +namespace LibcException::Libcxx { +static const char* APS5_VABI IostreamName_nid_no_patch(const CategoryObject*) { return "iostream"; } +static String* APS5_VABI IostreamMessage_nid_no_patch(String* result, const CategoryObject*, int value) { + return FillString(result, value == 1 || BeyondLast(value) ? "unspecified iostream_category error" : StrerrorMessage(value)); +} +const TypeRecord IostreamCategoryType {SingleTypeVtable + 2, "NSt3__119__iostream_categoryE", &DoMessageType}; +const void* const IostreamCategoryVtable[] { + nullptr, &IostreamCategoryType, + reinterpret_cast(CategoryDestroy_nid_no_patch), reinterpret_cast(CategoryDelete_nid_no_patch), + reinterpret_cast(IostreamName_nid_no_patch), reinterpret_cast(Condition_nid_no_patch), + reinterpret_cast(EquivalentCondition_nid_no_patch), reinterpret_cast(EquivalentCode_nid_no_patch), + reinterpret_cast(IostreamMessage_nid_no_patch) +}; +const CategoryObject IostreamCategory {IostreamCategoryVtable + 2}; + +static void ConstructFailure(LibcxxSystemErrorObject* self, std::string what, const LibcxxErrorCode* code) { + if (!code) throw std::invalid_argument("std::__1::ios_base::failure: null error code"); + ConstructSystemError(self, *code, std::move(what)); + self->base.vtable = &_ZTVNSt3__18ios_base7failureE_nid_postfix.destroy; +} +} + +extern "C" { +const LibcException::CategoryObject* APS5_VABI _ZNSt3__117iostream_categoryEv_nid_postfix() noexcept { + return &LibcException::Libcxx::IostreamCategory; +} +constinit const LibcException::TypeRecord _ZTINSt3__18ios_base7failureE_nid_postfix { + LibcException::SingleTypeVtable + 2, "NSt3__18ios_base7failureE", &_ZTINSt3__112system_errorE_nid_postfix, +}; +constinit const LibcException::ExceptionVtable _ZTVNSt3__18ios_base7failureE_nid_postfix { + 0, &_ZTINSt3__18ios_base7failureE_nid_postfix, LibcException::GuestDestroyMessage_nid_no_patch, + LibcException::GuestDeleteMessage_nid_no_patch, LibcException::GuestMessageWhat_nid_no_patch, +}; +void APS5_VABI _ZNSt3__18ios_base7failureC1EPKcRKNS_10error_codeE_nid_postfix( + LibcException::LibcxxSystemErrorObject* self, const char* what, const LibcException::LibcxxErrorCode* code) { + LibcException::Libcxx::ConstructFailure(self, LibcException::Libcxx::WhatArgument(what), code); +} +void APS5_VABI _ZNSt3__18ios_base7failureC1ERKNS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEERKNS_10error_codeE_nid_postfix( + LibcException::LibcxxSystemErrorObject* self, const void* what, const LibcException::LibcxxErrorCode* code) { + LibcException::Libcxx::ConstructFailure(self, + LibcException::Libcxx::ReadString(static_cast(what)), code); +} +void APS5_VABI _ZNSt3__18ios_base7failureD1Ev_nid_postfix(LibcException::LibcxxSystemErrorObject* self) noexcept { + LibcException::DestroyMessage(&self->base); +} +void APS5_VABI _ZNSt3__18ios_base7failureD2Ev_nid_postfix(LibcException::LibcxxSystemErrorObject* self) noexcept { + LibcException::DestroyMessage(&self->base); +} +} + namespace LibcException::SceV2 { static const char* APS5_VABI BadOptionalAccessWhat_nid_no_patch(const ExceptionObject*) { return "Bad optional access"; } static const char* APS5_VABI BadWeakPtrWhat_nid_no_patch(const ExceptionObject*) { return "bad_weak_ptr"; } diff --git a/core/libs/tests/GuestLibcxxSystemError.cpp b/core/libs/tests/GuestLibcxxSystemError.cpp index 1b9af9040e07..facdd51a279b 100644 --- a/core/libs/tests/GuestLibcxxSystemError.cpp +++ b/core/libs/tests/GuestLibcxxSystemError.cpp @@ -1,5 +1,6 @@ #include "prx/libc/include/Api.hpp" #include "prx/libc/include/ApplicationHeap.hpp" +#include "prx/libc/include/exceptions/Runtime.hpp" #include #include #include @@ -237,6 +238,159 @@ static const LibcException::CategoryObject* CheckThrow(int code, const char* wha return category; } +static void CheckIostreamCategory(const LibcException::CategoryObject* iostream, const LibcException::CategoryObject* generic) { + REQUIRE(iostream && iostream == _ZNSt3__117iostream_categoryEv_nid_postfix() && iostream != generic); + const auto* type = TypeOf(iostream->vtable); + REQUIRE(std::strcmp(type->name, "NSt3__119__iostream_categoryE") == 0); + REQUIRE(std::strcmp(KindOf(type), "N10__cxxabiv120__si_class_type_infoE") == 0); + REQUIRE(type->base == TypeOf(generic->vtable)->base); + REQUIRE(std::strcmp(std::bit_cast(Slot(iostream, 2))(iostream), "iostream") == 0); + CheckMessage(iostream, 1, "unspecified iostream_category error"); + CheckMessage(iostream, 5, Strerror(5)); + CheckMessage(iostream, 2, "No such file or directory"); + CheckMessage(iostream, sys_nerr_nid_postfix - 1, Strerror(sys_nerr_nid_postfix - 1)); + CheckMessage(iostream, -1, Strerror(-1)); + CheckMessage(iostream, sys_nerr_nid_postfix, "unspecified iostream_category error"); + CheckMessage(iostream, sys_nerr_nid_postfix + 1, "unspecified iostream_category error"); + const LibcException::LibcxxErrorCode mapped = std::bit_cast(Slot(iostream, 3))(iostream, 5); + REQUIRE(mapped.value == 5 && mapped.category == iostream); + const auto equivalentCondition = std::bit_cast(Slot(iostream, 4)); + const auto equivalentCode = std::bit_cast(Slot(iostream, 5)); + const LibcException::LibcxxErrorCode inSelf {5, 0, iostream}; + const LibcException::LibcxxErrorCode inGeneric {5, 0, generic}; + REQUIRE(equivalentCondition(iostream, 5, &inSelf) && !equivalentCondition(iostream, 6, &inSelf)); + REQUIRE(!equivalentCondition(iostream, 5, &inGeneric)); + REQUIRE(equivalentCode(iostream, &inSelf, 5) && !equivalentCode(iostream, &inSelf, 6)); + REQUIRE(!equivalentCode(iostream, &inGeneric, 5)); + bool rejected = false; + try { std::bit_cast(Slot(iostream, 1))(iostream); } + catch (const std::invalid_argument&) { rejected = true; } + REQUIRE(rejected); +} + +static std::string FailureWhat(const LibcException::LibcxxSystemErrorObject& object) { + REQUIRE(object.base.vtable == &_ZTVNSt3__18ios_base7failureE_nid_postfix.destroy); + return std::bit_cast(static_cast(object.base.vtable)[2])(&object.base); +} + +static void ConstructFailure(LibcException::LibcxxSystemErrorObject& object, const char* what, const LibcException::LibcxxErrorCode* code) { + std::memset(&object, 0xcd, sizeof(object)); + _ZNSt3__18ios_base7failureC1EPKcRKNS_10error_codeE_nid_postfix(&object, what, code); +} + +static void ConstructFailure(LibcException::LibcxxSystemErrorObject& object, const LibcxxString* what, const LibcException::LibcxxErrorCode* code) { + std::memset(&object, 0xcd, sizeof(object)); + _ZNSt3__18ios_base7failureC1ERKNS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEERKNS_10error_codeE_nid_postfix(&object, what, code); +} + +static void CheckFailure(const LibcException::CategoryObject* iostream, const LibcException::CategoryObject* generic) { + const auto& type = _ZTINSt3__18ios_base7failureE_nid_postfix; + REQUIRE(std::strcmp(type.name, "NSt3__18ios_base7failureE") == 0); + REQUIRE(std::strcmp(KindOf(&type), "N10__cxxabiv120__si_class_type_infoE") == 0); + REQUIRE(type.base == &_ZTINSt3__112system_errorE_nid_postfix); + const auto& table = _ZTVNSt3__18ios_base7failureE_nid_postfix; + const auto& base = _ZTVNSt3__112system_errorE_nid_postfix; + REQUIRE(table.offset == 0 && table.type == &type); + REQUIRE(table.destroy == base.destroy && table.deleteObject == base.deleteObject && table.what == base.what); + + const LibcException::LibcxxErrorCode stream {1, 0, iostream}; + LibcException::LibcxxSystemErrorObject object; + ConstructFailure(object, "stream", &stream); + REQUIRE(FailureWhat(object) == "stream: unspecified iostream_category error"); + REQUIRE(object.code.value == 1 && object.code.category == iostream); + _ZNSt3__18ios_base7failureD1Ev_nid_postfix(&object); + REQUIRE(object.base.message == nullptr && object.code.value == 1); + + ConstructFailure(object, "", &stream); + REQUIRE(FailureWhat(object) == "unspecified iostream_category error"); + _ZNSt3__18ios_base7failureD2Ev_nid_postfix(&object); + REQUIRE(object.base.message == nullptr); + + const LibcException::LibcxxErrorCode exists {17, 0, generic}; + ConstructFailure(object, "open", &exists); + REQUIRE(FailureWhat(object) == "open: File exists" && object.code.category == generic); + _ZNSt3__18ios_base7failureD1Ev_nid_postfix(&object); + + const LibcException::LibcxxErrorCode none {0, 0, iostream}; + ConstructFailure(object, "nothing failed", &none); + REQUIRE(FailureWhat(object) == "nothing failed" && object.code.value == 0 && object.code.category == iostream); + _ZNSt3__18ios_base7failureD1Ev_nid_postfix(&object); + + const LibcxxString shortWhat = MakeString("read"); + ConstructFailure(object, &shortWhat, &stream); + REQUIRE(FailureWhat(object) == "read: unspecified iostream_category error"); + REQUIRE(object.code.value == 1 && object.code.category == iostream); + _ZNSt3__18ios_base7failureD1Ev_nid_postfix(&object); + + const char* longText = "a stream message that does not fit inline"; + const LibcxxString longWhat = MakeString(longText); + const LibcException::LibcxxErrorCode invalid {22, 0, iostream}; + ConstructFailure(object, &longWhat, &invalid); + REQUIRE(FailureWhat(object) == std::string(longText) + ": Invalid argument" && object.code.value == 22); + _ZNSt3__18ios_base7failureD2Ev_nid_postfix(&object); + REQUIRE(object.base.message == nullptr); + + const LibcxxString emptyWhat = MakeString(""); + ConstructFailure(object, &emptyWhat, &stream); + REQUIRE(FailureWhat(object) == "unspecified iostream_category error"); + _ZNSt3__18ios_base7failureD1Ev_nid_postfix(&object); + + const LibcException::LibcxxErrorCode noCategory {1, 0, nullptr}; + bool rejected = false; + try { ConstructFailure(object, static_cast(nullptr), &stream); } + catch (const std::invalid_argument&) { rejected = true; } + REQUIRE(rejected); + rejected = false; + try { ConstructFailure(object, "x", nullptr); } + catch (const std::invalid_argument&) { rejected = true; } + REQUIRE(rejected); + rejected = false; + try { ConstructFailure(object, "x", &noCategory); } + catch (const std::invalid_argument&) { rejected = true; } + REQUIRE(rejected); + rejected = false; + try { ConstructFailure(object, static_cast(nullptr), &stream); } + catch (const std::invalid_argument&) { rejected = true; } + REQUIRE(rejected); + rejected = false; + try { ConstructFailure(object, &shortWhat, nullptr); } + catch (const std::invalid_argument&) { rejected = true; } + REQUIRE(rejected); +} + +[[noreturn]] static void ThrowFailure(const LibcException::LibcxxErrorCode& code, const char* what) { + auto* object = static_cast( + __cxa_allocate_exception_nid_postfix(sizeof(LibcException::LibcxxSystemErrorObject))); + _ZNSt3__18ios_base7failureC1EPKcRKNS_10error_codeE_nid_postfix(object, what, &code); + __cxa_throw_nid_postfix(object, + reinterpret_cast(const_cast(&_ZTINSt3__18ios_base7failureE_nid_postfix)), + reinterpret_cast(&_ZNSt3__18ios_base7failureD1Ev_nid_postfix)); +} + +static void CheckFailureThrow(const LibcException::CategoryObject* iostream) { + const LibcException::LibcxxErrorCode stream {1, 0, iostream}; + bool caught = false; + try { ThrowFailure(stream, "badbit"); } + catch (const std::runtime_error& error) { + REQUIRE(__cxa_current_exception_type_nid_postfix() == + reinterpret_cast(&_ZTINSt3__18ios_base7failureE_nid_postfix)); + const auto* object = reinterpret_cast(&error); + REQUIRE(FailureWhat(*object) == "badbit: unspecified iostream_category error"); + REQUIRE(object->code.value == 1 && object->code.category == iostream); + REQUIRE(TypeOf(object->base.vtable)->base == &_ZTINSt3__112system_errorE_nid_postfix); + caught = true; + } + REQUIRE(caught); + caught = false; + try { ThrowFailure(stream, ""); } + catch (const std::exception& error) { + const auto* object = reinterpret_cast(&error); + REQUIRE(FailureWhat(*object) == "unspecified iostream_category error"); + caught = true; + } + REQUIRE(caught); +} + int main() { const std::array api {}; ApplicationHeapRegister_nid_no_patch(api.data()); @@ -249,6 +403,10 @@ int main() { REQUIRE(CheckThrow(0, "no error", "no error") == system); REQUIRE(CheckThrow(97, "", "unspecified system_category error") == system); CheckSystemCategory(system, generic); + const LibcException::CategoryObject* iostream = _ZNSt3__117iostream_categoryEv_nid_postfix(); + CheckIostreamCategory(iostream, generic); + CheckFailure(iostream, generic); + CheckFailureThrow(iostream); bool rejected = false; try { _ZNSt3__120__throw_system_errorEiPKc_nid_postfix(5, nullptr); } catch (const std::invalid_argument&) { rejected = true; } diff --git a/docs/dev/debt/changes/feat-libc-libcxx-ios-failure.md b/docs/dev/debt/changes/feat-libc-libcxx-ios-failure.md new file mode 100644 index 000000000000..6b1491811ff8 --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-libcxx-ios-failure.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ ios_base::failure](../../../core/libs/prx/libc/src/exception/StandardExceptions.cpp) (libc) - the `std::__1` `iostream_category`, `ios_base::failure` constructors, destructors, RTTI and vtable imported by RetroArch Azahar (PPSA99169, #5927) follow [LLVM libc++ 17 ios.cpp](https://github.com/llvm/llvm-project/blob/llvmorg-17.0.6/libcxx/src/ios.cpp), not a console module; no firmware provider was measured. `iostream_category` reports `unspecified iostream_category error` for 1 (`io_errc::stream`) and from `sys_nerr` on, with the same unverified ELAST of 96 as the `system_error` categories. A null message, error code or category throws. From 888c8728e82e4bb01d34df7a2c7c36b53adc2ed4 Mon Sep 17 00:00:00 2001 From: LeandroLP23 Date: Thu, 3 Dec 2026 11:32:25 +0100 Subject: [PATCH 10/18] refactor(libc): share the libc++ ios_base layout Move the libc++ 17 ios_base object layout and its offset asserts from LibcxxIosInit.cpp to GuestLocale.hpp as LibcxxIosBase, next to LibcxxLocale, so the basic_ostream exports can read the stream state, exception mask, buffer and format flags through the same checked layout instead of a second copy. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libc/include/GuestLocale.hpp | 32 +++++++++++++++++++++ core/libs/prx/libc/src/LibcxxIosInit.cpp | 33 ++-------------------- 2 files changed, 34 insertions(+), 31 deletions(-) diff --git a/core/libs/prx/libc/include/GuestLocale.hpp b/core/libs/prx/libc/include/GuestLocale.hpp index d6454d4fcb52..5655601406ab 100644 --- a/core/libs/prx/libc/include/GuestLocale.hpp +++ b/core/libs/prx/libc/include/GuestLocale.hpp @@ -65,6 +65,38 @@ struct LibcxxLocale { static_assert(sizeof(LibcxxLocale) == 0x8); +using LibcxxIosCallback = void (APS5_VABI*)(int event, void* stream, int index); + +struct LibcxxIosBase { + const void* vtable; + std::uint32_t flags; + std::int64_t precision; + std::int64_t width; + std::uint32_t state; + std::uint32_t exceptions; + void* buffer; + LibcxxLocale locale; + const LibcxxIosCallback* callbacks; + const int* callbackIndexes; + std::uint64_t callbackCount; + std::uint64_t callbackCapacity; + void* integers; + std::uint64_t integerCount; + std::uint64_t integerCapacity; + void* pointers; + std::uint64_t pointerCount; + std::uint64_t pointerCapacity; +}; + +static_assert(offsetof(LibcxxIosBase, precision) == 0x10); +static_assert(offsetof(LibcxxIosBase, state) == 0x20); +static_assert(offsetof(LibcxxIosBase, buffer) == 0x28); +static_assert(offsetof(LibcxxIosBase, locale) == 0x30); +static_assert(offsetof(LibcxxIosBase, callbackCount) == 0x48); +static_assert(offsetof(LibcxxIosBase, integers) == 0x58); +static_assert(offsetof(LibcxxIosBase, pointers) == 0x70); +static_assert(sizeof(LibcxxIosBase) == 0x88); + struct CtypeFacet { Facet base; const std::int16_t* classification; diff --git a/core/libs/prx/libc/src/LibcxxIosInit.cpp b/core/libs/prx/libc/src/LibcxxIosInit.cpp index 74dd84bf00c7..8ce2493039bd 100644 --- a/core/libs/prx/libc/src/LibcxxIosInit.cpp +++ b/core/libs/prx/libc/src/LibcxxIosInit.cpp @@ -18,37 +18,8 @@ constexpr std::uint32_t SkipWhitespace = 0x1000; constexpr int EraseEvent = 0; constexpr int ImbueEvent = 1; -using Callback = void (APS5_VABI*)(int event, void* stream, int index); - -struct IosBase { - const void* vtable; - std::uint32_t flags; - std::int64_t precision; - std::int64_t width; - std::uint32_t state; - std::uint32_t exceptions; - void* buffer; - LibcxxLocale locale; - const Callback* callbacks; - const int* callbackIndexes; - std::uint64_t callbackCount; - std::uint64_t callbackCapacity; - void* integers; - std::uint64_t integerCount; - std::uint64_t integerCapacity; - void* pointers; - std::uint64_t pointerCount; - std::uint64_t pointerCapacity; -}; - -static_assert(offsetof(IosBase, precision) == 0x10); -static_assert(offsetof(IosBase, state) == 0x20); -static_assert(offsetof(IosBase, buffer) == 0x28); -static_assert(offsetof(IosBase, locale) == 0x30); -static_assert(offsetof(IosBase, callbackCount) == 0x48); -static_assert(offsetof(IosBase, integers) == 0x58); -static_assert(offsetof(IosBase, pointers) == 0x70); -static_assert(sizeof(IosBase) == 0x88); +using Callback = GuestLocale::LibcxxIosCallback; +using IosBase = GuestLocale::LibcxxIosBase; [[noreturn]] void Inaccessible() { throw std::invalid_argument("libc++ ios_base: inaccessible guest object"); From cd2c142e965ffe1e7b521cd8a137897e6a07acb0 Mon Sep 17 00:00:00 2001 From: LeandroLP23 Date: Thu, 3 Dec 2026 11:32:26 +0100 Subject: [PATCH 11/18] feat(libc): implement libc++ basic_ostream core members Add ios_base::clear and the basic_ostream sentry constructor and destructor, put, write, flush and the complete and base destructors, imported by RetroArch's Azahar core (PPSA99169). They follow LLVM libc++ 17.0.6 , , and ios.cpp. The basic_ios virtual base is found through the virtual-base offset at vtable slot -24, and the stream buffer's sync, xsputn and overflow are called through the guest object's vtable; put writes into the put area as the inline sputc does. clear throws ios_base::failure with io_errc::stream as a guest exception. Exceptions from the stream buffer are caught like libc++ does, since guest and host share libc's exception runtime: badbit is set and the exception is rethrown when the mask has badbit. The sentry destructor skips pubsync while libc's uncaught exception count is nonzero. The base destructor does nothing and ignores the VTT, matching clang's code for the empty destructor body; the complete destructor runs the basic_ios base destructor on the virtual base. Unreadable objects and missing virtual functions throw invalid_argument and are not turned into badbit. The gaps are recorded in the libc debt. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libc/CMakeLists.txt | 1 + core/libs/prx/libc/include/LibcxxIosInit.hpp | 9 + core/libs/prx/libc/src/LibcxxOstream.cpp | 249 +++++++++ .../tests/cmake/guest_libcxx_ostream.cmake | 12 + core/libs/tests/GuestLibcxxOstream.cpp | 483 ++++++++++++++++++ .../changes/feat-libc-libcxx-ostream-core.md | 5 + 6 files changed, 759 insertions(+) create mode 100644 core/libs/prx/libc/src/LibcxxOstream.cpp create mode 100644 core/libs/prx/libc/tests/cmake/guest_libcxx_ostream.cmake create mode 100644 core/libs/tests/GuestLibcxxOstream.cpp create mode 100644 docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md diff --git a/core/libs/prx/libc/CMakeLists.txt b/core/libs/prx/libc/CMakeLists.txt index 0855a0e16de2..84b0963cdc36 100644 --- a/core/libs/prx/libc/CMakeLists.txt +++ b/core/libs/prx/libc/CMakeLists.txt @@ -267,6 +267,7 @@ target_sources(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/AtomicWait.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxMutex.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxIosInit.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/LibcxxOstream.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Rename.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Errors.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Syslog.cpp diff --git a/core/libs/prx/libc/include/LibcxxIosInit.hpp b/core/libs/prx/libc/include/LibcxxIosInit.hpp index 6682ba5f2855..93cf702222c3 100644 --- a/core/libs/prx/libc/include/LibcxxIosInit.hpp +++ b/core/libs/prx/libc/include/LibcxxIosInit.hpp @@ -1,6 +1,7 @@ #pragma once #include "general/VabiMacros.hpp" +#include extern "C" { @@ -8,5 +9,13 @@ void APS5_VABI _ZNSt3__18ios_base4initEPv_nid_postfix(void* self, void* buffer); void* APS5_VABI _ZNKSt3__18ios_base6getlocEv_nid_postfix(void* result, const void* self); void* APS5_VABI _ZNSt3__18ios_base5imbueERKNS_6localeE_nid_postfix(void* result, void* self, const void* locale); void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED2Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__18ios_base5clearEj_nid_postfix(void* self, std::uint32_t state); +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryC1ERS3__nid_postfix(void* self, void* stream); +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryD1Ev_nid_postfix(void* self); +void* APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE3putEc_nid_postfix(void* self, char value); +void* APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5writeEPKcl_nid_postfix(void* self, const char* data, std::int64_t count); +void* APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5flushEv_nid_postfix(void* self); +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED2Ev_nid_postfix(void* self, const void* const* vtt); } diff --git a/core/libs/prx/libc/src/LibcxxOstream.cpp b/core/libs/prx/libc/src/LibcxxOstream.cpp new file mode 100644 index 000000000000..a580b1c84b71 --- /dev/null +++ b/core/libs/prx/libc/src/LibcxxOstream.cpp @@ -0,0 +1,249 @@ +#include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/GuestLocale.hpp" +#include "prx/libc/include/GuestPtr.hpp" +#include "prx/libc/include/exceptions/Runtime.hpp" +#include +#include +#include +#include + +namespace { + +using GuestLocale::LibcxxIosBase; + +constexpr std::uint32_t BadBit = 0x1; +constexpr std::uint32_t UnitBuffered = 0x2000; +constexpr int StreamError = 1; +constexpr int Eof = -1; +constexpr std::ptrdiff_t VirtualBaseOffsetSlot = -24; + +struct BasicIos { + LibcxxIosBase base; + void* tie; + int fill; +}; + +static_assert(offsetof(BasicIos, tie) == 0x88); +static_assert(offsetof(BasicIos, fill) == 0x90); +static_assert(sizeof(BasicIos) == 0x98); + +struct Streambuf; + +struct StreambufVtable { + std::uintptr_t beforeSync[6]; + int (APS5_VABI* sync)(Streambuf*); + std::uintptr_t beforeXsputn[5]; + std::int64_t (APS5_VABI* xsputn)(Streambuf*, const char*, std::int64_t); + int (APS5_VABI* overflow)(Streambuf*, int); +}; + +static_assert(offsetof(StreambufVtable, sync) == 0x30); +static_assert(offsetof(StreambufVtable, xsputn) == 0x60); +static_assert(offsetof(StreambufVtable, overflow) == 0x68); + +struct Streambuf { + const StreambufVtable* vtable; + GuestLocale::LibcxxLocale locale; + char* getStart; + char* getCurrent; + char* getEnd; + char* putStart; + char* putCurrent; + char* putEnd; +}; + +static_assert(offsetof(Streambuf, putCurrent) == 0x30); +static_assert(offsetof(Streambuf, putEnd) == 0x38); +static_assert(sizeof(Streambuf) == 0x40); + +struct Sentry { + bool ok; + void* stream; +}; + +static_assert(offsetof(Sentry, stream) == 0x8); +static_assert(sizeof(Sentry) == 0x10); + +class InaccessibleObject : public std::invalid_argument { +public: + using std::invalid_argument::invalid_argument; +}; + +[[noreturn]] void Inaccessible(const char* what) { + throw InaccessibleObject(what); +} + +template +T Read(const T* address) { + T value{}; + if (!GuestPtr(address).CopyIn(value)) Inaccessible("libc++ ostream: unreadable guest object"); + return value; +} + +template +void Write(T* address, const T& value) { + if (!GuestPtr(address).CopyOut(value)) Inaccessible("libc++ ostream: unwritable guest object"); +} + +template +TMethod Virtual(Streambuf* buffer, TMethod StreambufVtable::*slot) { + if (buffer == nullptr) Inaccessible("libc++ ostream: null stream buffer"); + const auto* vtable = Read(&buffer->vtable); + if (vtable == nullptr) Inaccessible("libc++ ostream: null stream buffer vtable"); + const auto method = Read(vtable).*slot; + if (method == nullptr) Inaccessible("libc++ ostream: missing stream buffer virtual function"); + return method; +} + +BasicIos* IosOf(void* stream) { + if (stream == nullptr) Inaccessible("libc++ ostream: null object"); + const auto* vtable = Read(static_cast(stream)); + if (vtable == nullptr) Inaccessible("libc++ ostream: null vtable"); + const auto offset = Read(reinterpret_cast(vtable + VirtualBaseOffsetSlot)); + return reinterpret_cast(static_cast(stream) + offset); +} + +Streambuf* BufferOf(BasicIos* ios) { + return static_cast(Read(&ios->base.buffer)); +} + +[[noreturn]] void ThrowFailure(const char* what) { + const LibcException::LibcxxErrorCode code{StreamError, 0, _ZNSt3__117iostream_categoryEv_nid_postfix()}; + auto* object = static_cast( + __cxa_allocate_exception_nid_postfix(sizeof(LibcException::LibcxxSystemErrorObject))); + try { + _ZNSt3__18ios_base7failureC1EPKcRKNS_10error_codeE_nid_postfix(object, what, &code); + } catch (...) { + __cxa_free_exception_nid_postfix(object); + throw; + } + __cxa_throw_nid_postfix(object, + reinterpret_cast(const_cast(&_ZTINSt3__18ios_base7failureE_nid_postfix)), + reinterpret_cast(&_ZNSt3__18ios_base7failureD1Ev_nid_postfix)); +} + +void Clear(LibcxxIosBase* ios, std::uint32_t state) { + const bool buffered = Read(&ios->buffer) != nullptr; + Write(&ios->state, buffered ? state : state | BadBit); + if (((state | (buffered ? 0u : BadBit)) & Read(&ios->exceptions)) != 0) ThrowFailure("ios_base::clear"); +} + +void SetState(BasicIos* ios, std::uint32_t state) { + Clear(&ios->base, Read(&ios->base.state) | state); +} + +void SetBadBitAndConsiderRethrow(BasicIos* ios) { + Write(&ios->base.state, Read(&ios->base.state) | BadBit); + if ((Read(&ios->base.exceptions) & BadBit) != 0) throw; +} + +void* Flush(void* stream); + +bool Prefix(BasicIos* ios) { + if (Read(&ios->base.state) != 0) return false; + if (auto* const tie = Read(&ios->tie)) Flush(tie); + return true; +} + +void Suffix(BasicIos* ios) { + auto* const buffer = BufferOf(ios); + if (buffer == nullptr || Read(&ios->base.state) != 0 || (Read(&ios->base.flags) & UnitBuffered) == 0 || + __cxa_uncaught_exception_nid_postfix()) + return; + try { + if (Virtual(buffer, &StreambufVtable::sync)(buffer) == Eof) SetState(ios, BadBit); + } catch (const InaccessibleObject&) { + throw; + } catch (...) { + } +} + +int PutCharacter(Streambuf* buffer, char value) { + auto* const current = Read(&buffer->putCurrent); + if (current == Read(&buffer->putEnd)) + return Virtual(buffer, &StreambufVtable::overflow)(buffer, static_cast(value)); + Write(current, value); + Write(&buffer->putCurrent, current + 1); + return static_cast(value); +} + +void* Flush(void* stream) { + auto* const ios = IosOf(stream); + try { + if (BufferOf(ios) != nullptr) { + if (Prefix(ios)) { + auto* const buffer = BufferOf(ios); + if (Virtual(buffer, &StreambufVtable::sync)(buffer) == Eof) SetState(ios, BadBit); + } + Suffix(ios); + } + } catch (const InaccessibleObject&) { + throw; + } catch (...) { + SetBadBitAndConsiderRethrow(ios); + } + return stream; +} + +} + +extern "C" { + +void APS5_VABI _ZNSt3__18ios_base5clearEj_nid_postfix(void* self, std::uint32_t state) { + Clear(static_cast(self), state); +} + +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryC1ERS3__nid_postfix(void* self, void* stream) { + auto* const sentry = static_cast(self); + Write(sentry, Sentry{false, stream}); + if (Prefix(IosOf(stream))) Write(&sentry->ok, true); +} + +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryD1Ev_nid_postfix(void* self) { + Suffix(IosOf(Read(&static_cast(self)->stream))); +} + +void* APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE3putEc_nid_postfix(void* self, char value) { + auto* const ios = IosOf(self); + try { + if (Prefix(ios)) { + auto* const buffer = BufferOf(ios); + if (buffer == nullptr || PutCharacter(buffer, value) == Eof) SetState(ios, BadBit); + } + Suffix(ios); + } catch (const InaccessibleObject&) { + throw; + } catch (...) { + SetBadBitAndConsiderRethrow(ios); + } + return self; +} + +void* APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5writeEPKcl_nid_postfix(void* self, const char* data, std::int64_t count) { + auto* const ios = IosOf(self); + try { + if (Prefix(ios) && count != 0) { + auto* const buffer = BufferOf(ios); + if (Virtual(buffer, &StreambufVtable::xsputn)(buffer, data, count) != count) SetState(ios, BadBit); + } + Suffix(ios); + } catch (const InaccessibleObject&) { + throw; + } catch (...) { + SetBadBitAndConsiderRethrow(ios); + } + return self; +} + +void* APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5flushEv_nid_postfix(void* self) { + return Flush(self); +} + +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(void* self) { + _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED2Ev_nid_postfix(IosOf(self)); +} + +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED2Ev_nid_postfix(void*, const void* const*) {} + +} diff --git a/core/libs/prx/libc/tests/cmake/guest_libcxx_ostream.cmake b/core/libs/prx/libc/tests/cmake/guest_libcxx_ostream.cmake new file mode 100644 index 000000000000..7deb94a92313 --- /dev/null +++ b/core/libs/prx/libc/tests/cmake/guest_libcxx_ostream.cmake @@ -0,0 +1,12 @@ +if(BUILD_TESTING) + add_test_executable(guest_libcxx_ostream_tests ${LIBS_INCLUDE_DIR}/tests/GuestLibcxxOstream.cpp) + target_include_directories(guest_libcxx_ostream_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_libcxx_ostream_tests PRIVATE libc) + configure_windows_unwind(guest_libcxx_ostream_tests) + add_test(NAME guest_libcxx_ostream COMMAND guest_libcxx_ostream_tests) + set_tests_properties(guest_libcxx_ostream PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_libcxx_ostream PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/tests/GuestLibcxxOstream.cpp b/core/libs/tests/GuestLibcxxOstream.cpp new file mode 100644 index 000000000000..85f7d259005a --- /dev/null +++ b/core/libs/tests/GuestLibcxxOstream.cpp @@ -0,0 +1,483 @@ +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/ApplicationHeap.hpp" +#include "prx/libc/include/GuestLocale.hpp" +#include "prx/libc/include/LibcxxIosInit.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr std::uint32_t BadBit = 0x1; +constexpr std::uint32_t EofBit = 0x2; +constexpr std::uint32_t FailBit = 0x4; +constexpr std::uint32_t UnitBuffered = 0x2000; +constexpr int Eof = -1; + +void Require(bool condition, std::source_location location = std::source_location::current()) { + if (condition) return; + std::fprintf(stderr, "check failed at line %u\n", location.line()); + std::abort(); +} + +template +void RequireInvalid(TAction&& action, std::source_location location = std::source_location::current()) { + bool thrown = false; + try { + action(); + } catch (const std::invalid_argument&) { + thrown = true; + } + Require(thrown, location); +} + +using What = const char* (APS5_VABI*)(const LibcException::ExceptionObject*); + +const std::type_info* TypeOf(const LibcException::TypeRecord& record) { + return reinterpret_cast(&record); +} + +template +void RequireFailure(TAction&& action, std::source_location location = std::source_location::current()) { + bool thrown = false; + try { + action(); + } catch (const std::runtime_error& error) { + Require(__cxa_current_exception_type_nid_postfix() == TypeOf(_ZTINSt3__18ios_base7failureE_nid_postfix), location); + const auto* object = reinterpret_cast(&error); + Require(object->code.value == 1 && object->code.category == _ZNSt3__117iostream_categoryEv_nid_postfix(), location); + const auto what = std::bit_cast(static_cast(object->base.vtable)[2]); + Require(std::string(what(&object->base)) == "ios_base::clear: unspecified iostream_category error", location); + thrown = true; + } + Require(thrown, location); +} + +template +void RequireGuestError(TAction&& action, std::source_location location = std::source_location::current()) { + bool thrown = false; + try { + action(); + } catch (const std::runtime_error&) { + Require(__cxa_current_exception_type_nid_postfix() == TypeOf(_ZTINSt3__112system_errorE_nid_postfix), location); + thrown = true; + } + Require(thrown, location); +} + +[[noreturn]] void ThrowGuest() { + _ZNSt3__120__throw_system_errorEiPKc_nid_postfix(5, "virtual"); +} + +struct Buffer { + const void* const* vtable{}; + void* locale{}; + char* getStart{}; + char* getCurrent{}; + char* getEnd{}; + char* putStart{}; + char* putCurrent{}; + char* putEnd{}; + int syncResult{}; + int syncCalls{}; + bool syncThrows{}; + bool xsputnThrows{}; + std::int64_t accepted{std::numeric_limits::max()}; + std::int64_t xsputnCalls{}; + char sent[32]{}; + std::size_t sentCount{}; + int overflowResult{}; + int overflowCalls{}; + int overflowValue{}; + char area[8]{}; +}; + +static_assert(offsetof(Buffer, putCurrent) == 0x30 && offsetof(Buffer, syncResult) == 0x40); + +int APS5_VABI Sync(Buffer* buffer) { + ++buffer->syncCalls; + if (buffer->syncThrows) ThrowGuest(); + return buffer->syncResult; +} + +std::int64_t APS5_VABI Xsputn(Buffer* buffer, const char* data, std::int64_t count) { + ++buffer->xsputnCalls; + if (buffer->xsputnThrows) ThrowGuest(); + const auto accepted = std::min(count, buffer->accepted); + std::memcpy(buffer->sent + buffer->sentCount, data, static_cast(accepted)); + buffer->sentCount += static_cast(accepted); + return accepted; +} + +int APS5_VABI Overflow(Buffer* buffer, int value) { + ++buffer->overflowCalls; + buffer->overflowValue = value; + return buffer->overflowResult; +} + +const void* const bufferVtable[14]{ + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, reinterpret_cast(&Sync), + nullptr, nullptr, nullptr, nullptr, nullptr, reinterpret_cast(&Xsputn), reinterpret_cast(&Overflow), +}; + +const void* const emptyVtable[14]{}; + +Buffer MakeBuffer() { + Buffer buffer; + buffer.vtable = bufferVtable; + buffer.putStart = buffer.area; + buffer.putCurrent = buffer.area; + buffer.putEnd = buffer.area + sizeof(buffer.area); + return buffer; +} + +struct BasicIos { + GuestLocale::LibcxxIosBase base; + void* tie; + int fill; +}; + +static_assert(offsetof(BasicIos, tie) == 0x88 && sizeof(BasicIos) == 0x98); + +struct WideStream { + const std::intptr_t* vptr{}; + unsigned char gap[0x20]{}; + BasicIos ios{}; + std::intptr_t vtable[3]{}; +}; + +struct NarrowStream { + const std::intptr_t* vptr{}; + BasicIos ios{}; + std::intptr_t vtable[3]{}; +}; + +static_assert(offsetof(WideStream, ios) == 0x28 && offsetof(NarrowStream, ios) == 0x8); + +template +void Prepare(TStream& stream, Buffer* buffer) { + std::memset(&stream.ios, 0, sizeof(stream.ios)); + stream.vtable[0] = offsetof(TStream, ios); + stream.vptr = stream.vtable + 3; + stream.ios.base.buffer = buffer; + stream.ios.base.state = buffer == nullptr ? BadBit : 0; +} + +WideStream MakeStream(Buffer* buffer) { + WideStream stream; + std::memset(stream.gap, 0xa5, sizeof(stream.gap)); + Prepare(stream, buffer); + return stream; +} + +struct Sentry { + bool ok; + void* stream; +}; + +Sentry Open(void* stream) { + Sentry sentry; + std::memset(&sentry, 0xcd, sizeof(sentry)); + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryC1ERS3__nid_postfix(&sentry, stream); + return sentry; +} + +void Close(Sentry& sentry) { + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryD1Ev_nid_postfix(&sentry); +} + +void* Put(void* stream, char value) { + return _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE3putEc_nid_postfix(stream, value); +} + +void* Write(void* stream, const char* data, std::int64_t count) { + return _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5writeEPKcl_nid_postfix(stream, data, count); +} + +void* Flush(void* stream) { + return _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5flushEv_nid_postfix(stream); +} + +void Clear(BasicIos& ios, std::uint32_t state) { + _ZNSt3__18ios_base5clearEj_nid_postfix(&ios, state); +} + +void TestClear() { + auto buffer = MakeBuffer(); + auto stream = MakeStream(&buffer); + Clear(stream.ios, EofBit | FailBit); + Require(stream.ios.base.state == (EofBit | FailBit)); + Clear(stream.ios, 0); + Require(stream.ios.base.state == 0); + + stream.ios.base.buffer = nullptr; + Clear(stream.ios, 0); + Require(stream.ios.base.state == BadBit); + Clear(stream.ios, EofBit); + Require(stream.ios.base.state == (EofBit | BadBit)); + + stream.ios.base.exceptions = BadBit; + RequireFailure([&] { Clear(stream.ios, 0); }); + Require(stream.ios.base.state == BadBit); + + stream.ios.base.buffer = &buffer; + Clear(stream.ios, EofBit); + Require(stream.ios.base.state == EofBit); + stream.ios.base.exceptions = FailBit; + RequireFailure([&] { Clear(stream.ios, FailBit | EofBit); }); + Require(stream.ios.base.state == (FailBit | EofBit)); + Clear(stream.ios, BadBit); + Require(stream.ios.base.state == BadBit); + + RequireInvalid([] { _ZNSt3__18ios_base5clearEj_nid_postfix(nullptr, 0); }); +} + +void TestSentry() { + auto buffer = MakeBuffer(); + auto stream = MakeStream(&buffer); + auto sentry = Open(&stream); + Require(sentry.ok && sentry.stream == &stream); + Close(sentry); + Require(buffer.syncCalls == 0 && stream.ios.base.state == 0); + + stream.ios.base.state = FailBit; + sentry = Open(&stream); + Require(!sentry.ok && sentry.stream == &stream); + stream.ios.base.state = 0; + + auto tieBuffer = MakeBuffer(); + NarrowStream tie; + Prepare(tie, &tieBuffer); + stream.ios.tie = &tie; + sentry = Open(&stream); + Require(sentry.ok && tieBuffer.syncCalls == 1 && buffer.syncCalls == 0); + tieBuffer.syncResult = Eof; + sentry = Open(&stream); + Require(sentry.ok && tieBuffer.syncCalls == 2 && tie.ios.base.state == BadBit && stream.ios.base.state == 0); + sentry = Open(&stream); + Require(sentry.ok && tieBuffer.syncCalls == 2); + stream.ios.base.state = EofBit; + sentry = Open(&stream); + Require(!sentry.ok && tieBuffer.syncCalls == 2); + stream.ios.base.state = 0; + stream.ios.tie = nullptr; + + stream.ios.base.flags = UnitBuffered; + sentry = Open(&stream); + Close(sentry); + Require(buffer.syncCalls == 1 && stream.ios.base.state == 0); + buffer.syncResult = Eof; + Close(sentry); + Require(buffer.syncCalls == 2 && stream.ios.base.state == BadBit); + Close(sentry); + Require(buffer.syncCalls == 2); + + stream.ios.base.state = 0; + stream.ios.base.exceptions = BadBit; + Close(sentry); + Require(buffer.syncCalls == 3 && stream.ios.base.state == BadBit); + + stream.ios.base.state = 0; + stream.ios.base.exceptions = 0; + buffer.syncThrows = true; + Close(sentry); + Require(buffer.syncCalls == 4 && stream.ios.base.state == 0); + buffer.syncThrows = false; + buffer.syncResult = 0; + + struct Closer { + Sentry* sentry; + ~Closer() { Close(*sentry); } + }; + RequireGuestError([&] { + Closer closer{&sentry}; + ThrowGuest(); + }); + Require(buffer.syncCalls == 4); + + stream.ios.base.flags = 0; + Close(sentry); + Require(buffer.syncCalls == 4); +} + +void TestPut() { + auto buffer = MakeBuffer(); + auto stream = MakeStream(&buffer); + Require(Put(&stream, 'a') == &stream); + Require(buffer.area[0] == 'a' && buffer.putCurrent == buffer.area + 1 && stream.ios.base.state == 0 && buffer.overflowCalls == 0); + + buffer.putCurrent = buffer.putEnd; + buffer.overflowResult = 0xff; + Put(&stream, static_cast(0xff)); + Require(buffer.overflowCalls == 1 && buffer.overflowValue == 0xff && stream.ios.base.state == 0); + buffer.overflowResult = Eof; + Put(&stream, 'b'); + Require(buffer.overflowCalls == 2 && buffer.overflowValue == 'b' && stream.ios.base.state == BadBit); + Put(&stream, 'c'); + Require(buffer.overflowCalls == 2); + + stream.ios.base.state = 0; + stream.ios.base.exceptions = BadBit; + RequireFailure([&] { Put(&stream, 'd'); }); + Require(buffer.overflowCalls == 3 && stream.ios.base.state == BadBit); + + stream.ios.base.state = 0; + stream.ios.base.exceptions = 0; + stream.ios.base.buffer = nullptr; + Put(&stream, 'e'); + Require(stream.ios.base.state == BadBit); + + stream.ios.base.buffer = &buffer; + stream.ios.base.state = 0; + stream.ios.base.flags = UnitBuffered; + buffer.putCurrent = buffer.area; + Put(&stream, 'f'); + Require(buffer.area[0] == 'f' && buffer.syncCalls == 1 && stream.ios.base.state == 0); +} + +void TestWrite() { + auto buffer = MakeBuffer(); + auto stream = MakeStream(&buffer); + Require(Write(&stream, "hello", 5) == &stream); + Require(buffer.sentCount == 5 && std::memcmp(buffer.sent, "hello", 5) == 0 && stream.ios.base.state == 0); + + Write(&stream, "x", 0); + Require(buffer.xsputnCalls == 1); + + buffer.accepted = 2; + Write(&stream, "world", 5); + Require(buffer.xsputnCalls == 2 && buffer.sentCount == 7 && stream.ios.base.state == BadBit); + Write(&stream, "more", 4); + Require(buffer.xsputnCalls == 2); + + stream.ios.base.state = 0; + buffer.xsputnThrows = true; + Write(&stream, "z", 1); + Require(buffer.xsputnCalls == 3 && stream.ios.base.state == BadBit); + + stream.ios.base.state = EofBit; + stream.ios.base.exceptions = BadBit; + Write(&stream, "z", 1); + Require(buffer.xsputnCalls == 3 && stream.ios.base.state == EofBit); + stream.ios.base.state = 0; + RequireGuestError([&] { Write(&stream, "z", 1); }); + Require(buffer.xsputnCalls == 4 && stream.ios.base.state == BadBit); + + stream.ios.base.state = 0; + stream.ios.base.exceptions = FailBit; + Write(&stream, "z", 1); + Require(buffer.xsputnCalls == 5 && stream.ios.base.state == BadBit); + stream.ios.base.state = FailBit; + Write(&stream, "z", 1); + Require(buffer.xsputnCalls == 5 && stream.ios.base.state == FailBit); +} + +void TestFlush() { + auto buffer = MakeBuffer(); + auto stream = MakeStream(&buffer); + Require(Flush(&stream) == &stream); + Require(buffer.syncCalls == 1 && stream.ios.base.state == 0); + buffer.syncResult = Eof; + Flush(&stream); + Require(buffer.syncCalls == 2 && stream.ios.base.state == BadBit); + Flush(&stream); + Require(buffer.syncCalls == 2); + + stream.ios.base.state = 0; + stream.ios.base.buffer = nullptr; + Flush(&stream); + Require(stream.ios.base.state == 0); + + stream.ios.base.buffer = &buffer; + buffer.syncResult = 0; + buffer.syncThrows = true; + Flush(&stream); + Require(buffer.syncCalls == 3 && stream.ios.base.state == BadBit); + stream.ios.base.state = 0; + stream.ios.base.exceptions = BadBit; + RequireGuestError([&] { Flush(&stream); }); + Require(buffer.syncCalls == 4 && stream.ios.base.state == BadBit); +} + +int erased = 0; +void* erasedStream = nullptr; + +void APS5_VABI CountErase(int event, void* stream, int index) { + Require(event == 0 && index == 7); + ++erased; + erasedStream = stream; +} + +void TestDestructors() { + auto buffer = MakeBuffer(); + auto stream = MakeStream(&buffer); + _ZNSt3__18ios_base4initEPv_nid_postfix(&stream.ios, &buffer); + auto* const callbacks = static_cast(malloc_nid_postfix(sizeof(GuestLocale::LibcxxIosCallback))); + auto* const indexes = static_cast(malloc_nid_postfix(sizeof(int))); + callbacks[0] = CountErase; + indexes[0] = 7; + stream.ios.base.callbacks = callbacks; + stream.ios.base.callbackIndexes = indexes; + stream.ios.base.callbackCount = 1; + stream.ios.base.callbackCapacity = 1; + + WideStream before; + std::memcpy(&before, &stream, sizeof(stream)); + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED2Ev_nid_postfix(&stream, nullptr); + Require(erased == 0 && std::memcmp(&before, &stream, sizeof(stream)) == 0); + + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(&stream); + Require(erased == 1 && erasedStream == &stream.ios); +} + +void TestInvalid() { + RequireInvalid([] { Put(nullptr, 'a'); }); + RequireInvalid([] { Write(nullptr, "a", 1); }); + RequireInvalid([] { Flush(nullptr); }); + RequireInvalid([] { _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(nullptr); }); + Sentry sentry{}; + RequireInvalid([&] { _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE6sentryC1ERS3__nid_postfix(&sentry, nullptr); }); + RequireInvalid([&] { Close(sentry); }); + + WideStream unrooted{}; + RequireInvalid([&] { Put(&unrooted, 'a'); }); + + auto buffer = MakeBuffer(); + buffer.vtable = emptyVtable; + auto stream = MakeStream(&buffer); + RequireInvalid([&] { Write(&stream, "a", 1); }); + RequireInvalid([&] { Flush(&stream); }); + Require(stream.ios.base.state == 0); + buffer.vtable = nullptr; + RequireInvalid([&] { Write(&stream, "a", 1); }); + Require(stream.ios.base.state == 0); + + stream.ios.base.buffer = nullptr; + stream.ios.base.state = 0; + RequireInvalid([&] { Write(&stream, "a", 1); }); + Require(stream.ios.base.state == 0); +} + +} + +int main() { + ApplicationHeapInitialize_nid_no_patch(ApplicationEmptyProcessParameters_nid_no_patch()); + TestClear(); + TestSentry(); + TestPut(); + TestWrite(); + TestFlush(); + TestDestructors(); + TestInvalid(); + std::puts("libc++ ostream tests passed"); + return 0; +} diff --git a/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md b/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md new file mode 100644 index 000000000000..15b104aa550b --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ basic_ostream](../../../core/libs/prx/libc/src/LibcxxOstream.cpp) (libc) - `ios_base::clear`, the `sentry` constructor and destructor, `put`, `write`, `flush` and the complete and base destructors follow [LLVM libc++ 17.0.6](https://github.com/llvm/llvm-project/blob/llvmorg-17.0.6/libcxx/include/ostream) ``, ``, `` and `ios.cpp`, not a console module. The base destructor does nothing and ignores its VTT, as clang emits no vtable pointer stores for the empty destructor body; the complete destructor runs the `basic_ios` base destructor on the virtual base found through the vtable's virtual-base offset. Both are unmeasured. A null or unreadable stream, stream buffer or vtable and a missing stream buffer virtual function throw `invalid_argument`, which `put`, `write`, `flush` and the sentry destructor let through instead of setting `badbit`, where libc++ crashes. The `operator<<` overloads are not exported. From d8c362890068869873706228dc3fcea4191fbe85 Mon Sep 17 00:00:00 2001 From: LeandroLP23 Date: Thu, 3 Dec 2026 12:04:26 +0100 Subject: [PATCH 12/18] test(libc): build the ostream fixtures in place and describe null stream buffers per export MakeStream and MakeBuffer returned objects that point into themselves, so the test relied on copy elision. The fixtures are now set up in the caller's objects. The debt entry now says what each export does with no stream buffer, instead of listing them all as throwing. Co-Authored-By: Claude Opus 5.5 --- core/libs/tests/GuestLibcxxOstream.cpp | 54 +++++++++++-------- .../changes/feat-libc-libcxx-ostream-core.md | 2 +- 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/core/libs/tests/GuestLibcxxOstream.cpp b/core/libs/tests/GuestLibcxxOstream.cpp index 85f7d259005a..96cf6a82d11c 100644 --- a/core/libs/tests/GuestLibcxxOstream.cpp +++ b/core/libs/tests/GuestLibcxxOstream.cpp @@ -131,13 +131,11 @@ const void* const bufferVtable[14]{ const void* const emptyVtable[14]{}; -Buffer MakeBuffer() { - Buffer buffer; +void InitBuffer(Buffer& buffer) { buffer.vtable = bufferVtable; buffer.putStart = buffer.area; buffer.putCurrent = buffer.area; buffer.putEnd = buffer.area + sizeof(buffer.area); - return buffer; } struct BasicIos { @@ -172,11 +170,9 @@ void Prepare(TStream& stream, Buffer* buffer) { stream.ios.base.state = buffer == nullptr ? BadBit : 0; } -WideStream MakeStream(Buffer* buffer) { - WideStream stream; +void InitStream(WideStream& stream, Buffer* buffer) { std::memset(stream.gap, 0xa5, sizeof(stream.gap)); Prepare(stream, buffer); - return stream; } struct Sentry { @@ -212,8 +208,10 @@ void Clear(BasicIos& ios, std::uint32_t state) { } void TestClear() { - auto buffer = MakeBuffer(); - auto stream = MakeStream(&buffer); + Buffer buffer; + InitBuffer(buffer); + WideStream stream; + InitStream(stream, &buffer); Clear(stream.ios, EofBit | FailBit); Require(stream.ios.base.state == (EofBit | FailBit)); Clear(stream.ios, 0); @@ -242,8 +240,10 @@ void TestClear() { } void TestSentry() { - auto buffer = MakeBuffer(); - auto stream = MakeStream(&buffer); + Buffer buffer; + InitBuffer(buffer); + WideStream stream; + InitStream(stream, &buffer); auto sentry = Open(&stream); Require(sentry.ok && sentry.stream == &stream); Close(sentry); @@ -254,7 +254,8 @@ void TestSentry() { Require(!sentry.ok && sentry.stream == &stream); stream.ios.base.state = 0; - auto tieBuffer = MakeBuffer(); + Buffer tieBuffer; + InitBuffer(tieBuffer); NarrowStream tie; Prepare(tie, &tieBuffer); stream.ios.tie = &tie; @@ -310,8 +311,10 @@ void TestSentry() { } void TestPut() { - auto buffer = MakeBuffer(); - auto stream = MakeStream(&buffer); + Buffer buffer; + InitBuffer(buffer); + WideStream stream; + InitStream(stream, &buffer); Require(Put(&stream, 'a') == &stream); Require(buffer.area[0] == 'a' && buffer.putCurrent == buffer.area + 1 && stream.ios.base.state == 0 && buffer.overflowCalls == 0); @@ -345,8 +348,10 @@ void TestPut() { } void TestWrite() { - auto buffer = MakeBuffer(); - auto stream = MakeStream(&buffer); + Buffer buffer; + InitBuffer(buffer); + WideStream stream; + InitStream(stream, &buffer); Require(Write(&stream, "hello", 5) == &stream); Require(buffer.sentCount == 5 && std::memcmp(buffer.sent, "hello", 5) == 0 && stream.ios.base.state == 0); @@ -382,8 +387,10 @@ void TestWrite() { } void TestFlush() { - auto buffer = MakeBuffer(); - auto stream = MakeStream(&buffer); + Buffer buffer; + InitBuffer(buffer); + WideStream stream; + InitStream(stream, &buffer); Require(Flush(&stream) == &stream); Require(buffer.syncCalls == 1 && stream.ios.base.state == 0); buffer.syncResult = Eof; @@ -418,8 +425,10 @@ void APS5_VABI CountErase(int event, void* stream, int index) { } void TestDestructors() { - auto buffer = MakeBuffer(); - auto stream = MakeStream(&buffer); + Buffer buffer; + InitBuffer(buffer); + WideStream stream; + InitStream(stream, &buffer); _ZNSt3__18ios_base4initEPv_nid_postfix(&stream.ios, &buffer); auto* const callbacks = static_cast(malloc_nid_postfix(sizeof(GuestLocale::LibcxxIosCallback))); auto* const indexes = static_cast(malloc_nid_postfix(sizeof(int))); @@ -451,9 +460,12 @@ void TestInvalid() { WideStream unrooted{}; RequireInvalid([&] { Put(&unrooted, 'a'); }); - auto buffer = MakeBuffer(); + Buffer buffer; + + InitBuffer(buffer); buffer.vtable = emptyVtable; - auto stream = MakeStream(&buffer); + WideStream stream; + InitStream(stream, &buffer); RequireInvalid([&] { Write(&stream, "a", 1); }); RequireInvalid([&] { Flush(&stream); }); Require(stream.ios.base.state == 0); diff --git a/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md b/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md index 15b104aa550b..7daf4d0f058f 100644 --- a/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md +++ b/docs/dev/debt/changes/feat-libc-libcxx-ostream-core.md @@ -2,4 +2,4 @@ ## add Functional -- [libc++ basic_ostream](../../../core/libs/prx/libc/src/LibcxxOstream.cpp) (libc) - `ios_base::clear`, the `sentry` constructor and destructor, `put`, `write`, `flush` and the complete and base destructors follow [LLVM libc++ 17.0.6](https://github.com/llvm/llvm-project/blob/llvmorg-17.0.6/libcxx/include/ostream) ``, ``, `` and `ios.cpp`, not a console module. The base destructor does nothing and ignores its VTT, as clang emits no vtable pointer stores for the empty destructor body; the complete destructor runs the `basic_ios` base destructor on the virtual base found through the vtable's virtual-base offset. Both are unmeasured. A null or unreadable stream, stream buffer or vtable and a missing stream buffer virtual function throw `invalid_argument`, which `put`, `write`, `flush` and the sentry destructor let through instead of setting `badbit`, where libc++ crashes. The `operator<<` overloads are not exported. +- [libc++ basic_ostream](../../../core/libs/prx/libc/src/LibcxxOstream.cpp) (libc) - `ios_base::clear`, the `sentry` constructor and destructor, `put`, `write`, `flush` and the complete and base destructors follow [LLVM libc++ 17.0.6](https://github.com/llvm/llvm-project/blob/llvmorg-17.0.6/libcxx/include/ostream) ``, ``, `` and `ios.cpp`, not a console module. The base destructor does nothing and ignores its VTT, as clang emits no vtable pointer stores for the empty destructor body; the complete destructor runs the `basic_ios` base destructor on the virtual base found through the vtable's virtual-base offset. Both are unmeasured. With no stream buffer, `put` sets `badbit`, and `flush` and the sentry destructor do nothing, as in libc++; a nonzero `write` on a good stream with no stream buffer throws `invalid_argument`, where libc++ crashes. A null or unreadable stream, stream buffer vtable or vtable, and a missing stream buffer virtual function, also throw `invalid_argument`, and the exports let it through instead of setting `badbit`. The `operator<<` overloads are not exported. From 6d0f8e190aeba9c4903a918865bf68f3a66ddba2 Mon Sep 17 00:00:00 2001 From: Mihai Date: Thu, 3 Dec 2026 15:55:26 +0200 Subject: [PATCH 13/18] feat(libc): expose libc++ input stream type information --- core/libs/prx/libc/src/exception/TypeInfo.cpp | 26 ++++++++++++++++++ core/libs/tests/GuestDynamicCast.cpp | 27 +++++++++++++++++++ .../changes/feat-libc-input-stream-rtti.md | 5 ++++ 3 files changed, 58 insertions(+) create mode 100644 docs/dev/debt/changes/feat-libc-input-stream-rtti.md diff --git a/core/libs/prx/libc/src/exception/TypeInfo.cpp b/core/libs/prx/libc/src/exception/TypeInfo.cpp index 856c5baf7c22..a29c71f9495e 100644 --- a/core/libs/prx/libc/src/exception/TypeInfo.cpp +++ b/core/libs/prx/libc/src/exception/TypeInfo.cpp @@ -287,3 +287,29 @@ LibcException::PointerTypeRecord _ZTIPKDi_nid_postfix {PointerVtable(), "PKDi", LibcException::PointerTypeRecord _ZTIPKDu_nid_postfix {PointerVtable(), "PKDu", 1, AsTypeInfo(_ZTIDu_nid_postfix)}; LibcException::PointerTypeRecord _ZTIPKDh_nid_postfix {PointerVtable(), "PKDh", 1, AsTypeInfo(_ZTIDh_nid_postfix)}; } + +namespace { + +constexpr std::int64_t PublicVirtualBase = + (-3 * static_cast(sizeof(void*)) * 256) | 3; + +} + +extern "C" { + +extern constinit const FundamentalTypeRecord _ZTINSt3__18ios_baseE_nid_postfix { + &_ZTVN10__cxxabiv117__class_type_infoE_nid_postfix.destroy, "NSt3__18ios_baseE", +}; + +extern const LibcException::TypeRecord _ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix { + SingleVtable(), "NSt3__19basic_iosIcNS_11char_traitsIcEEEE", + reinterpret_cast(&_ZTINSt3__18ios_baseE_nid_postfix), +}; + +extern const LibcException::MultipleTypeRecord<1> _ZTINSt3__113basic_istreamIcNS_11char_traitsIcEEEE_nid_postfix { + reinterpret_cast(&_ZTVN10__cxxabiv121__vmi_class_type_infoE_nid_postfix) + 2, + "NSt3__113basic_istreamIcNS_11char_traitsIcEEEE", 0, 1, + {{&_ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix, PublicVirtualBase}}, +}; + +} diff --git a/core/libs/tests/GuestDynamicCast.cpp b/core/libs/tests/GuestDynamicCast.cpp index a8b18f56c8a4..57dd8a11d13f 100644 --- a/core/libs/tests/GuestDynamicCast.cpp +++ b/core/libs/tests/GuestDynamicCast.cpp @@ -26,6 +26,8 @@ extern "C" { extern const unsigned char _ZTVN10__cxxabiv117__class_type_infoE_nid_postfix[]; extern const unsigned char _ZTVN10__cxxabiv120__si_class_type_infoE_nid_postfix[]; extern const unsigned char _ZTVN10__cxxabiv121__vmi_class_type_infoE_nid_postfix[]; +extern const LibcException::TypeRecord _ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix; +extern const LibcException::MultipleTypeRecord<1> _ZTINSt3__113basic_istreamIcNS_11char_traitsIcEEEE_nid_postfix; } namespace { @@ -95,9 +97,34 @@ bool CallDynamicCast(const TypeRecord* type, const TypeRecord* destination, cons return function(type, hint, 6, destination, object, source, sourceObject, result); } +void CheckLibcxxInputStreamTypes() { + const auto& ios = _ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix; + const auto& input = _ZTINSt3__113basic_istreamIcNS_11char_traitsIcEEEE_nid_postfix; + const auto* const base = ios.base; + Require(base != nullptr && std::strcmp(base->name, "NSt3__18ios_baseE") == 0); + Require(std::strcmp(ios.name, "NSt3__19basic_iosIcNS_11char_traitsIcEEEE") == 0); + Require(std::strcmp(input.name, "NSt3__113basic_istreamIcNS_11char_traitsIcEEEE") == 0); + Require(static_cast(base->vtable) == BaseType.vtable); + Require(static_cast(ios.vtable) == DerivedType.vtable); + Require(static_cast(input.vtable) == VirtualType.vtable); + Require(input.flags == 0 && input.baseCount == 1 && input.bases[0].type == &ios); + Require(input.bases[0].offsetFlags == (VirtualBaseSlot | 3)); + + constexpr auto baseOffset = 2 * static_cast(sizeof(void*)); + const auto dynamicType = reinterpret_cast(&input); + const std::array primary{static_cast(baseOffset), 0, dynamicType, 0}; + const std::array secondary{static_cast(-baseOffset), dynamicType, 0}; + const std::array stream{primary.data() + 3, nullptr, secondary.data() + 2}; + using ClassType = __cxxabiv1::__class_type_info; + const auto* inputType = reinterpret_cast(&input); + Require(__dynamic_cast_nid_postfix(&stream[2], reinterpret_cast(&ios), inputType, -1) == stream.data()); + Require(__dynamic_cast_nid_postfix(&stream[2], reinterpret_cast(base), inputType, -1) == stream.data()); +} + } // namespace int main() { + CheckLibcxxInputStreamTypes(); const Object derived{&DerivedVtable.first}; const Object base{&BaseVtable.first}; Require(__dynamic_cast_nid_postfix(&derived, reinterpret_cast(&BaseType), reinterpret_cast(&DerivedType), 0) == &derived); diff --git a/docs/dev/debt/changes/feat-libc-input-stream-rtti.md b/docs/dev/debt/changes/feat-libc-input-stream-rtti.md new file mode 100644 index 000000000000..4437b33d58a0 --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-input-stream-rtti.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ input-stream type information](../../../core/libs/prx/libc/src/exception/TypeInfo.cpp) (libc) - The retail firmware layouts and provider are unverified. These three type records follow the PS5 Payload SDK v0.42 inheritance and virtual-base offset. From bc6314e6ddf78ff4de9a4cf9377be755121f7a03 Mon Sep 17 00:00:00 2001 From: JJenkx <31495916+JJenkx@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:47:23 -0500 Subject: [PATCH 14/18] feat(libc): expose narrow libc++ stream vtables --- .../prx/libc/include/LibcxxStreamVtables.hpp | 62 +++++++++++++++ core/libs/prx/libc/src/LibcxxIosInit.cpp | 27 ++++++- core/libs/prx/libc/src/LibcxxOstream.cpp | 42 +++++++++- core/libs/prx/libc/src/exception/TypeInfo.cpp | 18 +++++ core/libs/tests/GuestLibcxxOstream.cpp | 78 ++++++++++++++++--- 5 files changed, 213 insertions(+), 14 deletions(-) create mode 100644 core/libs/prx/libc/include/LibcxxStreamVtables.hpp diff --git a/core/libs/prx/libc/include/LibcxxStreamVtables.hpp b/core/libs/prx/libc/include/LibcxxStreamVtables.hpp new file mode 100644 index 000000000000..e299e29b8634 --- /dev/null +++ b/core/libs/prx/libc/include/LibcxxStreamVtables.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include "general/VabiMacros.hpp" +#include +#include + +namespace LibcException { +struct TypeRecord; +template +struct MultipleTypeRecord; +} + +namespace GuestLocale { + +using StreamDestructor = void (APS5_VABI*)(void*); + +struct StreamDestructors { + StreamDestructor complete; + StreamDestructor deleting; +}; + +struct SimpleStreamVtable { + std::ptrdiff_t offsetToTop; + const void* type; + StreamDestructors destructors; +}; + +struct VirtualIosStreamVtable { + std::ptrdiff_t iosOffset; + SimpleStreamVtable primary; + std::ptrdiff_t iosVcallOffset; + SimpleStreamVtable secondary; +}; + +static_assert(offsetof(SimpleStreamVtable, destructors) == 0x10); +static_assert(sizeof(SimpleStreamVtable) == 0x20); +static_assert(offsetof(VirtualIosStreamVtable, primary) == 0x08); +static_assert(offsetof(VirtualIosStreamVtable, iosVcallOffset) == 0x28); +static_assert(offsetof(VirtualIosStreamVtable, secondary) == 0x30); +static_assert(sizeof(VirtualIosStreamVtable) == 0x50); + +} + +extern "C" { + +extern const GuestLocale::SimpleStreamVtable _ZTVNSt3__18ios_baseE_nid_postfix; +extern const GuestLocale::SimpleStreamVtable _ZTVNSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix; +extern const GuestLocale::VirtualIosStreamVtable _ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; +extern const std::array _ZTTNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; +extern const LibcException::TypeRecord _ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix; +extern const LibcException::MultipleTypeRecord<1> _ZTINSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; + +void APS5_VABI _ZNSt3__18ios_baseD0Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__18ios_baseD1Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__18ios_baseD2Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED0Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED1Ev_nid_postfix(void* self); +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix(void* self); +void APS5_VABI _ZTv0_n24_NSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix(void* self); +void APS5_VABI _ZTv0_n24_NSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(void* self); + +} diff --git a/core/libs/prx/libc/src/LibcxxIosInit.cpp b/core/libs/prx/libc/src/LibcxxIosInit.cpp index 8ce2493039bd..529c28a92a86 100644 --- a/core/libs/prx/libc/src/LibcxxIosInit.cpp +++ b/core/libs/prx/libc/src/LibcxxIosInit.cpp @@ -1,4 +1,5 @@ #include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" #include "prx/libc/include/Api.hpp" #include "prx/libc/include/GuestLocale.hpp" #include "prx/libc/include/GuestPtr.hpp" @@ -108,9 +109,11 @@ void* APS5_VABI _ZNSt3__18ios_base5imbueERKNS_6localeE_nid_postfix(void* result, return result; } -void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED2Ev_nid_postfix(void* self) { +void APS5_VABI _ZNSt3__18ios_baseD2Ev_nid_postfix(void* self) { auto* const ios = static_cast(self); if (Read(&ios->locale).imp == nullptr) return; + const void* const addressPoint = &_ZTVNSt3__18ios_baseE_nid_postfix.destructors; + Write(&ios->vtable, addressPoint); Notify(ios, EraseEvent); auto base = Read(ios); _ZNSt3__16localeD1Ev_nid_postfix(&base.locale); @@ -120,4 +123,26 @@ void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED2Ev_nid_postfix(void* free_nid_postfix(base.pointers); } +void APS5_VABI _ZNSt3__18ios_baseD1Ev_nid_postfix(void* self) { + _ZNSt3__18ios_baseD2Ev_nid_postfix(self); +} + +void APS5_VABI _ZNSt3__18ios_baseD0Ev_nid_postfix(void* self) { + _ZNSt3__18ios_baseD2Ev_nid_postfix(self); + _ZdlPv_nid_postfix(self); +} + +void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED2Ev_nid_postfix(void* self) { + _ZNSt3__18ios_baseD2Ev_nid_postfix(self); +} + +void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED1Ev_nid_postfix(void* self) { + _ZNSt3__18ios_baseD2Ev_nid_postfix(self); +} + +void APS5_VABI _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED0Ev_nid_postfix(void* self) { + _ZNSt3__18ios_baseD2Ev_nid_postfix(self); + _ZdlPv_nid_postfix(self); +} + } diff --git a/core/libs/prx/libc/src/LibcxxOstream.cpp b/core/libs/prx/libc/src/LibcxxOstream.cpp index a580b1c84b71..d94674fc40a4 100644 --- a/core/libs/prx/libc/src/LibcxxOstream.cpp +++ b/core/libs/prx/libc/src/LibcxxOstream.cpp @@ -1,4 +1,5 @@ #include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" #include "prx/libc/include/Api.hpp" #include "prx/libc/include/GuestLocale.hpp" #include "prx/libc/include/GuestPtr.hpp" @@ -96,12 +97,16 @@ TMethod Virtual(Streambuf* buffer, TMethod StreambufVtable::*slot) { return method; } -BasicIos* IosOf(void* stream) { - if (stream == nullptr) Inaccessible("libc++ ostream: null object"); - const auto* vtable = Read(static_cast(stream)); +void* AdjustVirtualBase(void* object) { + if (object == nullptr) Inaccessible("libc++ ostream: null object"); + const auto* vtable = Read(static_cast(object)); if (vtable == nullptr) Inaccessible("libc++ ostream: null vtable"); const auto offset = Read(reinterpret_cast(vtable + VirtualBaseOffsetSlot)); - return reinterpret_cast(static_cast(stream) + offset); + return static_cast(object) + offset; +} + +BasicIos* IosOf(void* stream) { + return static_cast(AdjustVirtualBase(stream)); } Streambuf* BufferOf(BasicIos* ios) { @@ -246,4 +251,33 @@ void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(v void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED2Ev_nid_postfix(void*, const void* const*) {} +void APS5_VABI _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix(void* self) { + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(self); + _ZdlPv_nid_postfix(self); +} + +void APS5_VABI _ZTv0_n24_NSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(void* self) { + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix(AdjustVirtualBase(self)); +} + +void APS5_VABI _ZTv0_n24_NSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix(void* self) { + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix(AdjustVirtualBase(self)); +} + +constinit const GuestLocale::VirtualIosStreamVtable _ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix { + 0x08, + {0, &_ZTINSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix, + {_ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix, + _ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix}}, + -0x08, + {-0x08, &_ZTINSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix, + {_ZTv0_n24_NSt3__113basic_ostreamIcNS_11char_traitsIcEEED1Ev_nid_postfix, + _ZTv0_n24_NSt3__113basic_ostreamIcNS_11char_traitsIcEEED0Ev_nid_postfix}}, +}; + +constinit const std::array _ZTTNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix { + &_ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix.primary.destructors, + &_ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix.secondary.destructors, +}; + } diff --git a/core/libs/prx/libc/src/exception/TypeInfo.cpp b/core/libs/prx/libc/src/exception/TypeInfo.cpp index a29c71f9495e..66c08a5bd9fb 100644 --- a/core/libs/prx/libc/src/exception/TypeInfo.cpp +++ b/core/libs/prx/libc/src/exception/TypeInfo.cpp @@ -1,4 +1,5 @@ #include "prx/libc/include/Api.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" #include "prx/libc/include/exceptions/Runtime.hpp" #include #include @@ -312,4 +313,21 @@ extern const LibcException::MultipleTypeRecord<1> _ZTINSt3__113basic_istreamIcNS {{&_ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix, PublicVirtualBase}}, }; +const LibcException::MultipleTypeRecord<1> _ZTINSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix { + reinterpret_cast(&_ZTVN10__cxxabiv121__vmi_class_type_infoE_nid_postfix) + 2, + "NSt3__113basic_ostreamIcNS_11char_traitsIcEEEE", 0, 1, + {{&_ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix, PublicVirtualBase}}, +}; + +constinit const GuestLocale::SimpleStreamVtable _ZTVNSt3__18ios_baseE_nid_postfix { + 0, &_ZTINSt3__18ios_baseE_nid_postfix, + {_ZNSt3__18ios_baseD1Ev_nid_postfix, _ZNSt3__18ios_baseD0Ev_nid_postfix}, +}; + +constinit const GuestLocale::SimpleStreamVtable _ZTVNSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix { + 0, &_ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix, + {_ZNSt3__19basic_iosIcNS_11char_traitsIcEEED1Ev_nid_postfix, + _ZNSt3__19basic_iosIcNS_11char_traitsIcEEED0Ev_nid_postfix}, +}; + } diff --git a/core/libs/tests/GuestLibcxxOstream.cpp b/core/libs/tests/GuestLibcxxOstream.cpp index 96cf6a82d11c..52f8901fba88 100644 --- a/core/libs/tests/GuestLibcxxOstream.cpp +++ b/core/libs/tests/GuestLibcxxOstream.cpp @@ -2,6 +2,7 @@ #include "prx/libc/include/ApplicationHeap.hpp" #include "prx/libc/include/GuestLocale.hpp" #include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" #include #include #include @@ -10,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -417,11 +419,25 @@ void TestFlush() { int erased = 0; void* erasedStream = nullptr; +const void* erasedVtable = nullptr; void APS5_VABI CountErase(int event, void* stream, int index) { Require(event == 0 && index == 7); ++erased; erasedStream = stream; + erasedVtable = static_cast(stream)->base.vtable; +} + +void InstallErase(BasicIos& ios, void* buffer) { + _ZNSt3__18ios_base4initEPv_nid_postfix(&ios, buffer); + auto* const callbacks = static_cast(malloc_nid_postfix(sizeof(GuestLocale::LibcxxIosCallback))); + auto* const indexes = static_cast(malloc_nid_postfix(sizeof(int))); + callbacks[0] = CountErase; + indexes[0] = 7; + ios.base.callbacks = callbacks; + ios.base.callbackIndexes = indexes; + ios.base.callbackCount = 1; + ios.base.callbackCapacity = 1; } void TestDestructors() { @@ -429,15 +445,7 @@ void TestDestructors() { InitBuffer(buffer); WideStream stream; InitStream(stream, &buffer); - _ZNSt3__18ios_base4initEPv_nid_postfix(&stream.ios, &buffer); - auto* const callbacks = static_cast(malloc_nid_postfix(sizeof(GuestLocale::LibcxxIosCallback))); - auto* const indexes = static_cast(malloc_nid_postfix(sizeof(int))); - callbacks[0] = CountErase; - indexes[0] = 7; - stream.ios.base.callbacks = callbacks; - stream.ios.base.callbackIndexes = indexes; - stream.ios.base.callbackCount = 1; - stream.ios.base.callbackCapacity = 1; + InstallErase(stream.ios, &buffer); WideStream before; std::memcpy(&before, &stream, sizeof(stream)); @@ -448,6 +456,57 @@ void TestDestructors() { Require(erased == 1 && erasedStream == &stream.ios); } +void TestGuestVtables() { + const auto& baseTable = _ZTVNSt3__18ios_baseE_nid_postfix; + const auto& iosTable = _ZTVNSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix; + const auto& ostreamTable = _ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; + const auto& ostreamVtt = _ZTTNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; + const auto& iosType = _ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix; + const auto& ostreamType = _ZTINSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; + + Require(baseTable.offsetToTop == 0 && baseTable.type == iosType.base); + Require(iosTable.offsetToTop == 0 && iosTable.type == &iosType); + Require(ostreamTable.iosOffset == 0x08 && ostreamTable.primary.offsetToTop == 0); + Require(ostreamTable.iosVcallOffset == -0x08 && ostreamTable.secondary.offsetToTop == -0x08); + Require(ostreamTable.primary.type == &ostreamType && ostreamTable.secondary.type == &ostreamType); + Require(ostreamVtt[0] == &ostreamTable.primary.destructors && + ostreamVtt[1] == &ostreamTable.secondary.destructors); + Require(std::strcmp(ostreamType.name, "NSt3__113basic_ostreamIcNS_11char_traitsIcEEEE") == 0 && + ostreamType.flags == 0 && ostreamType.baseCount == 1 && + ostreamType.bases[0].type == &iosType && ostreamType.bases[0].offsetFlags == -0x17fd); + + auto initialize = [&](NarrowStream& stream) { + stream.vptr = static_cast(ostreamVtt[0]); + stream.ios.base.vtable = ostreamVtt[1]; + InstallErase(stream.ios, nullptr); + }; + + NarrowStream stream; + initialize(stream); + using ClassType = __cxxabiv1::__class_type_info; + const auto* const target = reinterpret_cast(&ostreamType); + Require(__dynamic_cast_nid_postfix(&stream.ios, reinterpret_cast(&iosType), target, -1) == &stream); + Require(__dynamic_cast_nid_postfix(&stream.ios, reinterpret_cast(iosType.base), target, -1) == &stream); + int expected = erased; + ostreamTable.secondary.destructors.complete(&stream.ios); + Require(erased == ++expected && erasedStream == &stream.ios && erasedVtable == &baseTable.destructors); + + for (bool secondary : {false, true}) { + auto* const heapStream = std::construct_at(static_cast(_Znwm_nid_postfix(sizeof(NarrowStream)))); + initialize(*heapStream); + if (secondary) ostreamTable.secondary.destructors.deleting(&heapStream->ios); + else ostreamTable.primary.destructors.deleting(heapStream); + Require(erased == ++expected && erasedVtable == &baseTable.destructors); + } + for (const auto* table : {&baseTable, &iosTable}) { + auto* const heapIos = std::construct_at(static_cast(_Znwm_nid_postfix(sizeof(BasicIos)))); + heapIos->base.vtable = &table->destructors; + InstallErase(*heapIos, nullptr); + table->destructors.deleting(heapIos); + Require(erased == ++expected && erasedVtable == &baseTable.destructors); + } +} + void TestInvalid() { RequireInvalid([] { Put(nullptr, 'a'); }); RequireInvalid([] { Write(nullptr, "a", 1); }); @@ -489,6 +548,7 @@ int main() { TestWrite(); TestFlush(); TestDestructors(); + TestGuestVtables(); TestInvalid(); std::puts("libc++ ostream tests passed"); return 0; From cc91cc642ed0f221838b8ebaf7b89fa40861ca50 Mon Sep 17 00:00:00 2001 From: JJenkx <31495916+JJenkx@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:53:18 -0500 Subject: [PATCH 15/18] docs(libc): record the ios_base destructor vtable transition --- docs/dev/debt/changes/feat-libc-libcxx-ios-base.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/debt/changes/feat-libc-libcxx-ios-base.md b/docs/dev/debt/changes/feat-libc-libcxx-ios-base.md index a39eaa0dfd28..fae0e8f45314 100644 --- a/docs/dev/debt/changes/feat-libc-libcxx-ios-base.md +++ b/docs/dev/debt/changes/feat-libc-libcxx-ios-base.md @@ -2,4 +2,4 @@ ## add Functional -- [libc++ ios_base](../../../core/libs/prx/libc/src/LibcxxIosInit.cpp) (libc) - `ios_base::init`, `getloc`, `imbue` and the `basic_ios` base destructor follow LLVM libc++ 17.0.6 (``, `ios.cpp`), not measured on a console. The destructor leaves the object's vtable pointer as it is, since the `basic_ios` and `ios_base` vtables are not exported, so an erase callback sees the stream's own type. `register_callback`, `iword`, `pword` and `copyfmt` are not exported. +- [libc++ ios_base](../../../core/libs/prx/libc/src/LibcxxIosInit.cpp) (libc) - `ios_base::init`, `getloc` and `imbue` follow LLVM libc++ 17.0.6. Initialized streams switch to the `ios_base` vtable before erase callbacks, as in the [PS5 Payload SDK v0.42](https://github.com/ps5-payload-dev/sdk/releases/tag/v0.42). An exception from an erase callback propagates in AnyPS5. The SDK terminates in that case. `register_callback`, `iword`, `pword` and `copyfmt` remain unexported. Console execution is unverified. From 2016b6a5c16e7374e49d0af2d19b93b47e019e64 Mon Sep 17 00:00:00 2001 From: JJenkx <31495916+JJenkx@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:15:26 -0500 Subject: [PATCH 16/18] fix(libc): address narrow stream vtable review --- core/libs/prx/libc/libc.hpp | 1 + core/libs/prx/libc/src/LibcxxOstream.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/core/libs/prx/libc/libc.hpp b/core/libs/prx/libc/libc.hpp index cd6864cd6c72..03252c9be236 100644 --- a/core/libs/prx/libc/libc.hpp +++ b/core/libs/prx/libc/libc.hpp @@ -11,3 +11,4 @@ #include "prx/libc/include/LibcxxStringbufSet.hpp" #include "prx/libc/include/WindowsFormatting.hpp" #include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" diff --git a/core/libs/prx/libc/src/LibcxxOstream.cpp b/core/libs/prx/libc/src/LibcxxOstream.cpp index d94674fc40a4..bbaa1e97e251 100644 --- a/core/libs/prx/libc/src/LibcxxOstream.cpp +++ b/core/libs/prx/libc/src/LibcxxOstream.cpp @@ -129,6 +129,7 @@ Streambuf* BufferOf(BasicIos* ios) { } void Clear(LibcxxIosBase* ios, std::uint32_t state) { + if (ios == nullptr) Inaccessible("libc++ ostream: null ios_base"); const bool buffered = Read(&ios->buffer) != nullptr; Write(&ios->state, buffered ? state : state | BadBit); if (((state | (buffered ? 0u : BadBit)) & Read(&ios->exceptions)) != 0) ThrowFailure("ios_base::clear"); From e530cbb2461cb30a405c0aa7268ec5153db4a76f Mon Sep 17 00:00:00 2001 From: cmsierrave-coder <317402244+cmsierrave-coder@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:20:53 -0500 Subject: [PATCH 17/18] feat(libc): export narrow libc++ std::__1::cout and std::__1::cerr --- .../prx/libc/include/HostStandardStreams.hpp | 8 ++ core/libs/prx/libc/src/StandardStreams.cpp | 118 +++++++++++++++ core/libs/prx/libc/src/exception/TypeInfo.cpp | 5 + .../cmake/guest_libcxx_standard_output.cmake | 12 ++ core/libs/tests/GuestLibcxxStandardOutput.cpp | 136 ++++++++++++++++++ .../feat-libc-libcxx-standard-output.md | 5 + 6 files changed, 284 insertions(+) create mode 100644 core/libs/prx/libc/tests/cmake/guest_libcxx_standard_output.cmake create mode 100644 core/libs/tests/GuestLibcxxStandardOutput.cpp create mode 100644 docs/dev/debt/changes/feat-libc-libcxx-standard-output.md diff --git a/core/libs/prx/libc/include/HostStandardStreams.hpp b/core/libs/prx/libc/include/HostStandardStreams.hpp index 5c01f269cfe1..2b082d9b55f1 100644 --- a/core/libs/prx/libc/include/HostStandardStreams.hpp +++ b/core/libs/prx/libc/include/HostStandardStreams.hpp @@ -10,6 +10,14 @@ #include #endif +#ifdef __cplusplus +struct LibcxxStandardOstream; +extern "C" { +extern LibcxxStandardOstream _ZNSt3__14coutE_nid_postfix; +extern LibcxxStandardOstream _ZNSt3__14cerrE_nid_postfix; +} +#endif + #ifdef _WIN32 #undef stdout #undef stderr diff --git a/core/libs/prx/libc/src/StandardStreams.cpp b/core/libs/prx/libc/src/StandardStreams.cpp index 2d6b41b3c468..95b1bf6dedc5 100644 --- a/core/libs/prx/libc/src/StandardStreams.cpp +++ b/core/libs/prx/libc/src/StandardStreams.cpp @@ -7,6 +7,10 @@ #include #include #include +#include "prx/libc/include/HostStandardStreams.hpp" +#include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" #include #ifdef _WIN32 #include @@ -507,3 +511,117 @@ void APS5_VABI setbuf_nid_postfix(FileStream* stream, char* buffer) { } } + +struct LibcxxStandardOstream { + const GuestLocale::StreamDestructors* vtable; + GuestLocale::LibcxxIosBase ios; + void* tie; + int fill; +}; + +static_assert(offsetof(LibcxxStandardOstream, ios) == 0x08); +static_assert(offsetof(LibcxxStandardOstream, tie) == 0x90); +static_assert(offsetof(LibcxxStandardOstream, fill) == 0x98); +static_assert(sizeof(LibcxxStandardOstream) == 0xa0); + +extern "C" const LibcException::TypeRecord libcxxStandardOutputBufferType_nid_no_patch; + +namespace { + +struct OutputBuffer { + LibcxxStreambuf base; + FileStream* file; +}; + +struct OutputBufferVtable { + std::ptrdiff_t offsetToTop; + const LibcException::TypeRecord* type; + LibcxxStreambufVtable methods; +}; + +static_assert(offsetof(OutputBuffer, base) == 0); +static_assert(offsetof(OutputBufferVtable, methods) == 0x10); +static_assert(sizeof(OutputBufferVtable) == 0x80); + +FileStream* OutputFile(void* self) { + return reinterpret_cast(self)->file; +} + +void APS5_VABI DeleteOutputBuffer(LibcxxStreambuf* self) { + _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix(self); + _ZdlPv_nid_postfix(self); +} + +void APS5_VABI ImbueOutputBuffer(void*, const void* locale) { + const auto* requested = static_cast(locale); + if (requested->imp != _ZNSt3__16locale7classicEv_nid_postfix()->imp) + NotImplemented_nid_no_patch(__func__); +} + +int APS5_VABI SyncOutputBuffer(void* self) { + return fflush_nid_postfix(OutputFile(self)); +} + +std::int64_t APS5_VABI WriteOutputBuffer(LibcxxStreambuf* self, const char* source, std::int64_t size) { + if (size <= 0) return 0; + return static_cast(fwrite_nid_postfix(source, 1, static_cast(size), OutputFile(self))); +} + +int APS5_VABI OverflowOutputBuffer(void* self, int value) { + if (value == EOF) return 0; + return fputc_nid_postfix(static_cast(value), OutputFile(self)); +} + +constinit const OutputBufferVtable outputVtable { + 0, + &libcxxStandardOutputBufferType_nid_no_patch, + { + .destroy = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEED2Ev_nid_postfix, + .deleteObject = DeleteOutputBuffer, + .imbue = ImbueOutputBuffer, + .setbuf = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6setbufEPcl_nid_postfix, + .seekoff = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekoffExNS_8ios_base7seekdirEj_nid_postfix, + .seekpos = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE7seekposENS_4fposI11__mbstate_tEEj_nid_postfix, + .sync = SyncOutputBuffer, + .showmanyc = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9showmanycEv_nid_postfix, + .xsgetn = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsgetnEPcl_nid_postfix, + .underflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9underflowEv_nid_postfix, + .uflow = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE5uflowEv_nid_postfix, + .pbackfail = _ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE9pbackfailEi_nid_postfix, + .xsputn = WriteOutputBuffer, + .overflow = OverflowOutputBuffer, + }, +}; + +constinit OutputBuffer coutBuffer {{&outputVtable.methods, {}, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}, &_Stdout_nid_postfix}; +constinit OutputBuffer cerrBuffer {{&outputVtable.methods, {}, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}, &_Stderr_nid_postfix}; + +constexpr const auto& ostreamVtable = _ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; + +} + +extern "C" { + +constinit LibcxxStandardOstream _ZNSt3__14coutE_nid_postfix { + &ostreamVtable.primary.destructors, {.vtable = &ostreamVtable.secondary.destructors}, nullptr, -1, +}; + +constinit LibcxxStandardOstream _ZNSt3__14cerrE_nid_postfix { + &ostreamVtable.primary.destructors, {.vtable = &ostreamVtable.secondary.destructors}, &_ZNSt3__14coutE_nid_postfix, -1, +}; + +} + +namespace { + +const bool standardOutputInitialized = [] { + _ZNSt3__16localeC1Ev_nid_postfix(&coutBuffer.base.locale); + _ZNSt3__16localeC1Ev_nid_postfix(&cerrBuffer.base.locale); + _ZNSt3__18ios_base4initEPv_nid_postfix(&_ZNSt3__14coutE_nid_postfix.ios, &coutBuffer.base); + _ZNSt3__18ios_base4initEPv_nid_postfix(&_ZNSt3__14cerrE_nid_postfix.ios, &cerrBuffer.base); + constexpr std::uint32_t Unitbuf = 0x2000; + _ZNSt3__14cerrE_nid_postfix.ios.flags |= Unitbuf; + return true; +}(); + +} diff --git a/core/libs/prx/libc/src/exception/TypeInfo.cpp b/core/libs/prx/libc/src/exception/TypeInfo.cpp index 2e83dba5391d..746861310e3b 100644 --- a/core/libs/prx/libc/src/exception/TypeInfo.cpp +++ b/core/libs/prx/libc/src/exception/TypeInfo.cpp @@ -324,6 +324,11 @@ const LibcException::MultipleTypeRecord<1> _ZTINSt3__113basic_ostreamIcNS_11char {{&_ZTINSt3__19basic_iosIcNS_11char_traitsIcEEEE_nid_postfix, PublicVirtualBase}}, }; +extern const LibcException::TypeRecord libcxxStandardOutputBufferType_nid_no_patch { + SingleVtable(), "N6AnyPS520StandardOutputBufferE", + reinterpret_cast(&_ZTINSt3__115basic_streambufIcNS_11char_traitsIcEEEE_nid_postfix), +}; + constinit const GuestLocale::SimpleStreamVtable _ZTVNSt3__18ios_baseE_nid_postfix { 0, &_ZTINSt3__18ios_baseE_nid_postfix, {_ZNSt3__18ios_baseD1Ev_nid_postfix, _ZNSt3__18ios_baseD0Ev_nid_postfix}, diff --git a/core/libs/prx/libc/tests/cmake/guest_libcxx_standard_output.cmake b/core/libs/prx/libc/tests/cmake/guest_libcxx_standard_output.cmake new file mode 100644 index 000000000000..6e44c5f3246f --- /dev/null +++ b/core/libs/prx/libc/tests/cmake/guest_libcxx_standard_output.cmake @@ -0,0 +1,12 @@ +if(BUILD_TESTING) + add_test_executable(guest_libcxx_standard_output_tests ${LIBS_INCLUDE_DIR}/tests/GuestLibcxxStandardOutput.cpp) + target_include_directories(guest_libcxx_standard_output_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_libcxx_standard_output_tests PRIVATE libc) + configure_windows_unwind(guest_libcxx_standard_output_tests) + add_test(NAME guest_libcxx_standard_output COMMAND guest_libcxx_standard_output_tests) + set_tests_properties(guest_libcxx_standard_output PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_libcxx_standard_output PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/tests/GuestLibcxxStandardOutput.cpp b/core/libs/tests/GuestLibcxxStandardOutput.cpp new file mode 100644 index 000000000000..354f7ddb67d0 --- /dev/null +++ b/core/libs/tests/GuestLibcxxStandardOutput.cpp @@ -0,0 +1,136 @@ +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/LibcxxIosInit.hpp" +#include "prx/libc/include/LibcxxStreamVtables.hpp" +#include "prx/libc/include/LibcxxStreambufTransfer.hpp" +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include "prx/libc/include/HostStandardStreams.hpp" + +namespace { + +using GuestLocale::LibcxxIosBase; + +void Require(bool condition, std::source_location location = std::source_location::current()) { + if (condition) return; + std::fprintf(stderr, "check failed at line %u\n", location.line()); + std::abort(); +} + +#ifdef _WIN32 +using ::_close; +using ::_dup; +using ::_dup2; +using ::_fileno; +#else +int _close(int fd) { return ::close(fd); } +int _dup(int fd) { return ::dup(fd); } +int _dup2(int from, int to) { return ::dup2(from, to); } +int _fileno(std::FILE* file) { return ::fileno(file); } +#endif + +class Capture { +public: + explicit Capture(std::FILE* output) : output(output), file(std::tmpfile()) { + Require(file != nullptr && std::fflush(output) == 0); + const auto fd = _fileno(output); + saved = _dup(fd); + Require(saved >= 0 && _dup2(_fileno(file), fd) >= 0); + Require(std::setvbuf(output, nullptr, _IOFBF, BUFSIZ) == 0); + } + + ~Capture() { + Require(std::fflush(output) == 0 && _dup2(saved, _fileno(output)) >= 0); + Require(_close(saved) == 0 && std::fclose(file) == 0); + } + + std::string Read() { + Require(std::fseek(file, 0, SEEK_SET) == 0); + char bytes[128]{}; + const auto count = std::fread(bytes, 1, sizeof(bytes), file); + Require(std::ferror(file) == 0 && count < sizeof(bytes)); + return {bytes, count}; + } + +private: + std::FILE* output; + std::FILE* file; + int saved; +}; + +LibcxxIosBase& Ios(void* stream) { + const auto* const bytes = static_cast(stream); + const void* vptr{}; + std::memcpy(&vptr, bytes, sizeof(vptr)); + const auto& table = _ZTVNSt3__113basic_ostreamIcNS_11char_traitsIcEEEE_nid_postfix; + Require(vptr == &table.primary.destructors && table.iosOffset == 8); + auto& ios = *reinterpret_cast(static_cast(stream) + 8); + Require(ios.vtable == &table.secondary.destructors); + return ios; +} + +void Write(void* stream, const char* text) { + Require(_ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5writeEPKcl_nid_postfix(stream, text, std::strlen(text)) == stream); +} + +void Flush(void* stream) { + Require(_ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE5flushEv_nid_postfix(stream) == stream); +} + +void CheckStreams() { + auto* const out = &_ZNSt3__14coutE_nid_postfix; + auto* const err = &_ZNSt3__14cerrE_nid_postfix; + auto& outIos = Ios(out); + auto& errIos = Ios(err); + constexpr std::uint32_t Unitbuf = 0x2000; + Require(outIos.flags == 0x1002 && errIos.flags == (0x1002 | Unitbuf)); + Require(outIos.precision == 6 && errIos.precision == 6); + Require(outIos.width == 0 && errIos.width == 0); + Require(outIos.state == 0 && errIos.state == 0); + Require(outIos.exceptions == 0 && errIos.exceptions == 0); + Require(outIos.buffer != nullptr && errIos.buffer != nullptr && outIos.buffer != errIos.buffer); + Require(outIos.locale.imp != nullptr && outIos.locale.imp == errIos.locale.imp); + Require(static_cast(outIos.buffer)->locale.imp == outIos.locale.imp); + Require(static_cast(errIos.buffer)->locale.imp == errIos.locale.imp); + + const void* tie{}; + std::memcpy(&tie, reinterpret_cast(err) + 0x90, sizeof(tie)); + Require(tie == out); + + Capture outCapture(stdout); + Capture errCapture(stderr); + Write(out, "stdout"); + Flush(out); + Require(outCapture.Read() == "stdout"); + Write(out, " tied"); + Write(err, "stderr"); + Require(errCapture.Read() == "stderr"); + Require(outCapture.Read() == "stdout tied"); + Require(_ZNSt3__113basic_ostreamIcNS_11char_traitsIcEEE3putEc_nid_postfix(err, '!') == err); + Flush(err); + Require(errCapture.Read() == "stderr!"); + Require(outIos.state == 0 && errIos.state == 0); + + auto* const buffer = outIos.buffer; + outIos.buffer = nullptr; + _ZNSt3__18ios_base5clearEj_nid_postfix(&outIos, 0); + Require(outIos.state == 1); + outIos.buffer = buffer; + _ZNSt3__18ios_base5clearEj_nid_postfix(&outIos, 0); + Require(outIos.state == 0 && errIos.state == 0); +} + +} + +int main() { + CheckStreams(); + return 0; +} diff --git a/docs/dev/debt/changes/feat-libc-libcxx-standard-output.md b/docs/dev/debt/changes/feat-libc-libcxx-standard-output.md new file mode 100644 index 000000000000..d9350ae02841 --- /dev/null +++ b/docs/dev/debt/changes/feat-libc-libcxx-standard-output.md @@ -0,0 +1,5 @@ +# libc + +## add Functional + +- [libc++ cout and cerr](../../../core/libs/prx/libc/src/StandardStreams.cpp) (libc) - The narrow streams write through the guest C stdout and stderr streams. The streambufs use the classic narrow byte conversion. Nonclassic streambuf locale conversion remains pending. Console behavior and RetroArch startup are unverified. From face93fc29f2601c71291f1835a06cfe4642662a Mon Sep 17 00:00:00 2001 From: cmsierrave-coder <317402244+cmsierrave-coder@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:37:08 -0500 Subject: [PATCH 18/18] test(libc): allow classic locale ids initialized by standard streams --- core/libs/tests/GuestLibcxxCodecvtChar.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/libs/tests/GuestLibcxxCodecvtChar.cpp b/core/libs/tests/GuestLibcxxCodecvtChar.cpp index 6b1c96347d5a..06b591388410 100644 --- a/core/libs/tests/GuestLibcxxCodecvtChar.cpp +++ b/core/libs/tests/GuestLibcxxCodecvtChar.cpp @@ -57,8 +57,6 @@ const char* KindOf(const void* const* vtable) { } void CheckLocaleIds() { - const std::array zero{}; - for (const auto* id : exportedIds) Require(std::memcmp(id, zero.data(), zero.size()) == 0); for (std::size_t index = 0; index < std::size(exportedIds); ++index) Require(_ZNSt3__16locale2id5__getEv_nid_postfix(exportedIds[index]) == static_cast(index)); for (std::size_t index = std::size(exportedIds); index-- > 0;)