diff --git a/core/libs/prx/libSceLibcInternal/CMakeLists.txt b/core/libs/prx/libSceLibcInternal/CMakeLists.txt index 3aae2c755..6e4bc241c 100644 --- a/core/libs/prx/libSceLibcInternal/CMakeLists.txt +++ b/core/libs/prx/libSceLibcInternal/CMakeLists.txt @@ -20,4 +20,11 @@ if(BUILD_TESTING) set_tests_properties(guest_thread_atexit PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + if(NOT WIN32) + add_test_executable(guest_force_tls_destructor_tests ${LIBS_INCLUDE_DIR}/tests/GuestForceTlsDestructor.cpp) + target_include_directories(guest_force_tls_destructor_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_force_tls_destructor_tests PRIVATE libSceLibcInternal libkernel libc) + add_test(NAME guest_force_tls_destructor COMMAND guest_force_tls_destructor_tests) + set_tests_properties(guest_force_tls_destructor PROPERTIES TIMEOUT 20) + endif() endif() diff --git a/core/libs/prx/libSceLibcInternal/Export.cpp b/core/libs/prx/libSceLibcInternal/Export.cpp index c84ee09a1..f9425b744 100644 --- a/core/libs/prx/libSceLibcInternal/Export.cpp +++ b/core/libs/prx/libSceLibcInternal/Export.cpp @@ -2,6 +2,8 @@ #include "prx/libc/include/General.hpp" #include "prx/libc/include/HeapDiagnostics.hpp" #include "prx/libc/include/HostThreadLocal.hpp" +#include +#include #include #include #include @@ -12,6 +14,7 @@ #endif extern "C" void APS5_VABI sceKernelSetThreadDtors(thread_dtors_func_t dtors); +extern "C" int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t address, int flags, ModuleInfoEx* info); namespace { @@ -41,21 +44,53 @@ bool IsInLoadedImage(const void* address) { #endif } +void CallThreadDestructor(const ThreadDestructor& destructor) { + const auto* function = reinterpret_cast(destructor.function); + if (!IsInLoadedImage(function)) { + std::ostringstream message; + message << "thread_local destructor " << function << " of dso " << destructor.dsoSymbol << " is not in a loaded image"; + throw std::runtime_error(message.str()); + } + destructor.function(destructor.object); +} + void APS5_VABI RunThreadDestructors_nid_no_patch() { auto& destructors = ThreadDestructors(); while (!destructors.empty()) { const ThreadDestructor destructor = destructors.back(); destructors.pop_back(); - const auto* function = reinterpret_cast(destructor.function); - if (!IsInLoadedImage(function)) { - std::ostringstream message; - message << "thread_local destructor " << function << " of dso " << destructor.dsoSymbol << " is not in a loaded image"; - throw std::runtime_error(message.str()); - } - destructor.function(destructor.object); + CallThreadDestructor(destructor); } } +bool FindDsoModule(const void* dsoSymbol, KernelModule& handle) { + ModuleInfoEx info{}; + info.st_size = sizeof(ModuleInfoEx); + if (sceKernelGetModuleInfoFromAddr(reinterpret_cast(dsoSymbol), 2, &info) != 0) { + handle = 0; + return false; + } + handle = info.id; + return true; +} + +bool ForceThreadDestructorPass(KernelModule handle) { + auto& destructors = ThreadDestructors(); + bool found = false; + for (std::size_t index = destructors.size(); index-- > 0;) { + const ThreadDestructor destructor = destructors[index]; + KernelModule module = 0; + const bool loaded = FindDsoModule(destructor.dsoSymbol, module); + if (module != handle) + continue; + found = true; + destructors.erase(destructors.begin() + static_cast(index)); + if (loaded && *static_cast(destructor.dsoSymbol) == destructor.dsoSymbol) + CallThreadDestructor(destructor); + } + return found; +} + void RegisterThreadExitHook() { [[maybe_unused]] static const bool registered = [] { sceKernelSetThreadDtors(RunThreadDestructors_nid_no_patch); @@ -88,8 +123,10 @@ void APS5_VABI _sceLibcInternalThreadDtors_nid_postfix() { } int APS5_VABI _sceLibcInternalForceTlsDestructor_nid_postfix(KernelModule handle) { - (void)handle; - NotImplemented_nid_no_patch(__func__); + for (int pass = 0; pass < 4; ++pass) { + if (!ForceThreadDestructorPass(handle)) + break; + } return 0; } diff --git a/core/libs/tests/GuestForceTlsDestructor.cpp b/core/libs/tests/GuestForceTlsDestructor.cpp new file mode 100644 index 000000000..991538f24 --- /dev/null +++ b/core/libs/tests/GuestForceTlsDestructor.cpp @@ -0,0 +1,123 @@ +#include "SceTypes.hpp" +#include +#include +#include +#include + +extern "C" { +int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name); +int APS5_VABI scePthreadJoin(Pthread thread, void** retval); +int APS5_VABI sceKernelGetModuleInfoFromAddr(std::uint64_t address, int flags, ModuleInfoEx* info); +int APS5_VABI _sceLibcInternalThreadAtexit_nid_postfix(void (APS5_VABI* destructor)(void*), void* object, void* dsoSymbol); +void APS5_VABI _sceLibcInternalThreadDtors_nid_postfix(); +int APS5_VABI _sceLibcInternalForceTlsDestructor_nid_postfix(KernelModule handle); +} + +namespace { + +using Destructor = void (APS5_VABI*)(void*); + +void Require(bool value) { if (!value) std::abort(); } + +void* dsoHandle = &dsoHandle; +void* staleDsoHandle = nullptr; +KernelModule self = 0; +std::vector calls; + +void* Object(std::intptr_t value) { return reinterpret_cast(value); } + +int Register(Destructor destructor, std::intptr_t object, void* dso = &dsoHandle) { + return _sceLibcInternalThreadAtexit_nid_postfix(destructor, Object(object), dso); +} + +void APS5_VABI Record(void* object) { + calls.push_back(reinterpret_cast(object)); +} + +void APS5_VABI RecordAndRegister(void* object) { + Record(object); + const auto value = reinterpret_cast(object); + if (value < 17) + Require(Register(RecordAndRegister, value + 1) == 0); +} + +void* APS5_VABI Worker(void*) { + Require(Register(Record, 20) == 0); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls == std::vector{20}); + return nullptr; +} + +KernelModule ModuleOf(const void* address) { + ModuleInfoEx info{}; + info.st_size = sizeof(ModuleInfoEx); + Require(sceKernelGetModuleInfoFromAddr(reinterpret_cast(address), 2, &info) == 0); + return info.id; +} + +bool ForceThrows(KernelModule handle) { + try { + _sceLibcInternalForceTlsDestructor_nid_postfix(handle); + } catch (const std::runtime_error&) { + return true; + } + return false; +} + +} + +int main() { + self = ModuleOf(&dsoHandle); + void* otherDso = reinterpret_cast(&_sceLibcInternalThreadDtors_nid_postfix); + const KernelModule other = ModuleOf(otherDso); + Require(other != self && other != 0); + int local = 0; + + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls.empty()); + + Require(Register(Record, 1) == 0); + Require(Register(Record, 2, otherDso) == 0); + Require(Register(Record, 3) == 0); + Require(Register(Record, 4, &staleDsoHandle) == 0); + Require(Register(Record, 5, &local) == 0); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self + 1000) == 0); + Require(calls.empty()); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls == std::vector{3, 1}); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls.size() == 2); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(0) == 0); + Require(calls.size() == 2); + _sceLibcInternalThreadDtors_nid_postfix(); + Require(calls == std::vector{3, 1, 2}); + + calls.clear(); + Require(Register(Record, 6, otherDso) == 0); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(other) == 0); + Require(calls.empty()); + _sceLibcInternalThreadDtors_nid_postfix(); + Require(calls.empty()); + + Require(Register(RecordAndRegister, 10) == 0); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls == std::vector{10, 11, 12, 13}); + calls.clear(); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls == std::vector{14, 15, 16, 17}); + calls.clear(); + + Require(Register(Record, 30) == 0); + Pthread worker = nullptr; + Require(scePthreadCreate(&worker, nullptr, Worker, nullptr, "ForceTlsDestructor") == 0); + Require(scePthreadJoin(worker, nullptr) == 0); + Require(calls == std::vector{20}); + calls.clear(); + + std::vector heap(64); + Require(Register(reinterpret_cast(heap.data()), 7) == 0); + Require(ForceThrows(self)); + Require(calls.empty()); + Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0); + Require(calls == std::vector{30}); +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 90b28d786..a5ebe7ce6 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -102,7 +102,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceLibcInternalHeapErrorReportForGame](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libSceLibcInternal, implemented in libc) - unknown signature - [_sceLibcInternalThreadAtexit, _sceLibcInternalThreadDtors](../../core/libs/prx/libSceLibcInternal/Export.cpp) (libSceLibcInternal) - FreeBSD `__cxa_thread_atexit` semantics assumed; a null or non-image destructor and an allocation failure throw - [_sceKernelRtldThreadAtexitIncrement, _sceKernelRtldThreadAtexitDecrement](../../core/libs/prx/libkernel/System/src/Rtld.cpp) (libkernel) - the argument is the `dso` address a title's `libc.prx` passes to `__cxa_thread_atexit` (PPSA14632), which fails when Increment returns nonzero. As in the [fpPS4](https://github.com/red-prig/fpPS4) reimplementation, Increment takes a reference on the loaded image containing the address and Decrement releases one; the variants without the leading underscore are assumed to match -- [_sceLibcInternalForceTlsDestructor](../../core/libs/prx/libSceLibcInternal/Export.cpp) (libSceLibcInternal) - unknown return type and behaviour; a title's `libc.prx` calls it from `__cxa_finalize` with the module handle of a non-null dso +- [_sceLibcInternalForceTlsDestructor](../../core/libs/prx/libSceLibcInternal/Export.cpp) (libSceLibcInternal) - behaviour follows `sceLibcForceTlsDestructor(int)` in a title's `libc.prx` (disassembly): the calling thread's destructors whose dso belongs to the module run newest first, only if the dso's module is loaded and the dso points to itself, in up to 4 passes. The return type is unknown (that function returns nothing), 0 is returned. The module of each dso is looked up when the destructors are forced, not when they are registered as `libc.prx` does, and the lookup is Linux only, so on Windows the call throws when the thread has destructors - [std_execute_once](../../core/libs/prx/libc/Export.cpp) (libc) - assumed to be the plain-named twin of `std::_Execute_once` (`_ZSt13_Execute_onceRSt9once_flagPFiPvS1_PS1_ES1_`, the callee of Dinkumware `call_once`): it delegates there and gets the [thread.once.callonce] semantics already verified for that symbol (one invocation per flag, concurrent callers block until it completes, and a failing or throwing invocation leaves the flag unready so the next caller runs it). The name equivalence is not confirmed on a title, and the callback convention (called with (null, arg, null), non-zero return meaning success) is the twin's, unverified for this symbol - [__progname](../../core/libs/prx/libkernel/System/src/Process.cpp) (libkernel) - unknown data export - [pthread_barrierattr_setpshared](../../core/libs/prx/libkernel/Pthread/Posix/Barrier.cpp) (libkernel) - PTHREAD_PROCESS_SHARED is accepted on the assumption that the console follows FreeBSD 11.0 libthr, which accepts it (9.0 rejects it with EINVAL); unverified on hardware. Guest code runs in one process, so a shared barrier behaves as a private one