feat(libSceLibcInternal): implement _sceLibcInternalForceTlsDestructor

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Adrià Franch
2026-10-06 15:06:32 +02:00
parent 2b8f0b215e
commit cc789786de
4 changed files with 177 additions and 10 deletions
@@ -20,4 +20,11 @@ if(BUILD_TESTING)
set_tests_properties(guest_thread_atexit PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceLibcInternal>")
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()
+46 -9
View File
@@ -2,6 +2,8 @@
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/HeapDiagnostics.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <cstddef>
#include <cstdint>
#include <sstream>
#include <stdexcept>
#include <vector>
@@ -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<const void*>(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<const void*>(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<std::uintptr_t>(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<std::ptrdiff_t>(index));
if (loaded && *static_cast<void* const*>(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;
}
+123
View File
@@ -0,0 +1,123 @@
#include "SceTypes.hpp"
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <vector>
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<std::intptr_t> calls;
void* Object(std::intptr_t value) { return reinterpret_cast<void*>(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<std::intptr_t>(object));
}
void APS5_VABI RecordAndRegister(void* object) {
Record(object);
const auto value = reinterpret_cast<std::intptr_t>(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<std::intptr_t>{20});
return nullptr;
}
KernelModule ModuleOf(const void* address) {
ModuleInfoEx info{};
info.st_size = sizeof(ModuleInfoEx);
Require(sceKernelGetModuleInfoFromAddr(reinterpret_cast<std::uintptr_t>(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<void*>(&_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<std::intptr_t>{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<std::intptr_t>{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<std::intptr_t>{10, 11, 12, 13});
calls.clear();
Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0);
Require(calls == std::vector<std::intptr_t>{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<std::intptr_t>{20});
calls.clear();
std::vector<unsigned char> heap(64);
Require(Register(reinterpret_cast<Destructor>(heap.data()), 7) == 0);
Require(ForceThrows(self));
Require(calls.empty());
Require(_sceLibcInternalForceTlsDestructor_nid_postfix(self) == 0);
Require(calls == std::vector<std::intptr_t>{30});
}
+1 -1
View File
@@ -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